Skip to main content

rtci_sframe/
pending.rs

1//! A bounded store for ciphertexts whose key has not arrived yet (RFC 9605 section 4.4.4).
2
3use std::collections::VecDeque;
4
5use crate::error::Result;
6use crate::header::Header;
7
8/// A ciphertext waiting for its key, with the metadata it has to be decrypted with.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct PendingCiphertext {
11    /// The KID in the ciphertext's header.
12    pub kid: u64,
13    /// The metadata the application supplies to decryption.
14    pub metadata: Vec<u8>,
15    /// The SFrame ciphertext, whole.
16    pub ciphertext: Vec<u8>,
17}
18
19/// Ciphertexts that failed with [`Error::UnknownKeyId`](crate::Error::UnknownKeyId), kept to
20/// be decrypted once the key is there.
21///
22/// A client MAY do this (RFC 9605 section 4.4.4): a new key can reach a receiver after the
23/// first frames encrypted with it. The store is bounded in frames and in bytes and drops the
24/// oldest entry to make room, so a peer naming keys that never come cannot grow it. Nothing
25/// held here is authenticated: it is only ever handed back for decryption. It has no clock;
26/// an application that wants entries to expire calls [`discard_oldest`](Self::discard_oldest)
27/// or [`clear`](Self::clear) on its own timer.
28#[derive(Debug)]
29pub struct PendingCiphertexts {
30    max_frames: usize,
31    max_bytes: usize,
32    bytes: usize,
33    frames: VecDeque<PendingCiphertext>,
34}
35
36impl PendingCiphertexts {
37    /// A store of at most `max_frames` ciphertexts and `max_bytes` bytes (ciphertext plus
38    /// metadata).
39    #[must_use]
40    pub fn new(max_frames: usize, max_bytes: usize) -> Self {
41        Self {
42            max_frames,
43            max_bytes,
44            bytes: 0,
45            frames: VecDeque::new(),
46        }
47    }
48
49    /// The number of ciphertexts held.
50    #[must_use]
51    pub fn len(&self) -> usize {
52        self.frames.len()
53    }
54
55    /// Whether nothing is held.
56    #[must_use]
57    pub fn is_empty(&self) -> bool {
58        self.frames.is_empty()
59    }
60
61    /// The bytes held: ciphertexts and their metadata.
62    #[must_use]
63    pub fn bytes(&self) -> usize {
64        self.bytes
65    }
66
67    /// Keeps `ciphertext` and its `metadata` under the KID of its header, dropping the oldest
68    /// entries if the bounds require it. Returns the KID, or `None` when the ciphertext alone
69    /// exceeds the bounds and was not kept.
70    ///
71    /// Fails when the header does not parse: such a ciphertext can never be decrypted.
72    pub fn push(&mut self, metadata: &[u8], ciphertext: &[u8]) -> Result<Option<u64>> {
73        let (header, _) = Header::decode_lenient(ciphertext)?;
74        let size = metadata.len() + ciphertext.len();
75        if self.max_frames == 0 || size > self.max_bytes {
76            return Ok(None);
77        }
78        while self.frames.len() >= self.max_frames || self.bytes + size > self.max_bytes {
79            self.discard_oldest(1);
80        }
81        self.bytes += size;
82        self.frames.push_back(PendingCiphertext {
83            kid: header.kid,
84            metadata: metadata.to_vec(),
85            ciphertext: ciphertext.to_vec(),
86        });
87        Ok(Some(header.kid))
88    }
89
90    /// Removes and returns the ciphertexts waiting for `kid`, oldest first: call it when the
91    /// key for `kid` has been added, and decrypt each.
92    pub fn take(&mut self, kid: u64) -> Vec<PendingCiphertext> {
93        let (taken, kept): (VecDeque<_>, VecDeque<_>) = std::mem::take(&mut self.frames)
94            .into_iter()
95            .partition(|pending| pending.kid == kid);
96        self.frames = kept;
97        self.bytes = self.frames.iter().map(size_of_entry).sum();
98        taken.into()
99    }
100
101    /// Drops the `count` oldest ciphertexts.
102    pub fn discard_oldest(&mut self, count: usize) {
103        for _ in 0..count {
104            let Some(dropped) = self.frames.pop_front() else {
105                break;
106            };
107            self.bytes -= size_of_entry(&dropped);
108        }
109    }
110
111    /// Drops everything.
112    pub fn clear(&mut self) {
113        self.frames.clear();
114        self.bytes = 0;
115    }
116}
117
118fn size_of_entry(pending: &PendingCiphertext) -> usize {
119    pending.metadata.len() + pending.ciphertext.len()
120}