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.
255    pub created_at: i64,
256    /// `None` if it has never signed them in.
257    pub last_used_at: Option<i64>,
258    /// The relying party it was made for: the server's app relying party
259    /// ([`ServerId::rp_id`]), [`LEGACY_APP_RP_ID`], or the host of the
260    /// server's web UI.
261    pub rp_id: String,
262    /// Made in a Spoolframe app ([`is_app_rp_id`]).
263    pub app: bool,
264    /// An app can sign in with it: only an app passkey made for this
265    /// server's relying party. One made for [`LEGACY_APP_RP_ID`] is an
266    /// app passkey that cannot: list it as old, to add again. A web UI's
267    /// is listed so the user sees it, and can rename or remove it.
268    pub usable_here: bool,
269}
270
271// Byte fields are shown by length: they are not secrets, but a log of
272// them says nothing and takes a screen.
273
274impl fmt::Debug for PasskeyCreation {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        f.debug_struct("PasskeyCreation")
277            .field("rp_id", &self.rp_id)
278            .field("user_name", &self.user_name)
279            .field("display_name", &self.display_name)
280            .field("exclude", &self.exclude_credential_ids.len())
281            .finish_non_exhaustive()
282    }
283}
284
285impl fmt::Debug for PasskeyRegistrationBegun {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        f.debug_struct("PasskeyRegistrationBegun")
288            .field("user_name", &self.user_name)
289            .field("display_name", &self.display_name)
290            .field("exclude", &self.exclude_credential_ids.len())
291            .finish_non_exhaustive()
292    }
293}
294
295impl fmt::Debug for PasskeySignInBegun {
296    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297        f.debug_struct("PasskeySignInBegun")
298            .field("allow", &self.allow_credential_ids.len())
299            .finish_non_exhaustive()
300    }
301}
302
303impl fmt::Debug for FinishPasskeyRegistration {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        f.debug_struct("FinishPasskeyRegistration")
306            .field("name", &self.name)
307            .finish_non_exhaustive()
308    }
309}
310
311impl fmt::Debug for PasskeyRequest {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        f.debug_struct("PasskeyRequest")
314            .field("rp_id", &self.rp_id)
315            .field("allow", &self.allow_credential_ids.len())
316            .finish_non_exhaustive()
317    }
318}
319
320impl fmt::Debug for FinishPasskeySignIn {
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        f.debug_struct("FinishPasskeySignIn")
323            .field("user_handle", &self.user_handle.as_ref().map(Vec::len))
324            .finish_non_exhaustive()
325    }
326}
327
328/// A list of byte strings, each a CBOR byte string as `serde_bytes` makes
329/// one (it has no impl for a list of them).
330mod byte_strings {
331    use serde::{Deserialize, Deserializer, Serializer};
332    use serde_bytes::{ByteBuf, Bytes};
333
334    pub fn serialize<S: Serializer>(list: &[Vec<u8>], serializer: S) -> Result<S::Ok, S::Error> {
335        serializer.collect_seq(list.iter().map(|bytes| Bytes::new(bytes)))
336    }
337
338    pub fn deserialize<'de, D: Deserializer<'de>>(
339        deserializer: D,
340    ) -> Result<Vec<Vec<u8>>, D::Error> {
341        let list = Vec::<ByteBuf>::deserialize(deserializer)?;
342        Ok(list.into_iter().map(ByteBuf::into_vec).collect())
343    }
344}
345
346/// An optional byte string: CBOR bytes, or null. Its field is required:
347/// `with` makes serde ask for it, as it does not for a plain `Option`.
348mod optional_bytes {
349    use serde::{Deserialize, Deserializer, Serializer};
350    use serde_bytes::{ByteBuf, Bytes};
351
352    pub fn serialize<S: Serializer>(
353        bytes: &Option<Vec<u8>>,
354        serializer: S,
355    ) -> Result<S::Ok, S::Error> {
356        match bytes {
357            Some(bytes) => serializer.serialize_some(Bytes::new(bytes)),
358            None => serializer.serialize_none(),
359        }
360    }
361
362    pub fn deserialize<'de, D: Deserializer<'de>>(
363        deserializer: D,
364    ) -> Result<Option<Vec<u8>>, D::Error> {
365        Ok(Option::<ByteBuf>::deserialize(deserializer)?.map(ByteBuf::into_vec))
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn a_name_is_trimmed_and_cut_to_64_characters() {
375        assert_eq!(
376            fit_name("  Living room TV \n").as_deref(),
377            Some("Living room TV")
378        );
379        assert_eq!(fit_name(" \t"), None);
380        let long = "é".repeat(70);
381        assert_eq!(fit_name(&long).unwrap().chars().count(), 64);
382        let spaced = format!("{} b", "a".repeat(63));
383        assert_eq!(fit_name(&spaced), Some("a".repeat(63)));
384    }
385
386    const NONCE: [u8; NONCE_LEN] = [7; NONCE_LEN];
387
388    #[test]
389    fn the_challenge_differs_for_another_server_with_the_same_nonce() {
390        assert_ne!(
391            app_passkey_challenge(&[1; 32], &NONCE),
392            app_passkey_challenge(&[2; 32], &NONCE)
393        );
394    }
395
396    #[test]
397    fn the_challenge_is_the_tagged_sha256_of_the_server_and_nonce() {
398        let mut bytes = b"spoolframe/app-passkey-challenge/1".to_vec();
399        bytes.extend([1; 32]);
400        bytes.extend(NONCE);
401        assert_eq!(
402            app_passkey_challenge(&[1; 32], &NONCE),
403            Sha256::digest(&bytes).to_vec()
404        );
405    }
406
407    fn server_id() -> ServerId {
408        ServerId::parse("mzxw6ytbojtg633c").unwrap()
409    }
410
411    #[test]
412    fn a_request_for_a_server_signs_its_challenge_for_its_relying_party() {
413        let begun = PasskeySignInBegun {
414            nonce: NONCE.to_vec(),
415            allow_credential_ids: vec![vec![4]],
416        };
417        assert_eq!(
418            begun.for_server(&[1; 32], &server_id()),
419            PasskeyRequest {
420                rp_id: "mzxw6ytbojtg633c.spoolframe.app".into(),
421                origin: "https://mzxw6ytbojtg633c.spoolframe.app".into(),
422                challenge: app_passkey_challenge(&[1; 32], &NONCE),
423                allow_credential_ids: vec![vec![4]],
424            }
425        );
426    }
427
428    #[test]
429    fn a_creation_for_a_server_is_for_its_relying_party() {
430        let begun = PasskeyRegistrationBegun {
431            nonce: NONCE.to_vec(),
432            user_id: vec![9],
433            user_name: "alice @ Nimble".into(),
434            display_name: "Alice".into(),
435            exclude_credential_ids: Vec::new(),
436        };
437        let creation = begun.for_server(&[1; 32], &server_id());
438        assert_eq!(
439            (creation.rp_id.as_str(), creation.origin.as_str()),
440            (
441                "mzxw6ytbojtg633c.spoolframe.app",
442                "https://mzxw6ytbojtg633c.spoolframe.app"
443            )
444        );
445        assert_eq!(creation.challenge, app_passkey_challenge(&[1; 32], &NONCE));
446    }
447
448    #[test]
449    fn app_passkeys_are_known_by_their_relying_party() {
450        for app in ["spoolframe.app", "mzxw6ytbojtg633c.spoolframe.app"] {
451            assert!(is_app_rp_id(app), "{app}");
452        }
453        for not in [
454            "media.example.org",
455            "localhost",
456            "evil.spoolframe.app",
457            "mzxw6ytbojtg633c.spoolframe.app.example.org",
458            "mzxw6ytbojtg633cspoolframe.app",
459        ] {
460            assert!(!is_app_rp_id(not), "{not}");
461        }
462    }
463}