Skip to main content

coven_format/
sealed_slot.rs

1//! Clear slot routing and bounded slot envelopes (D9). Writes stream separately.
2
3use crate::admin::StoreChange;
4use crate::error::{bound, exact_length, require, Error, Rule};
5use crate::sealed;
6use crate::sealed_key::{CopyBox, KeyCopyPrefix};
7use crate::sequence::{SlotFrame, MAX_BOUNDED_SLOT};
8use crate::wire::{Decoder, Encoder, Wire};
9use coven_crypto::{
10    CircleKey, Signature, StoreKey, KEY_BOX_HEAD_LEN, KEY_BOX_TAG_LEN,
11    SEALED_OBJECT_CHUNK_OVERHEAD, SIGNATURE_LEN,
12};
13use coven_foundation::id_source::KeyId;
14
15/// Where a key box sits in its slot's clear prefix, which its context binds
16/// (D9, D11).
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum BoxPlace {
19    /// The one box of a key-copy slot.
20    KeyCopy,
21    /// The box at this index of an admission's copies.
22    Admission(u32),
23    /// An admission's own copy: the joining member's circle key, sealed by
24    /// the joining phone before any slot was known, so its context binds the
25    /// store and routing rather than the slot (D11).
26    Own,
27}
28
29/// Slot kind and the routing which exists only for key-copy slots and
30/// admissions.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub enum SlotKind {
33    /// One admin operation.
34    Admin,
35    /// One device's queued inner writes.
36    Writes,
37    /// A recipient's anonymous box.
38    KeyCopy(CopyBox),
39    /// An immutable snapshot's announcement.
40    Announcement,
41    /// The entry admitting a member and registering their first device, or
42    /// creating the store and its first admin, with that member's boxes, all
43    /// to one recipient and sealing key, in increasing `(audience, key)`
44    /// order (§10.3, §13.2).
45    Admission {
46        /// The member's copies of the keys introduced before the slot.
47        copies: Vec<CopyBox>,
48        /// An admitted member's copy of their new circle's key, as the
49        /// request carried it, after the others; a creation has none.
50        own: Option<CopyBox>,
51    },
52}
53impl SlotKind {
54    /// The D9 kind byte.
55    pub fn tag(&self) -> u8 {
56        match self {
57            Self::Admin => 0,
58            Self::Writes => 1,
59            Self::KeyCopy(_) => 2,
60            Self::Announcement => 3,
61            Self::Admission { .. } => 4,
62        }
63    }
64    /// The key boxes the clear prefix carries, each with its place.
65    pub fn boxes(&self) -> impl Iterator<Item = (BoxPlace, &CopyBox)> {
66        let (single, many) = match self {
67            Self::KeyCopy(copy) => (Some(copy), &[][..]),
68            Self::Admission { copies, .. } => (None, &copies[..]),
69            Self::Admin | Self::Writes | Self::Announcement => (None, &[][..]),
70        };
71        let own = match self {
72            Self::Admission { own: Some(own), .. } => Some((BoxPlace::Own, own)),
73            _ => None,
74        };
75        single
76            .map(|copy| (BoxPlace::KeyCopy, copy))
77            .into_iter()
78            .chain(
79                many.iter()
80                    .enumerate()
81                    .map(|(index, copy)| (BoxPlace::Admission(index as u32), copy)),
82            )
83            .chain(own)
84    }
85    /// Check the opened second frame against the clear kind. Only an
86    /// admission holds an admit-member, recover-member or create-store
87    /// change, and it holds nothing else (D6).
88    pub fn check_frame(&self, frame: &SlotFrame) -> Result<(), Error> {
89        let admits = matches!(
90            frame,
91            SlotFrame::Admin(
92                StoreChange::AdmitMember { .. }
93                    | StoreChange::RecoverMember { .. }
94                    | StoreChange::CreateStore { .. }
95            )
96        );
97        require(
98            match (self, frame) {
99                (Self::Admin, SlotFrame::Admin(_)) => !admits,
100                (Self::Admission { .. }, SlotFrame::Admin(_)) => admits,
101                (Self::KeyCopy(_), SlotFrame::KeyCopy)
102                | (Self::Announcement, SlotFrame::Announcement(_)) => true,
103                _ => false,
104            },
105            "slot kind",
106            Rule::Kind,
107        )
108    }
109}
110
111/// An admission's boxes: at least one copy and the member's own circle box,
112/// all to one recipient and sealing key, the copies in strictly increasing
113/// `(audience, key)` order, and the own box for a circle (D9).
114fn check_copies(copies: &[CopyBox], own: Option<&CopyBox>) -> Result<(), Error> {
115    require(!copies.is_empty(), "admission copies", Rule::Required)?;
116    let first = &copies[0];
117    require(
118        copies.iter().chain(own).all(|copy| {
119            copy.routing.member == first.routing.member
120                && copy.routing.sealing == first.routing.sealing
121        }),
122        "admission copy recipient",
123        Rule::Recipient,
124    )?;
125    require(
126        own.is_none_or(|own| matches!(own.routing.audience, coven_merge::Audience::Circle(_))),
127        "admission own copy",
128        Rule::Audience,
129    )?;
130    require(
131        copies.windows(2).all(|pair| {
132            (&pair[0].routing.audience, pair[0].routing.key)
133                < (&pair[1].routing.audience, pair[1].routing.key)
134        }),
135        "admission copy order",
136        Rule::Order,
137    )
138}
139
140/// The complete clear routing, without any device, claim number or part audience.
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct SlotObjectPrefix {
143    /// The recorded format of this claim attempt.
144    pub format: crate::FormatVersion,
145    /// The store key sealing the body.
146    pub key: KeyId,
147    /// Kind and any key boxes.
148    pub kind: SlotKind,
149}
150impl SlotObjectPrefix {
151    /// Longest prefix of any slot but an admission, including a circle key
152    /// copy. An admission's prefix is bounded only by its slot's 4 MiB.
153    pub const MAX_LENGTH: usize = Self::FIXED_LEN
154        + KeyCopyPrefix::CIRCLE_LEN
155        + KEY_BOX_HEAD_LEN
156        + 4
157        + CircleKey::ENCODED_LEN
158        + KEY_BOX_TAG_LEN;
159    /// Kind, version, slot kind, key and the copy flag, before any box.
160    const FIXED_LEN: usize = 1 + 2 + 1 + 16 + 1;
161    /// Encode the exact associated-data prefix, including any anonymous box.
162    pub fn encode(&self) -> Result<Vec<u8>, Error> {
163        let mut out = self.start()?;
164        match &self.kind {
165            SlotKind::KeyCopy(copy) => {
166                1u8.put(&mut out)?;
167                copy.put(&mut out)?;
168            }
169            SlotKind::Admission { copies, own } => {
170                check_copies(copies, own.as_ref())?;
171                copies.put(&mut out)?;
172                own.put(&mut out)?;
173            }
174            SlotKind::Admin | SlotKind::Writes | SlotKind::Announcement => 0u8.put(&mut out)?,
175        }
176        Ok(out.bytes)
177    }
178    fn start(&self) -> Result<Encoder, Error> {
179        let mut out = Encoder::new();
180        out.bytes(&self.format.prefix(crate::kinds::SEQUENCE_SLOT))?;
181        self.kind.tag().put(&mut out)?;
182        self.key.put(&mut out)?;
183        Ok(out)
184    }
185    /// Box context through the recipient's sealing key, before generating its
186    /// ephemeral key and ciphertext: the slot's fixed fields, the box's place
187    /// and its routing. This context binds the slot path in crypto.
188    pub fn copy_context(
189        format: crate::FormatVersion,
190        key: KeyId,
191        place: BoxPlace,
192        routing: &KeyCopyPrefix,
193    ) -> Result<Vec<u8>, Error> {
194        let mut out = Encoder::new();
195        out.bytes(&format.prefix(crate::kinds::SEQUENCE_SLOT))?;
196        match place {
197            BoxPlace::KeyCopy => {
198                2u8.put(&mut out)?;
199                key.put(&mut out)?;
200                1u8.put(&mut out)?;
201            }
202            BoxPlace::Admission(index) => {
203                4u8.put(&mut out)?;
204                key.put(&mut out)?;
205                index.put(&mut out)?;
206            }
207            // The own copy's context binds no slot: `own_binding` is its.
208            BoxPlace::Own => return Err(Error::Invalid { field: "box place", rule: Rule::Kind }),
209        }
210        routing.put(&mut out)?;
211        Ok(out.bytes)
212    }
213    /// What an admission's own copy is sealed and opened with: the store and
214    /// the box's routing. The joining phone knows both when it makes its
215    /// request, and neither the slot nor its path (D11).
216    pub fn own_binding(
217        store: coven_foundation::id_source::StoreId,
218        routing: &KeyCopyPrefix,
219    ) -> Result<Vec<u8>, Error> {
220        let mut out = Encoder::new();
221        store.put(&mut out)?;
222        routing.put(&mut out)?;
223        Ok(out.bytes)
224    }
225    /// Whether the prefix `bytes` begins is an admission's, whose length only
226    /// its whole bounded slot bounds. It reads the first four bytes.
227    pub fn admission(bytes: &[u8]) -> Result<bool, Error> {
228        sealed::prefix(bytes, crate::kinds::SEQUENCE_SLOT)?;
229        Ok(*bytes.get(3).ok_or(Error::Truncated)? == 4)
230    }
231    /// Bound the clear prefix before reading its boxes. No length supplied by
232    /// a peer can enlarge the fixed store/circle box sizes.
233    pub fn length(bytes: &[u8]) -> Result<usize, Error> {
234        sealed::prefix(bytes, crate::kinds::SEQUENCE_SLOT)?;
235        let kind = *bytes.get(3).ok_or(Error::Truncated)?;
236        require(kind <= 4, "slot kind", Rule::Kind)?;
237        if kind == 4 {
238            let start = Self::FIXED_LEN - 1;
239            let count = bytes.get(start..start + 4).ok_or(Error::Truncated)?;
240            let count = u32::from_be_bytes(count.try_into().expect("four bytes")) as usize;
241            require(count > 0, "admission copies", Rule::Required)?;
242            bound(count, crate::wire::MAX_ITEMS, "admission copies")?;
243            let mut end = start + 4;
244            for _ in 0..count {
245                end = box_end(bytes, end)?;
246            }
247            // The member's own circle box, if any, follows the copies.
248            return match *bytes.get(end).ok_or(Error::Truncated)? {
249                0 => Ok(end + 1),
250                1 => box_end(bytes, end + 1),
251                tag => Err(Error::UnknownTag { field: "own copy", tag }),
252            };
253        }
254        let copy = *bytes.get(Self::FIXED_LEN - 1).ok_or(Error::Truncated)?;
255        require(copy == u8::from(kind == 2), "slot copy routing", Rule::Kind)?;
256        if kind != 2 {
257            return Ok(Self::FIXED_LEN);
258        }
259        box_end(bytes, Self::FIXED_LEN)
260    }
261    /// Decode exactly the prefix, without authenticating routing.
262    pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
263        exact_length(bytes.len(), Self::length(bytes)?)?;
264        let mut input = Decoder::new(&bytes[4..])?;
265        let key = KeyId::get(&mut input)?;
266        let kind = match bytes[3] {
267            4 => {
268                let copies = Vec::<CopyBox>::get(&mut input)?;
269                let own = Option::<CopyBox>::get(&mut input)?;
270                check_copies(&copies, own.as_ref())?;
271                SlotKind::Admission { copies, own }
272            }
273            tag => {
274                let copy = Option::<CopyBox>::get(&mut input)?;
275                match tag {
276                    0 => SlotKind::Admin,
277                    1 => SlotKind::Writes,
278                    2 => SlotKind::KeyCopy(copy.expect("copy tag checked")),
279                    3 => SlotKind::Announcement,
280                    _ => unreachable!("kind checked"),
281                }
282            }
283        };
284        input.finish()?;
285        Ok(Self { format: crate::FormatVersion::decode(bytes)?, key, kind })
286    }
287    /// Whether the complete bounded slot with this prefix and `plaintext`
288    /// bytes of frames stays within its 4-MiB limit, signature included (D2).
289    /// An operation checks it before it claims anything.
290    pub fn fits(&self, plaintext: usize) -> Result<bool, Error> {
291        Ok(bound(
292            Self::bounded_size(self.encode()?.len(), plaintext + SEALED_OBJECT_CHUNK_OVERHEAD),
293            MAX_BOUNDED_SLOT,
294            "slot object",
295        )
296        .is_ok())
297    }
298    /// The complete bounded slot's size: its prefix, the chunk's length
299    /// field and bytes, and the signature.
300    fn bounded_size(prefix: usize, chunk: usize) -> usize {
301        prefix + 4 + chunk + SIGNATURE_LEN
302    }
303    /// Frame the sole sealed chunk of an admin, admission, copy or
304    /// announcement slot.
305    /// Checks the complete 4-MiB limit including the eventual signature.
306    pub fn encode_chunk(&self, chunk: &[u8]) -> Result<Vec<u8>, Error> {
307        require(!matches!(self.kind, SlotKind::Writes), "bounded slot kind", Rule::Kind)?;
308        let mut bytes = self.encode()?;
309        let length =
310            chunk.len().checked_sub(SEALED_OBJECT_CHUNK_OVERHEAD).ok_or(Error::Truncated)?;
311        require(length >= 2 * crate::FRAME_PREFIX_LEN, "slot frames", Rule::Chunk)?;
312        bound(Self::bounded_size(bytes.len(), chunk.len()), MAX_BOUNDED_SLOT, "slot object")?;
313        bytes.extend_from_slice(&sealed::encode_chunk(chunk)?);
314        Ok(bytes)
315    }
316}
317
318/// Where the box that starts at `start` ends: its routing, whose audience
319/// fixes the key material's length, the ephemeral key and nonce, the declared
320/// ciphertext length, the ciphertext and the tag.
321fn box_end(bytes: &[u8], start: usize) -> Result<usize, Error> {
322    let (routing, ciphertext) = match *bytes.get(start).ok_or(Error::Truncated)? {
323        0 => (KeyCopyPrefix::STORE_LEN, StoreKey::ENCODED_LEN),
324        1 => (KeyCopyPrefix::CIRCLE_LEN, CircleKey::ENCODED_LEN),
325        tag => return Err(Error::UnknownTag { field: "audience", tag }),
326    };
327    let offset = start + routing + KEY_BOX_HEAD_LEN;
328    let declared = bytes.get(offset..offset + 4).ok_or(Error::Truncated)?;
329    require(
330        u32::from_be_bytes(declared.try_into().expect("four bytes")) as usize == ciphertext,
331        "key box ciphertext",
332        Rule::StreamLength,
333    )?;
334    Ok(offset + 4 + ciphertext + KEY_BOX_TAG_LEN)
335}
336
337/// One complete bounded slot envelope; cryptographic verification is separate.
338#[derive(Debug)]
339pub struct BoundedSlot<'a> {
340    /// Clear routing covered by both chunk authentication and final signature.
341    pub prefix: SlotObjectPrefix,
342    /// Stored nonce, ciphertext and tag.
343    pub chunk: &'a [u8],
344    /// Signature over every preceding byte, bound to the slot path.
345    pub signature: Signature,
346}
347impl<'a> BoundedSlot<'a> {
348    /// Decode without allocating the body.
349    pub fn decode(bytes: &'a [u8]) -> Result<Self, Error> {
350        bound(bytes.len(), MAX_BOUNDED_SLOT, "slot object")?;
351        let prefix_length = SlotObjectPrefix::length(bytes)?;
352        let prefix = SlotObjectPrefix::decode(bytes.get(..prefix_length).ok_or(Error::Truncated)?)?;
353        require(!matches!(prefix.kind, SlotKind::Writes), "bounded slot kind", Rule::Kind)?;
354        let body = &bytes[prefix_length..];
355        let length = sealed::chunk_length(body, MAX_BOUNDED_SLOT)?;
356        let chunk = body.get(4..length).ok_or(Error::Truncated)?;
357        require(
358            chunk.len() >= SEALED_OBJECT_CHUNK_OVERHEAD + 2 * crate::FRAME_PREFIX_LEN,
359            "slot frames",
360            Rule::Chunk,
361        )?;
362        let signature = sealed::signature(body.get(length..).ok_or(Error::Truncated)?)?;
363        Ok(Self { prefix, chunk, signature })
364    }
365    /// Reproduce the original sealed envelope.
366    pub fn encode(&self) -> Result<Vec<u8>, Error> {
367        let mut bytes = self.prefix.encode_chunk(self.chunk)?;
368        bytes.extend_from_slice(self.signature.as_bytes());
369        Ok(bytes)
370    }
371}
372
373#[cfg(test)]
374#[path = "sealed_slot_tests.rs"]
375mod tests;