Skip to main content

rings_node/processor/
horizon.rs

1//! The signing horizon of a node's own delegation: until when the process can send anything
2//! (#1063, #1153).
3//!
4//! A node signs every frame it sends with its own delegation, whose expiry is `e`. From
5//! `h = e − Δ` on, the sender refuses every frame that carries it ([`signing_horizon_ms`]), so
6//! without a renewal the node is mute from `h` on:
7//!
8//! ```text
9//!   Signing ──(t ≥ h − lead)──▶ Expiring ──(t ≥ h)──▶ Mute      (Mute is absorbing)
10//!                                  │
11//!                        renew(h' > h)
12//!                                  ▼
13//!                               Signing
14//! ```
15//!
16//! Laws (#1153):
17//! - **Monotone horizon**: After a successful renewal, `h' > h`. A renewal never shortens the
18//!   horizon.
19//! - **No unsigned gap**: At every instant in `[renewal, e)`, the node holds some key whose
20//!   delegation verifies, and retains the previous key until `e` so envelopes sealed to it before
21//!   peers observe the republished descriptors still open.
22//! - **Fallback**: No delegator key, or a failed mint, gives the #1063 behaviour (warn at
23//!   `h − lead` and exit at `h`).
24//!
25//! This module classifies instants and guards in-memory key rotation ([`SessionKeyRing`]); the
26//! process shell (`native::horizon`) drives renewal and exit.
27
28use std::sync::PoisonError;
29use std::sync::RwLock;
30
31use rings_core::delegation::DelegateeKey;
32use rings_core::delegation::Delegation;
33use rings_core::swarm::signing_horizon_ms;
34
35use crate::error::Error;
36use crate::error::Result;
37
38/// How long before its horizon a node starts warning that it will go mute: one day, so an
39/// operator can rotate the delegation before the process ends.
40pub const SIGNING_HORIZON_LEAD_MS: u128 = 24 * 60 * 60 * 1000;
41
42/// What a node can do at one instant, by its own delegation.
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub enum SigningState {
45    /// Frames leave, and the horizon is `remaining_ms` away, more than
46    /// [`SIGNING_HORIZON_LEAD_MS`].
47    Signing {
48        /// Time left until the horizon.
49        remaining_ms: u128,
50    },
51    /// Frames leave, but the horizon is `remaining_ms` away, within the lead.
52    Expiring {
53        /// Time left until the horizon.
54        remaining_ms: u128,
55    },
56    /// Past the horizon: every frame is refused until the process restarts.
57    Mute,
58}
59
60/// The signing horizon `h = e − Δ` of a node's own delegation.
61#[derive(Clone, Copy, Debug, Eq, PartialEq)]
62pub struct DelegationHorizon {
63    /// The delegation's expiry `e`.
64    expires_at_ms: u128,
65    /// `h = e − Δ`.
66    horizon_ms: u128,
67}
68
69impl DelegationHorizon {
70    /// The horizon of `delegation`.
71    pub fn of(delegation: &Delegation) -> Self {
72        Self::expiring_at(delegation.expires_at_ms())
73    }
74
75    /// The horizon of a delegation that expires at `expires_at_ms`.
76    pub const fn expiring_at(expires_at_ms: u128) -> Self {
77        Self {
78            expires_at_ms,
79            horizon_ms: signing_horizon_ms(expires_at_ms),
80        }
81    }
82
83    /// The delegation's expiry `e`.
84    pub const fn expires_at_ms(self) -> u128 {
85        self.expires_at_ms
86    }
87
88    /// `h`: the first instant at which the node can send nothing.
89    pub const fn horizon_ms(self) -> u128 {
90        self.horizon_ms
91    }
92
93    /// Whether the node can still send at `now_ms`: `now < h`.
94    pub const fn signs_at(self, now_ms: u128) -> bool {
95        now_ms < self.horizon_ms
96    }
97
98    /// A process may start at `now_ms` only while it can still send: a delegation with less
99    /// than `Δ` left would make it mute from its first frame.
100    ///
101    /// # Errors
102    ///
103    /// [`Error::DelegationHorizonReached`] at or past the horizon.
104    pub const fn admitted_at(self, now_ms: u128) -> Result<()> {
105        if self.signs_at(now_ms) {
106            Ok(())
107        } else {
108            Err(self.reached())
109        }
110    }
111
112    /// The error of a node at or past this horizon.
113    pub const fn reached(self) -> Error {
114        Error::DelegationHorizonReached {
115            expires_at_ms: self.expires_at_ms,
116            horizon_ms: self.horizon_ms,
117        }
118    }
119
120    /// The state at `now_ms` (module diagram). Law: `state_at(t) = Mute ⇔ ¬signs_at(t)`, and the
121    /// state never goes back along the diagram as `t` grows.
122    pub const fn state_at(self, now_ms: u128) -> SigningState {
123        if !self.signs_at(now_ms) {
124            return SigningState::Mute;
125        }
126        let remaining_ms = self.horizon_ms - now_ms;
127        if remaining_ms <= SIGNING_HORIZON_LEAD_MS {
128            SigningState::Expiring { remaining_ms }
129        } else {
130            SigningState::Signing { remaining_ms }
131        }
132    }
133
134    /// The earliest instant at which in-process renewal is due for a delegation stamped at
135    /// `created_at_ms`: `max(h − lead, c + ⌊(h − c) / 2⌋)`.
136    ///
137    /// Law (**Renewal instant**): For every delegation with `c < h`, `renew_at_ms(c) ∈ [c, h)`,
138    /// and when `h − c ≥ 2`, `renew_at_ms(c) > c` so minting a replacement with the same TTL at
139    /// `t ≥ renew_at_ms(c)` strictly advances the horizon (`h' > h`).
140    pub const fn renew_at_ms(self, created_at_ms: u128) -> u128 {
141        let lead_start = self.horizon_ms.saturating_sub(SIGNING_HORIZON_LEAD_MS);
142        let half_life =
143            created_at_ms.saturating_add(self.horizon_ms.saturating_sub(created_at_ms) / 2);
144        if lead_start >= half_life {
145            lead_start
146        } else {
147            half_life
148        }
149    }
150}
151
152/// Pure Kleisli validation of a candidate [`DelegateeKey`] against `current` at `now_ms`.
153///
154/// Separates all cryptographic and horizon-order invariants from key-file I/O and lock mutation:
155/// - **Same delegator**: `next.delegator_did() == current.delegator_did()`.
156/// - **No unsigned gap**: `next`'s delegation verifies at `now_ms` and `now_ms < h'`.
157/// - **Monotone horizon**: `h' > h`. A renewal never shortens the signing horizon.
158fn validate_delegation_renewal(
159    current: &DelegateeKey,
160    next: DelegateeKey,
161    now_ms: u128,
162) -> Result<(DelegateeKey, DelegationHorizon)> {
163    (next.delegator_did() == current.delegator_did())
164        .then_some(())
165        .ok_or_else(|| {
166            Error::VerifyError(
167                "renewed delegatee key delegator DID does not match node DID".to_string(),
168            )
169        })
170        .and_then(|()| next.verify_at(now_ms).map_err(Error::CoreError))
171        .and_then(|()| {
172            let current_horizon = DelegationHorizon::of(&current.delegation());
173            let next_horizon = DelegationHorizon::of(&next.delegation());
174            next_horizon.admitted_at(now_ms).and_then(|()| {
175                (next_horizon.horizon_ms() > current_horizon.horizon_ms())
176                    .then_some((next, next_horizon))
177                    .ok_or_else(|| current_horizon.reached())
178            })
179        })
180}
181
182/// Mutable state behind [`SessionKeyRing`].
183#[derive(Debug)]
184struct SessionKeyRingState {
185    /// Active key used for all new signatures and descriptor publications.
186    current: DelegateeKey,
187    /// Previous keys retained until their delegation expiry `e` so mail or onion hops sealed to a
188    /// prior key before descriptor republication settles can still be opened.
189    retained: Vec<DelegateeKey>,
190    /// Successful runtime rotations in this process lifetime.
191    rotation_succeeded_total: u64,
192    /// Failed runtime rotation attempts in this process lifetime.
193    rotation_failed_total: u64,
194}
195
196/// Shared live session key and retained unexpired previous keys for a [`super::Processor`].
197///
198/// Enforces the **Monotone horizon** (`h' > h`) and **No unsigned gap** laws across every clone
199/// of the processor.
200#[derive(Debug)]
201pub(crate) struct SessionKeyRing {
202    state: RwLock<SessionKeyRingState>,
203}
204
205impl SessionKeyRing {
206    /// Construct a key ring starting with `current`.
207    pub(crate) const fn new(current: DelegateeKey) -> Self {
208        Self {
209            state: RwLock::new(SessionKeyRingState {
210                current,
211                retained: Vec::new(),
212                rotation_succeeded_total: 0,
213                rotation_failed_total: 0,
214            }),
215        }
216    }
217
218    /// Return the active [`DelegateeKey`].
219    pub(crate) fn current(&self) -> DelegateeKey {
220        self.state
221            .read()
222            .unwrap_or_else(PoisonError::into_inner)
223            .current
224            .clone()
225    }
226
227    /// Return the [`DelegationHorizon`] of the active key.
228    pub(crate) fn horizon(&self) -> DelegationHorizon {
229        let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
230        DelegationHorizon::of(&state.current.delegation())
231    }
232
233    /// Return the active key followed by any retained previous keys that have not yet expired at
234    /// `now_ms` (`t < e`).
235    pub(crate) fn decryption_keys_at(&self, now_ms: u128) -> Vec<DelegateeKey> {
236        let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
237        std::iter::once(state.current.clone())
238            .chain(
239                state
240                    .retained
241                    .iter()
242                    .rev()
243                    .filter(|key| !key.delegation().is_expired_at(now_ms))
244                    .cloned(),
245            )
246            .collect()
247    }
248
249    /// Return `(rotation_succeeded_total, rotation_failed_total)`.
250    pub(crate) fn rotation_counts(&self) -> (u64, u64) {
251        let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
252        (state.rotation_succeeded_total, state.rotation_failed_total)
253    }
254
255    /// Monadic `Result` Kleisli pipeline (`mint >=> validate_delegation_renewal >=> persist`) that
256    /// installs `next` while retaining the displaced unexpired key; any error from `mint`, pure
257    /// law validation, or `persist` short-circuits, increments `rotation_failed_total`, and leaves
258    /// the active key and retained list untouched.
259    ///
260    /// `persist` receives `(&current, &next)` **while the write lock is held**, so callers that
261    /// synchronize auxiliary components (such as transport session credentials) always roll back to
262    /// the exact committed `current` key even under concurrent renewal races.
263    ///
264    /// Laws:
265    /// - **Same delegator**: `next.delegator_did() == current.delegator_did()`.
266    /// - **No unsigned gap**: `next`'s delegation verifies at `now_ms` and `now_ms < h'`.
267    /// - **Monotone horizon**: `h' > h`. A renewal never shortens the signing horizon.
268    /// - **Transactional failure**: `Err(_)` preserves `state.current` and `state.retained`.
269    pub(crate) fn renew_with<M, P>(
270        &self,
271        now_ms: u128,
272        mint: M,
273        persist: P,
274    ) -> Result<(DelegateeKey, DelegationHorizon)>
275    where
276        M: FnOnce(&DelegateeKey) -> Result<DelegateeKey>,
277        P: FnOnce(&DelegateeKey, &DelegateeKey) -> Result<()>,
278    {
279        let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
280        let outcome = mint(&state.current)
281            .and_then(|next| validate_delegation_renewal(&state.current, next, now_ms))
282            .and_then(|(next, next_horizon)| {
283                persist(&state.current, &next).map(|()| (next, next_horizon))
284            });
285        match outcome {
286            Ok((next, next_horizon)) => {
287                state
288                    .retained
289                    .retain(|key| !key.delegation().is_expired_at(now_ms));
290                let previous = std::mem::replace(&mut state.current, next.clone());
291                if !previous.delegation().is_expired_at(now_ms)
292                    && previous.delegatee_public_key() != state.current.delegatee_public_key()
293                {
294                    state.retained.push(previous);
295                }
296                state.rotation_succeeded_total = state.rotation_succeeded_total.saturating_add(1);
297                Ok((next, next_horizon))
298            }
299            Err(error) => {
300                state.rotation_failed_total = state.rotation_failed_total.saturating_add(1);
301                Err(error)
302            }
303        }
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use rings_core::delegation::DelegateeKey;
310    use rings_core::ecc::SecretKey;
311    use rings_core::swarm::signing_horizon_ms;
312
313    use super::DelegationHorizon;
314    use super::SessionKeyRing;
315    use super::SigningState;
316    use super::SIGNING_HORIZON_LEAD_MS;
317    use crate::error::Error;
318
319    /// The states follow the diagram: `Mute` exactly when not signing, `Expiring` only within the
320    /// lead, and no instant goes back to an earlier state, around the lead's start and the
321    /// horizon of an expiry well past both.
322    #[test]
323    fn test_states_follow_the_horizon_and_never_go_back() {
324        let expires_at_ms = 10 * SIGNING_HORIZON_LEAD_MS;
325        let horizon = DelegationHorizon::expiring_at(expires_at_ms);
326        let h = horizon.horizon_ms();
327        assert_eq!(h, signing_horizon_ms(expires_at_ms));
328        let rank = |state| match state {
329            SigningState::Signing { .. } => 0,
330            SigningState::Expiring { .. } => 1,
331            SigningState::Mute => 2,
332        };
333        let lead_start = h - SIGNING_HORIZON_LEAD_MS;
334        let instants = [
335            0,
336            lead_start - 1,
337            lead_start,
338            lead_start + 1,
339            h - 1,
340            h,
341            h + 1,
342        ];
343        let states = instants.map(|now| horizon.state_at(now));
344        assert_eq!(states.map(rank), [0, 0, 1, 1, 1, 2, 2]);
345        assert_eq!(states[4], SigningState::Expiring { remaining_ms: 1 });
346        for (now, state) in instants.into_iter().zip(states) {
347            assert_eq!(state == SigningState::Mute, !horizon.signs_at(now));
348        }
349    }
350
351    /// A process starts only while it signs: one instant before the horizon it starts, and at
352    /// the horizon, which a delegation with exactly `Δ` left reaches at once, it is refused
353    /// with the horizon named.
354    #[test]
355    fn test_a_process_starts_only_before_its_horizon() {
356        let horizon = DelegationHorizon::expiring_at(10 * SIGNING_HORIZON_LEAD_MS);
357        let h = horizon.horizon_ms();
358        assert!(horizon.admitted_at(h - 1).is_ok());
359        for now_ms in [h, h + 1] {
360            assert!(matches!(
361                horizon.admitted_at(now_ms),
362                Err(Error::DelegationHorizonReached { horizon_ms, .. }) if horizon_ms == h
363            ));
364        }
365    }
366
367    /// Laws (**Monotone horizon** and **No unsigned gap**, #1153): `SessionKeyRing::renew_with`
368    /// refuses any key that shortens or stalls `h`, or changes the delegator DID, while a valid
369    /// renewal advances `h' > h`, keeps a verifying delegation across `[renewal, e)`, and retains
370    /// the previous key for decryption until its expiry `e`.
371    #[test]
372    fn test_session_key_ring_enforces_monotone_horizon_and_no_unsigned_gap() {
373        let delegator = SecretKey::random();
374        let other_delegator = SecretKey::random();
375        let t0: u128 = 1_800_000_000_000;
376        let ttl_ms = u64::try_from(4 * SIGNING_HORIZON_LEAD_MS).unwrap_or(u64::MAX);
377        let initial = match DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, t0) {
378            Ok(key) => key,
379            Err(error) => panic!("initial key mint must succeed: {error}"),
380        };
381        let initial_pubkey = initial.delegatee_public_key();
382        let initial_expires = initial.delegation().expires_at_ms();
383        let ring = SessionKeyRing::new(initial);
384        let h0 = ring.horizon().horizon_ms();
385        let renew_ms = h0 - SIGNING_HORIZON_LEAD_MS;
386
387        // Same or earlier horizon (`h' <= h`) is rejected and leaves the active key untouched.
388        let non_advancing = match DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, t0) {
389            Ok(key) => key,
390            Err(error) => panic!("non-advancing key mint must succeed: {error}"),
391        };
392        assert!(matches!(
393            ring.renew_with(renew_ms, |_| Ok(non_advancing), |_, _| Ok(())),
394            Err(Error::DelegationHorizonReached { horizon_ms, .. }) if horizon_ms == h0
395        ));
396        assert_eq!(ring.rotation_counts(), (0, 1));
397        assert_eq!(ring.current().delegatee_public_key(), initial_pubkey);
398
399        // Wrong delegator DID is rejected.
400        let wrong_did_key =
401            match DelegateeKey::new_with_seckey_at(&other_delegator, ttl_ms, renew_ms) {
402                Ok(key) => key,
403                Err(error) => panic!("wrong-did key mint must succeed: {error}"),
404            };
405        assert!(matches!(
406            ring.renew_with(renew_ms, |_| Ok(wrong_did_key), |_, _| Ok(())),
407            Err(Error::VerifyError(_))
408        ));
409        assert_eq!(ring.rotation_counts(), (0, 2));
410
411        // Valid renewal at `h0 - R` advances `h1 > h0` and retains the previous key until `e0`.
412        let renewed = match DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, renew_ms) {
413            Ok(key) => key,
414            Err(error) => panic!("renewed key mint must succeed: {error}"),
415        };
416        let renewed_pubkey = renewed.delegatee_public_key();
417        let h1 = match ring.renew_with(renew_ms, |_| Ok(renewed), |_, _| Ok(())) {
418            Ok((_, horizon)) => horizon.horizon_ms(),
419            Err(error) => panic!("valid renewal must succeed: {error}"),
420        };
421        assert!(h1 > h0);
422        assert_eq!(ring.rotation_counts(), (1, 2));
423
424        for instant in [renew_ms, h0, initial_expires - 1, initial_expires] {
425            assert!(ring
426                .current()
427                .delegation()
428                .verify_delegator_authorization_at(instant)
429                .is_ok());
430            let keys: Vec<_> = ring
431                .decryption_keys_at(instant)
432                .into_iter()
433                .map(|key| key.delegatee_public_key())
434                .collect();
435            assert_eq!(keys, vec![renewed_pubkey, initial_pubkey]);
436        }
437
438        // Once the previous delegation expires (`t > e0`), only the active key remains.
439        let keys_after_expiry: Vec<_> = ring
440            .decryption_keys_at(initial_expires + 1)
441            .into_iter()
442            .map(|key| key.delegatee_public_key())
443            .collect();
444        assert_eq!(keys_after_expiry, vec![renewed_pubkey]);
445    }
446
447    /// Law (**Renewal instant**, #1153): `renew_at_ms(c) = max(h − lead, c + ⌊(h − c) / 2⌋)`,
448    /// which lies in `(c, h)` whenever `h − c ≥ 2`.
449    #[test]
450    fn test_renew_at_ms_respects_lead_and_half_life_law() {
451        let c: u128 = 1_800_000_000_000;
452        let long_horizon = DelegationHorizon::expiring_at(c + 4 * SIGNING_HORIZON_LEAD_MS);
453        assert_eq!(
454            long_horizon.renew_at_ms(c),
455            long_horizon.horizon_ms() - SIGNING_HORIZON_LEAD_MS
456        );
457
458        let short_horizon = DelegationHorizon::expiring_at(c + SIGNING_HORIZON_LEAD_MS);
459        let h_short = short_horizon.horizon_ms();
460        let r_short = short_horizon.renew_at_ms(c);
461        assert_eq!(r_short, c + (h_short - c) / 2);
462        assert!(r_short > c && r_short < h_short);
463    }
464
465    /// Four-Component Two-Phase Lockstep Integration Test (Issue #1291 §4):
466    /// Exercises the concrete `Processor::renew_delegatee_key_with` two-phase commit pipeline
467    /// across all failure stages (`MintErr`, `RingValidateErr`, `SwarmValidateErr`,
468    /// `TransportPrepareErr`, `PersistErr`, `CommitOk`) and concurrent renewal contention,
469    /// asserting `\square (k_ring == k_disk == k_swarm == k_transport)` without compensating
470    /// rollbacks.
471    #[test]
472    fn test_processor_renew_delegatee_key_preserves_three_component_lockstep_invariant() {
473        use std::sync::atomic::AtomicBool;
474        use std::sync::atomic::AtomicUsize;
475        use std::sync::atomic::Ordering;
476        use std::sync::Arc;
477        use std::sync::Mutex;
478
479        use rings_core::utils::ManualClock;
480        use rings_transport::core::transport::SharedTransport;
481        use rings_turn::format_turn_server_url;
482        use rings_turn::TurnCredentialSigner;
483
484        use crate::processor::NodeNetworkParameters;
485        use crate::processor::ProcessorBuilder;
486        use crate::processor::ProcessorConfig;
487        use crate::processor::SessionRotationCommit;
488        use crate::processor::TransportNetworkConfig;
489
490        /// Fault-injectable [`NodeNetworkParameters`] wrapper around [`TransportNetworkConfig`]
491        /// that counts phase-1 `prepare_session_key_rotation` calls vs phase-2 commit executions
492        /// and allows injecting phase-1 preparation failures.
493        #[derive(Clone, Debug)]
494        struct FaultInjectableNetworkParams {
495            /// Underlying assisted-traversal transport configuration.
496            inner: TransportNetworkConfig,
497            /// When `true`, `prepare_session_key_rotation` fails before mutating the transport.
498            fail_rotation: Arc<AtomicBool>,
499            /// Count of phase-1 preparation calls.
500            prepare_calls: Arc<AtomicUsize>,
501            /// Count of phase-2 commit closure executions.
502            commit_calls: Arc<AtomicUsize>,
503        }
504
505        impl NodeNetworkParameters for FaultInjectableNetworkParams {
506            /// Delegate initial transport construction to the inner [`TransportNetworkConfig`].
507            fn build_transport(
508                &self,
509                delegatee_key: &DelegateeKey,
510            ) -> crate::error::Result<SharedTransport> {
511                NodeNetworkParameters::build_transport(&self.inner, delegatee_key)
512            }
513
514            /// Delegate endpoint hint inspection to the inner [`TransportNetworkConfig`].
515            fn endpoint_hint(&self) -> Option<&str> {
516                NodeNetworkParameters::endpoint_hint(&self.inner)
517            }
518
519            /// Fail in phase 1 when `fail_rotation` is armed; otherwise prepare the inner
520            /// [`TransportNetworkConfig`] rotation without mutating `transport`.
521            fn prepare_session_key_rotation(
522                &self,
523                transport: &SharedTransport,
524                next_key: &DelegateeKey,
525            ) -> crate::error::Result<SessionRotationCommit> {
526                self.prepare_calls.fetch_add(1, Ordering::SeqCst);
527                if self.fail_rotation.load(Ordering::SeqCst) {
528                    return Err(Error::InvalidConfig(
529                        "injected transport session-key rotation prepare failure".to_string(),
530                    ));
531                }
532                let inner_commit = NodeNetworkParameters::prepare_session_key_rotation(
533                    &self.inner,
534                    transport,
535                    next_key,
536                )?;
537                let commits = Arc::clone(&self.commit_calls);
538                Ok(Box::new(move || {
539                    commits.fetch_add(1, Ordering::SeqCst);
540                    inner_commit();
541                }))
542            }
543        }
544
545        let delegator = SecretKey::random();
546        let other_delegator = SecretKey::random();
547        let turn_server_pubkey = SecretKey::random().pubkey();
548        let turn_url =
549            format_turn_server_url("turn://turn.rings.rs:3478", turn_server_pubkey).unwrap();
550        let raw_ice = format!("stun://stun.l.google.com:19302;{turn_url}");
551
552        let t0: u128 = 1_800_000_000_000;
553        let ttl_ms = u64::try_from(4 * SIGNING_HORIZON_LEAD_MS).unwrap_or(u64::MAX);
554        let k0 = DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, t0).unwrap();
555        let clock = Arc::new(ManualClock::new(t0));
556        let fail_rotation = Arc::new(AtomicBool::new(false));
557        let prepare_calls = Arc::new(AtomicUsize::new(0));
558        let commit_calls = Arc::new(AtomicUsize::new(0));
559        let persisted_disk_key = Arc::new(Mutex::new(k0.clone()));
560
561        let config = ProcessorConfig::new(1, raw_ice.clone(), k0.clone(), 15)
562            .with_clock(clock)
563            .with_network_parameters(FaultInjectableNetworkParams {
564                inner: TransportNetworkConfig::new(raw_ice.clone(), None, None),
565                fail_rotation: Arc::clone(&fail_rotation),
566                prepare_calls: Arc::clone(&prepare_calls),
567                commit_calls: Arc::clone(&commit_calls),
568            });
569        let processor = ProcessorBuilder::from_config(&config)
570            .unwrap()
571            .build_at(t0)
572            .unwrap();
573
574        let assert_lockstep = |expected_key: &DelegateeKey| {
575            let k_ring = processor.delegatee_key();
576            let k_disk = persisted_disk_key.lock().unwrap().clone();
577            let k_swarm = processor.swarm.delegatee_key();
578            let k_transport = processor
579                .session_transport_credentials()
580                .expect("transport must report active session credentials");
581            let expected_credentials = expected_key.sign_ice_servers(&raw_ice).unwrap();
582
583            assert_eq!(
584                k_ring.delegatee_public_key(),
585                expected_key.delegatee_public_key(),
586                "k_ring diverged from expected key"
587            );
588            assert_eq!(
589                k_disk.delegatee_public_key(),
590                expected_key.delegatee_public_key(),
591                "k_disk diverged from k_ring"
592            );
593            assert_eq!(
594                k_swarm.delegatee_public_key(),
595                expected_key.delegatee_public_key(),
596                "k_swarm diverged from k_ring"
597            );
598            assert_eq!(
599                k_transport, expected_credentials,
600                "k_transport diverged from k_ring session credentials"
601            );
602        };
603
604        assert_lockstep(&k0);
605
606        let h0 = processor.signing_horizon().horizon_ms();
607        let renew_ms = h0 - SIGNING_HORIZON_LEAD_MS;
608        let k1 = DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, renew_ms).unwrap();
609
610        // 1. MintErr: failure at Stage 1 preserves (k0, k0, k0, k0).
611        let mint_err = processor.renew_delegatee_key_with(
612            renew_ms,
613            |_| Err(Error::VerifyError("injected mint failure".to_string())),
614            |next| {
615                *persisted_disk_key.lock().unwrap() = next.clone();
616                Ok(())
617            },
618        );
619        assert!(mint_err.is_err());
620        assert_lockstep(&k0);
621
622        // 2. RingValidateErr (non-advancing horizon): failure at Stage 2 preserves (k0, k0, k0, k0).
623        let non_advancing = DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, t0).unwrap();
624        let val_err_horizon = processor.renew_delegatee_key_with(
625            renew_ms,
626            |_| Ok(non_advancing),
627            |next| {
628                *persisted_disk_key.lock().unwrap() = next.clone();
629                Ok(())
630            },
631        );
632        assert!(val_err_horizon.is_err());
633        assert_lockstep(&k0);
634
635        // 3. RingValidateErr (wrong delegator DID): failure at Stage 2 preserves (k0, k0, k0, k0).
636        let wrong_did =
637            DelegateeKey::new_with_seckey_at(&other_delegator, ttl_ms, renew_ms).unwrap();
638        let val_err_did = processor.renew_delegatee_key_with(
639            renew_ms,
640            |_| Ok(wrong_did),
641            |next| {
642                *persisted_disk_key.lock().unwrap() = next.clone();
643                Ok(())
644            },
645        );
646        assert!(val_err_did.is_err());
647        assert_lockstep(&k0);
648
649        // 4. TransportPrepareErr: failure in phase 1 (`prepare_session_key_rotation`) aborts
650        //    before touching disk, swarm, or key ring, with zero phase-2 commits.
651        fail_rotation.store(true, Ordering::SeqCst);
652        let rot_err = processor.renew_delegatee_key_with(
653            renew_ms,
654            |_| Ok(k1.clone()),
655            |next| {
656                *persisted_disk_key.lock().unwrap() = next.clone();
657                Ok(())
658            },
659        );
660        fail_rotation.store(false, Ordering::SeqCst);
661        assert!(rot_err.is_err());
662        assert_eq!(commit_calls.load(Ordering::SeqCst), 0);
663        assert_lockstep(&k0);
664
665        // 5. PersistErr: failure at the single commit point (`persist`) aborts BEFORE any
666        //    in-memory state (`swarm`, `transport`, `ring`) is mutated — `commit_calls` stays 0!
667        let persist_err = processor.renew_delegatee_key_with(
668            renew_ms,
669            |_| Ok(k1.clone()),
670            |_| Err(Error::CreateFileError("injected disk failure".to_string())),
671        );
672        assert!(persist_err.is_err());
673        assert_eq!(
674            commit_calls.load(Ordering::SeqCst),
675            0,
676            "PersistErr must abort before executing phase-2 transport commit"
677        );
678        assert_lockstep(&k0);
679
680        // 6. CommitOk: atomic transition advances all four components to (k1, k1, k1, k1).
681        let h1 = processor
682            .renew_delegatee_key_with(
683                renew_ms,
684                |_| Ok(k1.clone()),
685                |next| {
686                    *persisted_disk_key.lock().unwrap() = next.clone();
687                    Ok(())
688                },
689            )
690            .expect("valid renewal must commit");
691        assert!(h1.horizon_ms() > h0);
692        assert_eq!(commit_calls.load(Ordering::SeqCst), 1);
693        assert_lockstep(&k1);
694
695        // 7. Subsequent TransportPrepareErr from committed state `k1` preserves (k1, k1, k1, k1).
696        let renew_ms_2 = h1.horizon_ms() - SIGNING_HORIZON_LEAD_MS;
697        let k2 = DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, renew_ms_2).unwrap();
698        fail_rotation.store(true, Ordering::SeqCst);
699        let rot_err_2 = processor.renew_delegatee_key_with(
700            renew_ms_2,
701            |_| Ok(k2.clone()),
702            |next| {
703                *persisted_disk_key.lock().unwrap() = next.clone();
704                Ok(())
705            },
706        );
707        fail_rotation.store(false, Ordering::SeqCst);
708        assert!(rot_err_2.is_err());
709        assert_lockstep(&k1);
710
711        // 8. SwarmValidateErr: on an isolated processor whose swarm horizon was synthetically
712        //    advanced ahead of its ring (`k2` vs `k0`), attempting to renew the ring to `k1`
713        //    fails at `Swarm::validate_next_delegatee_key` BEFORE `prepare_session_key_rotation`
714        //    or `persist(next)` ever runs.
715        {
716            let skew_prepares = Arc::new(AtomicUsize::new(0));
717            let skew_commits = Arc::new(AtomicUsize::new(0));
718            let skew_disk = Arc::new(Mutex::new(k0.clone()));
719            let skew_cfg = ProcessorConfig::new(1, raw_ice.clone(), k0.clone(), 15)
720                .with_network_parameters(FaultInjectableNetworkParams {
721                    inner: TransportNetworkConfig::new(raw_ice.clone(), None, None),
722                    fail_rotation: Arc::new(AtomicBool::new(false)),
723                    prepare_calls: Arc::clone(&skew_prepares),
724                    commit_calls: Arc::clone(&skew_commits),
725                });
726            let skew_proc = ProcessorBuilder::from_config(&skew_cfg)
727                .unwrap()
728                .build_at(t0)
729                .unwrap();
730            skew_proc
731                .swarm
732                .set_delegatee_key(k2.clone())
733                .expect("advancing swarm key to k2 must succeed");
734            let swarm_val_err = skew_proc.renew_delegatee_key_with(
735                renew_ms,
736                |_| Ok(k1.clone()),
737                |next| {
738                    *skew_disk.lock().unwrap() = next.clone();
739                    Ok(())
740                },
741            );
742            assert!(
743                swarm_val_err.is_err(),
744                "SwarmValidateErr must reject renewal when swarm rejects candidate key"
745            );
746            assert_eq!(
747                skew_prepares.load(Ordering::SeqCst),
748                0,
749                "SwarmValidateErr must short-circuit before transport prepare"
750            );
751            assert_eq!(skew_commits.load(Ordering::SeqCst), 0);
752            assert_eq!(
753                skew_disk.lock().unwrap().delegatee_public_key(),
754                k0.delegatee_public_key(),
755                "SwarmValidateErr must never touch disk"
756            );
757            assert_eq!(
758                skew_proc.delegatee_key().delegatee_public_key(),
759                k0.delegatee_public_key(),
760                "SwarmValidateErr must leave key ring untouched"
761            );
762        }
763
764        // 9. Concurrent renewal race (native multi-threaded): Thread A blocks waiting for the
765        //    key-ring write lock while Thread B commits `k1 -> k2`. Thread A then attempts
766        //    `k2 -> k3` whose `persist` fails; because phase 1 never mutated `transport` or
767        //    `swarm`, `(k2, k2, k2, k2)` stays intact without any rollback race.
768        #[cfg(not(target_family = "wasm"))]
769        {
770            let renew_ms_3 =
771                DelegationHorizon::of(&k2.delegation()).horizon_ms() - SIGNING_HORIZON_LEAD_MS;
772            let k3 = DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, renew_ms_3).unwrap();
773            let entered_b = Arc::new(std::sync::Barrier::new(2));
774            let release_b = Arc::new(std::sync::Barrier::new(2));
775
776            let proc_b = processor.clone();
777            let disk_b = Arc::clone(&persisted_disk_key);
778            let k2_for_b = k2.clone();
779            let entered_b_tx = Arc::clone(&entered_b);
780            let release_b_rx = Arc::clone(&release_b);
781            let handle_b = std::thread::spawn(move || {
782                proc_b.renew_delegatee_key_with(
783                    renew_ms_2,
784                    |_| {
785                        entered_b_tx.wait();
786                        release_b_rx.wait();
787                        Ok(k2_for_b)
788                    },
789                    |next| {
790                        *disk_b.lock().unwrap() = next.clone();
791                        Ok(())
792                    },
793                )
794            });
795
796            entered_b.wait();
797            let proc_a = processor.clone();
798            let handle_a = std::thread::spawn(move || {
799                proc_a.renew_delegatee_key_with(
800                    renew_ms_3,
801                    |_| Ok(k3),
802                    |_| {
803                        Err(Error::CreateFileError(
804                            "concurrent persist fail".to_string(),
805                        ))
806                    },
807                )
808            });
809
810            std::thread::sleep(std::time::Duration::from_millis(20));
811            release_b.wait();
812
813            assert!(handle_b.join().unwrap().is_ok());
814            assert!(handle_a.join().unwrap().is_err());
815            assert_lockstep(&k2);
816        }
817    }
818
819    /// Exhaustive Stateright Model Check & Mutant Refutation for Two-Phase Session Rotation
820    /// (Issue #1291 F4 + Impl #1):
821    ///
822    /// Explores every reachable state `(k_ring, k_disk, k_swarm, k_transport, step)` across
823    /// arbitrary sequences of `{MintErr, RingValidateErr, SwarmValidateErr, TransportPrepareErr,
824    /// PersistErr, PersistErrWithRollbackFault, CommitOk}` over up to 3 sequential rotations:
825    /// 1. Proves `ProtocolVariant::TwoPhase` satisfies `\square (k_ring == k_disk == k_swarm ==
826    ///    k_transport)` across 100% of reachable states.
827    /// 2. Refutes `ProtocolVariant::MutantPersistBeforeSwarmValidate` (proving that running
828    ///    `persist` before `Swarm::validate_next_delegatee_key` breaks `k_disk == k_swarm`).
829    /// 3. Refutes `ProtocolVariant::MutantMutateTransportWithFallibleRollback` (proving that
830    ///    mutating `transport` before `persist` with best-effort `let _ = rollback` breaks
831    ///    `k_transport == k_ring` when rollback fails).
832    #[cfg(not(target_family = "wasm"))]
833    #[test]
834    fn test_stateright_two_phase_rotation_lockstep_and_mutant_refutation() {
835        use stateright::Checker;
836        use stateright::Model;
837        use stateright::Property;
838
839        #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
840        enum ProtocolVariant {
841            TwoPhase,
842            MutantPersistBeforeSwarmValidate,
843            MutantMutateTransportWithFallibleRollback,
844        }
845
846        #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
847        struct RotationState {
848            k_ring: u8,
849            k_disk: u8,
850            k_swarm: u8,
851            k_transport: u8,
852            depth: u8,
853        }
854
855        #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
856        enum RotationAction {
857            MintErr,
858            RingValidateErr,
859            SwarmValidateErr,
860            TransportPrepareErr,
861            PersistErr,
862            PersistErrWithRollbackFault,
863            CommitOk,
864        }
865
866        struct RotationModel {
867            variant: ProtocolVariant,
868            max_depth: u8,
869        }
870
871        impl Model for RotationModel {
872            type State = RotationState;
873            type Action = RotationAction;
874
875            fn init_states(&self) -> Vec<Self::State> {
876                vec![RotationState {
877                    k_ring: 0,
878                    k_disk: 0,
879                    k_swarm: 0,
880                    k_transport: 0,
881                    depth: 0,
882                }]
883            }
884
885            fn actions(&self, state: &Self::State, actions: &mut Vec<Self::Action>) {
886                if state.depth >= self.max_depth {
887                    return;
888                }
889                actions.extend([
890                    RotationAction::MintErr,
891                    RotationAction::RingValidateErr,
892                    RotationAction::SwarmValidateErr,
893                    RotationAction::TransportPrepareErr,
894                    RotationAction::PersistErr,
895                    RotationAction::PersistErrWithRollbackFault,
896                    RotationAction::CommitOk,
897                ]);
898            }
899
900            fn next_state(&self, last: &Self::State, action: Self::Action) -> Option<Self::State> {
901                let mut next = *last;
902                next.depth = last.depth + 1;
903                let candidate = last.k_ring + 1;
904
905                match self.variant {
906                    ProtocolVariant::TwoPhase => {
907                        // Phase 1 (pure): mint -> ring_validate -> swarm_validate -> transport_prepare
908                        // Single commit point: persist(candidate)
909                        // Phase 2 (infallible): swarm_commit -> transport_commit -> ring_commit
910                        match action {
911                            RotationAction::MintErr
912                            | RotationAction::RingValidateErr
913                            | RotationAction::SwarmValidateErr
914                            | RotationAction::TransportPrepareErr
915                            | RotationAction::PersistErr
916                            | RotationAction::PersistErrWithRollbackFault => Some(next),
917                            RotationAction::CommitOk => {
918                                next.k_disk = candidate;
919                                next.k_swarm = candidate;
920                                next.k_transport = candidate;
921                                next.k_ring = candidate;
922                                Some(next)
923                            }
924                        }
925                    }
926                    ProtocolVariant::MutantPersistBeforeSwarmValidate => match action {
927                        RotationAction::MintErr
928                        | RotationAction::RingValidateErr
929                        | RotationAction::TransportPrepareErr
930                        | RotationAction::PersistErr
931                        | RotationAction::PersistErrWithRollbackFault => Some(next),
932                        RotationAction::SwarmValidateErr => {
933                            // Bug: persisted to disk BEFORE swarm validation rejected the key!
934                            next.k_disk = candidate;
935                            Some(next)
936                        }
937                        RotationAction::CommitOk => {
938                            next.k_disk = candidate;
939                            next.k_swarm = candidate;
940                            next.k_transport = candidate;
941                            next.k_ring = candidate;
942                            Some(next)
943                        }
944                    },
945                    ProtocolVariant::MutantMutateTransportWithFallibleRollback => match action {
946                        RotationAction::MintErr
947                        | RotationAction::RingValidateErr
948                        | RotationAction::SwarmValidateErr
949                        | RotationAction::TransportPrepareErr => Some(next),
950                        RotationAction::PersistErr => {
951                            // Mutated transport, then rolled back successfully.
952                            next.k_transport = last.k_ring;
953                            Some(next)
954                        }
955                        RotationAction::PersistErrWithRollbackFault => {
956                            // Bug: mutated transport before persist, and `let _ = rollback` failed!
957                            next.k_transport = candidate;
958                            Some(next)
959                        }
960                        RotationAction::CommitOk => {
961                            next.k_disk = candidate;
962                            next.k_swarm = candidate;
963                            next.k_transport = candidate;
964                            next.k_ring = candidate;
965                            Some(next)
966                        }
967                    },
968                }
969            }
970
971            fn properties(&self) -> Vec<Property<Self>> {
972                vec![Property::<Self>::always(
973                    "four-component lockstep invariant",
974                    |_, s| {
975                        s.k_ring == s.k_disk && s.k_ring == s.k_swarm && s.k_ring == s.k_transport
976                    },
977                )]
978            }
979        }
980
981        // 1. Two-phase protocol satisfies lockstep across every reachable interleaving.
982        let checker_ok = RotationModel {
983            variant: ProtocolVariant::TwoPhase,
984            max_depth: 3,
985        }
986        .checker()
987        .spawn_bfs()
988        .join();
989        checker_ok.assert_properties();
990        assert!(
991            checker_ok.unique_state_count() > 1,
992            "BFS must explore multi-epoch transitions"
993        );
994
995        // 2. Mutant A (`persist` before `Swarm::validate_next_delegatee_key`) is refuted.
996        let checker_mutant_a = RotationModel {
997            variant: ProtocolVariant::MutantPersistBeforeSwarmValidate,
998            max_depth: 2,
999        }
1000        .checker()
1001        .spawn_bfs()
1002        .join();
1003        assert!(
1004            checker_mutant_a
1005                .discovery("four-component lockstep invariant")
1006                .is_some(),
1007            "Stateright must refute persist-before-swarm-validate mutant"
1008        );
1009
1010        // 3. Mutant B (`mutate transport before persist` with fallible rollback) is refuted.
1011        let checker_mutant_b = RotationModel {
1012            variant: ProtocolVariant::MutantMutateTransportWithFallibleRollback,
1013            max_depth: 2,
1014        }
1015        .checker()
1016        .spawn_bfs()
1017        .join();
1018        assert!(
1019            checker_mutant_b
1020                .discovery("four-component lockstep invariant")
1021                .is_some(),
1022            "Stateright must refute fallible-rollback mutant"
1023        );
1024    }
1025}