1use super::{
4 AdmissionAuthorization, MembershipAuthorization, Workspace,
5 history::MembershipHistory,
6 invitation::RetainedAdmission,
7 storage::{self, number, take},
8};
9use openmls_rust_crypto::OpenMlsRustCrypto;
10use openmls_traits::OpenMlsProvider;
11use std::collections::BTreeMap;
12use zeroize::Zeroizing;
13
14pub type SecurityRecords = BTreeMap<Vec<u8>, Zeroizing<Vec<u8>>>;
15const META: &[u8] = b"security/meta";
16const PROVIDER: &[u8] = b"security/provider/";
17const ADMISSION: &[u8] = b"security/admission/";
18const CHECKPOINT: &[u8] = b"security/history/checkpoint";
19const STEP: &[u8] = b"security/history/step/";
20const INVITATION_CHECKPOINT: &[u8] = b"security/invitation-checkpoint/";
21
22fn named(prefix: &[u8], suffix: &[u8]) -> Vec<u8> {
23 [prefix, suffix].concat()
24}
25fn blob(out: &mut Vec<u8>, value: &[u8]) -> Result<(), &'static str> {
26 out.extend(
27 u32::try_from(value.len())
28 .map_err(|_| "record value too large")?
29 .to_be_bytes(),
30 );
31 out.extend(value);
32 Ok(())
33}
34fn read_blob(bytes: &mut &[u8]) -> Result<Vec<u8>, &'static str> {
35 let length = number(bytes)?;
36 Ok(take(bytes, length)?.to_vec())
37}
38fn read_count(bytes: &mut &[u8]) -> Result<usize, &'static str> {
39 usize::try_from(u64::from_be_bytes(take(bytes, 8)?.try_into().unwrap()))
40 .map_err(|_| "record count too large")
41}
42fn put_auth(out: &mut Vec<u8>, auth: &AdmissionAuthorization) {
43 out.extend(auth.invitation_key);
44 out.extend(auth.grant_signature);
45 out.extend(auth.redemption_signature);
46}
47fn read_auth(bytes: &mut &[u8]) -> Result<AdmissionAuthorization, &'static str> {
48 Ok(AdmissionAuthorization {
49 invitation_key: take(bytes, 32)?.try_into().unwrap(),
50 grant_signature: take(bytes, 64)?.try_into().unwrap(),
51 redemption_signature: take(bytes, 64)?.try_into().unwrap(),
52 })
53}
54fn step(auth: &MembershipAuthorization, commit: &[u8]) -> Result<Zeroizing<Vec<u8>>, &'static str> {
55 let mut bytes = Zeroizing::new(Vec::new());
56 match auth {
57 MembershipAuthorization::Admission(auth) => {
58 bytes.push(0);
59 put_auth(&mut bytes, auth);
60 }
61 MembershipAuthorization::AdmissionBatch(auths) => {
62 if auths.is_empty() || auths.len() > super::MAX_ADMISSION_BATCH {
63 return Err("invalid admission batch size");
64 }
65 bytes.push(11);
66 bytes.extend((auths.len() as u16).to_be_bytes());
67 for auth in auths {
68 put_auth(&mut bytes, auth);
69 }
70 }
71 MembershipAuthorization::Management(action) => {
72 let (tag, id) = match action {
73 super::ManagementAction::Promote(id) => (1, id),
74 super::ManagementAction::Demote(id) => (2, id),
75 super::ManagementAction::Remove(id) => (3, id),
76 super::ManagementAction::Leave(id, _) => (4, id),
77 super::ManagementAction::CreateInvitation(id, ..) => (5, id),
78 super::ManagementAction::CreateAutomaticInvitation(id, ..) => (8, id),
79 super::ManagementAction::CreateRequestInvitation(id, ..) => (9, id),
80 super::ManagementAction::DeclineInvitationRequest(id, _) => (10, id),
81 super::ManagementAction::DisableInvitation(id) => (6, id),
82 super::ManagementAction::ApproveInvitation(id, _) => (7, id),
83 };
84 bytes.push(tag);
85 bytes.extend(id);
86 if let super::ManagementAction::Leave(_, signature) = action {
87 bytes.extend(signature);
88 }
89 if let super::ManagementAction::CreateInvitation(_, expires, personal) = action {
90 bytes.extend(expires.to_be_bytes());
91 bytes.push(u8::from(*personal));
92 }
93 if let super::ManagementAction::CreateAutomaticInvitation(_, expires)
94 | super::ManagementAction::CreateRequestInvitation(_, expires) = action
95 {
96 bytes.extend(expires.to_be_bytes());
97 }
98 if let super::ManagementAction::ApproveInvitation(_, package)
99 | super::ManagementAction::DeclineInvitationRequest(_, package) = action
100 {
101 bytes.extend(package);
102 }
103 }
104 }
105 blob(&mut bytes, commit)?;
106 Ok(bytes)
107}
108fn read_step(mut bytes: &[u8]) -> Result<(MembershipAuthorization, Vec<u8>), &'static str> {
109 let auth = match take(&mut bytes, 1)?[0] {
110 0 => MembershipAuthorization::Admission(read_auth(&mut bytes)?),
111 11 => {
112 let count = u16::from_be_bytes(take(&mut bytes, 2)?.try_into().unwrap()) as usize;
113 if count == 0 || count > super::MAX_ADMISSION_BATCH {
114 return Err("invalid admission batch size");
115 }
116 MembershipAuthorization::AdmissionBatch(
117 (0..count)
118 .map(|_| read_auth(&mut bytes))
119 .collect::<Result<Vec<_>, _>>()?,
120 )
121 }
122 tag @ 1..=10 => {
123 let id = take(&mut bytes, 32)?.try_into().unwrap();
124 MembershipAuthorization::Management(match tag {
125 1 => super::ManagementAction::Promote(id),
126 2 => super::ManagementAction::Demote(id),
127 3 => super::ManagementAction::Remove(id),
128 4 => super::ManagementAction::Leave(id, take(&mut bytes, 64)?.try_into().unwrap()),
129 5 => super::ManagementAction::CreateInvitation(
130 id,
131 u64::from_be_bytes(take(&mut bytes, 8)?.try_into().unwrap()),
132 match take(&mut bytes, 1)?[0] {
133 0 => false,
134 1 => true,
135 _ => return Err("invalid invitation mode"),
136 },
137 ),
138 6 => super::ManagementAction::DisableInvitation(id),
139 7 => super::ManagementAction::ApproveInvitation(
140 id,
141 take(&mut bytes, 32)?.try_into().unwrap(),
142 ),
143 9 => super::ManagementAction::CreateRequestInvitation(
144 id,
145 u64::from_be_bytes(take(&mut bytes, 8)?.try_into().unwrap()),
146 ),
147 10 => super::ManagementAction::DeclineInvitationRequest(
148 id,
149 take(&mut bytes, 32)?.try_into().unwrap(),
150 ),
151 _ => super::ManagementAction::CreateAutomaticInvitation(
152 id,
153 u64::from_be_bytes(take(&mut bytes, 8)?.try_into().unwrap()),
154 ),
155 })
156 }
157 _ => return Err("unknown membership history action"),
158 };
159 let commit = read_blob(&mut bytes)?;
160 if commit.is_empty() || !bytes.is_empty() {
161 return Err("invalid membership record");
162 }
163 Ok((auth, commit))
164}
165
166impl Workspace {
167 pub fn export_records(&self) -> Result<SecurityRecords, &'static str> {
171 let mut records = SecurityRecords::new();
172 let provider = self
173 .provider
174 .storage()
175 .values
176 .read()
177 .map_err(|_| "storage unavailable")?;
178 let mut meta = Zeroizing::new(b"DFWR\x02".to_vec());
179 meta.extend(self.id);
180 meta.extend(self.endpoint);
181 meta.extend(self.epoch().to_be_bytes());
182 meta.push(u8::from(self.member.is_some()));
183 if let Some(member) = &self.member {
184 storage::write_profile(&mut meta, member);
185 }
186 meta.extend((provider.len() as u64).to_be_bytes());
187 meta.extend((self.admissions.len() as u64).to_be_bytes());
188 meta.push(u8::from(self.join_history.is_some()));
189 for (key, value) in provider.iter() {
190 records.insert(named(PROVIDER, key), Zeroizing::new(value.clone()));
191 }
192 for entry in &self.admissions {
193 let mut bytes = Zeroizing::new(Vec::new());
194 bytes.extend(entry.endpoint);
195 bytes.extend(entry.issuer);
196 bytes.extend(entry.reply.epoch.to_be_bytes());
197 put_auth(&mut bytes, &entry.reply.authorization);
198 blob(&mut bytes, &entry.reply.commit)?;
199 blob(&mut bytes, &entry.reply.welcome)?;
200 if records
201 .insert(named(ADMISSION, &entry.digest), bytes)
202 .is_some()
203 {
204 return Err("duplicate retained admission");
205 }
206 }
207 if let Some(history) = &self.join_history {
208 meta.extend((history.steps.len() as u64).to_be_bytes());
209 records.insert(
210 CHECKPOINT.to_vec(),
211 Zeroizing::new(history.checkpoint.clone()),
212 );
213 for (index, (auth, commit)) in history.steps.iter().enumerate() {
214 records.insert(
215 named(STEP, &(index as u64).to_be_bytes()),
216 step(auth, commit)?,
217 );
218 }
219 }
220 meta.extend((self.invitation_checkpoints.len() as u64).to_be_bytes());
221 for saved in &self.invitation_checkpoints {
222 let mut value = Zeroizing::new(saved.grant.to_vec());
223 value.extend(&saved.checkpoint);
224 records.insert(named(INVITATION_CHECKPOINT, &saved.grant[101..133]), value);
225 }
226 records.insert(META.to_vec(), meta);
227 Ok(records)
228 }
229
230 pub fn restore_records(
233 endpoint: [u8; 32],
234 id: [u8; 32],
235 records: &SecurityRecords,
236 ) -> Result<Self, &'static str> {
237 let mut meta = records
238 .get(META)
239 .ok_or("security metadata missing")?
240 .as_slice();
241 let version = take(&mut meta, 5)?;
242 if !matches!(version, b"DFWR\x01" | b"DFWR\x02")
243 || take(&mut meta, 32)? != id
244 || take(&mut meta, 32)? != endpoint
245 {
246 return Err("security record scope mismatch");
247 }
248 let epoch = u64::from_be_bytes(take(&mut meta, 8)?.try_into().unwrap());
249 let member = match take(&mut meta, 1)?[0] {
250 0 => None,
251 1 => Some(storage::read_profile(&mut meta)?),
252 _ => return Err("invalid stored profile flag"),
253 };
254 let provider_count = read_count(&mut meta)?;
255 let admission_count = read_count(&mut meta)?;
256 let history_count = match take(&mut meta, 1)?[0] {
257 0 => None,
258 1 => Some(read_count(&mut meta)?),
259 _ => return Err("invalid stored history flag"),
260 };
261 let invitation_checkpoint_count = if version == b"DFWR\x02" {
262 read_count(&mut meta)?
263 } else {
264 0
265 };
266 if invitation_checkpoint_count > super::invitation::MAX_RETAINED_CHECKPOINTS {
267 return Err("invalid invitation checkpoint count");
268 }
269 let expected = [
270 1usize,
271 provider_count,
272 admission_count,
273 usize::from(history_count.is_some()),
274 history_count.unwrap_or(0),
275 invitation_checkpoint_count,
276 ]
277 .into_iter()
278 .try_fold(0usize, |sum, n| sum.checked_add(n))
279 .ok_or("record count overflow")?;
280 if expected != records.len() || !meta.is_empty() {
281 return Err("security record set incomplete");
282 }
283 let provider = OpenMlsRustCrypto::default();
284 {
285 let mut target = provider
286 .storage()
287 .values
288 .write()
289 .map_err(|_| "storage unavailable")?;
290 for (name, value) in records {
291 if let Some(key) = name.strip_prefix(PROVIDER) {
292 target.insert(key.to_vec(), value.to_vec());
293 }
294 }
295 if target.len() != provider_count {
296 return Err("provider record set incomplete");
297 }
298 }
299 let mut admissions = Vec::new();
300 let mut shared = super::invitation::SharedReplies::default();
301 let mut epochs = BTreeMap::new();
302 for (name, value) in records {
303 let Some(digest) = name.strip_prefix(ADMISSION) else {
304 continue;
305 };
306 let digest = digest
307 .try_into()
308 .map_err(|_| "invalid admission record key")?;
309 let mut bytes = value.as_slice();
310 let endpoint = take(&mut bytes, 32)?.try_into().unwrap();
311 let issuer = take(&mut bytes, 32)?.try_into().unwrap();
312 let admitted_epoch = u64::from_be_bytes(take(&mut bytes, 8)?.try_into().unwrap());
313 if admitted_epoch == 0 || admitted_epoch > epoch {
314 return Err("invalid admission record epoch");
315 }
316 let authorization = read_auth(&mut bytes)?;
317 let commit = read_blob(&mut bytes)?;
318 let welcome = read_blob(&mut bytes)?;
319 if !bytes.is_empty() || commit.is_empty() || welcome.is_empty() {
320 return Err("invalid admission record");
321 }
322 if epochs
323 .entry(admitted_epoch)
324 .or_insert_with(|| commit.clone())
325 != &commit
326 {
327 return Err("admission records disagree on shared epoch commit");
328 }
329 admissions.push(RetainedAdmission {
330 digest,
331 endpoint,
332 issuer,
333 reply: shared.reply(admitted_epoch, commit, welcome, authorization),
334 });
335 }
336 if admissions.len() != admission_count {
337 return Err("admission record set incomplete");
338 }
339 admissions.sort_by_key(|entry| entry.reply.epoch);
340 let history = if let Some(count) = history_count {
341 let checkpoint = records
342 .get(CHECKPOINT)
343 .ok_or("history checkpoint missing")?
344 .to_vec();
345 let mut steps = Vec::new();
346 for index in 0..count {
347 steps.push(read_step(
348 records
349 .get(&named(STEP, &(index as u64).to_be_bytes()))
350 .ok_or("history record missing")?,
351 )?);
352 }
353 Some(MembershipHistory { checkpoint, steps })
354 } else {
355 None
356 };
357 let mut invitation_checkpoints = Vec::new();
358 for (name, value) in records {
359 let Some(key) = name.strip_prefix(INVITATION_CHECKPOINT) else {
360 continue;
361 };
362 if key.len() != 32 || value.len() <= super::invitation::PUBLIC {
363 return Err("invalid invitation checkpoint record");
364 }
365 let grant: [u8; super::invitation::PUBLIC] =
366 value[..super::invitation::PUBLIC].try_into().unwrap();
367 if grant[101..133] != *key {
368 return Err("invitation checkpoint record key mismatch");
369 }
370 invitation_checkpoints.push(super::invitation::RetainedInvitationCheckpoint {
371 grant,
372 checkpoint: value[super::invitation::PUBLIC..].to_vec(),
373 });
374 }
375 if invitation_checkpoints.len() != invitation_checkpoint_count {
376 return Err("invitation checkpoint record set incomplete");
377 }
378 Self::restore_owner(
379 provider,
380 endpoint,
381 id,
382 epoch,
383 member,
384 admissions,
385 history,
386 invitation_checkpoints,
387 )
388 }
389}