//! Token-signing keys: how a key is made, which key signs now, which keys are published, and when the //! next key is due. //! //! The chain (contracts section 2.2, architecture section 8): a key is created at least 24 hours before //! it signs, so it is published first. A key signs for 90 days. When its successor is created, it is //! retired at the successor's activation time, and it stays published for 7 more days, so tokens it //! signed before then still verify. Every instant here is a stored stamp; the comparisons are text. use std::time::Duration; use ed25519_dalek::SigningKey; use crate::model::KeyRecord; use crate::time::{stamp_minus, stamp_plus}; const DAY: Duration = Duration::from_secs(24 * 60 * 60); /// How long a key signs before its successor takes over. pub const ROTATION_PERIOD: Duration = Duration::from_secs(90 * 24 * 60 * 60); /// How long before it signs a new key is created and published. pub const PUBLISH_LEAD: Duration = DAY; /// How long a retired key stays published after its retirement. pub const OVERLAP: Duration = Duration::from_secs(7 * 24 * 60 * 60); /// A freshly generated key: its id, its seed (the private key) and its public key. pub struct FreshKey { /// Random key id, 32 hex characters. pub kid: String, /// The 32-byte Ed25519 seed. Seal it before storing. pub seed: [u8; 32], /// The 32-byte public key. pub public: [u8; 32], } /// Generates a new Ed25519 key with a random seed and a random `kid`. pub fn generate() -> FreshKey { let mut seed = [0u8; 32]; rand::fill(&mut seed); let public = SigningKey::from_bytes(&seed).verifying_key().to_bytes(); let mut id = [0u8; 16]; rand::fill(&mut id); FreshKey { kid: hex::encode(id), seed, public, } } /// The key that signs at `now`: the newest one whose activation has come and that is not yet retired. pub fn current<'a>(keys: &'a [KeyRecord], now: &str) -> Option<&'a KeyRecord> { keys.iter() .filter(|key| { key.activates_at.as_str() <= now && key .retires_at .as_deref() .is_none_or(|retired| retired > now) }) .max_by(|a, b| a.activates_at.cmp(&b.activates_at)) } /// The keys published at `now`: every key not retired, and every key retired less than [`OVERLAP`] ago. pub fn published<'a>(keys: &'a [KeyRecord], now: &str) -> Vec<&'a KeyRecord> { let cutoff = stamp_minus(now, OVERLAP).unwrap_or_else(|| now.to_owned()); keys.iter() .filter(|key| { key.retires_at .as_deref() .is_none_or(|retired| retired > cutoff.as_str()) }) .collect() } /// Whether a new key must be created at `now`, and if so when it activates. `None` means the chain is /// fine: a key is pending, or the current one is not due within the publish lead. /// /// With no key at all, the new key activates at once. Otherwise it activates [`PUBLISH_LEAD`] from now, /// which is the first moment it can be published, and the newest key is retired at that same instant. pub fn next_activation(keys: &[KeyRecord], now: &str) -> Option { let head = keys .iter() .filter(|key| key.retires_at.is_none()) .max_by(|a, b| a.activates_at.cmp(&b.activates_at)); let Some(head) = head else { return Some(now.to_owned()); }; if head.activates_at.as_str() > now { return None; } let activates_at = stamp_plus(now, PUBLISH_LEAD)?; let due = stamp_plus(&head.activates_at, ROTATION_PERIOD)?; (activates_at >= due).then_some(activates_at) } #[cfg(test)] mod tests { use super::*; fn key(kid: &str, activates_at: &str, retires_at: Option<&str>) -> KeyRecord { KeyRecord { kid: kid.into(), private_sealed: String::new(), public_raw: vec![0; 32], created_at: activates_at.into(), activates_at: activates_at.into(), retires_at: retires_at.map(str::to_owned), } } #[test] fn the_chain_creates_its_successor_a_day_ahead_and_retires_the_old_key_then() { let now = "2026-10-28T00:00:00.000000000Z"; assert_eq!(next_activation(&[], now).as_deref(), Some(now)); let first = key("a", now, None); // Far from due: nothing to do. assert_eq!(next_activation(std::slice::from_ref(&first), now), None); // Due within the lead: the successor activates one day from now. let due_soon = "2027-01-25T12:00:00.000000000Z"; assert_eq!( next_activation(std::slice::from_ref(&first), due_soon).as_deref(), Some("2027-01-26T12:00:00.000000000Z") ); let retired = key("a", now, Some("2027-01-26T12:00:00.000000000Z")); let successor = key("b", "2027-01-26T12:00:00.000000000Z", None); let rows = [retired.clone(), successor.clone()]; // Before the handover the old key still signs; after it the successor does. assert_eq!( current(&rows, "2027-01-26T11:59:59.000000000Z").map(|k| k.kid.as_str()), Some("a") ); assert_eq!( current(&rows, "2027-01-26T12:00:00.000000000Z").map(|k| k.kid.as_str()), Some("b") ); // Both stay published across the overlap, and the retired one drops out after seven days. assert_eq!(published(&rows, "2027-01-30T00:00:00.000000000Z").len(), 2); assert_eq!(published(&rows, "2027-02-03T12:00:00.000000000Z").len(), 1); } }