1use std::collections::HashMap;
5use std::sync::Arc;
6
7use crypto::{RTCCryptoProvider, SecretVec, constant_time_eq};
8
9use crate::cipher_suite::CipherSuite;
10use crate::context::{KeyContext, SFrameConfig, SFrameContext};
11use crate::error::{Error, Result};
12use crate::header::Header;
13use crate::key_id::MlsKeyIdLayout;
14
15pub const MLS_EXPORTER_LABEL: &str = "SFrame 1.0 Base Key";
19
20pub const DEFAULT_MAX_MLS_KEYS: usize = 4096;
22
23struct EpochSlot {
25 epoch: u64,
27 base_key: Option<SecretVec>,
29}
30
31pub struct MlsContext {
42 context: SFrameContext,
43 layout: MlsKeyIdLayout,
44 sender_index: u64,
45 slots: HashMap<u64, EpochSlot>,
46 max_keys: usize,
47}
48
49impl MlsContext {
50 pub fn new(
54 suite: CipherSuite,
55 provider: Arc<dyn RTCCryptoProvider>,
56 layout: MlsKeyIdLayout,
57 sender_index: u64,
58 ) -> Result<Self> {
59 Self::with_config(
60 suite,
61 provider,
62 layout,
63 sender_index,
64 SFrameConfig::default(),
65 )
66 }
67
68 pub fn with_config(
70 suite: CipherSuite,
71 provider: Arc<dyn RTCCryptoProvider>,
72 layout: MlsKeyIdLayout,
73 sender_index: u64,
74 config: SFrameConfig,
75 ) -> Result<Self> {
76 layout.key_id(0, sender_index, 0)?;
78 Ok(Self {
79 context: SFrameContext::with_config(suite, provider, config),
80 layout,
81 sender_index,
82 slots: HashMap::new(),
83 max_keys: DEFAULT_MAX_MLS_KEYS,
84 })
85 }
86
87 pub fn set_max_keys(&mut self, max_keys: usize) {
90 self.max_keys = max_keys;
91 }
92
93 #[must_use]
95 pub fn layout(&self) -> MlsKeyIdLayout {
96 self.layout
97 }
98
99 #[must_use]
101 pub fn sender_index(&self) -> u64 {
102 self.sender_index
103 }
104
105 #[must_use]
107 pub fn context(&self) -> &SFrameContext {
108 &self.context
109 }
110
111 #[must_use]
113 pub fn has_epoch(&self, epoch: u64) -> bool {
114 self.secret(epoch).is_some()
115 }
116
117 fn secret(&self, epoch: u64) -> Option<&SecretVec> {
118 let slot = self.slots.get(&self.layout.epoch_slot(epoch))?;
119 if slot.epoch == epoch {
120 slot.base_key.as_ref()
121 } else {
122 None
123 }
124 }
125
126 fn purge(&mut self, slot: u64) {
128 let layout = self.layout;
129 self.context
130 .retain_keys(|kid| layout.epoch_slot(kid) != slot);
131 }
132
133 pub fn add_epoch(&mut self, epoch: u64, base_key: &[u8]) -> Result<()> {
140 if base_key.is_empty() {
141 return Err(Error::EmptyBaseKey);
142 }
143 let slot = self.layout.epoch_slot(epoch);
144 if let Some(current) = self.slots.get(&slot) {
145 if current.epoch > epoch {
146 return Err(Error::StaleEpoch(epoch));
147 }
148 if current.epoch == epoch {
149 return match ¤t.base_key {
150 Some(known) if constant_time_eq(known.as_ref(), base_key) => Ok(()),
151 _ => Err(Error::StaleEpoch(epoch)),
152 };
153 }
154 self.purge(slot);
155 }
156 self.slots.insert(
157 slot,
158 EpochSlot {
159 epoch,
160 base_key: Some(SecretVec::new(base_key.to_vec())),
161 },
162 );
163 Ok(())
164 }
165
166 pub fn remove_epoch(&mut self, epoch: u64) -> bool {
169 let slot = self.layout.epoch_slot(epoch);
170 match self.slots.get_mut(&slot) {
171 Some(current) if current.epoch == epoch && current.base_key.is_some() => {
172 current.base_key = None;
173 self.purge(slot);
174 true
175 }
176 _ => false,
177 }
178 }
179
180 pub fn key_id(&self, epoch: u64, context: u64) -> Result<u64> {
182 self.layout.key_id(epoch, self.sender_index, context)
183 }
184
185 pub fn encrypt(
188 &mut self,
189 epoch: u64,
190 context: u64,
191 metadata: &[u8],
192 plaintext: &[u8],
193 ) -> Result<Vec<u8>> {
194 let mut out = Vec::with_capacity(plaintext.len() + self.context.max_overhead());
195 self.encrypt_into(epoch, context, metadata, plaintext, &mut out)?;
196 Ok(out)
197 }
198
199 pub fn encrypt_into(
201 &mut self,
202 epoch: u64,
203 context: u64,
204 metadata: &[u8],
205 plaintext: &[u8],
206 out: &mut Vec<u8>,
207 ) -> Result<Header> {
208 let kid = self.key_id(epoch, context)?;
209 if self.context.key_usage(kid).is_none() {
210 let slot = self.slots.get(&self.layout.epoch_slot(epoch));
211 let Some(base_key) = slot
212 .filter(|slot| slot.epoch == epoch)
213 .and_then(|slot| slot.base_key.as_ref())
214 else {
215 return Err(Error::UnknownEpoch(epoch));
216 };
217 if self.context.key_count() >= self.max_keys {
218 return Err(Error::TooManyKeys);
219 }
220 self.context.add_send_key(kid, base_key.as_ref())?;
221 } else if !self.has_epoch(epoch) {
222 return Err(Error::UnknownEpoch(epoch));
224 }
225 self.context.encrypt_into(kid, metadata, plaintext, out)
226 }
227
228 pub fn decrypt(&mut self, metadata: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>> {
234 let mut out = Vec::with_capacity(ciphertext.len());
235 self.decrypt_into(metadata, ciphertext, &mut out)?;
236 Ok(out)
237 }
238
239 pub fn decrypt_into(
242 &mut self,
243 metadata: &[u8],
244 ciphertext: &[u8],
245 out: &mut Vec<u8>,
246 ) -> Result<Header> {
247 if let Ok((header, _)) = self.context.decode_header(ciphertext)
248 && self.context.key_usage(header.kid).is_some()
249 {
250 return self.context.decrypt_into(metadata, ciphertext, out);
251 }
252 let result = self.decrypt_on_demand(metadata, ciphertext, out);
253 self.context.count(&result);
254 result
255 }
256
257 fn decrypt_on_demand(
260 &mut self,
261 metadata: &[u8],
262 ciphertext: &[u8],
263 out: &mut Vec<u8>,
264 ) -> Result<Header> {
265 let (header, header_len) = self.context.decode_header(ciphertext)?;
266 let parts = self.layout.split(header.kid);
267 if parts.sender_index == self.sender_index {
268 return Err(Error::KeyRoleConflict(header.kid));
269 }
270 let Some(base_key) = self
271 .slots
272 .get(&parts.epoch)
273 .and_then(|slot| slot.base_key.as_ref())
274 else {
275 return Err(Error::UnknownKeyId(header.kid));
276 };
277 if self.context.key_count() >= self.max_keys {
278 return Err(Error::TooManyKeys);
279 }
280 let mut key = KeyContext::derive_recv(
281 self.context.provider().crypto(),
282 self.context.cipher_suite(),
283 header.kid,
284 base_key.as_ref(),
285 self.context.config().replay_window,
286 )?;
287 self.context
288 .decrypt_with(&mut key, header, header_len, metadata, ciphertext, out)?;
289 self.context.insert_key(header.kid, key);
290 Ok(header)
291 }
292}
293
294impl std::fmt::Debug for MlsContext {
295 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296 formatter
297 .debug_struct("MlsContext")
298 .field("context", &self.context)
299 .field("layout", &self.layout)
300 .field("sender_index", &self.sender_index)
301 .field("epochs", &self.slots.len())
302 .finish_non_exhaustive()
303 }
304}