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)]
145pub struct PasskeyCreation {
146    /// The relying party to make it for: the server's,
147    /// `<server id>.spoolframe.app`. Never `spoolframe.app` itself.
148    pub rp_id: String,
149    /// The origin a platform that takes one writes into `clientDataJSON`:
150    /// `https://<server id>.spoolframe.app`. The server accepts no other.
151    pub origin: String,
152    /// To sign: [`app_passkey_challenge`] of the server and its nonce.
153    #[serde(with = "serde_bytes")]
154    pub challenge: Vec<u8>,
155    /// The user handle: random, this server's for this user.
156    #[serde(with = "serde_bytes")]
157    pub user_id: Vec<u8>,
158    /// The account's name in the platform's passkey list,
159    /// `<username> @ <server name>`: the relying party is an opaque id, so
160    /// the server's name says which server it is.
161    pub user_name: String,
162    /// The user's display name, or their username without one.
163    pub display_name: String,
164    /// The user's app passkeys on this server: an authenticator holding
165    /// one of these is not to make another.
166    #[serde(with = "byte_strings")]
167    pub exclude_credential_ids: Vec<Vec<u8>>,
168}
169
170/// A passkey made for a [`PasskeyCreation`], to keep
171/// (`FinishPasskeyRegistration`).
172#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct FinishPasskeyRegistration {
174    #[serde(with = "serde_bytes")]
175    pub credential_id: Vec<u8>,
176    /// The attestation object (CBOR), as the platform gave it.
177    #[serde(with = "serde_bytes")]
178    pub attestation_object: Vec<u8>,
179    /// `clientDataJSON`, as the platform gave it.
180    #[serde(with = "serde_bytes")]
181    pub client_data_json: Vec<u8>,
182    /// What the device calls itself; the user's profile shows the passkey
183    /// as "Spoolframe app · \<name\>". 1 to 64 characters.
184    pub name: String,
185}
186
187/// What signing in with a passkey needs: the platform's options. Not on
188/// the wire: the client makes it from a [`PasskeySignInBegun`].
189#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
190pub struct PasskeyRequest {
191    /// The relying party to sign for, as [`PasskeyCreation::rp_id`].
192    pub rp_id: String,
193    /// The origin, as [`PasskeyCreation::origin`].
194    pub origin: String,
195    /// To sign: [`app_passkey_challenge`] of the server and its nonce.
196    #[serde(with = "serde_bytes")]
197    pub challenge: Vec<u8>,
198    /// The passkeys that may answer; empty: any the platform finds for
199    /// `rp_id` (a discoverable sign-in), so only this server's.
200    #[serde(with = "byte_strings")]
201    pub allow_credential_ids: Vec<Vec<u8>>,
202}
203
204/// A passkey's answer to a [`PasskeyRequest`] (`FinishPasskeySignIn`).
205#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
206pub struct FinishPasskeySignIn {
207    #[serde(with = "serde_bytes")]
208    pub credential_id: Vec<u8>,
209    #[serde(with = "serde_bytes")]
210    pub authenticator_data: Vec<u8>,
211    #[serde(with = "serde_bytes")]
212    pub client_data_json: Vec<u8>,
213    #[serde(with = "serde_bytes")]
214    pub signature: Vec<u8>,
215    /// The user handle the authenticator keeps with the passkey, or
216    /// `None` when the platform gave none (webauthn-authenticator-rs, for
217    /// a phone over caBLE). Never `Some` of no bytes: the server refuses
218    /// that as `InvalidInput`. The client SDK sends an empty handle as
219    /// `None`. On the wire a CBOR byte string, or null for `None`; the key
220    /// is always there.
221    #[serde(with = "optional_bytes")]
222    pub user_handle: Option<Vec<u8>>,
223}
224
225/// One of the session user's passkeys (`ListPasskeys`), the web UI's as
226/// well as the apps': the user sees every way they sign in, and the web
227/// UI's `me.passkeys` lists the same ones.
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229pub struct PasskeyInfo {
230    /// Its credential id, base64url with no padding, as the web UI names
231    /// it: what `RenamePasskey` and `RemovePasskey` take. For an app
232    /// passkey, that of the `credential_id` bytes the platform gave.
233    pub id: String,
234    /// What its user called it; an app passkey's is the device's (the web
235    /// UI shows it as "Spoolframe app · \<name\>").
236    pub name: String,
237    /// Unix seconds.
238    pub created_at: i64,
239    /// `None` if it has never signed them in.
240    pub last_used_at: Option<i64>,
241    /// The relying party it was made for: the server's app relying party
242    /// ([`ServerId::rp_id`]), [`LEGACY_APP_RP_ID`], or the host of the
243    /// server's web UI.
244    pub rp_id: String,
245    /// Made in a Spoolframe app ([`is_app_rp_id`]).
246    pub app: bool,
247    /// An app can sign in with it: only an app passkey made for this
248    /// server's relying party. One made for [`LEGACY_APP_RP_ID`] is an
249    /// app passkey that cannot: list it as old, to add again. A web UI's
250    /// is listed so the user sees it, and can rename or remove it.
251    pub usable_here: bool,
252}
253
254// Byte fields are shown by length: they are not secrets, but a log of
255// them says nothing and takes a screen.
256
257impl fmt::Debug for PasskeyCreation {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.debug_struct("PasskeyCreation")
260            .field("rp_id", &self.rp_id)
261            .field("user_name", &self.user_name)
262            .field("display_name", &self.display_name)
263            .field("exclude", &self.exclude_credential_ids.len())
264            .finish_non_exhaustive()
265    }
266}
267
268impl fmt::Debug for PasskeyRegistrationBegun {
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        f.debug_struct("PasskeyRegistrationBegun")
271            .field("user_name", &self.user_name)
272            .field("display_name", &self.display_name)
273            .field("exclude", &self.exclude_credential_ids.len())
274            .finish_non_exhaustive()
275    }
276}
277
278impl fmt::Debug for PasskeySignInBegun {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.debug_struct("PasskeySignInBegun")
281            .field("allow", &self.allow_credential_ids.len())
282            .finish_non_exhaustive()
283    }
284}
285
286impl fmt::Debug for FinishPasskeyRegistration {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        f.debug_struct("FinishPasskeyRegistration")
289            .field("name", &self.name)
290            .finish_non_exhaustive()
291    }
292}
293
294impl fmt::Debug for PasskeyRequest {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        f.debug_struct("PasskeyRequest")
297            .field("rp_id", &self.rp_id)
298            .field("allow", &self.allow_credential_ids.len())
299            .finish_non_exhaustive()
300    }
301}
302
303impl fmt::Debug for FinishPasskeySignIn {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        f.debug_struct("FinishPasskeySignIn")
306            .field("user_handle", &self.user_handle.as_ref().map(Vec::len))
307            .finish_non_exhaustive()
308    }
309}
310
311/// A list of byte strings, each a CBOR byte string as `serde_bytes` makes
312/// one (it has no impl for a list of them).
313mod byte_strings {
314    use serde::{Deserialize, Deserializer, Serializer};
315    use serde_bytes::{ByteBuf, Bytes};
316
317    pub fn serialize<S: Serializer>(list: &[Vec<u8>], serializer: S) -> Result<S::Ok, S::Error> {
318        serializer.collect_seq(list.iter().map(|bytes| Bytes::new(bytes)))
319    }
320
321    pub fn deserialize<'de, D: Deserializer<'de>>(
322        deserializer: D,
323    ) -> Result<Vec<Vec<u8>>, D::Error> {
324        let list = Vec::<ByteBuf>::deserialize(deserializer)?;
325        Ok(list.into_iter().map(ByteBuf::into_vec).collect())
326    }
327}
328
329/// An optional byte string: CBOR bytes, or null. Its field is required:
330/// `with` makes serde ask for it, as it does not for a plain `Option`.
331mod optional_bytes {
332    use serde::{Deserialize, Deserializer, Serializer};
333    use serde_bytes::{ByteBuf, Bytes};
334
335    pub fn serialize<S: Serializer>(
336        bytes: &Option<Vec<u8>>,
337        serializer: S,
338    ) -> Result<S::Ok, S::Error> {
339        match bytes {
340            Some(bytes) => serializer.serialize_some(Bytes::new(bytes)),
341            None => serializer.serialize_none(),
342        }
343    }
344
345    pub fn deserialize<'de, D: Deserializer<'de>>(
346        deserializer: D,
347    ) -> Result<Option<Vec<u8>>, D::Error> {
348        Ok(Option::<ByteBuf>::deserialize(deserializer)?.map(ByteBuf::into_vec))
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    const NONCE: [u8; NONCE_LEN] = [7; NONCE_LEN];
357
358    #[test]
359    fn the_challenge_differs_for_another_server_with_the_same_nonce() {
360        assert_ne!(
361            app_passkey_challenge(&[1; 32], &NONCE),
362            app_passkey_challenge(&[2; 32], &NONCE)
363        );
364    }
365
366    #[test]
367    fn the_challenge_is_the_tagged_sha256_of_the_server_and_nonce() {
368        let mut bytes = b"spoolframe/app-passkey-challenge/1".to_vec();
369        bytes.extend([1; 32]);
370        bytes.extend(NONCE);
371        assert_eq!(
372            app_passkey_challenge(&[1; 32], &NONCE),
373            Sha256::digest(&bytes).to_vec()
374        );
375    }
376
377    fn server_id() -> ServerId {
378        ServerId::parse("mzxw6ytbojtg633c").unwrap()
379    }
380
381    #[test]
382    fn a_request_for_a_server_signs_its_challenge_for_its_relying_party() {
383        let begun = PasskeySignInBegun {
384            nonce: NONCE.to_vec(),
385            allow_credential_ids: vec![vec![4]],
386        };
387        assert_eq!(
388            begun.for_server(&[1; 32], &server_id()),
389            PasskeyRequest {
390                rp_id: "mzxw6ytbojtg633c.spoolframe.app".into(),
391                origin: "https://mzxw6ytbojtg633c.spoolframe.app".into(),
392                challenge: app_passkey_challenge(&[1; 32], &NONCE),
393                allow_credential_ids: vec![vec![4]],
394            }
395        );
396    }
397
398    #[test]
399    fn a_creation_for_a_server_is_for_its_relying_party() {
400        let begun = PasskeyRegistrationBegun {
401            nonce: NONCE.to_vec(),
402            user_id: vec![9],
403            user_name: "alice @ Nimble".into(),
404            display_name: "Alice".into(),
405            exclude_credential_ids: Vec::new(),
406        };
407        let creation = begun.for_server(&[1; 32], &server_id());
408        assert_eq!(
409            (creation.rp_id.as_str(), creation.origin.as_str()),
410            (
411                "mzxw6ytbojtg633c.spoolframe.app",
412                "https://mzxw6ytbojtg633c.spoolframe.app"
413            )
414        );
415        assert_eq!(creation.challenge, app_passkey_challenge(&[1; 32], &NONCE));
416    }
417
418    #[test]
419    fn app_passkeys_are_known_by_their_relying_party() {
420        for app in ["spoolframe.app", "mzxw6ytbojtg633c.spoolframe.app"] {
421            assert!(is_app_rp_id(app), "{app}");
422        }
423        for not in [
424            "media.example.org",
425            "localhost",
426            "evil.spoolframe.app",
427            "mzxw6ytbojtg633c.spoolframe.app.example.org",
428            "mzxw6ytbojtg633cspoolframe.app",
429        ] {
430            assert!(!is_app_rp_id(not), "{not}");
431        }
432    }
433}