Skip to main content

srt_runtime/
km_refresh.rs

1//! SEK-rotation ("KM Refresh") driver — `draft-sharabayko-srt-01` §6.1.6 (KM
2//! Refresh), curated at `private/specs-verified/rules/srt-crypto.md` ("KM Refresh — §6.1.6").
3//!
4//! Sans-IO: [`KmRefreshDriver::on_packet_sent`] / [`KmRefreshDriver::tick`]
5//! take a caller-supplied packet count — this crate never reads a wall clock
6//! or a socket (the same contract as [`crate::handshake_sm`] / [`crate::arq`]
7//! / [`crate::tsbpd`]). The driver only tracks *when* to rotate and *which*
8//! parity is active; it does not generate, wrap, or send key material
9//! itself — the actual SEK PRNG/wrap/Key-Material-message send is the
10//! caller's job (mirroring [`crate::handshake_sm::CryptoConfig`]'s design:
11//! this crate's sans-IO core never owns a CSPRNG), triggered by
12//! [`KmRefreshEvent::PreAnnounce`].
13//!
14//! # Thresholds (§6.1.6, "Recommended values")
15//!
16//! - **KM Refresh Period = `2^25` packets**: how long a key stays active
17//!   before switchover.
18//! - **KM Pre-Announcement Period = `4000` packets**: how long *before*
19//!   switchover the new key is announced, and — symmetrically — how long
20//!   *after* switchover the old key stays valid before decommission. "Both
21//!   keys are valid in parallel for `2 * Pre-Announcement Period`", to
22//!   tolerate late/retransmitted packets that were encrypted under the old
23//!   key.
24//!
25//! All three thresholds are measured from the start of the *current* active
26//! key's epoch (packet 0 of that key):
27//!
28//! ```text
29//! 0 ── refresh - pre_announce ── refresh ── refresh + pre_announce
30//!      PreAnnounce fires         Switchover  Decommission fires
31//!      (generate + wrap +       (old key     (old key dropped)
32//!       ready next key)          still valid)
33//! ```
34//!
35//! [`KmRefreshThresholds::RECOMMENDED`] is the spec's `2^25`/`4000` pair;
36//! `tests/it/km_refresh.rs` drives the same state machine with a scaled-down
37//! threshold pair so the test suite does not need `2^25` real iterations —
38//! the state machine logic is identical, only the threshold constants
39//! differ.
40
41use alloc::vec::Vec;
42
43use broadcast_common::error::InvalidField;
44
45use crate::error::Error;
46
47/// Which of the two alternating SEKs (`draft-sharabayko-srt-01` §3.1's data
48/// packet `KK` field / §6.1.6's odd/even alternation) is meant.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize))]
51#[non_exhaustive]
52pub enum KeyParity {
53    /// The even-numbered SEK.
54    Even,
55    /// The odd-numbered SEK.
56    Odd,
57}
58
59impl KeyParity {
60    /// The other parity — every rotation alternates (§6.1.6).
61    pub fn other(self) -> Self {
62        match self {
63            KeyParity::Even => KeyParity::Odd,
64            KeyParity::Odd => KeyParity::Even,
65        }
66    }
67
68    /// Spec label.
69    pub fn name(&self) -> &'static str {
70        match self {
71            KeyParity::Even => "even",
72            KeyParity::Odd => "odd",
73        }
74    }
75}
76
77broadcast_common::impl_spec_display!(KeyParity);
78
79/// KM Refresh packet-count thresholds (`draft-sharabayko-srt-01` §6.1.6).
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81#[non_exhaustive]
82pub struct KmRefreshThresholds {
83    refresh_period: u64,
84    pre_announcement_period: u64,
85}
86
87impl KmRefreshThresholds {
88    /// The draft's own recommended values (§6.1.6): `2^25` packets refresh
89    /// period, `4000` packets pre-announcement period.
90    pub const RECOMMENDED: KmRefreshThresholds = KmRefreshThresholds {
91        refresh_period: 1 << 25,
92        pre_announcement_period: 4000,
93    };
94
95    /// Thresholds for `refresh_period` packets between switchovers and a
96    /// `pre_announcement_period` ahead of it.
97    ///
98    /// # Errors
99    ///
100    /// [`Error::InvalidField`] unless `0 < pre_announcement_period <
101    /// refresh_period`: a zero period would rotate on every packet, and a
102    /// pre-announcement at or past the refresh point would announce the next
103    /// key only once it had already replaced the current one.
104    pub fn new(refresh_period: u64, pre_announcement_period: u64) -> Result<Self, Error> {
105        if pre_announcement_period == 0 || pre_announcement_period >= refresh_period {
106            return Err(Error::InvalidField(InvalidField {
107                field: "pre_announcement_period",
108                reason: "must be non-zero and below refresh_period",
109            }));
110        }
111        Ok(KmRefreshThresholds {
112            refresh_period,
113            pre_announcement_period,
114        })
115    }
116
117    /// Packets an active key is used for before switchover.
118    pub const fn refresh_period(&self) -> u64 {
119        self.refresh_period
120    }
121
122    /// Packets before switchover the next key is announced, and after
123    /// switchover the old key stays valid.
124    pub const fn pre_announcement_period(&self) -> u64 {
125        self.pre_announcement_period
126    }
127}
128
129/// One state transition [`KmRefreshDriver::on_packet_sent`] /
130/// [`KmRefreshDriver::tick`] can fire (`draft-sharabayko-srt-01` §6.1.6).
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132#[non_exhaustive]
133pub enum KmRefreshEvent {
134    /// `refresh_period - pre_announcement_period` packets sent under the
135    /// active key: generate, wrap, and send a fresh SEK for `next_parity`
136    /// now (§6.1.5's Key Material exchange, driven out-of-band of this
137    /// driver — see the module doc).
138    PreAnnounce {
139        /// The parity the newly-generated key will use.
140        next_parity: KeyParity,
141    },
142    /// `refresh_period` packets sent under the active key: start encrypting
143    /// *new* outgoing packets with `new_active` from now on. The previous
144    /// key remains valid for decrypting late/retransmitted packets until
145    /// [`KmRefreshEvent::Decommission`] fires for it.
146    Switchover {
147        /// The parity now active for new packets.
148        new_active: KeyParity,
149    },
150    /// `pre_announcement_period` packets after switchover: the previous key
151    /// may be dropped — no more retransmits will need it (§6.1.6, "both keys
152    /// valid in parallel for `2 * Pre-Announcement Period`").
153    Decommission {
154        /// The parity being retired.
155        retired: KeyParity,
156    },
157}
158
159/// Sans-IO SEK-rotation state machine (`draft-sharabayko-srt-01` §6.1.6).
160///
161/// Tracks which [`KeyParity`] is currently active and fires
162/// [`KmRefreshEvent`]s as the packet count crosses the configured
163/// [`KmRefreshThresholds`]. Does not hold key material itself — see the
164/// module doc. Rotates indefinitely: once a cycle's [`KmRefreshEvent::Decommission`]
165/// fires, the next cycle's thresholds are armed again against the new active
166/// key's epoch.
167#[derive(Debug, Clone, PartialEq)]
168pub struct KmRefreshDriver {
169    thresholds: KmRefreshThresholds,
170    active: KeyParity,
171    /// Packet count at which `active` most recently became active (`0` for
172    /// the initial key negotiated at handshake time).
173    epoch_start: u64,
174    /// Total packets sent so far (monotonic).
175    total_sent: u64,
176    pre_announced: bool,
177    switched_over: bool,
178    decommissioned: bool,
179}
180
181impl KmRefreshDriver {
182    /// A fresh driver. `initial_parity` is the SEK negotiated at handshake
183    /// time (this crate's handshake convention is [`KeyParity::Even`] — see
184    /// `crate::handshake_sm::build_key_material_extension`, `crypto` feature
185    /// only).
186    pub fn new(thresholds: KmRefreshThresholds, initial_parity: KeyParity) -> Self {
187        KmRefreshDriver {
188            thresholds,
189            active: initial_parity,
190            epoch_start: 0,
191            total_sent: 0,
192            pre_announced: false,
193            switched_over: false,
194            decommissioned: false,
195        }
196    }
197
198    /// The currently-active parity for *new* outgoing packets.
199    pub fn active_parity(&self) -> KeyParity {
200        self.active
201    }
202
203    /// Total packets recorded via [`Self::on_packet_sent`]/[`Self::tick`].
204    pub fn total_sent(&self) -> u64 {
205        self.total_sent
206    }
207
208    /// Whether `parity`'s key should still be considered held/valid. The
209    /// active key always is; the just-retired key is too, from switchover
210    /// until decommission (§6.1.6's "both keys valid in parallel" transition
211    /// window) — a data packet under either may legitimately arrive during
212    /// that window (in-flight or retransmitted).
213    pub fn is_key_valid(&self, parity: KeyParity) -> bool {
214        if parity == self.active {
215            return true;
216        }
217        self.switched_over && !self.decommissioned
218    }
219
220    /// Record `n` more packets sent under the active key and return any
221    /// [`KmRefreshEvent`]s newly crossed, in spec order (PreAnnounce,
222    /// Switchover, Decommission). A single call can fire more than one event
223    /// if `n` is large enough to cross multiple thresholds at once.
224    pub fn on_packet_sent(&mut self, n: u64) -> Vec<KmRefreshEvent> {
225        self.total_sent = self.total_sent.saturating_add(n);
226        let mut events = Vec::new();
227        let pre_announce_at = self
228            .thresholds
229            .refresh_period
230            .saturating_sub(self.thresholds.pre_announcement_period);
231        loop {
232            let since_epoch = self.total_sent.saturating_sub(self.epoch_start);
233            let mut crossed = false;
234
235            if !self.pre_announced && since_epoch >= pre_announce_at {
236                self.pre_announced = true;
237                crossed = true;
238                events.push(KmRefreshEvent::PreAnnounce {
239                    next_parity: self.active.other(),
240                });
241            }
242
243            if !self.switched_over && since_epoch >= self.thresholds.refresh_period {
244                self.switched_over = true;
245                crossed = true;
246                let new_active = self.active.other();
247                self.active = new_active;
248                // The new epoch starts exactly at the switchover point, so the
249                // decommission threshold below (measured from `epoch_start`) is
250                // `pre_announcement_period` packets *after* switchover — §6.1.6's
251                // `refresh_period + pre_announcement_period`, not
252                // `2 * refresh_period + pre_announcement_period`.
253                self.epoch_start += self.thresholds.refresh_period;
254                events.push(KmRefreshEvent::Switchover { new_active });
255            }
256
257            if self.switched_over && !self.decommissioned {
258                let since_switchover = self.total_sent.saturating_sub(self.epoch_start);
259                if since_switchover >= self.thresholds.pre_announcement_period {
260                    self.decommissioned = true;
261                    crossed = true;
262                    events.push(KmRefreshEvent::Decommission {
263                        retired: self.active.other(),
264                    });
265                    // Arm the next cycle: `epoch_start` already marks the
266                    // current key's start, so the next PreAnnounce/Switchover
267                    // are correctly measured from here.
268                    self.pre_announced = false;
269                    self.switched_over = false;
270                    self.decommissioned = false;
271                }
272            }
273
274            if !crossed {
275                break;
276            }
277        }
278
279        events
280    }
281
282    /// Record exactly one packet sent — convenience wrapper over
283    /// [`Self::on_packet_sent`].
284    pub fn tick(&mut self) -> Vec<KmRefreshEvent> {
285        self.on_packet_sent(1)
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use alloc::string::ToString;
293
294    const SCALED: KmRefreshThresholds = KmRefreshThresholds {
295        refresh_period: 100,
296        pre_announcement_period: 10,
297    };
298
299    #[test]
300    fn recommended_thresholds_match_spec_values() {
301        assert_eq!(KmRefreshThresholds::RECOMMENDED.refresh_period(), 1 << 25);
302        assert_eq!(
303            KmRefreshThresholds::RECOMMENDED.pre_announcement_period(),
304            4000
305        );
306    }
307
308    #[test]
309    fn new_rejects_degenerate_thresholds() {
310        for (refresh, pre_announce) in [(0, 0), (100, 0), (100, 100), (100, 101)] {
311            assert!(
312                matches!(
313                    KmRefreshThresholds::new(refresh, pre_announce),
314                    Err(Error::InvalidField(_))
315                ),
316                "refresh {refresh}, pre-announce {pre_announce} must be rejected"
317            );
318        }
319        let t = KmRefreshThresholds::new(100, 10).unwrap();
320        assert_eq!(t.refresh_period(), 100);
321        assert_eq!(t.pre_announcement_period(), 10);
322    }
323
324    #[test]
325    fn one_batch_larger_than_a_refresh_period_rotates_every_cycle_it_crosses() {
326        let mut d = KmRefreshDriver::new(SCALED, KeyParity::Even);
327        let events = d.on_packet_sent(295);
328        assert_eq!(
329            events,
330            alloc::vec![
331                KmRefreshEvent::PreAnnounce {
332                    next_parity: KeyParity::Odd
333                },
334                KmRefreshEvent::Switchover {
335                    new_active: KeyParity::Odd
336                },
337                KmRefreshEvent::Decommission {
338                    retired: KeyParity::Even
339                },
340                KmRefreshEvent::PreAnnounce {
341                    next_parity: KeyParity::Even
342                },
343                KmRefreshEvent::Switchover {
344                    new_active: KeyParity::Even
345                },
346                KmRefreshEvent::Decommission {
347                    retired: KeyParity::Odd
348                },
349                KmRefreshEvent::PreAnnounce {
350                    next_parity: KeyParity::Odd
351                },
352            ]
353        );
354        assert_eq!(d.active_parity(), KeyParity::Even);
355        assert_eq!(d.total_sent(), 295);
356    }
357
358    #[test]
359    fn key_parity_alternates_and_labels() {
360        assert_eq!(KeyParity::Even.other(), KeyParity::Odd);
361        assert_eq!(KeyParity::Odd.other(), KeyParity::Even);
362        assert_eq!(KeyParity::Even.to_string(), "even");
363        assert_eq!(KeyParity::Odd.to_string(), "odd");
364    }
365
366    #[test]
367    fn fires_pre_announce_switchover_decommission_in_order() {
368        let mut d = KmRefreshDriver::new(SCALED, KeyParity::Even);
369        assert_eq!(d.active_parity(), KeyParity::Even);
370        assert!(d.is_key_valid(KeyParity::Even));
371        assert!(!d.is_key_valid(KeyParity::Odd));
372
373        // Just before pre-announce: nothing fires.
374        assert_eq!(d.on_packet_sent(89), Vec::new());
375        assert_eq!(d.active_parity(), KeyParity::Even);
376
377        // Crosses 90 (100 - 10): PreAnnounce for the *other* (Odd) parity.
378        assert_eq!(
379            d.on_packet_sent(1),
380            alloc::vec![KmRefreshEvent::PreAnnounce {
381                next_parity: KeyParity::Odd
382            }]
383        );
384        // Active key hasn't changed yet.
385        assert_eq!(d.active_parity(), KeyParity::Even);
386        assert!(d.is_key_valid(KeyParity::Even));
387        assert!(!d.is_key_valid(KeyParity::Odd));
388
389        // Re-crossing the same threshold does not re-fire. (total: 91)
390        assert_eq!(d.on_packet_sent(1), Vec::new());
391
392        // Crosses 100: Switchover to Odd.
393        assert_eq!(d.on_packet_sent(8), Vec::new()); // total 99, not yet
394        assert_eq!(
395            d.on_packet_sent(1), // total 100
396            alloc::vec![KmRefreshEvent::Switchover {
397                new_active: KeyParity::Odd
398            }]
399        );
400        assert_eq!(d.active_parity(), KeyParity::Odd);
401        // Both keys valid during the transition window.
402        assert!(d.is_key_valid(KeyParity::Odd));
403        assert!(d.is_key_valid(KeyParity::Even));
404
405        // Crosses 110 (100 + 10): Decommission the old (Even) key.
406        assert_eq!(d.on_packet_sent(9), Vec::new()); // total 109
407        assert_eq!(
408            d.on_packet_sent(1), // total 110
409            alloc::vec![KmRefreshEvent::Decommission {
410                retired: KeyParity::Even
411            }]
412        );
413        assert_eq!(d.active_parity(), KeyParity::Odd);
414        assert!(d.is_key_valid(KeyParity::Odd));
415        assert!(!d.is_key_valid(KeyParity::Even), "old key must be dropped");
416    }
417
418    #[test]
419    fn large_jump_fires_all_three_events_in_one_call() {
420        let mut d = KmRefreshDriver::new(SCALED, KeyParity::Even);
421        let events = d.on_packet_sent(115);
422        assert_eq!(
423            events,
424            alloc::vec![
425                KmRefreshEvent::PreAnnounce {
426                    next_parity: KeyParity::Odd
427                },
428                KmRefreshEvent::Switchover {
429                    new_active: KeyParity::Odd
430                },
431                KmRefreshEvent::Decommission {
432                    retired: KeyParity::Even
433                },
434            ]
435        );
436        assert_eq!(d.active_parity(), KeyParity::Odd);
437        assert!(!d.is_key_valid(KeyParity::Even));
438    }
439
440    #[test]
441    fn tick_is_a_single_packet_and_rotation_repeats_forever() {
442        let mut d = KmRefreshDriver::new(SCALED, KeyParity::Even);
443        let mut all = Vec::new();
444        for _ in 0..250 {
445            all.extend(d.tick());
446        }
447        assert_eq!(d.total_sent(), 250);
448        // Two full cycles of 100 packets each fit in 250 ticks: expect two
449        // full PreAnnounce/Switchover/Decommission triples, alternating
450        // parity, plus one more PreAnnounce (at 90 packets into the third
451        // 100-packet cycle, i.e. total 290 — not reached at 250) which does
452        // NOT fire yet.
453        let switchovers: Vec<_> = all
454            .iter()
455            .filter(|e| matches!(e, KmRefreshEvent::Switchover { .. }))
456            .collect();
457        assert_eq!(switchovers.len(), 2);
458        assert_eq!(
459            switchovers[0],
460            &KmRefreshEvent::Switchover {
461                new_active: KeyParity::Odd
462            }
463        );
464        assert_eq!(
465            switchovers[1],
466            &KmRefreshEvent::Switchover {
467                new_active: KeyParity::Even
468            }
469        );
470        assert_eq!(d.active_parity(), KeyParity::Even);
471    }
472}