Skip to main content

spoolframe_protocol/
passkeys.rs

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