Skip to main content

coven_format/
handover.rs

1//! A pairing's handover: the member's private pair, sealed to the sealing key
2//! of the request the person approved (D8, D11).
3
4use crate::error::{exact_length, Error};
5use crate::path::ObjectPath;
6use coven_crypto::{
7    seal_handover, CryptoError, MemberKeys, SealingKey, KEY_BOX_HEAD_LEN, KEY_BOX_TAG_LEN,
8};
9use coven_foundation::id_source::MemberId;
10use zeroize::Zeroizing;
11
12const KIND: u8 = crate::kinds::HANDOVER;
13const PREFIX_LEN: usize = 3;
14// The plaintext is the member id, then the pair as a length-prefixed blob.
15const PLAINTEXT_LEN: usize = 16 + 4 + MemberKeys::SECRET_LEN;
16/// A handover's complete length in bytes.
17pub const LENGTH: usize = PREFIX_LEN + KEY_BOX_HEAD_LEN + PLAINTEXT_LEN + KEY_BOX_TAG_LEN;
18
19/// What the approving write puts at the request's path in the request's place
20/// (ยง13.2). It is one anonymous box with no chunks and no signature: the box
21/// authenticates every byte, and the pair it carries proves nothing until the
22/// new device's loading checks it against history.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct Handover {
25    /// The box's ephemeral key, nonce, ciphertext and tag.
26    sealed: Vec<u8>,
27}
28
29impl Handover {
30    /// Seal `member`'s private pair to the sealing key of the request at
31    /// `path`. The bytes are fixed here; a retry of the create repeats them.
32    pub fn seal(
33        member: MemberId,
34        keys: &MemberKeys,
35        recipient: &SealingKey,
36        path: &ObjectPath,
37    ) -> Result<Self, CryptoError> {
38        let blob = keys.to_secret_bytes();
39        let mut plaintext = Zeroizing::new(Vec::with_capacity(PLAINTEXT_LEN));
40        plaintext.extend_from_slice(member.0.as_bytes());
41        plaintext.extend_from_slice(&(blob.as_bytes().len() as u32).to_be_bytes());
42        plaintext.extend_from_slice(blob.as_bytes());
43        let prefix = crate::FormatVersion::CURRENT.prefix(KIND);
44        let sealed = seal_handover(&plaintext, recipient, path.as_str(), &prefix)?;
45        Ok(Self { sealed })
46    }
47
48    /// The object's complete bytes: its kind and format, then the box.
49    pub fn encode(&self) -> Vec<u8> {
50        let mut bytes = Vec::with_capacity(LENGTH);
51        bytes.extend_from_slice(&crate::FormatVersion::CURRENT.prefix(KIND));
52        bytes.extend_from_slice(&self.sealed);
53        bytes
54    }
55
56    /// Read a handover. Bytes of another kind, such as a join request or an
57    /// ended pairing's marker, fail with `UnknownTag`; one of another length
58    /// is truncated or has trailing bytes.
59    pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
60        crate::sealed::prefix(bytes, KIND)?;
61        exact_length(bytes.len(), LENGTH)?;
62        Ok(Self { sealed: bytes[PREFIX_LEN..].to_vec() })
63    }
64
65    /// Open it at `path` with the pair the request carried the sealing key of.
66    /// Returns the member whose pair it is and the pair; the caller requires
67    /// the member to be the pairing's and loading to check the pair.
68    #[expect(
69        clippy::map_err_ignore,
70        reason = "a sealed value whose pair does not decode is malformed as a whole"
71    )]
72    pub fn open(
73        &self,
74        path: &ObjectPath,
75        asking: &MemberKeys,
76    ) -> Result<(MemberId, MemberKeys), CryptoError> {
77        let prefix = crate::FormatVersion::CURRENT.prefix(KIND);
78        let plaintext = asking.open_handover(path.as_str(), &prefix, &self.sealed)?;
79        let (member, rest) = plaintext.split_first_chunk::<16>().ok_or(CryptoError::Malformed)?;
80        let (length, rest) = rest.split_first_chunk::<4>().ok_or(CryptoError::Malformed)?;
81        if u32::from_be_bytes(*length) as usize != rest.len() {
82            return Err(CryptoError::Malformed);
83        }
84        let keys = MemberKeys::from_secret_bytes(rest).map_err(|_| CryptoError::Malformed)?;
85        Ok((MemberId(uuid::Uuid::from_bytes(*member)), keys))
86    }
87}
88
89#[cfg(test)]
90#[path = "handover_tests.rs"]
91mod tests;