Skip to main content

aurelin_passkeys/
lib.rs

1//! Laravel-style passkey ceremonies backed by `webauthn-rs`.
2
3use std::{
4    collections::HashMap,
5    fmt::{self, Debug, Formatter},
6    sync::{Arc, Mutex, MutexGuard},
7    time::{Duration, Instant},
8};
9
10use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
11use hmac::{Hmac, KeyInit, Mac};
12use serde_json::{Value, json};
13use sha2::Sha256;
14use thiserror::Error;
15use url::Url;
16use uuid::Uuid;
17use webauthn_rs::prelude::{
18    CredentialID, DiscoverableAuthentication, DiscoverableKey, Passkey, PasskeyAuthentication, PasskeyRegistration,
19    PublicKeyCredential, RegisterPublicKeyCredential, Webauthn, WebauthnBuilder, WebauthnError,
20};
21
22type HmacSha256 = Hmac<Sha256>;
23
24#[derive(Clone, Debug)]
25pub struct PasskeyConfig {
26    pub relying_party_id: String,
27    pub relying_party_name: String,
28    pub allowed_origins: Vec<Url>,
29    pub user_handle_secret: Vec<u8>,
30    pub timeout: Duration,
31}
32
33impl PasskeyConfig {
34    pub fn for_origin(
35        relying_party_name: impl Into<String>,
36        origin: &str,
37        user_handle_secret: impl Into<Vec<u8>>,
38    ) -> Result<Self, PasskeyError> {
39        let origin = Url::parse(origin).map_err(|_| PasskeyError::InvalidOrigin)?;
40        let relying_party_id = origin.host_str().ok_or(PasskeyError::InvalidOrigin)?.to_owned();
41        Ok(Self {
42            relying_party_id,
43            relying_party_name: relying_party_name.into(),
44            allowed_origins: vec![origin],
45            user_handle_secret: user_handle_secret.into(),
46            timeout: Duration::from_secs(60),
47        })
48    }
49}
50
51#[derive(Clone, Debug)]
52pub struct PasskeyUser {
53    pub id: String,
54    pub username: String,
55    pub display_name: String,
56}
57
58#[derive(Clone, Debug)]
59pub struct StoredPasskey {
60    pub credential: String,
61}
62
63#[derive(Clone, Debug)]
64pub struct PasskeyCeremony {
65    pub id: String,
66    pub options: Value,
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct VerifiedPasskey {
71    pub credential_id: String,
72    pub credential: String,
73}
74
75#[derive(Clone, Debug)]
76pub struct PasskeyAuthenticationRequest<'a> {
77    pub ceremony_id: &'a str,
78    pub user: &'a PasskeyUser,
79    pub credential: Value,
80    pub stored_passkey: &'a StoredPasskey,
81}
82
83#[derive(Clone)]
84pub struct Passkeys {
85    webauthn: Webauthn,
86    user_handle_secret: Arc<[u8]>,
87    timeout: Duration,
88    registrations: Arc<Mutex<HashMap<String, PendingRegistration>>>,
89    authentications: Arc<Mutex<HashMap<String, PendingAuthentication>>>,
90}
91
92impl Debug for Passkeys {
93    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
94        formatter.debug_struct("Passkeys").finish_non_exhaustive()
95    }
96}
97
98impl Passkeys {
99    pub fn new(config: PasskeyConfig) -> Result<Self, PasskeyError> {
100        let (origin, additional_origins) =
101            config.allowed_origins.split_first().ok_or(PasskeyError::MissingAllowedOrigin)?;
102        if config.user_handle_secret.is_empty() {
103            return Err(PasskeyError::EmptyUserHandleSecret);
104        }
105        let mut builder = WebauthnBuilder::new(&config.relying_party_id, origin)?
106            .rp_name(&config.relying_party_name)
107            .timeout(config.timeout);
108        for origin in additional_origins {
109            builder = builder.append_allowed_origin(origin);
110        }
111        Ok(Self {
112            webauthn: builder.build()?,
113            user_handle_secret: config.user_handle_secret.into(),
114            timeout: config.timeout,
115            registrations: Arc::default(),
116            authentications: Arc::default(),
117        })
118    }
119
120    pub fn user_handle(&self, user_id: &str) -> Result<Uuid, PasskeyError> {
121        let mut mac =
122            HmacSha256::new_from_slice(&self.user_handle_secret).map_err(|_| PasskeyError::InvalidUserHandleSecret)?;
123        mac.update(user_id.as_bytes());
124        let digest = mac.finalize().into_bytes();
125        let mut bytes = [0_u8; 16];
126        bytes.copy_from_slice(&digest[..16]);
127        Ok(Uuid::from_bytes(bytes))
128    }
129
130    pub fn start_registration(
131        &self,
132        user: &PasskeyUser,
133        existing_passkeys: &[StoredPasskey],
134    ) -> Result<PasskeyCeremony, PasskeyError> {
135        let handle = self.user_handle(&user.id)?;
136        let excluded = credentials(existing_passkeys)?;
137        let (mut options, state) = self.webauthn.start_passkey_registration(
138            handle,
139            &user.username,
140            &user.display_name,
141            (!excluded.is_empty()).then_some(excluded),
142        )?;
143        let mut options = serde_json::to_value(&mut options)?;
144        options["publicKey"]["authenticatorSelection"]["residentKey"] = json!("required");
145        options["publicKey"]["authenticatorSelection"]["requireResidentKey"] = json!(true);
146        let id = Uuid::new_v4().to_string();
147        let mut registrations = self.registration_states()?;
148        registrations.retain(|_, pending| pending.created_at.elapsed() <= self.timeout);
149        registrations
150            .insert(id.clone(), PendingRegistration { created_at: Instant::now(), user_handle: handle, state });
151        Ok(PasskeyCeremony { id, options })
152    }
153
154    pub fn finish_registration(
155        &self,
156        ceremony_id: &str,
157        user: &PasskeyUser,
158        credential: Value,
159    ) -> Result<VerifiedPasskey, PasskeyError> {
160        let pending = self.registration_states()?.remove(ceremony_id).ok_or(PasskeyError::MissingCeremony)?;
161        if pending.created_at.elapsed() > self.timeout || pending.user_handle != self.user_handle(&user.id)? {
162            return Err(PasskeyError::ExpiredCeremony);
163        }
164        let credential: RegisterPublicKeyCredential = serde_json::from_value(credential)?;
165        let passkey = self.webauthn.finish_passkey_registration(&credential, &pending.state)?;
166        verified_passkey(&passkey)
167    }
168
169    pub fn start_login(&self) -> Result<PasskeyCeremony, PasskeyError> {
170        let (mut options, state) = self.webauthn.start_discoverable_authentication()?;
171        options.mediation = None;
172        let id = Uuid::new_v4().to_string();
173        let mut authentications = self.authentication_states()?;
174        authentications.retain(|_, pending| pending.created_at.elapsed() <= self.timeout);
175        authentications.insert(
176            id.clone(),
177            PendingAuthentication { created_at: Instant::now(), state: AuthenticationState::Discoverable(state) },
178        );
179        Ok(PasskeyCeremony { id, options: serde_json::to_value(options)? })
180    }
181
182    pub fn start_confirmation(
183        &self,
184        user: &PasskeyUser,
185        passkeys: &[StoredPasskey],
186    ) -> Result<PasskeyCeremony, PasskeyError> {
187        let passkeys = deserialize_passkeys(passkeys)?;
188        if passkeys.is_empty() {
189            return Err(PasskeyError::NoPasskeys);
190        }
191        let (options, state) = self.webauthn.start_passkey_authentication(&passkeys)?;
192        let id = Uuid::new_v4().to_string();
193        let mut authentications = self.authentication_states()?;
194        authentications.retain(|_, pending| pending.created_at.elapsed() <= self.timeout);
195        authentications.insert(
196            id.clone(),
197            PendingAuthentication {
198                created_at: Instant::now(),
199                state: AuthenticationState::Known { user_handle: self.user_handle(&user.id)?, state },
200            },
201        );
202        Ok(PasskeyCeremony { id, options: serde_json::to_value(options)? })
203    }
204
205    pub fn credential_id(&self, credential: Value) -> Result<String, PasskeyError> {
206        let credential: PublicKeyCredential = serde_json::from_value(credential)?;
207        Ok(URL_SAFE_NO_PAD.encode(credential.get_credential_id()))
208    }
209
210    pub fn finish_authentication(
211        &self,
212        authentication: PasskeyAuthenticationRequest<'_>,
213    ) -> Result<VerifiedPasskey, PasskeyError> {
214        let pending =
215            self.authentication_states()?.remove(authentication.ceremony_id).ok_or(PasskeyError::MissingCeremony)?;
216        if pending.created_at.elapsed() > self.timeout {
217            return Err(PasskeyError::ExpiredCeremony);
218        }
219        let credential: PublicKeyCredential = serde_json::from_value(authentication.credential)?;
220        let mut passkey: Passkey = serde_json::from_str(&authentication.stored_passkey.credential)?;
221        let result = match pending.state {
222            AuthenticationState::Discoverable(state) => {
223                let (handle, credential_id) = self.webauthn.identify_discoverable_authentication(&credential)?;
224                if handle != self.user_handle(&authentication.user.id)? || credential_id != passkey.cred_id() {
225                    return Err(PasskeyError::PasskeyDoesNotBelongToUser);
226                }
227                self.webauthn.finish_discoverable_authentication_v2(
228                    &credential,
229                    state,
230                    DiscoverableKey::from(&passkey),
231                )?
232            }
233            AuthenticationState::Known { user_handle, state } => {
234                if user_handle != self.user_handle(&authentication.user.id)? {
235                    return Err(PasskeyError::PasskeyDoesNotBelongToUser);
236                }
237                self.webauthn.finish_passkey_authentication(&credential, &state)?
238            }
239        };
240        passkey.update_credential(&result);
241        verified_passkey(&passkey)
242    }
243
244    fn registration_states(&self) -> Result<MutexGuard<'_, HashMap<String, PendingRegistration>>, PasskeyError> {
245        self.registrations.lock().map_err(|_| PasskeyError::StateUnavailable)
246    }
247
248    fn authentication_states(&self) -> Result<MutexGuard<'_, HashMap<String, PendingAuthentication>>, PasskeyError> {
249        self.authentications.lock().map_err(|_| PasskeyError::StateUnavailable)
250    }
251}
252
253#[derive(Debug)]
254struct PendingRegistration {
255    created_at: Instant,
256    user_handle: Uuid,
257    state: PasskeyRegistration,
258}
259
260#[derive(Debug)]
261struct PendingAuthentication {
262    created_at: Instant,
263    state: AuthenticationState,
264}
265
266#[derive(Debug)]
267enum AuthenticationState {
268    Discoverable(DiscoverableAuthentication),
269    Known { user_handle: Uuid, state: PasskeyAuthentication },
270}
271
272#[derive(Debug, Error)]
273pub enum PasskeyError {
274    #[error("the WebAuthn origin is invalid")]
275    InvalidOrigin,
276    #[error("at least one WebAuthn origin must be allowed")]
277    MissingAllowedOrigin,
278    #[error("the passkey user-handle secret cannot be empty")]
279    EmptyUserHandleSecret,
280    #[error("the passkey user-handle secret is invalid")]
281    InvalidUserHandleSecret,
282    #[error("the passkey ceremony is missing or was already used")]
283    MissingCeremony,
284    #[error("the passkey ceremony expired or belongs to another user")]
285    ExpiredCeremony,
286    #[error("the passkey does not belong to this user")]
287    PasskeyDoesNotBelongToUser,
288    #[error("the user has no registered passkeys")]
289    NoPasskeys,
290    #[error("passkey ceremony state is unavailable")]
291    StateUnavailable,
292    #[error(transparent)]
293    Webauthn(#[from] WebauthnError),
294    #[error(transparent)]
295    Json(#[from] serde_json::Error),
296}
297
298fn credentials(passkeys: &[StoredPasskey]) -> Result<Vec<CredentialID>, PasskeyError> {
299    Ok(deserialize_passkeys(passkeys)?.into_iter().map(|passkey| passkey.cred_id().clone()).collect())
300}
301
302fn deserialize_passkeys(passkeys: &[StoredPasskey]) -> Result<Vec<Passkey>, PasskeyError> {
303    passkeys.iter().map(|passkey| serde_json::from_str(&passkey.credential).map_err(PasskeyError::from)).collect()
304}
305
306fn verified_passkey(passkey: &Passkey) -> Result<VerifiedPasskey, PasskeyError> {
307    Ok(VerifiedPasskey {
308        credential_id: URL_SAFE_NO_PAD.encode(passkey.cred_id()),
309        credential: serde_json::to_string(&passkey)?,
310    })
311}