Skip to main content

spoolframe_protocol/
passkeys.rs

1//! Passkeys in the apps (P3-19), each server through a relying party of
2//! its own under `spoolframe.app` (PX-14): [`ServerId::rp_id`].
3//!
4//! A platform's passkey API works only for a domain the app is associated
5//! with when it is built; a self-hosted server's own domain is not known
6//! then. So the apps make and use their passkeys for
7//! `<server id>.spoolframe.app`, which one association file at
8//! `spoolframe.app` covers, with a wildcard. Sign-in runs between the app
9//! and the server over this protocol; the server never contacts
10//! `spoolframe.app`.
11//!
12//! Every server once shared `spoolframe.app` itself ([`LEGACY_APP_RP_ID`]).
13//! A security key with passkeys for two servers then offered both to a
14//! sign-in that listed none, the platform took one, and the other server
15//! refused it. With a relying party per server, a key offers only that
16//! server's. Passkeys made for the shared one sign in nowhere now.
17//!
18//! Every server keeps its own passkeys, so a passkey made on one is
19//! refused by another. Each user has a random user handle per server, so
20//! one server's says nothing about the same person on another.
21//!
22//! The relying party comes from the server id the server names in
23//! `ServerInfo`, and a server may name another's. So the challenge still
24//! names the server by its key (PX-09, finding 2): a server sends a random
25//! nonce, never a challenge, and the challenge is [`app_passkey_challenge`]
26//! of the server's endpoint id and that nonce. The server computes it with
27//! its own id; the client with the id it pinned and dialled, never one the
28//! server names. A server that claims another's server id and hands on
29//! its nonce, to relay a sign-in, has the app sign a challenge for itself,
30//! which the other refuses.
31//!
32//! The bytes are WebAuthn's own, as the platform API gives and takes them;
33//! the app maps them to and from it and changes nothing.
34
35use std::fmt;
36
37use serde::{Deserialize, Serialize};
38use sha2::{Digest, Sha256};
39
40use crate::server_id::{APP_RP_DOMAIN, ServerId};
41
42/// The relying party every server's app passkeys were made for before
43/// each server had its own (PX-14). A passkey stored with it signs in
44/// nowhere now: its user adds it again.
45pub const LEGACY_APP_RP_ID: &str = APP_RP_DOMAIN;
46
47/// Whether a passkey made for `rp_id` was made in an app: for a server's
48/// relying party ([`ServerId::rp_id`]), or the one all shared before.
49pub fn is_app_rp_id(rp_id: &str) -> bool {
50    rp_id == LEGACY_APP_RP_ID
51        || rp_id
52            .strip_suffix(APP_RP_DOMAIN)
53            .and_then(|id| id.strip_suffix('.'))
54            .is_some_and(|id| ServerId::parse(id).is_ok())
55}
56
57/// Bytes of a nonce a server sends.
58pub const NONCE_LEN: usize = 32;
59
60/// What [`app_passkey_challenge`] hashes first, so its digest is of use
61/// for nothing else.
62const CHALLENGE_TAG: &[u8] = b"spoolframe/app-passkey-challenge/1";
63
64/// The WebAuthn challenge for an app passkey ceremony with the server
65/// whose endpoint id is `server`, from the `nonce` it sent: SHA-256 of
66/// `CHALLENGE_TAG`, the 32 bytes of the id, then the nonce. The tag and
67/// the id are of fixed length, so nothing else hashes the same.
68pub fn app_passkey_challenge(server: &[u8; 32], nonce: &[u8]) -> Vec<u8> {
69    Sha256::new()
70        .chain_update(CHALLENGE_TAG)
71        .chain_update(server)
72        .chain_update(nonce)
73        .finalize()
74        .to_vec()
75}
76
77/// A server's answer to `BeginPasskeyRegistration`, on the wire: a nonce,
78/// not a challenge. [`PasskeyRegistrationBegun::for_server`] makes the
79/// [`PasskeyCreation`] the platform is given.
80#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct PasskeyRegistrationBegun {
82    /// Of use once, for 5 minutes, from this device.
83    #[serde(with = "serde_bytes")]
84    pub nonce: Vec<u8>,
85    /// The user handle: random, this server's for this user.
86    #[serde(with = "serde_bytes")]
87    pub user_id: Vec<u8>,
88    /// As [`PasskeyCreation::user_name`].
89    pub user_name: String,
90    /// As [`PasskeyCreation::display_name`].
91    pub display_name: String,
92    /// As [`PasskeyCreation::exclude_credential_ids`].
93    #[serde(with = "byte_strings")]
94    pub exclude_credential_ids: Vec<Vec<u8>>,
95}
96
97impl PasskeyRegistrationBegun {
98    /// What the platform makes the passkey with, for the server whose
99    /// endpoint id is `server`, the one the client dialled, and whose
100    /// server id is `server_id`, the one it pinned with it.
101    pub fn for_server(self, server: &[u8; 32], server_id: &ServerId) -> PasskeyCreation {
102        PasskeyCreation {
103            rp_id: server_id.rp_id(),
104            origin: server_id.origin(),
105            challenge: app_passkey_challenge(server, &self.nonce),
106            user_id: self.user_id,
107            user_name: self.user_name,
108            display_name: self.display_name,
109            exclude_credential_ids: self.exclude_credential_ids,
110        }
111    }
112}
113
114/// A server's answer to `BeginPasskeySignIn` and `BeginConfirmPasskey`,
115/// on the wire: a nonce, not a challenge.
116/// [`PasskeySignInBegun::for_server`] makes the [`PasskeyRequest`] the
117/// platform is given.
118#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
119pub struct PasskeySignInBegun {
120    /// Of use once, for 5 minutes, from this device.
121    #[serde(with = "serde_bytes")]
122    pub nonce: Vec<u8>,
123    /// As [`PasskeyRequest::allow_credential_ids`]. Always empty for
124    /// `BeginPasskeySignIn`: anyone can begin one.
125    #[serde(with = "byte_strings")]
126    pub allow_credential_ids: Vec<Vec<u8>>,
127}
128
129impl PasskeySignInBegun {
130    /// What the platform signs, for the server whose endpoint id is
131    /// `server`, the one the client dialled, and whose server id is
132    /// `server_id`, the one it pinned with it.
133    pub fn for_server(self, server: &[u8; 32], server_id: &ServerId) -> PasskeyRequest {
134        PasskeyRequest {
135            rp_id: server_id.rp_id(),
136            origin: server_id.origin(),
137            challenge: app_passkey_challenge(server, &self.nonce),
138            allow_credential_ids: self.allow_credential_ids,
139        }
140    }
141}
142
143/// What making a passkey needs: the platform's options. User verification
144/// is required. Not on the wire: the client makes it from a
145/// [`PasskeyRegistrationBegun`].
146#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct PasskeyCreation {
148    /// The relying party to make it for: the server's,
149    /// `<server id>.spoolframe.app`. Never `spoolframe.app` itself.
150    pub rp_id: String,
151    /// The origin a platform that takes one writes into `clientDataJSON`:
152    /// `https://<server id>.spoolframe.app`. The server accepts no other.
153    pub origin: String,
154    /// To sign: [`app_passkey_challenge`] of the server and its nonce.
155    #[serde(with = "serde_bytes")]
156    pub challenge: Vec<u8>,
157    /// The user handle: random, this server's for this user.
158    #[serde(with = "serde_bytes")]
159    pub user_id: Vec<u8>,
160    /// The account's name in the platform's passkey list,
161    /// `<username> @ <server name>`: the relying party is an opaque id, so
162    /// the server's name says which server it is.
163    pub user_name: String,
164    /// The user's display name, or their username without one.
165    pub display_name: String,
166    /// The user's app passkeys on this server: an authenticator holding
167    /// one of these is not to make another.
168    #[serde(with = "byte_strings")]
169    pub exclude_credential_ids: Vec<Vec<u8>>,
170}
171
172/// A passkey made for a [`PasskeyCreation`], to keep
173/// (`FinishPasskeyRegistration`).
174#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
175pub struct FinishPasskeyRegistration {
176    #[serde(with = "serde_bytes")]
177    pub credential_id: Vec<u8>,
178    /// The attestation object (CBOR), as the platform gave it.
179    #[serde(with = "serde_bytes")]
180    pub attestation_object: Vec<u8>,
181    /// `clientDataJSON`, as the platform gave it.
182    #[serde(with = "serde_bytes")]
183    pub client_data_json: Vec<u8>,
184    /// What the device calls itself; the user's profile shows the passkey
185    /// as "Spoolframe app · \<name\>". 1 to 64 characters.
186    pub name: String,
187}
188
189/// What signing in with a passkey needs: the platform's options. Not on
190/// the wire: the client makes it from a [`PasskeySignInBegun`].
191#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
192pub struct PasskeyRequest {
193    /// The relying party to sign for, as [`PasskeyCreation::rp_id`].
194    pub rp_id: String,
195    /// The origin, as [`PasskeyCreation::origin`].
196    pub origin: String,
197    /// To sign: [`app_passkey_challenge`] of the server and its nonce.
198    #[serde(with = "serde_bytes")]
199    pub challenge: Vec<u8>,
200    /// The passkeys that may answer; empty: any the platform finds for
201    /// `rp_id` (a discoverable sign-in), so only this server's.
202    #[serde(with = "byte_strings")]
203    pub allow_credential_ids: Vec<Vec<u8>>,
204}
205
206/// A passkey's answer to a [`PasskeyRequest`] (`FinishPasskeySignIn`).
207#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
208pub struct FinishPasskeySignIn {
209    #[serde(with = "serde_bytes")]
210    pub credential_id: Vec<u8>,
211    #[serde(with = "serde_bytes")]
212    pub authenticator_data: Vec<u8>,
213    #[serde(with = "serde_bytes")]
214    pub client_data_json: Vec<u8>,
215    #[serde(with = "serde_bytes")]
216    pub signature: Vec<u8>,
217    /// The user handle the authenticator keeps with the passkey, or
218    /// `None` when the platform gave none (webauthn-authenticator-rs, for
219    /// a phone over caBLE). Never `Some` of no bytes: the server refuses
220    /// that as `InvalidInput`. The client SDK sends an empty handle as
221    /// `None`. On the wire a CBOR byte string, or null for `None`; the key
222    /// is always there.
223    #[serde(with = "optional_bytes")]
224    pub user_handle: Option<Vec<u8>>,
225}
226
227/// One of the session user's passkeys (`ListPasskeys`), the web UI's as
228/// well as the apps': the user sees every way they sign in, and the web
229/// UI's `me.passkeys` lists the same ones.
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231pub struct PasskeyInfo {
232    /// Its credential id, base64url with no padding, as the web UI names
233    /// it: what `RenamePasskey` and `RemovePasskey` take. For an app
234    /// passkey, that of the `credential_id` bytes the platform gave.
235    pub id: String,
236    /// What its user called it; an app passkey's is the device's (the web
237    /// UI shows it as "Spoolframe app · \<name\>").
238    pub name: String,
239    /// Unix seconds.
240    pub created_at: i64,
241    /// `None` if it has never signed them in.
242    pub last_used_at: Option<i64>,
243    /// The relying party it was made for: the server's app relying party
244    /// ([`ServerId::rp_id`]), [`LEGACY_APP_RP_ID`], or the host of the
245    /// server's web UI.
246    pub rp_id: String,
247    /// Made in a Spoolframe app ([`is_app_rp_id`]).
248    pub app: bool,
249    /// An app can sign in with it: only an app passkey made for this
250    /// server's relying party. One made for [`LEGACY_APP_RP_ID`] is an
251    /// app passkey that cannot: list it as old, to add again. A web UI's
252    /// is listed so the user sees it, and can rename or remove it.
253    pub usable_here: bool,
254}
255
256// Byte fields are shown by length: they are not secrets, but a log of
257// them says nothing and takes a screen.
258
259impl fmt::Debug for PasskeyCreation {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        f.debug_struct("PasskeyCreation")
262            .field("rp_id", &self.rp_id)
263            .field("user_name", &self.user_name)
264            .field("display_name", &self.display_name)
265            .field("exclude", &self.exclude_credential_ids.len())
266            .finish_non_exhaustive()
267    }
268}
269
270impl fmt::Debug for PasskeyRegistrationBegun {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        f.debug_struct("PasskeyRegistrationBegun")
273            .field("user_name", &self.user_name)
274            .field("display_name", &self.display_name)
275            .field("exclude", &self.exclude_credential_ids.len())
276            .finish_non_exhaustive()
277    }
278}
279
280impl fmt::Debug for PasskeySignInBegun {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        f.debug_struct("PasskeySignInBegun")
283            .field("allow", &self.allow_credential_ids.len())
284            .finish_non_exhaustive()
285    }
286}
287
288impl fmt::Debug for FinishPasskeyRegistration {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        f.debug_struct("FinishPasskeyRegistration")
291            .field("name", &self.name)
292            .finish_non_exhaustive()
293    }
294}
295
296impl fmt::Debug for PasskeyRequest {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        f.debug_struct("PasskeyRequest")
299            .field("rp_id", &self.rp_id)
300            .field("allow", &self.allow_credential_ids.len())
301            .finish_non_exhaustive()
302    }
303}
304
305impl fmt::Debug for FinishPasskeySignIn {
306    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307        f.debug_struct("FinishPasskeySignIn")
308            .field("user_handle", &self.user_handle.as_ref().map(Vec::len))
309            .finish_non_exhaustive()
310    }
311}
312
313/// A list of byte strings, each a CBOR byte string as `serde_bytes` makes
314/// one (it has no impl for a list of them).
315mod byte_strings {
316    use serde::{Deserialize, Deserializer, Serializer};
317    use serde_bytes::{ByteBuf, Bytes};
318
319    pub fn serialize<S: Serializer>(list: &[Vec<u8>], serializer: S) -> Result<S::Ok, S::Error> {
320        serializer.collect_seq(list.iter().map(|bytes| Bytes::new(bytes)))
321    }
322
323    pub fn deserialize<'de, D: Deserializer<'de>>(
324        deserializer: D,
325    ) -> Result<Vec<Vec<u8>>, D::Error> {
326        let list = Vec::<ByteBuf>::deserialize(deserializer)?;
327        Ok(list.into_iter().map(ByteBuf::into_vec).collect())
328    }
329}
330
331/// An optional byte string: CBOR bytes, or null. Its field is required:
332/// `with` makes serde ask for it, as it does not for a plain `Option`.
333mod optional_bytes {
334    use serde::{Deserialize, Deserializer, Serializer};
335    use serde_bytes::{ByteBuf, Bytes};
336
337    pub fn serialize<S: Serializer>(
338        bytes: &Option<Vec<u8>>,
339        serializer: S,
340    ) -> Result<S::Ok, S::Error> {
341        match bytes {
342            Some(bytes) => serializer.serialize_some(Bytes::new(bytes)),
343            None => serializer.serialize_none(),
344        }
345    }
346
347    pub fn deserialize<'de, D: Deserializer<'de>>(
348        deserializer: D,
349    ) -> Result<Option<Vec<u8>>, D::Error> {
350        Ok(Option::<ByteBuf>::deserialize(deserializer)?.map(ByteBuf::into_vec))
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    const NONCE: [u8; NONCE_LEN] = [7; NONCE_LEN];
359
360    #[test]
361    fn the_challenge_differs_for_another_server_with_the_same_nonce() {
362        assert_ne!(
363            app_passkey_challenge(&[1; 32], &NONCE),
364            app_passkey_challenge(&[2; 32], &NONCE)
365        );
366    }
367
368    #[test]
369    fn the_challenge_is_the_tagged_sha256_of_the_server_and_nonce() {
370        let mut bytes = b"spoolframe/app-passkey-challenge/1".to_vec();
371        bytes.extend([1; 32]);
372        bytes.extend(NONCE);
373        assert_eq!(
374            app_passkey_challenge(&[1; 32], &NONCE),
375            Sha256::digest(&bytes).to_vec()
376        );
377    }
378
379    fn server_id() -> ServerId {
380        ServerId::parse("mzxw6ytbojtg633c").unwrap()
381    }
382
383    #[test]
384    fn a_request_for_a_server_signs_its_challenge_for_its_relying_party() {
385        let begun = PasskeySignInBegun {
386            nonce: NONCE.to_vec(),
387            allow_credential_ids: vec![vec![4]],
388        };
389        assert_eq!(
390            begun.for_server(&[1; 32], &server_id()),
391            PasskeyRequest {
392                rp_id: "mzxw6ytbojtg633c.spoolframe.app".into(),
393                origin: "https://mzxw6ytbojtg633c.spoolframe.app".into(),
394                challenge: app_passkey_challenge(&[1; 32], &NONCE),
395                allow_credential_ids: vec![vec![4]],
396            }
397        );
398    }
399
400    #[test]
401    fn a_creation_for_a_server_is_for_its_relying_party() {
402        let begun = PasskeyRegistrationBegun {
403            nonce: NONCE.to_vec(),
404            user_id: vec![9],
405            user_name: "alice @ Nimble".into(),
406            display_name: "Alice".into(),
407            exclude_credential_ids: Vec::new(),
408        };
409        let creation = begun.for_server(&[1; 32], &server_id());
410        assert_eq!(
411            (creation.rp_id.as_str(), creation.origin.as_str()),
412            (
413                "mzxw6ytbojtg633c.spoolframe.app",
414                "https://mzxw6ytbojtg633c.spoolframe.app"
415            )
416        );
417        assert_eq!(creation.challenge, app_passkey_challenge(&[1; 32], &NONCE));
418    }
419
420    #[test]
421    fn app_passkeys_are_known_by_their_relying_party() {
422        for app in ["spoolframe.app", "mzxw6ytbojtg633c.spoolframe.app"] {
423            assert!(is_app_rp_id(app), "{app}");
424        }
425        for not in [
426            "media.example.org",
427            "localhost",
428            "evil.spoolframe.app",
429            "mzxw6ytbojtg633c.spoolframe.app.example.org",
430            "mzxw6ytbojtg633cspoolframe.app",
431        ] {
432            assert!(!is_app_rp_id(not), "{not}");
433        }
434    }
435}