use std::sync::PoisonError;
use std::sync::RwLock;
use rings_core::delegation::DelegateeKey;
use rings_core::delegation::Delegation;
use rings_core::swarm::signing_horizon_ms;
use crate::error::Error;
use crate::error::Result;
pub const SIGNING_HORIZON_LEAD_MS: u128 = 24 * 60 * 60 * 1000;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SigningState {
Signing {
remaining_ms: u128,
},
Expiring {
remaining_ms: u128,
},
Mute,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DelegationHorizon {
expires_at_ms: u128,
horizon_ms: u128,
}
impl DelegationHorizon {
pub fn of(delegation: &Delegation) -> Self {
Self::expiring_at(delegation.expires_at_ms())
}
pub const fn expiring_at(expires_at_ms: u128) -> Self {
Self {
expires_at_ms,
horizon_ms: signing_horizon_ms(expires_at_ms),
}
}
pub const fn expires_at_ms(self) -> u128 {
self.expires_at_ms
}
pub const fn horizon_ms(self) -> u128 {
self.horizon_ms
}
pub const fn signs_at(self, now_ms: u128) -> bool {
now_ms < self.horizon_ms
}
pub const fn admitted_at(self, now_ms: u128) -> Result<()> {
if self.signs_at(now_ms) {
Ok(())
} else {
Err(self.reached())
}
}
pub const fn reached(self) -> Error {
Error::DelegationHorizonReached {
expires_at_ms: self.expires_at_ms,
horizon_ms: self.horizon_ms,
}
}
pub const fn state_at(self, now_ms: u128) -> SigningState {
if !self.signs_at(now_ms) {
return SigningState::Mute;
}
let remaining_ms = self.horizon_ms - now_ms;
if remaining_ms <= SIGNING_HORIZON_LEAD_MS {
SigningState::Expiring { remaining_ms }
} else {
SigningState::Signing { remaining_ms }
}
}
pub const fn renew_at_ms(self, created_at_ms: u128) -> u128 {
let lead_start = self.horizon_ms.saturating_sub(SIGNING_HORIZON_LEAD_MS);
let half_life =
created_at_ms.saturating_add(self.horizon_ms.saturating_sub(created_at_ms) / 2);
if lead_start >= half_life {
lead_start
} else {
half_life
}
}
}
fn validate_delegation_renewal(
current: &DelegateeKey,
next: DelegateeKey,
now_ms: u128,
) -> Result<(DelegateeKey, DelegationHorizon)> {
(next.delegator_did() == current.delegator_did())
.then_some(())
.ok_or_else(|| {
Error::VerifyError(
"renewed delegatee key delegator DID does not match node DID".to_string(),
)
})
.and_then(|()| next.verify_at(now_ms).map_err(Error::CoreError))
.and_then(|()| {
let current_horizon = DelegationHorizon::of(¤t.delegation());
let next_horizon = DelegationHorizon::of(&next.delegation());
next_horizon.admitted_at(now_ms).and_then(|()| {
(next_horizon.horizon_ms() > current_horizon.horizon_ms())
.then_some((next, next_horizon))
.ok_or_else(|| current_horizon.reached())
})
})
}
#[derive(Debug)]
struct SessionKeyRingState {
current: DelegateeKey,
retained: Vec<DelegateeKey>,
rotation_succeeded_total: u64,
rotation_failed_total: u64,
}
#[derive(Debug)]
pub(crate) struct SessionKeyRing {
state: RwLock<SessionKeyRingState>,
}
impl SessionKeyRing {
pub(crate) const fn new(current: DelegateeKey) -> Self {
Self {
state: RwLock::new(SessionKeyRingState {
current,
retained: Vec::new(),
rotation_succeeded_total: 0,
rotation_failed_total: 0,
}),
}
}
pub(crate) fn current(&self) -> DelegateeKey {
self.state
.read()
.unwrap_or_else(PoisonError::into_inner)
.current
.clone()
}
pub(crate) fn horizon(&self) -> DelegationHorizon {
let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
DelegationHorizon::of(&state.current.delegation())
}
pub(crate) fn decryption_keys_at(&self, now_ms: u128) -> Vec<DelegateeKey> {
let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
std::iter::once(state.current.clone())
.chain(
state
.retained
.iter()
.rev()
.filter(|key| !key.delegation().is_expired_at(now_ms))
.cloned(),
)
.collect()
}
pub(crate) fn rotation_counts(&self) -> (u64, u64) {
let state = self.state.read().unwrap_or_else(PoisonError::into_inner);
(state.rotation_succeeded_total, state.rotation_failed_total)
}
pub(crate) fn renew_with<M, P>(
&self,
now_ms: u128,
mint: M,
persist: P,
) -> Result<(DelegateeKey, DelegationHorizon)>
where
M: FnOnce(&DelegateeKey) -> Result<DelegateeKey>,
P: FnOnce(&DelegateeKey) -> Result<()>,
{
let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner);
let outcome = mint(&state.current)
.and_then(|next| validate_delegation_renewal(&state.current, next, now_ms))
.and_then(|(next, next_horizon)| persist(&next).map(|()| (next, next_horizon)));
match outcome {
Ok((next, next_horizon)) => {
state
.retained
.retain(|key| !key.delegation().is_expired_at(now_ms));
let previous = std::mem::replace(&mut state.current, next.clone());
if !previous.delegation().is_expired_at(now_ms)
&& previous.delegatee_public_key() != state.current.delegatee_public_key()
{
state.retained.push(previous);
}
state.rotation_succeeded_total = state.rotation_succeeded_total.saturating_add(1);
Ok((next, next_horizon))
}
Err(error) => {
state.rotation_failed_total = state.rotation_failed_total.saturating_add(1);
Err(error)
}
}
}
}
#[cfg(test)]
mod tests {
use rings_core::delegation::DelegateeKey;
use rings_core::ecc::SecretKey;
use rings_core::swarm::signing_horizon_ms;
use super::DelegationHorizon;
use super::SessionKeyRing;
use super::SigningState;
use super::SIGNING_HORIZON_LEAD_MS;
use crate::error::Error;
#[test]
fn test_states_follow_the_horizon_and_never_go_back() {
let expires_at_ms = 10 * SIGNING_HORIZON_LEAD_MS;
let horizon = DelegationHorizon::expiring_at(expires_at_ms);
let h = horizon.horizon_ms();
assert_eq!(h, signing_horizon_ms(expires_at_ms));
let rank = |state| match state {
SigningState::Signing { .. } => 0,
SigningState::Expiring { .. } => 1,
SigningState::Mute => 2,
};
let lead_start = h - SIGNING_HORIZON_LEAD_MS;
let instants = [
0,
lead_start - 1,
lead_start,
lead_start + 1,
h - 1,
h,
h + 1,
];
let states = instants.map(|now| horizon.state_at(now));
assert_eq!(states.map(rank), [0, 0, 1, 1, 1, 2, 2]);
assert_eq!(states[4], SigningState::Expiring { remaining_ms: 1 });
for (now, state) in instants.into_iter().zip(states) {
assert_eq!(state == SigningState::Mute, !horizon.signs_at(now));
}
}
#[test]
fn test_a_process_starts_only_before_its_horizon() {
let horizon = DelegationHorizon::expiring_at(10 * SIGNING_HORIZON_LEAD_MS);
let h = horizon.horizon_ms();
assert!(horizon.admitted_at(h - 1).is_ok());
for now_ms in [h, h + 1] {
assert!(matches!(
horizon.admitted_at(now_ms),
Err(Error::DelegationHorizonReached { horizon_ms, .. }) if horizon_ms == h
));
}
}
#[test]
fn test_session_key_ring_enforces_monotone_horizon_and_no_unsigned_gap() {
let delegator = SecretKey::random();
let other_delegator = SecretKey::random();
let t0: u128 = 1_800_000_000_000;
let ttl_ms = u64::try_from(4 * SIGNING_HORIZON_LEAD_MS).unwrap_or(u64::MAX);
let initial = match DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, t0) {
Ok(key) => key,
Err(error) => panic!("initial key mint must succeed: {error}"),
};
let initial_pubkey = initial.delegatee_public_key();
let initial_expires = initial.delegation().expires_at_ms();
let ring = SessionKeyRing::new(initial);
let h0 = ring.horizon().horizon_ms();
let renew_ms = h0 - SIGNING_HORIZON_LEAD_MS;
let non_advancing = match DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, t0) {
Ok(key) => key,
Err(error) => panic!("non-advancing key mint must succeed: {error}"),
};
assert!(matches!(
ring.renew_with(renew_ms, |_| Ok(non_advancing), |_| Ok(())),
Err(Error::DelegationHorizonReached { horizon_ms, .. }) if horizon_ms == h0
));
assert_eq!(ring.rotation_counts(), (0, 1));
assert_eq!(ring.current().delegatee_public_key(), initial_pubkey);
let wrong_did_key =
match DelegateeKey::new_with_seckey_at(&other_delegator, ttl_ms, renew_ms) {
Ok(key) => key,
Err(error) => panic!("wrong-did key mint must succeed: {error}"),
};
assert!(matches!(
ring.renew_with(renew_ms, |_| Ok(wrong_did_key), |_| Ok(())),
Err(Error::VerifyError(_))
));
assert_eq!(ring.rotation_counts(), (0, 2));
let renewed = match DelegateeKey::new_with_seckey_at(&delegator, ttl_ms, renew_ms) {
Ok(key) => key,
Err(error) => panic!("renewed key mint must succeed: {error}"),
};
let renewed_pubkey = renewed.delegatee_public_key();
let h1 = match ring.renew_with(renew_ms, |_| Ok(renewed), |_| Ok(())) {
Ok((_, horizon)) => horizon.horizon_ms(),
Err(error) => panic!("valid renewal must succeed: {error}"),
};
assert!(h1 > h0);
assert_eq!(ring.rotation_counts(), (1, 2));
for instant in [renew_ms, h0, initial_expires - 1, initial_expires] {
assert!(ring
.current()
.delegation()
.verify_delegator_authorization_at(instant)
.is_ok());
let keys: Vec<_> = ring
.decryption_keys_at(instant)
.into_iter()
.map(|key| key.delegatee_public_key())
.collect();
assert_eq!(keys, vec![renewed_pubkey, initial_pubkey]);
}
let keys_after_expiry: Vec<_> = ring
.decryption_keys_at(initial_expires + 1)
.into_iter()
.map(|key| key.delegatee_public_key())
.collect();
assert_eq!(keys_after_expiry, vec![renewed_pubkey]);
}
#[test]
fn test_renew_at_ms_respects_lead_and_half_life_law() {
let c: u128 = 1_800_000_000_000;
let long_horizon = DelegationHorizon::expiring_at(c + 4 * SIGNING_HORIZON_LEAD_MS);
assert_eq!(
long_horizon.renew_at_ms(c),
long_horizon.horizon_ms() - SIGNING_HORIZON_LEAD_MS
);
let short_horizon = DelegationHorizon::expiring_at(c + SIGNING_HORIZON_LEAD_MS);
let h_short = short_horizon.horizon_ms();
let r_short = short_horizon.renew_at_ms(c);
assert_eq!(r_short, c + (h_short - c) / 2);
assert!(r_short > c && r_short < h_short);
}
}