Skip to main content

coven_format/
codes.rs

1//! Restore, invite and pairing codes keep every owned secret buffer zeroizing (§13).
2
3use crate::code_fields::MAX_STORAGE;
4use crate::error::{bound, require, Error, Rule};
5use crate::kinds;
6use crate::value::name;
7use crate::wire::{decode_frame_of, Decoder, Wire};
8use crate::{frame_prefix, FormatVersion, FRAME_PREFIX_LEN};
9use coven_crypto::{InviteSecret, MemberKeys, SecretBytes};
10use coven_foundation::id_source::{DeviceId, InviteId, KeyId, MemberId, StoreId};
11use coven_merge::Slot;
12use zeroize::Zeroizing;
13
14// Room for the largest invite: two 1,024-byte names, 16 KiB of storage and the
15// frame's fixed fields.
16const MAX_CODE_BYTES: usize = 19 * 1024;
17// A saved code adds its frame prefix, a name of at most 1,024 bytes, its slot
18// and the code's length to the code itself.
19const MAX_KEYCHAIN_BYTES: usize =
20    MAX_CODE_BYTES + crate::FRAME_PREFIX_LEN + 4 + crate::value::MAX_NAME + 8 + 4;
21const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
22
23/// A person's keys and the store's identity and location (§13.1).
24#[derive(Debug)]
25pub struct RestoreCode {
26    /// The store's id.
27    pub store: StoreId,
28    /// The stable member the private pair belongs to. Restore requires this
29    /// id's current pair; an old code cannot rebind it (D13).
30    pub member: MemberId,
31    /// Crypto owns both member key pairs, their encoding and erasure.
32    pub member_keys: MemberKeys,
33    /// Storage location only, interpreted by storage; never credentials.
34    pub storage: SecretBytes,
35}
36impl RestoreCode {
37    /// Encode a bounded frame into a buffer erased on drop, allocated once.
38    pub fn to_bytes(&self) -> Result<Zeroizing<Vec<u8>>, Error> {
39        let keys = self.member_keys.to_secret_bytes();
40        encode_code(
41            kinds::RESTORE_CODE,
42            self.store,
43            &[
44                self.member.0.as_bytes(),
45                &(keys.as_bytes().len() as u32).to_be_bytes(),
46                keys.as_bytes(),
47            ],
48            &self.storage,
49        )
50    }
51    /// Decode a borrowed frame; every owned copy of private material erases on drop.
52    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
53        bound(bytes.len() + 4, MAX_CODE_BYTES, "code bytes")?;
54        let mut input = decode_frame_of(bytes, kinds::RESTORE_CODE, "restore code kind")?;
55        let store = Wire::get(&mut input)?;
56        let member = Wire::get(&mut input)?;
57        let keys_len = u32::get(&mut input)? as usize;
58        let member_keys =
59            MemberKeys::from_secret_bytes(input.take(keys_len)?).map_err(Error::Material)?;
60        let storage = storage(&mut input)?;
61        input.finish()?;
62        Ok(Self { store, member, member_keys, storage })
63    }
64    /// How a restore code's text starts: its kind and version.
65    pub const TEXT_PREFIX: &'static str = "CVR1-";
66    /// Canonical uppercase base32, with CRC-32C, erased on drop.
67    pub fn to_text(&self) -> Result<Zeroizing<String>, Error> {
68        text_encode(Self::TEXT_PREFIX, &self.to_bytes()?)
69    }
70    /// Decode borrowed text without retaining any unerased private copies.
71    pub fn from_text(text: &str) -> Result<Self, Error> {
72        Self::from_bytes(&text_decode(Self::TEXT_PREFIX, text)?)
73    }
74}
75
76/// A restore code as coven saves it in iCloud Keychain or Block Store: the
77/// store's name as the
78/// saving device had it, the slot that set that name, and the code (D13). The
79/// name is a label for the person's list; the code's store id finds the store.
80#[derive(Debug)]
81pub struct KeychainRestoreCode {
82    /// The store's name; a rename made while no device of the person had the
83    /// store open leaves it as they last saw it (§13.1).
84    pub name: String,
85    /// The slot that set `name`: 1 for creation, otherwise the rename's slot.
86    /// Only a name from a later slot replaces it.
87    pub named_at: Slot,
88    /// The member's current restore code.
89    pub code: RestoreCode,
90}
91impl KeychainRestoreCode {
92    /// Encode a bounded frame into a buffer erased on drop, allocated once.
93    pub fn to_bytes(&self) -> Result<Zeroizing<Vec<u8>>, Error> {
94        Self::encode(&self.name, self.named_at, &self.code)
95    }
96    /// Encode the frame for these fields without owning the code.
97    pub fn encode(
98        label: &str,
99        named_at: Slot,
100        code: &RestoreCode,
101    ) -> Result<Zeroizing<Vec<u8>>, Error> {
102        name(label)?;
103        let code = code.to_bytes()?;
104        let size = FRAME_PREFIX_LEN + 4 + label.len() + 8 + 4 + code.len();
105        let mut bytes = Zeroizing::new(Vec::new());
106        bytes.try_reserve_exact(size)?;
107        bytes.extend_from_slice(&frame_prefix(
108            kinds::SAVED_RESTORE_CODE,
109            FormatVersion::CURRENT,
110            (size - FRAME_PREFIX_LEN) as u32,
111        ));
112        bytes.extend_from_slice(&(label.len() as u32).to_be_bytes());
113        bytes.extend_from_slice(label.as_bytes());
114        bytes.extend_from_slice(&named_at.get().to_be_bytes());
115        bytes.extend_from_slice(&(code.len() as u32).to_be_bytes());
116        bytes.extend_from_slice(&code);
117        debug_assert_eq!(bytes.len(), size);
118        Ok(bytes)
119    }
120    /// Decode a borrowed frame; every owned copy of private material erases on drop.
121    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
122        bound(bytes.len(), MAX_KEYCHAIN_BYTES, "saved code bytes")?;
123        let mut input =
124            decode_frame_of(bytes, kinds::SAVED_RESTORE_CODE, "saved restore code kind")?;
125        let label = crate::wire::get_name(&mut input)?;
126        let named_at = <Slot as Wire>::get(&mut input)?;
127        let len = u32::get(&mut input)? as usize;
128        let code = RestoreCode::from_bytes(input.take(len)?)?;
129        input.finish()?;
130        Ok(Self { name: label, named_at, code })
131    }
132}
133
134/// Who an invite code admits, fixed when the admin makes it (§13.2, §13.3):
135/// the byte the code carries. It decides which person a join request may name
136/// (`objects::Joiner`); the joining device reads it from the decoded code.
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub enum InviteAdmits {
139    /// A new person: the join request carries the name they typed.
140    NewPerson,
141    /// An existing member's new keys: their profile already has a name, so
142    /// the request carries none.
143    MemberKeys,
144}
145impl Wire for InviteAdmits {
146    fn put(&self, out: &mut crate::wire::Encoder) -> Result<(), Error> {
147        match self {
148            Self::NewPerson => 0u8,
149            Self::MemberKeys => 1,
150        }
151        .put(out)
152    }
153    fn get(input: &mut Decoder<'_>) -> Result<Self, Error> {
154        match u8::get(input)? {
155            0 => Ok(Self::NewPerson),
156            1 => Ok(Self::MemberKeys),
157            tag => Err(Error::UnknownTag { field: "invite admits", tag }),
158        }
159    }
160}
161
162/// A one-time invitation; the secret permits a join request, not store access.
163#[derive(Debug)]
164pub struct InviteCode {
165    /// The store's id.
166    pub store: StoreId,
167    /// The store's display name.
168    pub name: String,
169    /// The inviting admin's name, as their app gave it when it made the
170    /// invite: the joining device can't read who is who until it is let in.
171    pub inviter: String,
172    /// Whether the invite admits a new person or a member's new keys.
173    pub admits: InviteAdmits,
174    /// When the invite ends, in seconds since the Unix epoch by the inviting
175    /// device's clock: a joining device sends no first request after it.
176    pub expires_at: u64,
177    /// The invite named by the join request.
178    pub invite: InviteId,
179    /// The member id the admin fixed: fresh for an addition, or an existing
180    /// active id for a re-binding. The signed request must repeat it (D13).
181    pub member: MemberId,
182    /// Crypto owns the one-time secret and its erasure.
183    pub secret: InviteSecret,
184    /// The store key introduced by the creation entry, even after rotations.
185    pub initial_key: KeyId,
186    /// The device whose claimed approval supplies binding evidence.
187    pub inviting_writer: DeviceId,
188    /// The inviting device's last applied slot.
189    pub read_through: u64,
190    /// Storage settings, including any credentials for the recipient.
191    pub storage: SecretBytes,
192}
193impl InviteCode {
194    /// Where the joining device's request goes: under the device that made the
195    /// invite, as this code names it (§13.2).
196    pub fn request_path(&self) -> crate::path::ObjectPath {
197        crate::path::ObjectPath::join_request(self.store, self.inviting_writer, self.invite)
198    }
199
200    /// Encode a bounded frame into a buffer erased on drop, allocated once.
201    pub fn to_bytes(&self) -> Result<Zeroizing<Vec<u8>>, Error> {
202        let secret = self.secret.to_secret_bytes();
203        name(&self.name)?;
204        name(&self.inviter)?;
205        let admits = match self.admits {
206            InviteAdmits::NewPerson => 0,
207            InviteAdmits::MemberKeys => 1,
208        };
209        encode_code(
210            kinds::INVITE_CODE,
211            self.store,
212            &[
213                &(self.name.len() as u32).to_be_bytes(),
214                self.name.as_bytes(),
215                &(self.inviter.len() as u32).to_be_bytes(),
216                self.inviter.as_bytes(),
217                &[admits],
218                &self.expires_at.to_be_bytes(),
219                self.invite.0.as_bytes(),
220                self.member.0.as_bytes(),
221                secret.as_bytes(),
222                self.initial_key.0.as_bytes(),
223                &self.inviting_writer.0.to_be_bytes(),
224                &self.read_through.to_be_bytes(),
225            ],
226            &self.storage,
227        )
228    }
229    /// Decode a borrowed frame; every owned secret buffer erases on drop.
230    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
231        bound(bytes.len() + 4, MAX_CODE_BYTES, "code bytes")?;
232        let mut input = decode_frame_of(bytes, kinds::INVITE_CODE, "invite code kind")?;
233        let store = Wire::get(&mut input)?;
234        let label = crate::wire::get_name(&mut input)?;
235        let inviter = crate::wire::get_name(&mut input)?;
236        let admits = InviteAdmits::get(&mut input)?;
237        let expires_at = u64::get(&mut input)?;
238        let invite = Wire::get(&mut input)?;
239        let member = Wire::get(&mut input)?;
240        let mut secret = Zeroizing::new([0; 32]);
241        secret.copy_from_slice(input.take(32)?);
242        let secret = InviteSecret::from_bytes(*secret);
243        let initial_key = Wire::get(&mut input)?;
244        let inviting_writer = Wire::get(&mut input)?;
245        let read_through = u64::get(&mut input)?;
246        let storage = storage(&mut input)?;
247        input.finish()?;
248        Ok(Self {
249            store,
250            name: label,
251            inviter,
252            admits,
253            expires_at,
254            invite,
255            member,
256            secret,
257            initial_key,
258            inviting_writer,
259            read_through,
260            storage,
261        })
262    }
263    /// How an invite code's text starts: its kind and version.
264    pub const TEXT_PREFIX: &'static str = "CVI1-";
265    /// Canonical uppercase base32, with CRC-32C, erased on drop.
266    pub fn to_text(&self) -> Result<Zeroizing<String>, Error> {
267        text_encode(Self::TEXT_PREFIX, &self.to_bytes()?)
268    }
269    /// Decode borrowed text without retaining any unerased private copies.
270    pub fn from_text(text: &str) -> Result<Self, Error> {
271        Self::from_bytes(&text_decode(Self::TEXT_PREFIX, text)?)
272    }
273}
274
275/// A pairing code: what the person's new device needs to find the store and
276/// to send a request its showing device can open. It holds no keys (§13.2, D13).
277#[derive(Debug)]
278pub struct PairingCode {
279    /// The store's id.
280    pub store: StoreId,
281    /// When the pairing ends, in seconds since the Unix epoch by the showing
282    /// device's clock: the asking device sends no first request after it.
283    pub expires_at: u64,
284    /// The pairing named by the request's path, in an invite's place.
285    pub pairing: InviteId,
286    /// The showing device's member, whose pair the handover carries. The
287    /// signed request must repeat it.
288    pub member: MemberId,
289    /// Crypto owns the one-time secret and its erasure.
290    pub secret: InviteSecret,
291    /// The device that made the pairing, under whose id the request goes.
292    pub showing: DeviceId,
293    /// The store's location, and on S3 the key the showing device connects
294    /// with where the code is the QR code.
295    pub storage: SecretBytes,
296}
297impl PairingCode {
298    /// Where the asking device's request goes: under the showing device, as
299    /// this code names it (§13.2).
300    pub fn request_path(&self) -> crate::path::ObjectPath {
301        crate::path::ObjectPath::join_request(self.store, self.showing, self.pairing)
302    }
303
304    /// Encode a bounded frame into a buffer erased on drop, allocated once.
305    pub fn to_bytes(&self) -> Result<Zeroizing<Vec<u8>>, Error> {
306        let secret = self.secret.to_secret_bytes();
307        encode_code(
308            kinds::PAIRING_CODE,
309            self.store,
310            &[
311                &self.expires_at.to_be_bytes(),
312                self.pairing.0.as_bytes(),
313                self.member.0.as_bytes(),
314                secret.as_bytes(),
315                &self.showing.0.to_be_bytes(),
316            ],
317            &self.storage,
318        )
319    }
320    /// Decode a borrowed frame; every owned secret buffer erases on drop.
321    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
322        bound(bytes.len() + 4, MAX_CODE_BYTES, "code bytes")?;
323        let mut input = decode_frame_of(bytes, kinds::PAIRING_CODE, "pairing code kind")?;
324        let store = Wire::get(&mut input)?;
325        let expires_at = u64::get(&mut input)?;
326        let pairing = Wire::get(&mut input)?;
327        let member = Wire::get(&mut input)?;
328        let mut secret = Zeroizing::new([0; 32]);
329        secret.copy_from_slice(input.take(32)?);
330        let secret = InviteSecret::from_bytes(*secret);
331        let showing = Wire::get(&mut input)?;
332        let storage = storage(&mut input)?;
333        input.finish()?;
334        Ok(Self { store, expires_at, pairing, member, secret, showing, storage })
335    }
336    /// How a pairing code's text starts: its kind and version.
337    pub const TEXT_PREFIX: &'static str = "CVP1-";
338    /// Canonical uppercase base32, with CRC-32C, erased on drop.
339    pub fn to_text(&self) -> Result<Zeroizing<String>, Error> {
340        text_encode(Self::TEXT_PREFIX, &self.to_bytes()?)
341    }
342    /// Decode borrowed text without retaining any unerased private copies.
343    pub fn from_text(text: &str) -> Result<Self, Error> {
344        Self::from_bytes(&text_decode(Self::TEXT_PREFIX, text)?)
345    }
346}
347
348fn storage(input: &mut Decoder<'_>) -> Result<SecretBytes, Error> {
349    let len = u32::get(input)? as usize;
350    bound(len, MAX_STORAGE, "storage settings")?;
351    let source = input.take(len)?;
352    let mut bytes = Zeroizing::new(Vec::new());
353    bytes.try_reserve_exact(len)?;
354    bytes.extend_from_slice(source);
355    Ok(SecretBytes::new(std::mem::take(&mut *bytes)))
356}
357
358fn encode_code(
359    kind: u8,
360    store: StoreId,
361    material: &[&[u8]],
362    storage: &SecretBytes,
363) -> Result<Zeroizing<Vec<u8>>, Error> {
364    bound(storage.as_bytes().len(), MAX_STORAGE, "storage settings")?;
365    let size = FRAME_PREFIX_LEN
366        + 16
367        + material.iter().map(|s| s.len()).sum::<usize>()
368        + 4
369        + storage.as_bytes().len();
370    bound(size + 4, MAX_CODE_BYTES, "code bytes")?;
371    let mut bytes = Zeroizing::new(Vec::new());
372    bytes.try_reserve_exact(size)?;
373    bytes.extend_from_slice(&frame_prefix(
374        kind,
375        FormatVersion::CURRENT,
376        (size - FRAME_PREFIX_LEN) as u32,
377    ));
378    bytes.extend_from_slice(store.0.as_bytes());
379    for part in material {
380        bytes.extend_from_slice(part);
381    }
382    bytes.extend_from_slice(&(storage.as_bytes().len() as u32).to_be_bytes());
383    bytes.extend_from_slice(storage.as_bytes());
384    debug_assert_eq!(bytes.len(), size);
385    Ok(bytes)
386}
387
388// CRC-32C: reflected Castagnoli polynomial, init/final XOR all ones. This is
389// accidental-error detection, not authentication; sealing/signing belong to crypto.
390fn checksum(bytes: &[u8]) -> u32 {
391    let mut crc = u32::MAX;
392    for byte in bytes {
393        crc ^= u32::from(*byte);
394        for _ in 0..8 {
395            crc = (crc >> 1) ^ (0x82f6_3b78 & 0u32.wrapping_sub(crc & 1));
396        }
397    }
398    !crc
399}
400
401fn text_encode(prefix: &str, bytes: &[u8]) -> Result<Zeroizing<String>, Error> {
402    bound(bytes.len() + 4, MAX_CODE_BYTES, "code bytes")?;
403    let crc = Zeroizing::new(checksum(bytes).to_be_bytes());
404    let mut text = Zeroizing::new(String::new());
405    text.try_reserve_exact(prefix.len() + ((bytes.len() + 4) * 8).div_ceil(5))?;
406    text.push_str(prefix);
407    let mut pending = Zeroizing::new(0u16);
408    let mut bits = 0;
409    for byte in bytes.iter().chain(crc.iter()) {
410        *pending = (*pending << 8) | u16::from(*byte);
411        bits += 8;
412        while bits >= 5 {
413            bits -= 5;
414            text.push(ALPHABET[((*pending >> bits) & 31) as usize] as char);
415        }
416    }
417    if bits > 0 {
418        text.push(ALPHABET[((*pending << (5 - bits)) & 31) as usize] as char);
419    }
420    Ok(text)
421}
422
423fn text_decode(prefix: &str, text: &str) -> Result<Zeroizing<Vec<u8>>, Error> {
424    bound(text.len(), prefix.len() + (MAX_CODE_BYTES * 8).div_ceil(5), "code text")?;
425    require(text.starts_with(prefix), "code prefix", Rule::Kind)?;
426    let symbols = &text.as_bytes()[prefix.len()..];
427    require(matches!(symbols.len() % 8, 0 | 2 | 4 | 5 | 7), "base32 length", Rule::CodePadding)?;
428    let mut bytes = Zeroizing::new(Vec::new());
429    bytes.try_reserve_exact(symbols.len() * 5 / 8)?;
430    let mut pending = Zeroizing::new(0u16);
431    let mut bits = 0;
432    for (offset, symbol) in symbols.iter().enumerate() {
433        let value = ALPHABET
434            .iter()
435            .position(|c| c == symbol)
436            .ok_or(Error::CodeCharacter { offset: offset + prefix.len() })?;
437        *pending = (*pending << 5) | value as u16;
438        bits += 5;
439        if bits >= 8 {
440            bits -= 8;
441            bytes.push((*pending >> bits) as u8);
442        }
443    }
444    require(*pending & ((1 << bits) - 1) == 0, "base32 padding bits", Rule::CodePadding)?;
445    let payload_len = bytes.len().checked_sub(4).ok_or(Error::Truncated)?;
446    let mut expected = [0; 4];
447    expected.copy_from_slice(&bytes[payload_len..]);
448    if checksum(&bytes[..payload_len]) != u32::from_be_bytes(expected) {
449        return Err(Error::Checksum);
450    }
451    bytes.truncate(payload_len);
452    Ok(bytes)
453}
454
455#[cfg(test)]
456#[path = "codes_tests.rs"]
457mod tests;