Skip to main content

capsule_core/crypto/keys/
directory.rs

1//! The signed device directory: how peers learn which device public keys to trust for a
2//! user, and the anti-rollback `directory_version` (SSoT: [Cryptography — Keys § Device
3//! Directory]).
4//!
5//! Each user publishes a directory listing their devices' public halves — the hybrid **DSK**
6//! (signing) and the **DEK** (key encapsulation) — master-signed (here, by the user IK). That
7//! one IK signature over the canonical core is the cross-signature the design means by "both are
8//! signed by the IK": it is what lets a peer trust a device key it has never seen, for
9//! *encryption* ([`DeviceEntry::encapsulate`]) as much as for verification.
10//!
11//! `verify_asset` reads the directory to resolve the `created_by_device` of a manifest and to
12//! enforce that a device's `added_at` precedes the manifest timestamp. The monotonic
13//! `directory_version` lets readers refuse a rolled-back directory (a server hiding a
14//! revocation).
15//!
16//! ## Wire presence is signature-visible here
17//!
18//! `DirectoryCore::signing_bytes` is the canonical CBOR of the *whole* core, so every field of
19//! every [`DeviceEntry`] is inside the IK-signed bytes and field **presence** is part of the
20//! signature — exactly as it is for an [asset manifest](crate::crypto::provenance::AssetManifest).
21//! [`DeviceEntry::dek_public`] is therefore an **absent-key** optional
22//! (`skip_serializing_if = "Option::is_none"`): a present-`null` encoding would change
23//! `signing_bytes()` for every entry that has no DEK and silently break re-verification of every
24//! directory signed before the field existed, including the cross-platform fixtures.
25//! `added_at`/`revoked_at` predate that rule and keep their legacy present-`null` encoding — the
26//! directory carries both conventions, and reconciling them would itself be a signature-visible
27//! change to already-signed entries, not a cleanup.
28//!
29//! [Cryptography — Keys § Device Directory]: https://docs/design/cryptography/keys/#device-directory
30
31use std::collections::BTreeMap;
32
33use ciborium::value::Value;
34use serde::{Deserialize, Serialize};
35use uuid::Uuid;
36
37use super::hybrid_sig::{HybridSignature, HybridSigningKey, HybridVerifyingKey};
38use super::kem::{DEK_PUBLIC_LEN, encapsulate_to_public};
39use super::kem_p256::{DEK_P256_PUBLIC_LEN, encapsulate_to_p256_public};
40use crate::cbor::OpenMap;
41use crate::crypto::CryptoError;
42
43/// A device's published **DEK** public encapsulation key: the bytes a peer wraps a key to so
44/// that only that device can open it (SSoT: [Cryptography — Keys § Device Keys]).
45///
46/// ## One field, both compositions, discriminated by length
47///
48/// Capsule ships two DEK compositions and this single field carries either:
49///
50/// - the software **X-Wing** DEK, `pk_M ‖ pk_X` — [`DEK_PUBLIC_LEN`] (1216) bytes;
51/// - the hardware-bound **P-256 hybrid** DEK, `ek_M ‖ pk_P` — [`DEK_P256_PUBLIC_LEN`] (1249).
52///
53/// They are **length-disjoint by construction** (see [`P256HybridDek`](super::P256HybridDek)), so the
54/// composition is recovered from the bytes themselves and needs no tag — the same way a
55/// [`HybridVerifyingKey`] recovers its Ed25519-vs-P-256 classical half from the wire length, and
56/// the same way [`DeviceDek::public_bytes`](super::keystore::DeviceDek::public_bytes) already
57/// hands both compositions to callers as one opaque `Vec<u8>`. An explicit tag would be a second
58/// signature-covered source of truth that can *disagree* with the key bytes it labels; the length
59/// cannot, and a mismatched length is refused outright by [`DekPublic::encapsulate`].
60///
61/// Serializes as a CBOR **byte string** (major type 2) — never an array of integers — so
62/// canonical encodings are byte-identical across implementations.
63///
64/// [Cryptography — Keys § Device Keys]: https://docs/design/cryptography/keys/#device-keys
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct DekPublic(pub Vec<u8>);
67
68impl DekPublic {
69    /// The published key bytes.
70    pub fn as_bytes(&self) -> &[u8] {
71        &self.0
72    }
73
74    /// Encapsulate a fresh shared secret to this published key, returning the KEM ciphertext and
75    /// the 32-byte sender-side secret. The composition is selected by length; a key of any other
76    /// length is refused rather than guessed at.
77    pub fn encapsulate(&self) -> Result<(Vec<u8>, [u8; 32]), CryptoError> {
78        match self.0.len() {
79            DEK_PUBLIC_LEN => {
80                tracing::trace!(len = self.0.len(), "dek: encapsulating to an X-Wing DEK");
81                encapsulate_to_public(&self.0)
82            }
83            DEK_P256_PUBLIC_LEN => {
84                tracing::trace!(
85                    len = self.0.len(),
86                    "dek: encapsulating to a P-256 hybrid DEK"
87                );
88                encapsulate_to_p256_public(&self.0)
89            }
90            other => {
91                tracing::warn!(
92                    len = other,
93                    "dek: published key matches no known composition"
94                );
95                Err(CryptoError::Key(
96                    "published DEK length matches no known composition",
97                ))
98            }
99        }
100    }
101}
102
103impl Serialize for DekPublic {
104    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
105        s.serialize_bytes(&self.0)
106    }
107}
108
109impl<'de> Deserialize<'de> for DekPublic {
110    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
111        struct V;
112        impl<'de> serde::de::Visitor<'de> for V {
113            type Value = DekPublic;
114            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115                f.write_str("a device DEK public key as a byte string")
116            }
117            fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<DekPublic, E> {
118                Ok(DekPublic(v.to_vec()))
119            }
120            fn visit_seq<A: serde::de::SeqAccess<'de>>(
121                self,
122                mut seq: A,
123            ) -> Result<DekPublic, A::Error> {
124                // Tolerate decoders that surface a byte string as a sequence.
125                let mut out = Vec::new();
126                while let Some(b) = seq.next_element()? {
127                    out.push(b);
128                }
129                Ok(DekPublic(out))
130            }
131        }
132        d.deserialize_bytes(V)
133    }
134}
135
136/// One device's published entry. A revoked device's entry is **retained** (marked with
137/// `revoked_at`), never deleted, so manifests it signed before revocation stay verifiable.
138#[derive(Debug, Clone, PartialEq, Serialize)]
139pub struct DeviceEntry {
140    /// Stable device id.
141    pub device_id: Uuid,
142    /// The device signing key's hybrid public half.
143    pub dsk_public: HybridVerifyingKey,
144    /// The device encryption key's public half — what a peer encapsulates to.
145    ///
146    /// **Wire-absent when unpublished**, never a present `null`: the entry is inside the
147    /// IK-signed core, so presence is signature-visible (see the module docs). A device that has
148    /// not published a DEK encodes exactly the bytes it did before this field existed.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub dek_public: Option<DekPublic>,
151    /// RFC3339 time the device was added (must precede any manifest it signs).
152    pub added_at: String,
153    /// RFC3339 revocation time, if revoked.
154    pub revoked_at: Option<String>,
155    /// Keys a newer writer added that this build does not know, preserved verbatim and signed
156    /// over as part of the core. Empty (and so wire-absent) on everything this build writes.
157    ///
158    /// A key here must never collide with a known field name: the decoder only ever places the
159    /// keys it did not recognise here, and a caller building an entry by hand must do the same.
160    #[serde(flatten)]
161    pub unknown: BTreeMap<String, Value>,
162}
163
164// `Value` holds floats, so it is only `PartialEq`; see `ManifestCore` for why `Eq` stays.
165impl Eq for DeviceEntry {}
166
167impl<'de> Deserialize<'de> for DeviceEntry {
168    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
169        let mut m = OpenMap::deserialize("device entry", d)?;
170        Ok(Self {
171            device_id: m.take("device_id")?,
172            dsk_public: m.take("dsk_public")?,
173            dek_public: m.take_opt("dek_public")?,
174            added_at: m.take("added_at")?,
175            // Legacy present-`null`: an absent key and a `null` both read as `None`, exactly as
176            // the derived decoder did, and `None` re-emits as `null`.
177            revoked_at: m.take_opt("revoked_at")?,
178            unknown: m.into_unknown(),
179        })
180    }
181}
182
183impl DeviceEntry {
184    /// Encapsulate a fresh shared secret to **this published entry** — the whole point of
185    /// cross-signing the DEK: a peer holding nothing but an IK-verified directory can wrap a key
186    /// to a device it has never met.
187    ///
188    /// Refused (rather than silently mis-wrapped) when the device is **revoked** — the design
189    /// forbids delivering new key wraps to a revoked device — or when it has published no DEK.
190    pub fn encapsulate(&self) -> Result<(Vec<u8>, [u8; 32]), CryptoError> {
191        if self.revoked_at.is_some() {
192            tracing::debug!(device_id = %self.device_id, "dek: refusing to wrap to a revoked device");
193            return Err(CryptoError::Key("device is revoked"));
194        }
195        let dek = self
196            .dek_public
197            .as_ref()
198            .ok_or(CryptoError::Key("device publishes no DEK"))?;
199        dek.encapsulate()
200    }
201}
202
203/// The unsigned core of a directory — exactly the bytes the master signature covers.
204///
205/// **Unknown keys survive under the signature** ([Versioning — invariant 2]), here and in every
206/// [`DeviceEntry`]: a directory from a newer writer that only adds a key decodes, re-emits that
207/// key canonically, and so still verifies; stripping it fails verification.
208///
209/// [Versioning — invariant 2]: https://docs/design/versioning/#system-invariants
210#[derive(Debug, Clone, PartialEq, Serialize)]
211pub struct DirectoryCore {
212    /// Account owner.
213    pub user_id: Uuid,
214    /// Monotonic; +1 on every change. Readers refuse a version below their high-water mark.
215    pub directory_version: u64,
216    /// RFC3339 last-update time.
217    pub updated_at: String,
218    /// The user's devices.
219    pub devices: Vec<DeviceEntry>,
220    /// Keys a newer writer added that this build does not know, preserved verbatim and signed
221    /// over. Empty (and so wire-absent) on everything this build writes.
222    ///
223    /// A key here must never collide with a known field name: the decoder only ever places the
224    /// keys it did not recognise here, and a caller building a core by hand must do the same.
225    #[serde(flatten)]
226    pub unknown: BTreeMap<String, Value>,
227}
228
229// `Value` holds floats, so it is only `PartialEq`; see `ManifestCore` for why `Eq` stays.
230impl Eq for DirectoryCore {}
231
232impl<'de> Deserialize<'de> for DirectoryCore {
233    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
234        let mut m = OpenMap::deserialize("directory core", d)?;
235        Ok(Self {
236            user_id: m.take("user_id")?,
237            directory_version: m.take("directory_version")?,
238            updated_at: m.take("updated_at")?,
239            devices: m.take("devices")?,
240            unknown: m.into_unknown(),
241        })
242    }
243}
244
245/// Why a device could not be cross-signed into a directory.
246#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
247pub enum DirectoryError {
248    /// The directory already lists a device under this id — enrolling it again would leave two
249    /// entries a peer cannot choose between.
250    #[error("device {0} is already in the directory")]
251    DeviceAlreadyListed(Uuid),
252    /// The new entry's signing key is already published under another device id. One key under
253    /// two ids would let a manifest's `created_by_device` name either.
254    #[error("the signing key of device {new} is already published for device {existing}")]
255    SigningKeyAlreadyListed {
256        /// The id the new entry claims.
257        new: Uuid,
258        /// The device already publishing that key.
259        existing: Uuid,
260    },
261    /// The new entry is marked revoked; a device is enrolled live and revoked later, never
262    /// enrolled already revoked.
263    #[error("device {0} is marked revoked and cannot be enrolled")]
264    EntryRevoked(Uuid),
265    /// `directory_version` is at its ceiling, so no later version can be signed.
266    #[error("directory_version cannot advance past {0}")]
267    VersionExhausted(u64),
268}
269
270/// A master/IK-signed device directory.
271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
272pub struct DeviceDirectory {
273    /// The signed core.
274    pub core: DirectoryCore,
275    /// Hybrid signature by the user IK over the canonical core bytes.
276    pub signature: HybridSignature,
277}
278
279impl DirectoryCore {
280    fn signing_bytes(&self) -> Vec<u8> {
281        crate::cbor::to_canonical_vec(self).expect("directory core serializes")
282    }
283
284    /// Add a newly enrolled device's entry — the **cross-sign** step of a cross-device add — at
285    /// the next `directory_version`, stamping `updated_at`. Sign the result with
286    /// [`sign`](Self::sign) to publish it.
287    ///
288    /// Refused, leaving `self` unchanged, when the entry's id or signing key is already listed
289    /// (including on a revoked entry, which is retained so its past manifests stay verifiable),
290    /// when the entry arrives already revoked, or when the version cannot advance.
291    pub fn add_device(
292        &mut self,
293        entry: DeviceEntry,
294        updated_at: String,
295    ) -> Result<(), DirectoryError> {
296        if entry.revoked_at.is_some() {
297            return Err(DirectoryError::EntryRevoked(entry.device_id));
298        }
299        if self.devices.iter().any(|d| d.device_id == entry.device_id) {
300            return Err(DirectoryError::DeviceAlreadyListed(entry.device_id));
301        }
302        if let Some(existing) = self
303            .devices
304            .iter()
305            .find(|d| d.dsk_public == entry.dsk_public)
306        {
307            return Err(DirectoryError::SigningKeyAlreadyListed {
308                new: entry.device_id,
309                existing: existing.device_id,
310            });
311        }
312        let next = self
313            .directory_version
314            .checked_add(1)
315            .ok_or(DirectoryError::VersionExhausted(self.directory_version))?;
316        tracing::info!(
317            device_id = %entry.device_id,
318            directory_version = next,
319            "directory: cross-signing a device in"
320        );
321        self.directory_version = next;
322        self.updated_at = updated_at;
323        self.devices.push(entry);
324        Ok(())
325    }
326
327    /// Sign this core with the user IK, producing a [`DeviceDirectory`].
328    pub fn sign(self, ik: &HybridSigningKey) -> DeviceDirectory {
329        let signature = ik.sign(&self.signing_bytes());
330        DeviceDirectory {
331            core: self,
332            signature,
333        }
334    }
335}
336
337impl DeviceDirectory {
338    /// Verify the directory's signature against the user IK public key.
339    pub fn verify(&self, ik_public: &HybridVerifyingKey) -> bool {
340        ik_public.verify(&self.core.signing_bytes(), &self.signature)
341    }
342
343    /// Look up a device entry by id.
344    pub fn device(&self, device_id: &Uuid) -> Option<&DeviceEntry> {
345        self.core.devices.iter().find(|d| &d.device_id == device_id)
346    }
347}
348
349#[cfg(test)]
350mod tests;