forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

keys.rs143 lines, 5.5 KiBHistoryRawDownload
1//! Token-signing keys: how a key is made, which key signs now, which keys are published, and when the
2//! next key is due.
3//!
4//! The chain (contracts section 2.2, architecture section 8): a key is created at least 24 hours before
5//! it signs, so it is published first. A key signs for 90 days. When its successor is created, it is
6//! retired at the successor's activation time, and it stays published for 7 more days, so tokens it
7//! signed before then still verify. Every instant here is a stored stamp; the comparisons are text.
8
9use std::time::Duration;
10
11use ed25519_dalek::SigningKey;
12
13use crate::model::KeyRecord;
14use crate::time::{stamp_minus, stamp_plus};
15
16const DAY: Duration = Duration::from_secs(24 * 60 * 60);
17
18/// How long a key signs before its successor takes over.
19pub const ROTATION_PERIOD: Duration = Duration::from_secs(90 * 24 * 60 * 60);
20
21/// How long before it signs a new key is created and published.
22pub const PUBLISH_LEAD: Duration = DAY;
23
24/// How long a retired key stays published after its retirement.
25pub const OVERLAP: Duration = Duration::from_secs(7 * 24 * 60 * 60);
26
27/// A freshly generated key: its id, its seed (the private key) and its public key.
28pub struct FreshKey {
29 /// Random key id, 32 hex characters.
30 pub kid: String,
31 /// The 32-byte Ed25519 seed. Seal it before storing.
32 pub seed: [u8; 32],
33 /// The 32-byte public key.
34 pub public: [u8; 32],
35}
36
37/// Generates a new Ed25519 key with a random seed and a random `kid`.
38pub fn generate() -> FreshKey {
39 let mut seed = [0u8; 32];
40 rand::fill(&mut seed);
41 let public = SigningKey::from_bytes(&seed).verifying_key().to_bytes();
42 let mut id = [0u8; 16];
43 rand::fill(&mut id);
44 FreshKey {
45 kid: hex::encode(id),
46 seed,
47 public,
48 }
49}
50
51/// The key that signs at `now`: the newest one whose activation has come and that is not yet retired.
52pub fn current<'a>(keys: &'a [KeyRecord], now: &str) -> Option<&'a KeyRecord> {
53 keys.iter()
54 .filter(|key| {
55 key.activates_at.as_str() <= now
56 && key
57 .retires_at
58 .as_deref()
59 .is_none_or(|retired| retired > now)
60 })
61 .max_by(|a, b| a.activates_at.cmp(&b.activates_at))
62}
63
64/// The keys published at `now`: every key not retired, and every key retired less than [`OVERLAP`] ago.
65pub fn published<'a>(keys: &'a [KeyRecord], now: &str) -> Vec<&'a KeyRecord> {
66 let cutoff = stamp_minus(now, OVERLAP).unwrap_or_else(|| now.to_owned());
67 keys.iter()
68 .filter(|key| {
69 key.retires_at
70 .as_deref()
71 .is_none_or(|retired| retired > cutoff.as_str())
72 })
73 .collect()
74}
75
76/// Whether a new key must be created at `now`, and if so when it activates. `None` means the chain is
77/// fine: a key is pending, or the current one is not due within the publish lead.
78///
79/// With no key at all, the new key activates at once. Otherwise it activates [`PUBLISH_LEAD`] from now,
80/// which is the first moment it can be published, and the newest key is retired at that same instant.
81pub fn next_activation(keys: &[KeyRecord], now: &str) -> Option<String> {
82 let head = keys
83 .iter()
84 .filter(|key| key.retires_at.is_none())
85 .max_by(|a, b| a.activates_at.cmp(&b.activates_at));
86 let Some(head) = head else {
87 return Some(now.to_owned());
88 };
89 if head.activates_at.as_str() > now {
90 return None;
91 }
92 let activates_at = stamp_plus(now, PUBLISH_LEAD)?;
93 let due = stamp_plus(&head.activates_at, ROTATION_PERIOD)?;
94 (activates_at >= due).then_some(activates_at)
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 fn key(kid: &str, activates_at: &str, retires_at: Option<&str>) -> KeyRecord {
102 KeyRecord {
103 kid: kid.into(),
104 private_sealed: String::new(),
105 public_raw: vec![0; 32],
106 created_at: activates_at.into(),
107 activates_at: activates_at.into(),
108 retires_at: retires_at.map(str::to_owned),
109 }
110 }
111
112 #[test]
113 fn the_chain_creates_its_successor_a_day_ahead_and_retires_the_old_key_then() {
114 let now = "2026-10-28T00:00:00.000000000Z";
115 assert_eq!(next_activation(&[], now).as_deref(), Some(now));
116
117 let first = key("a", now, None);
118 // Far from due: nothing to do.
119 assert_eq!(next_activation(std::slice::from_ref(&first), now), None);
120 // Due within the lead: the successor activates one day from now.
121 let due_soon = "2027-01-25T12:00:00.000000000Z";
122 assert_eq!(
123 next_activation(std::slice::from_ref(&first), due_soon).as_deref(),
124 Some("2027-01-26T12:00:00.000000000Z")
125 );
126
127 let retired = key("a", now, Some("2027-01-26T12:00:00.000000000Z"));
128 let successor = key("b", "2027-01-26T12:00:00.000000000Z", None);
129 let rows = [retired.clone(), successor.clone()];
130 // Before the handover the old key still signs; after it the successor does.
131 assert_eq!(
132 current(&rows, "2027-01-26T11:59:59.000000000Z").map(|k| k.kid.as_str()),
133 Some("a")
134 );
135 assert_eq!(
136 current(&rows, "2027-01-26T12:00:00.000000000Z").map(|k| k.kid.as_str()),
137 Some("b")
138 );
139 // Both stay published across the overlap, and the retired one drops out after seven days.
140 assert_eq!(published(&rows, "2027-01-30T00:00:00.000000000Z").len(), 2);
141 assert_eq!(published(&rows, "2027-02-03T12:00:00.000000000Z").len(), 1);
142 }
143}