capsule_core/enrollment.rs
1//! The wire form of the cross-device add ceremony (SSoT: [Device Enrollment § Cross-Device
2//! Add]): what each device advertises, the payloads they relay, and the safety code over them.
3//!
4//! The server leg (code issue/redeem, the relay channel, close) carries **opaque strings**; this
5//! module defines what goes inside them. The ceremony, in relay order:
6//!
7//! 1. enrollee B → initiator A: [`EnrollmentPayload::Commitment`] to B's [`EnrolleeKeys`];
8//! 2. A → B: [`EnrollmentPayload::InitiatorKeys`], carrying a fresh nonce;
9//! 3. B → A: [`EnrollmentPayload::EnrolleeKeys`], which A checks against the commitment
10//! ([`EnrolleeKeys::matches_commitment`]);
11//! 4. both display [`enrollment_safety_code`] over what they hold and the user compares them;
12//! 5. A admits B with `Workspace::cross_sign_device` (`capsule-library`) and sends
13//! [`EnrollmentPayload::Directory`], which B verifies under the user IK.
14//!
15//! The commit-before-reveal order in steps 1–3, over inputs that each carry a fresh per-ceremony
16//! nonce, is what makes a twelve-digit code sound against a man in the middle (see
17//! the safety-code module, `crypto::keys::safety_code`). Each side therefore draws its
18//! bundle **once per ceremony** and keeps the one it sent: a second call draws a new nonce, and
19//! so a different code. The master-key transfer under a
20//! channel key (design step 5) is not here: the channel's ephemeral key agreement is not yet
21//! defined.
22//!
23//! ## Wire form
24//!
25//! A payload is canonical CBOR of `{ "v": 1, "payload": <tagged payload> }`, written as
26//! lowercase hex — the relay's field is a JSON string, and hex needs no new dependency. Decoding
27//! refuses anything that does not re-encode to the exact same string, so every payload has one
28//! spelling and a key set hashes to one safety code.
29//!
30//! [Device Enrollment § Cross-Device Add]: https://docs/design/device-enrollment/#cross-device-add
31
32use serde::{Deserialize, Serialize};
33use thiserror::Error;
34use uuid::Uuid;
35
36use crate::crypto::keys::{
37 DekPublic, DeviceDirectory, DeviceEntry, HybridVerifyingKey, KEY_COMMITMENT_LEN,
38 commitment_matches, key_commitment, safety_code,
39};
40
41/// The payload format version this build writes and the only one it reads.
42pub const ENROLLMENT_PAYLOAD_VERSION: u8 = 1;
43
44/// The longest encoded payload this build writes or reads, in characters — the relay's own
45/// per-payload ceiling, so a payload this side accepts is one the relay would have carried.
46pub const MAX_ENROLLMENT_PAYLOAD_CHARS: usize = 64 * 1024;
47
48/// The length of each side's per-ceremony nonce. Device keys are static — the initiator's are
49/// already published — so without fresh randomness on both sides a man in the middle could
50/// predict one side's input and grind the code offline.
51pub const ENROLLMENT_NONCE_LEN: usize = 32;
52
53/// What the **initiator** (the enrolled device A) advertises: the account it is adding to, the
54/// identity key the directory it will send verifies under, and its own device signing key.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct InitiatorKeys {
57 /// The account's user id.
58 pub user_id: Uuid,
59 /// The user identity public key — the key B verifies the cross-signed directory under.
60 pub user_ik_public: HybridVerifyingKey,
61 /// The initiator's device id.
62 pub device_id: Uuid,
63 /// The initiator's device signing public key.
64 pub dsk_public: HybridVerifyingKey,
65 /// Fresh random bytes drawn for this ceremony alone, which the safety code covers. Revealed
66 /// only after the enrollee has committed, so a man in the middle commits toward A before it
67 /// can know what A's input to the code will be.
68 #[serde(with = "serde_bytes")]
69 pub nonce: [u8; ENROLLMENT_NONCE_LEN],
70}
71
72impl InitiatorKeys {
73 /// The canonical bytes the safety code is derived over.
74 pub fn canonical_bytes(&self) -> Vec<u8> {
75 crate::cbor::to_canonical_vec(self).expect("initiator keys serialize")
76 }
77}
78
79/// What the **enrollee** (the new device B) advertises: the public halves of the device keys it
80/// generated, which A cross-signs into the directory.
81///
82/// The DEK is required, not optional: a device admitted without one could never be wrapped to,
83/// so it could not join a single album.
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85pub struct EnrolleeKeys {
86 /// The enrollee's device id.
87 pub device_id: Uuid,
88 /// The enrollee's device signing public key.
89 pub dsk_public: HybridVerifyingKey,
90 /// The enrollee's device encryption public key.
91 pub dek_public: DekPublic,
92 /// Fresh random bytes drawn for this ceremony alone, which the commitment and the safety code
93 /// cover. Hidden under the commitment until A has revealed, so B's input stays unpredictable
94 /// even when its keys are known (a retried ceremony has already revealed them).
95 #[serde(with = "serde_bytes")]
96 pub nonce: [u8; ENROLLMENT_NONCE_LEN],
97}
98
99impl EnrolleeKeys {
100 /// The canonical bytes the safety code and the commitment are derived over.
101 pub fn canonical_bytes(&self) -> Vec<u8> {
102 crate::cbor::to_canonical_vec(self).expect("enrollee keys serialize")
103 }
104
105 /// The commitment B sends before A reveals its keys.
106 pub fn commitment(&self) -> [u8; KEY_COMMITMENT_LEN] {
107 key_commitment(&self.canonical_bytes())
108 }
109
110 /// Whether these revealed keys are the ones `commitment` was made to.
111 pub fn matches_commitment(&self, commitment: &[u8; KEY_COMMITMENT_LEN]) -> bool {
112 commitment_matches(commitment, &self.canonical_bytes())
113 }
114
115 /// The directory entry A cross-signs for these keys. `added_at` is the initiator's clock,
116 /// never the enrollee's claim: it bounds which manifests the new device can have signed.
117 pub fn into_device_entry(self, added_at: String) -> DeviceEntry {
118 DeviceEntry {
119 device_id: self.device_id,
120 dsk_public: self.dsk_public,
121 dek_public: Some(self.dek_public),
122 added_at,
123 revoked_at: None,
124 unknown: Default::default(),
125 }
126 }
127}
128
129/// The safety code both devices display, over the initiator's and the enrollee's advertised
130/// keys as each side received them.
131pub fn enrollment_safety_code(initiator: &InitiatorKeys, enrollee: &EnrolleeKeys) -> String {
132 safety_code(&initiator.canonical_bytes(), &enrollee.canonical_bytes())
133}
134
135/// One message relayed between the two devices.
136///
137/// Variants are held inline rather than boxed: a ceremony relays four of them, once, so the
138/// size spread clippy flags costs nothing and boxing would only burden every caller's match.
139#[allow(clippy::large_enum_variant)]
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(rename_all = "snake_case")]
142pub enum EnrollmentPayload {
143 /// B → A, first: the commitment to B's [`EnrolleeKeys`].
144 Commitment(#[serde(with = "serde_bytes")] [u8; KEY_COMMITMENT_LEN]),
145 /// A → B: what A advertises.
146 InitiatorKeys(InitiatorKeys),
147 /// B → A, after A's keys: the keys B committed to.
148 EnrolleeKeys(EnrolleeKeys),
149 /// A → B, last: the cross-signed directory that admits B.
150 Directory(DeviceDirectory),
151}
152
153#[derive(Serialize, Deserialize)]
154struct Envelope {
155 v: u8,
156 payload: EnrollmentPayload,
157}
158
159/// Why a relayed payload could not be encoded or decoded.
160#[derive(Debug, Clone, PartialEq, Eq, Error)]
161pub enum EnrollmentPayloadError {
162 /// Longer than [`MAX_ENROLLMENT_PAYLOAD_CHARS`], or empty.
163 #[error("enrollment payload is {0} characters; it must be 1..={MAX_ENROLLMENT_PAYLOAD_CHARS}")]
164 Size(usize),
165 /// Not hex, not CBOR, or not a payload this build knows.
166 #[error("enrollment payload is malformed: {0}")]
167 Malformed(String),
168 /// A payload version this build does not read.
169 #[error("enrollment payload version {0} is not supported")]
170 UnsupportedVersion(u8),
171 /// Decodes, but is not the one canonical spelling of its value.
172 #[error("enrollment payload is not canonically encoded")]
173 NonCanonical,
174}
175
176impl EnrollmentPayload {
177 /// Encode this payload as the string the relay carries.
178 pub fn encode(&self) -> std::result::Result<String, EnrollmentPayloadError> {
179 let envelope = Envelope {
180 v: ENROLLMENT_PAYLOAD_VERSION,
181 payload: self.clone(),
182 };
183 let bytes = crate::cbor::to_canonical_vec(&envelope)
184 .map_err(|e| EnrollmentPayloadError::Malformed(e.to_string()))?;
185 let encoded = hex::encode(bytes);
186 if encoded.len() > MAX_ENROLLMENT_PAYLOAD_CHARS {
187 tracing::warn!(
188 chars = encoded.len(),
189 "enrollment: payload exceeds the relay ceiling"
190 );
191 return Err(EnrollmentPayloadError::Size(encoded.len()));
192 }
193 tracing::trace!(chars = encoded.len(), "enrollment: encoded a payload");
194 Ok(encoded)
195 }
196
197 /// Decode a relayed string. The relay is untrusted, so anything but a canonical payload of
198 /// this build's version is refused rather than tolerated.
199 pub fn decode(encoded: &str) -> std::result::Result<Self, EnrollmentPayloadError> {
200 if encoded.is_empty() || encoded.len() > MAX_ENROLLMENT_PAYLOAD_CHARS {
201 return Err(EnrollmentPayloadError::Size(encoded.len()));
202 }
203 let bytes =
204 hex::decode(encoded).map_err(|e| EnrollmentPayloadError::Malformed(e.to_string()))?;
205 let value: ciborium::Value = crate::cbor::from_slice(&bytes)
206 .map_err(|e| EnrollmentPayloadError::Malformed(e.to_string()))?;
207 // Read the version before the body, so a newer build's payload is reported as a version
208 // mismatch rather than as whatever its unfamiliar body fails to parse as.
209 let version = value
210 .as_map()
211 .and_then(|m| m.iter().find(|(k, _)| k.as_text() == Some("v")))
212 .and_then(|(_, v)| v.as_integer())
213 .and_then(|v| u8::try_from(v).ok())
214 .ok_or_else(|| EnrollmentPayloadError::Malformed("missing version".into()))?;
215 if version != ENROLLMENT_PAYLOAD_VERSION {
216 tracing::warn!(version, "enrollment: unsupported payload version");
217 return Err(EnrollmentPayloadError::UnsupportedVersion(version));
218 }
219 let envelope: Envelope = crate::cbor::from_slice(&bytes)
220 .map_err(|e| EnrollmentPayloadError::Malformed(e.to_string()))?;
221 if envelope.payload.encode()? != encoded {
222 tracing::warn!("enrollment: refusing a non-canonical payload");
223 return Err(EnrollmentPayloadError::NonCanonical);
224 }
225 Ok(envelope.payload)
226 }
227}
228
229#[cfg(test)]
230mod tests;