Skip to main content

coven_crypto/
member.rs

1//! A member's signing and sealing key pairs, kept together (Appendix D).
2
3use crate::{cipher, derivation, randomness, wire};
4use crate::{CircleKey, CryptoError, MaterialError, ObjectDigest, SecretBytes, StoreKey};
5use coven_foundation::id_source::MemberId;
6use ed25519_dalek::{Signer, VerifyingKey};
7use std::fmt;
8use x25519_dalek::{PublicKey, StaticSecret};
9use zeroize::Zeroizing;
10
11/// A member's validated Ed25519 public signing key (Appendix D). It is bound to a
12/// stable [`MemberId`] by admin entries and is never that identity.
13#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
14pub struct SigningKey([u8; 32]);
15
16impl SigningKey {
17    /// Validate a public signing key, refusing invalid and weak Ed25519 points.
18    #[expect(
19        clippy::map_err_ignore,
20        reason = "Ed25519's key error is opaque by design; InvalidSigningKey is all it says"
21    )]
22    pub fn from_bytes(bytes: [u8; 32]) -> Result<Self, CryptoError> {
23        let key = VerifyingKey::from_bytes(&bytes).map_err(|_| CryptoError::InvalidSigningKey)?;
24        if key.is_weak() {
25            return Err(CryptoError::InvalidSigningKey);
26        }
27        Ok(Self(bytes))
28    }
29
30    /// The validated Ed25519 public key's 32 bytes.
31    pub fn as_bytes(&self) -> &[u8; 32] {
32        &self.0
33    }
34
35    /// Verify a detached signature against this public key (§12).
36    #[expect(
37        clippy::map_err_ignore,
38        reason = "Ed25519's verification error is opaque by design; Signature is all it says"
39    )]
40    pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), CryptoError> {
41        let key = VerifyingKey::from_bytes(&self.0)
42            .expect("SigningKey contains a validated Ed25519 public key");
43        key.verify_strict(message, &ed25519_dalek::Signature::from_bytes(&signature.0))
44            .map_err(|_| CryptoError::Signature)
45    }
46
47    /// Verify an object's signature after hashing all bytes before it (Appendix D.3).
48    /// The domain and path are authenticated along with the SHA-256 digest.
49    /// Panics if the storage path is empty.
50    pub fn verify_object(
51        &self,
52        path: &str,
53        digest: &ObjectDigest,
54        signature: &Signature,
55    ) -> Result<(), CryptoError> {
56        self.verify(&object_message(path, digest), signature)
57    }
58
59    /// Verify a snapshot prefix independently of its encrypted data (D9).
60    /// `prefix` is exactly kind, version and routing fields, without signatures.
61    /// Panics if the storage path is empty.
62    pub fn verify_prefix(
63        &self,
64        path: &str,
65        prefix: &[u8],
66        signature: &Signature,
67    ) -> Result<(), CryptoError> {
68        self.verify(&prefix_message(path, prefix), signature)
69    }
70
71    /// Verify a write's header signature without its part chunks (D9): the
72    /// exact cleartext prefix, the complete sealed header chunk and the part
73    /// roots. Snapshots carry these to authenticate another member's leaves.
74    /// Panics if the storage path is empty.
75    pub fn verify_write_header(
76        &self,
77        path: &str,
78        prefix: &[u8],
79        header: &[u8],
80        roots: &[[u8; 32]],
81        signature: &Signature,
82    ) -> Result<(), CryptoError> {
83        self.verify(&header_message(path, prefix, header, roots), signature)
84    }
85}
86
87/// The public half of a member's X25519 pair, used for anonymous sealed keys.
88/// A copy names the exact sealing key it is sealed to (D9).
89#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
90pub struct SealingKey([u8; 32]);
91
92impl SealingKey {
93    /// Read a public sealing key. Low-order keys are refused when sealing.
94    pub fn from_bytes(bytes: [u8; 32]) -> Self {
95        Self(bytes)
96    }
97    /// The public bytes carried with the member's join request (§13.2).
98    pub fn as_bytes(&self) -> &[u8; 32] {
99        &self.0
100    }
101}
102
103/// A member's public signing and sealing keys, independent of their stable
104/// [`MemberId`] (§10, D2). Creation, addition and replacement bind a pair to an id.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
106pub struct MemberPublicKeys {
107    /// The Ed25519 key that verifies the member's signatures.
108    pub signing: SigningKey,
109    /// The X25519 key to which store and circle keys are sealed.
110    pub sealing: SealingKey,
111}
112
113/// The bytes of a detached Ed25519 signature.
114pub const SIGNATURE_LEN: usize = 64;
115
116/// A detached Ed25519 signature on bytes authored by a member (§12).
117#[derive(Clone, Debug, Eq, PartialEq)]
118pub struct Signature([u8; SIGNATURE_LEN]);
119
120impl Signature {
121    /// Read a detached signature; authenticity is checked by `SigningKey::verify`.
122    pub fn from_bytes(bytes: [u8; SIGNATURE_LEN]) -> Self {
123        Self(bytes)
124    }
125    /// The signature bytes written beside the signed message.
126    pub fn as_bytes(&self) -> &[u8; SIGNATURE_LEN] {
127        &self.0
128    }
129}
130
131/// A member's Ed25519 signing pair and independent X25519 sealing pair (Appendix D).
132/// Both secrets erase on drop. Clone is needed by in-memory custody to keep
133/// its keys while returning an independently owned unlocked pair.
134#[derive(Clone)]
135pub struct MemberKeys {
136    signing: ed25519_dalek::SigningKey,
137    sealing: StaticSecret,
138}
139
140impl MemberKeys {
141    /// The length of `to_secret_bytes`.
142    pub const SECRET_LEN: usize = MEMBER_KEYS_LENGTH;
143
144    /// A pair whose signing and sealing seeds are both `seed`: public test
145    /// data, never a person's keys.
146    #[cfg(any(test, feature = "test-utils"))]
147    pub fn from_seed(seed: u8) -> Self {
148        Self {
149            signing: ed25519_dalek::SigningKey::from_bytes(&[seed; 32]),
150            sealing: StaticSecret::from([seed; 32]),
151        }
152    }
153
154    /// Make both member key pairs using the operating system's randomness.
155    pub fn generate() -> Result<Self, CryptoError> {
156        let signing = randomness::secret_bytes()?;
157        let sealing = randomness::secret_bytes()?;
158        Ok(Self {
159            signing: ed25519_dalek::SigningKey::from_bytes(&signing),
160            sealing: StaticSecret::from(*sealing),
161        })
162    }
163
164    /// The public pair admin entries bind to a stable member id (§10).
165    pub fn public_keys(&self) -> MemberPublicKeys {
166        MemberPublicKeys {
167            signing: SigningKey(self.signing.verifying_key().to_bytes()),
168            sealing: SealingKey(PublicKey::from(&self.sealing).to_bytes()),
169        }
170    }
171
172    /// Sign bytes with the member's Ed25519 pair (§12).
173    pub fn sign(&self, bytes: &[u8]) -> Signature {
174        Signature(self.signing.sign(bytes).to_bytes())
175    }
176
177    /// Sign the digest of every object byte before the signature (Appendix D.3).
178    /// Feed the prefix, length fields and sealed chunks to [`crate::ObjectHasher`]
179    /// in storage order. The signed message binds its domain, path and digest.
180    /// Panics if the storage path is empty.
181    ///
182    /// A file's content hash cannot stand in for an object's digest.
183    /// ```compile_fail
184    /// use coven_crypto::{ContentHasher, MemberKeys};
185    /// let member = MemberKeys::generate().unwrap();
186    /// member.sign_object("10101010-1010-1010-1010-101010101010/seq/1", &ContentHasher::new().finish());
187    /// ```
188    pub fn sign_object(&self, path: &str, digest: &ObjectDigest) -> Signature {
189        self.sign(&object_message(path, digest))
190    }
191
192    /// Sign a snapshot's exact kind, version and routing fields (D9).
193    /// The prefix domain and path are bound separately from whole-object signing.
194    /// Panics if the storage path is empty.
195    pub fn sign_prefix(&self, path: &str, prefix: &[u8]) -> Signature {
196        self.sign(&prefix_message(path, prefix))
197    }
198
199    /// Sign a write's cleartext prefix, sealed header chunk and part roots
200    /// (D9), separately from the whole-object signature.
201    /// Panics if the storage path is empty.
202    pub fn sign_write_header(
203        &self,
204        path: &str,
205        prefix: &[u8],
206        header: &[u8],
207        roots: &[[u8; 32]],
208    ) -> Signature {
209        self.sign(&header_message(path, prefix, header, roots))
210    }
211
212    /// Encode both private seeds for custody or the person's restore code (§13.1).
213    pub fn to_secret_bytes(&self) -> SecretBytes {
214        let mut bytes = Zeroizing::new(Vec::with_capacity(MEMBER_KEYS_LENGTH));
215        bytes.extend_from_slice(MEMBER_KEYS_MAGIC);
216        bytes.extend_from_slice(self.signing.as_bytes());
217        bytes.extend_from_slice(self.sealing.as_bytes());
218        SecretBytes(bytes)
219    }
220
221    /// Restore both pairs from custody or the person's restore code (§13.1).
222    pub fn from_secret_bytes(mut bytes: &[u8]) -> Result<Self, MaterialError> {
223        wire::prefix(&mut bytes, MEMBER_KEYS_MAGIC)?;
224        let signing = Zeroizing::new(wire::array(&mut bytes)?);
225        let sealing = Zeroizing::new(wire::array(&mut bytes)?);
226        wire::end(bytes)?;
227        Ok(Self {
228            signing: ed25519_dalek::SigningKey::from_bytes(&signing),
229            sealing: StaticSecret::from(*sealing),
230        })
231    }
232
233    /// Open a store-key box, authenticating the exact path and opaque clear prefix.
234    /// Format checks the recipient and opened identity; the caller checks the
235    /// introduction commitment before accepting the candidate key.
236    /// Panics if the storage path is empty.
237    pub fn open_store_key(
238        &self,
239        path: &str,
240        prefix: &[u8],
241        sealed: &[u8],
242    ) -> Result<StoreKey, CryptoError> {
243        let plaintext = self.open_box::<{ StoreKey::ENCODED_LEN }>(
244            |sender, recipient| box_context(b"store", path, prefix, sender, recipient),
245            sealed,
246        )?;
247        Ok(StoreKey::from_encoded(&plaintext))
248    }
249
250    /// Open a circle-key box, authenticating the exact path and opaque clear prefix.
251    /// Format checks the recipient and opened identity; the caller checks the
252    /// introduction commitment before accepting the candidate key.
253    /// Panics if the storage path is empty.
254    pub fn open_circle_key(
255        &self,
256        path: &str,
257        prefix: &[u8],
258        sealed: &[u8],
259    ) -> Result<CircleKey, CryptoError> {
260        let plaintext = self.open_box::<{ CircleKey::ENCODED_LEN }>(
261            |sender, recipient| box_context(b"circle", path, prefix, sender, recipient),
262            sealed,
263        )?;
264        Ok(CircleKey::from_encoded(&plaintext))
265    }
266
267    /// Open the copy of a circle key a joining request carries for its own
268    /// member, sealed by `seal_own_circle_key` with the same `binding` (D11).
269    /// It binds no slot path, so it opens wherever its bytes are found, and
270    /// only for the sealing key it was sealed to.
271    pub fn open_own_circle_key(
272        &self,
273        binding: &[u8],
274        sealed: &[u8],
275    ) -> Result<CircleKey, CryptoError> {
276        let plaintext = self.open_box::<{ CircleKey::ENCODED_LEN }>(
277            |sender, recipient| own_copy_context(binding, sender, recipient),
278            sealed,
279        )?;
280        Ok(CircleKey::from_encoded(&plaintext))
281    }
282
283    /// Open a pairing's handover: the ephemeral key, nonce, ciphertext and tag
284    /// `seal_handover` returned, at the exact path and clear prefix it was
285    /// sealed for, with the private half of the sealing key it was sealed to
286    /// (D11). The plaintext is erased on drop.
287    /// Panics if the storage path is empty.
288    pub fn open_handover(
289        &self,
290        path: &str,
291        prefix: &[u8],
292        sealed: &[u8],
293    ) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
294        let (sender, rest) = sealed.split_first_chunk::<32>().ok_or(CryptoError::Malformed)?;
295        if rest.len() < cipher::NONCE_LEN + KEY_BOX_TAG_LEN {
296            return Err(CryptoError::Malformed);
297        }
298        let recipient = self.public_keys().sealing;
299        let shared = self.sealing.diffie_hellman(&PublicKey::from(*sender));
300        if !shared.was_contributory() {
301            return Err(CryptoError::WeakSealingKey);
302        }
303        let context = handover_context(path, prefix, sender, recipient.as_bytes());
304        let key = derivation::derive(shared.as_bytes(), &context);
305        cipher::open_random(&key, &context, rest).map(Zeroizing::new)
306    }
307
308    /// Open a box holding exactly `N` plaintext bytes; any other length is
309    /// malformed.
310    fn open_box<const N: usize>(
311        &self,
312        context: impl FnOnce(&[u8; 32], &[u8; 32]) -> Vec<u8>,
313        sealed: &[u8],
314    ) -> Result<Zeroizing<[u8; N]>, CryptoError> {
315        let (sender, rest) = sealed.split_first_chunk::<32>().ok_or(CryptoError::Malformed)?;
316        let (nonce, rest) =
317            rest.split_first_chunk::<{ cipher::NONCE_LEN }>().ok_or(CryptoError::Malformed)?;
318        let (ciphertext, rest) = rest.split_first_chunk::<N>().ok_or(CryptoError::Malformed)?;
319        let (tag, rest) =
320            rest.split_first_chunk::<KEY_BOX_TAG_LEN>().ok_or(CryptoError::Malformed)?;
321        if !rest.is_empty() {
322            return Err(CryptoError::Malformed);
323        }
324        let recipient = self.public_keys().sealing;
325        let shared = self.sealing.diffie_hellman(&PublicKey::from(*sender));
326        if !shared.was_contributory() {
327            return Err(CryptoError::WeakSealingKey);
328        }
329        let context = context(sender, recipient.as_bytes());
330        let key = derivation::derive(shared.as_bytes(), &context);
331        cipher::open_exact(&key, nonce, &context, ciphertext, tag)
332    }
333}
334
335impl fmt::Debug for MemberKeys {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        f.write_str("MemberKeys([REDACTED])")
338    }
339}
340
341/// This device's member: the stable id and every private pair it holds
342/// (E1, E11). Identity custody keeps it; the id never derives from the keys.
343/// The active pair is the one the last installed binding made current. A
344/// self-replacement keeps its candidate here before publishing it, and every
345/// pair a kept replacement retired stays held, because copies name the exact
346/// credential they open with (§12.1). Which pair may sign is replay's decision,
347/// never this record's (§12.3).
348#[derive(Clone)]
349pub struct MemberIdentity {
350    member: MemberId,
351    keys: MemberKeys,
352    retained: Vec<MemberKeys>,
353    candidate: Option<MemberKeys>,
354}
355
356impl MemberIdentity {
357    /// Bind a private pair to the stable id its admin entry names.
358    pub fn new(member: MemberId, keys: MemberKeys) -> Self {
359        Self { member, keys, retained: Vec::new(), candidate: None }
360    }
361
362    /// Make both key pairs for an independently generated id (§10).
363    pub fn generate(member: MemberId) -> Result<Self, CryptoError> {
364        Ok(Self::new(member, MemberKeys::generate()?))
365    }
366
367    /// The stable member id.
368    pub fn member(&self) -> MemberId {
369        self.member
370    }
371
372    /// The active private pair: the one this device signs with and a
373    /// restore code exports.
374    pub fn keys(&self) -> &MemberKeys {
375        &self.keys
376    }
377
378    /// A self-replacement's fresh pair, kept before its binding is published.
379    pub fn candidate(&self) -> Option<&MemberKeys> {
380        self.candidate.as_ref()
381    }
382
383    /// Every held pair: the active one, retired ones, then the candidate.
384    fn held(&self) -> impl Iterator<Item = &MemberKeys> {
385        std::iter::once(&self.keys).chain(&self.retained).chain(&self.candidate)
386    }
387
388    /// The held private pair whose sealing key is `sealing`. A copy names the
389    /// exact credential it is sealed to, and opens only with that one, never
390    /// with whichever pair is latest (§12.1).
391    pub fn credential(&self, sealing: &SealingKey) -> Option<&MemberKeys> {
392        self.held().find(|keys| keys.public_keys().sealing == *sealing)
393    }
394
395    /// Whether some held pair is exactly `keys`.
396    pub fn holds(&self, keys: &MemberPublicKeys) -> bool {
397        self.held().any(|held| held.public_keys() == *keys)
398    }
399
400    /// This identity keeping `candidate` for a self-replacement. A candidate
401    /// already held stays held as a retired credential: its copies may exist.
402    pub fn with_candidate(&self, candidate: MemberKeys) -> Self {
403        let mut next = self.clone();
404        next.retained.extend(next.candidate.replace(candidate));
405        next
406    }
407
408    /// This identity with the held pair `current` active, as replay's current
409    /// binding selects it (§12.3). The previously active pair and any other
410    /// candidate stay held as retired credentials. `None` when no held pair
411    /// is `current`.
412    pub fn activate(&self, current: &MemberPublicKeys) -> Option<Self> {
413        if self.keys.public_keys() == *current && self.candidate.is_none() {
414            return Some(self.clone());
415        }
416        let mut pairs: Vec<MemberKeys> = self.held().cloned().collect();
417        let index = pairs.iter().position(|keys| keys.public_keys() == *current)?;
418        let keys = pairs.remove(index);
419        let mut retained = Vec::new();
420        for pair in pairs {
421            if !retained.iter().any(|held: &MemberKeys| held.public_keys() == pair.public_keys()) {
422                retained.push(pair);
423            }
424        }
425        Some(Self { member: self.member, keys, retained, candidate: None })
426    }
427
428    /// This identity with its candidate retired: a replacement that never
429    /// became current leaves its copies, so its pair stays held (§12.4).
430    pub fn retire_candidate(&self) -> Self {
431        let mut next = self.clone();
432        next.retained.extend(next.candidate.take());
433        next
434    }
435
436    /// This identity without its candidate: a self-replacement cancelled
437    /// before reserving anything never sent a copy to it.
438    pub fn without_candidate(&self) -> Self {
439        let mut next = self.clone();
440        next.candidate = None;
441        next
442    }
443
444    /// Encode the id and every held private pair for identity custody: the
445    /// active pair, the retired ones, then the candidate if any. This custody
446    /// encoding is not a restore code (D13).
447    pub fn to_secret_bytes(&self) -> SecretBytes {
448        // Allocate once so growth cannot leave an unerased copy of the seeds.
449        let pairs = 1 + self.retained.len() + usize::from(self.candidate.is_some());
450        // Magic, id, the active pair, the retired count and pairs, and the
451        // candidate's flag and pair.
452        let mut bytes = Zeroizing::new(Vec::with_capacity(
453            IDENTITY_MAGIC.len() + 16 + 8 + 1 + pairs * MEMBER_KEYS_LENGTH,
454        ));
455        bytes.extend_from_slice(IDENTITY_MAGIC);
456        bytes.extend_from_slice(self.member.0.as_bytes());
457        bytes.extend_from_slice(self.keys.to_secret_bytes().as_bytes());
458        bytes.extend_from_slice(&(self.retained.len() as u64).to_le_bytes());
459        for keys in &self.retained {
460            bytes.extend_from_slice(keys.to_secret_bytes().as_bytes());
461        }
462        match &self.candidate {
463            Some(keys) => {
464                bytes.push(1);
465                bytes.extend_from_slice(keys.to_secret_bytes().as_bytes());
466            }
467            None => bytes.push(0),
468        }
469        SecretBytes(bytes)
470    }
471
472    /// Restore the id and every held pair from identity custody.
473    pub fn from_secret_bytes(mut bytes: &[u8]) -> Result<Self, MaterialError> {
474        fn pair(bytes: &mut &[u8]) -> Result<MemberKeys, MaterialError> {
475            MemberKeys::from_secret_bytes(wire::take(bytes, MEMBER_KEYS_LENGTH)?)
476        }
477        wire::prefix(&mut bytes, IDENTITY_MAGIC)?;
478        let member = MemberId(uuid::Uuid::from_bytes(wire::array(&mut bytes)?));
479        let keys = pair(&mut bytes)?;
480        let count = wire::number(&mut bytes)?;
481        if count > (bytes.len() / MEMBER_KEYS_LENGTH) as u64 {
482            return Err(MaterialError::Encoding);
483        }
484        let retained = (0..count).map(|_| pair(&mut bytes)).collect::<Result<Vec<_>, _>>()?;
485        let candidate = match wire::array(&mut bytes)? {
486            [0] => None,
487            [1] => Some(pair(&mut bytes)?),
488            _ => return Err(MaterialError::Encoding),
489        };
490        wire::end(bytes)?;
491        let identity = Self { member, keys, retained, candidate };
492        // Each credential is held once.
493        let mut public: Vec<_> = identity.held().map(MemberKeys::public_keys).collect();
494        public.sort();
495        public.dedup();
496        if public.len() != identity.held().count() {
497            return Err(MaterialError::Encoding);
498        }
499        Ok(identity)
500    }
501}
502
503/// The first bytes of a private pair's encoding: its magic and version.
504const MEMBER_KEYS_MAGIC: &[u8] = b"CVMK\x01";
505/// The first bytes of an identity's custody encoding: its magic and version.
506const IDENTITY_MAGIC: &[u8] = b"CVMI\x01";
507/// The length of a private-pair blob: its magic and both 32-byte secrets.
508const MEMBER_KEYS_LENGTH: usize = MEMBER_KEYS_MAGIC.len() + 2 * 32;
509
510impl fmt::Debug for MemberIdentity {
511    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512        f.debug_struct("MemberIdentity")
513            .field("member", &self.member)
514            .field("retained", &self.retained.len())
515            .field("candidate", &self.candidate.is_some())
516            .finish_non_exhaustive()
517    }
518}
519
520/// A key box's bytes before its ciphertext: the ephemeral public key, then
521/// the nonce.
522pub const KEY_BOX_HEAD_LEN: usize = 32 + cipher::NONCE_LEN;
523/// A key box's authentication tag, after its ciphertext.
524pub const KEY_BOX_TAG_LEN: usize = cipher::FILE_CHUNK_TAG_LEN;
525
526/// Seal a store key anonymously, authenticating its path and exact clear prefix (D11).
527/// Returns ephemeral key, nonce, ciphertext and tag; format supplies the prefix.
528/// Panics if the storage path is empty.
529pub fn seal_store_key(
530    key: &StoreKey,
531    recipient: &SealingKey,
532    path: &str,
533    prefix: &[u8],
534) -> Result<Vec<u8>, CryptoError> {
535    let mut bytes = Zeroizing::new(Vec::with_capacity(StoreKey::ENCODED_LEN));
536    key.encode_into(&mut bytes);
537    seal_box(b"store", recipient, path, prefix, &bytes)
538}
539
540/// Seal a circle key anonymously, authenticating its path and exact clear prefix (D11).
541/// Returns ephemeral key, nonce, ciphertext and tag; format supplies the prefix.
542/// Panics if the storage path is empty.
543pub fn seal_circle_key(
544    key: &CircleKey,
545    recipient: &SealingKey,
546    path: &str,
547    prefix: &[u8],
548) -> Result<Vec<u8>, CryptoError> {
549    let mut bytes = Zeroizing::new(Vec::with_capacity(CircleKey::ENCODED_LEN));
550    key.encode_into(&mut bytes);
551    seal_box(b"circle", recipient, path, prefix, &bytes)
552}
553
554/// Seal a circle key to the sealing key of the joining member who made it,
555/// for the copy their join request carries (D11). Unlike a slot's box it binds
556/// no path: the joining phone doesn't know the slot its copy will land in, so
557/// `binding` is what the request can fix, the store and the box's routing.
558/// Returns the ephemeral key, nonce, ciphertext and tag.
559pub fn seal_own_circle_key(
560    key: &CircleKey,
561    recipient: &SealingKey,
562    binding: &[u8],
563) -> Result<Vec<u8>, CryptoError> {
564    let mut bytes = Zeroizing::new(Vec::with_capacity(CircleKey::ENCODED_LEN));
565    key.encode_into(&mut bytes);
566    seal_with(recipient, &bytes, |sender| own_copy_context(binding, sender, &recipient.0))
567}
568
569/// Seal a pairing's handover anonymously to the sealing key of the request it
570/// answers, authenticating its path and clear prefix (D11). Returns the
571/// ephemeral key, nonce, ciphertext and tag; format supplies the prefix.
572/// Panics if the storage path is empty.
573pub fn seal_handover(
574    plaintext: &[u8],
575    recipient: &SealingKey,
576    path: &str,
577    prefix: &[u8],
578) -> Result<Vec<u8>, CryptoError> {
579    let seed = randomness::secret_bytes()?;
580    let ephemeral = StaticSecret::from(*seed);
581    let sender = PublicKey::from(&ephemeral).to_bytes();
582    let shared = ephemeral.diffie_hellman(&PublicKey::from(recipient.0));
583    if !shared.was_contributory() {
584        return Err(CryptoError::WeakSealingKey);
585    }
586    let context = handover_context(path, prefix, &sender, &recipient.0);
587    let key = derivation::derive(shared.as_bytes(), &context);
588    let body = cipher::seal_random(&key, &context, plaintext)?;
589    let mut bytes = Vec::with_capacity(32 + body.len());
590    bytes.extend_from_slice(&sender);
591    bytes.extend_from_slice(&body);
592    Ok(bytes)
593}
594
595fn handover_context(path: &str, prefix: &[u8], sender: &[u8; 32], recipient: &[u8; 32]) -> Vec<u8> {
596    cipher::context(&[derivation::HANDOVER, cipher::storage_path(path), prefix, sender, recipient])
597}
598
599fn object_message(path: &str, digest: &ObjectDigest) -> Vec<u8> {
600    cipher::context(&[b"coven/object-signature/v1", cipher::storage_path(path), digest.as_bytes()])
601}
602
603fn prefix_message(path: &str, prefix: &[u8]) -> Vec<u8> {
604    cipher::context(&[b"coven/prefix-signature/v1", cipher::storage_path(path), prefix])
605}
606
607fn header_message(path: &str, prefix: &[u8], header: &[u8], roots: &[[u8; 32]]) -> Vec<u8> {
608    let roots: Vec<u8> = roots.iter().flatten().copied().collect();
609    cipher::context(&[
610        b"coven/write-header-signature/v1",
611        cipher::storage_path(path),
612        prefix,
613        header,
614        &roots,
615    ])
616}
617
618fn box_context(
619    kind: &[u8],
620    path: &str,
621    prefix: &[u8],
622    sender: &[u8; 32],
623    recipient: &[u8; 32],
624) -> Vec<u8> {
625    cipher::context(&[
626        derivation::SEALED_BOX,
627        kind,
628        cipher::storage_path(path),
629        prefix,
630        sender,
631        recipient,
632    ])
633}
634
635fn own_copy_context(binding: &[u8], sender: &[u8; 32], recipient: &[u8; 32]) -> Vec<u8> {
636    cipher::context(&[derivation::OWN_COPY, b"circle", binding, sender, recipient])
637}
638
639fn seal_box(
640    kind: &[u8],
641    recipient: &SealingKey,
642    path: &str,
643    prefix: &[u8],
644    plaintext: &[u8],
645) -> Result<Vec<u8>, CryptoError> {
646    seal_with(recipient, plaintext, |sender| box_context(kind, path, prefix, sender, &recipient.0))
647}
648
649/// Seal `plaintext` to `recipient` under an ephemeral key, with the context
650/// `context` makes from that key's public half.
651fn seal_with(
652    recipient: &SealingKey,
653    plaintext: &[u8],
654    context: impl FnOnce(&[u8; 32]) -> Vec<u8>,
655) -> Result<Vec<u8>, CryptoError> {
656    let seed = randomness::secret_bytes()?;
657    let ephemeral = StaticSecret::from(*seed);
658    let sender = PublicKey::from(&ephemeral).to_bytes();
659    let shared = ephemeral.diffie_hellman(&PublicKey::from(recipient.0));
660    if !shared.was_contributory() {
661        return Err(CryptoError::WeakSealingKey);
662    }
663    let context = context(&sender);
664    let key = derivation::derive(shared.as_bytes(), &context);
665    let body = cipher::seal_random(&key, &context, plaintext)?;
666    let mut bytes = Vec::with_capacity(32 + body.len());
667    bytes.extend_from_slice(&sender);
668    bytes.extend_from_slice(&body);
669    Ok(bytes)
670}
671
672#[cfg(test)]
673#[path = "member_tests.rs"]
674mod tests;