Skip to main content

auth_framework/api/
webauthn.rs

1use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
2use axum::{extract::State, http::HeaderMap, response::Json};
3use base64::Engine;
4use rand::Rng;
5use serde::{Deserialize, Serialize};
6use sha2::{Digest, Sha256};
7
8/// WebAuthn Relying Party configuration.
9///
10/// Collects the RP identity, default timeouts, and attestation preference
11/// in a single struct so that individual handlers don't need to scatter
12/// `std::env::var` calls.
13///
14/// # Example
15/// ```rust
16/// use auth_framework::api::webauthn::WebAuthnConfig;
17///
18/// // Minimal — defaults to "localhost" / "AuthFramework" / "none"
19/// let cfg = WebAuthnConfig::default();
20/// assert_eq!(cfg.rp_id, "localhost");
21///
22/// // Typical production use
23/// let cfg = WebAuthnConfig::new("auth.example.com", "My Service")
24///     .attestation("none")
25///     .timeout(120_000);
26/// assert_eq!(cfg.rp_id, "auth.example.com");
27/// assert_eq!(cfg.attestation, "none");
28/// ```
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct WebAuthnConfig {
31    /// Relying Party identifier (usually the domain name).
32    pub rp_id: String,
33    /// Human-readable Relying Party name.
34    pub rp_name: String,
35    /// Attestation conveyance preference. This server does not verify
36    /// attestation statements, so only `"none"` is accepted by the
37    /// registration endpoints; any other value makes them refuse rather
38    /// than request an attestation that would then be ignored.
39    pub attestation: String,
40    /// Timeout for ceremonies in milliseconds (default: 60 000).
41    pub timeout_ms: u64,
42    /// Origins (`scheme://host[:port]`) the relying party is served from. The client-data
43    /// `origin` of a ceremony must equal one of these exactly. Empty (the default) means
44    /// `https://{rp_id}` (plus `http://localhost` when the rp id is `localhost`).
45    #[serde(default)]
46    pub rp_origins: Vec<String>,
47    /// User-verification requirement of ceremonies: `"required"`, `"preferred"` or
48    /// `"discouraged"`. Set by the server, never by the request. With `"required"` an
49    /// assertion whose authenticator data does not carry the UV flag is refused.
50    #[serde(default = "default_user_verification")]
51    pub user_verification: String,
52}
53
54fn default_user_verification() -> String {
55    "preferred".to_string()
56}
57
58impl Default for WebAuthnConfig {
59    fn default() -> Self {
60        Self {
61            rp_id: "localhost".to_string(),
62            rp_name: "AuthFramework".to_string(),
63            attestation: "none".to_string(),
64            timeout_ms: 60_000,
65            rp_origins: Vec::new(),
66            user_verification: default_user_verification(),
67        }
68    }
69}
70
71impl WebAuthnConfig {
72    /// Create a config with the given RP id and name.
73    pub fn new(rp_id: impl Into<String>, rp_name: impl Into<String>) -> Self {
74        Self {
75            rp_id: rp_id.into(),
76            rp_name: rp_name.into(),
77            ..Self::default()
78        }
79    }
80
81    /// Build a config from environment variables.
82    ///
83    /// | Variable | Default |
84    /// |----------|---------|
85    /// | `WEBAUTHN_RP_ID` | `"localhost"` |
86    /// | `WEBAUTHN_RP_NAME` | `"AuthFramework"` |
87    /// | `WEBAUTHN_ATTESTATION` | `"none"` |
88    /// | `WEBAUTHN_TIMEOUT_MS` | `60000` |
89    /// | `WEBAUTHN_ORIGINS` | (empty: `https://{rp_id}`); comma-separated origins |
90    /// | `WEBAUTHN_USER_VERIFICATION` | `"preferred"` |
91    pub fn from_env() -> Self {
92        Self {
93            rp_id: std::env::var("WEBAUTHN_RP_ID").unwrap_or_else(|_| "localhost".to_string()),
94            rp_name: std::env::var("WEBAUTHN_RP_NAME")
95                .unwrap_or_else(|_| "AuthFramework".to_string()),
96            attestation: std::env::var("WEBAUTHN_ATTESTATION")
97                .unwrap_or_else(|_| "none".to_string()),
98            timeout_ms: std::env::var("WEBAUTHN_TIMEOUT_MS")
99                .ok()
100                .and_then(|v| v.parse().ok())
101                .unwrap_or(60_000),
102            rp_origins: std::env::var("WEBAUTHN_ORIGINS")
103                .map(|v| {
104                    v.split(',')
105                        .map(|s| s.trim().to_string())
106                        .filter(|s| !s.is_empty())
107                        .collect()
108                })
109                .unwrap_or_default(),
110            user_verification: match std::env::var("WEBAUTHN_USER_VERIFICATION") {
111                Err(_) => default_user_verification(),
112                Ok(v) => match v.trim().to_lowercase().as_str() {
113                    "required" => "required".to_string(),
114                    "preferred" => "preferred".to_string(),
115                    "discouraged" => "discouraged".to_string(),
116                    other => {
117                        // A typo must not silently weaken the policy.
118                        tracing::error!(
119                            "WEBAUTHN_USER_VERIFICATION={other:?} is not one of required / \
120                             preferred / discouraged; treating it as \"required\""
121                        );
122                        "required".to_string()
123                    }
124                },
125            },
126        }
127    }
128
129    /// Set the origins the relying party is served from (see [`Self::rp_origins`]).
130    pub fn origins(mut self, origins: Vec<String>) -> Self {
131        self.rp_origins = origins;
132        self
133    }
134
135    /// Set the user-verification requirement (`required` / `preferred` / `discouraged`).
136    pub fn user_verification(mut self, requirement: impl Into<String>) -> Self {
137        self.user_verification = requirement.into();
138        self
139    }
140
141    /// The origins a ceremony may come from, normalised (`scheme://host[:port]`).
142    fn expected_origins(&self) -> Vec<String> {
143        let configured: Vec<String> = self
144            .rp_origins
145            .iter()
146            .filter_map(|o| normalize_origin(o))
147            .collect();
148        if !configured.is_empty() {
149            return configured;
150        }
151        let mut origins = vec![format!("https://{}", self.rp_id)];
152        if self.rp_id == "localhost" {
153            origins.push("http://localhost".to_string());
154        }
155        origins
156            .into_iter()
157            .filter_map(|o| normalize_origin(&o))
158            .collect()
159    }
160
161    /// Set the attestation conveyance preference.
162    pub fn attestation(mut self, attestation: impl Into<String>) -> Self {
163        self.attestation = attestation.into();
164        self
165    }
166
167    /// Set the ceremony timeout in milliseconds.
168    pub fn timeout(mut self, ms: u64) -> Self {
169        self.timeout_ms = ms;
170        self
171    }
172}
173
174/// Whether this server can honour an attestation conveyance preference.
175///
176/// The server does not verify attestation statements, so it only accepts
177/// `"none"`: asking an authenticator for an attestation it then ignores
178/// would look like provenance checking while providing none.
179pub(crate) fn attestation_supported(preference: &str) -> bool {
180    preference == "none"
181}
182
183/// Request to initiate WebAuthn registration
184#[derive(Debug, Serialize, Deserialize)]
185pub struct WebAuthnRegistrationInitRequest {
186    pub username: String,
187    pub display_name: Option<String>,
188    pub authenticator_attachment: Option<String>, // "platform" or "cross-platform"
189    pub user_verification: Option<String>,        // "required", "preferred", "discouraged"
190}
191
192/// WebAuthn registration challenge response
193#[derive(Serialize, Deserialize)]
194pub struct WebAuthnRegistrationResponse {
195    pub challenge: String,
196    pub rp: PublicKeyCredentialRpEntity,
197    pub user: PublicKeyCredentialUserEntity,
198    pub pubkey_cred_params: Vec<PublicKeyCredentialParameters>,
199    pub timeout: Option<u64>,
200    #[serde(rename = "excludeCredentials")]
201    pub exclude_credentials: Option<Vec<PublicKeyCredentialDescriptor>>,
202    #[serde(rename = "authenticatorSelection")]
203    pub authenticator_selection: Option<AuthenticatorSelectionCriteria>,
204    pub attestation: String,
205    pub session_id: String,
206}
207
208impl std::fmt::Debug for WebAuthnRegistrationResponse {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        let mut d = f.debug_struct("WebAuthnRegistrationResponse");
211        d.field("challenge", &self.challenge);
212        d.field("rp", &self.rp);
213        d.field("user", &self.user);
214        d.field("pubkey_cred_params", &self.pubkey_cred_params);
215        d.field("timeout", &self.timeout);
216        d.field("exclude_credentials", &self.exclude_credentials);
217        d.field("authenticator_selection", &self.authenticator_selection);
218        d.field("attestation", &self.attestation);
219        d.field(
220            "session_id",
221            &crate::utils::redact::redacted(&self.session_id),
222        );
223        d.finish()
224    }
225}
226
227/// Complete WebAuthn registration
228#[derive(Serialize, Deserialize)]
229pub struct WebAuthnRegistrationCompleteRequest {
230    pub session_id: String,
231    pub credential_id: String,
232    pub credential_public_key: String,
233    pub attestation_object: String,
234    pub client_data_json: String,
235    pub authenticator_data: String,
236    pub signature: String,
237}
238
239impl std::fmt::Debug for WebAuthnRegistrationCompleteRequest {
240    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241        let mut d = f.debug_struct("WebAuthnRegistrationCompleteRequest");
242        d.field(
243            "session_id",
244            &crate::utils::redact::redacted(&self.session_id),
245        );
246        d.field("credential_id", &self.credential_id);
247        d.field("credential_public_key", &self.credential_public_key);
248        d.field("attestation_object", &self.attestation_object);
249        d.field("client_data_json", &self.client_data_json);
250        d.field("authenticator_data", &self.authenticator_data);
251        d.field("signature", &self.signature);
252        d.finish()
253    }
254}
255
256/// WebAuthn authentication initiation request
257#[derive(Debug, Serialize, Deserialize)]
258pub struct WebAuthnAuthenticationRequest {
259    pub username: Option<String>,
260    pub user_verification: Option<String>,
261}
262
263/// WebAuthn authentication challenge response
264#[derive(Serialize, Deserialize)]
265pub struct WebAuthnAuthenticationResponse {
266    pub challenge: String,
267    pub allow_credentials: Vec<PublicKeyCredentialDescriptor>,
268    pub timeout: Option<u64>,
269    pub user_verification: String,
270    pub session_id: String,
271}
272
273impl std::fmt::Debug for WebAuthnAuthenticationResponse {
274    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275        let mut d = f.debug_struct("WebAuthnAuthenticationResponse");
276        d.field("challenge", &self.challenge);
277        d.field("allow_credentials", &self.allow_credentials);
278        d.field("timeout", &self.timeout);
279        d.field("user_verification", &self.user_verification);
280        d.field(
281            "session_id",
282            &crate::utils::redact::redacted(&self.session_id),
283        );
284        d.finish()
285    }
286}
287
288/// Complete WebAuthn authentication
289#[derive(Serialize, Deserialize)]
290pub struct WebAuthnAuthenticationCompleteRequest {
291    pub session_id: String,
292    pub credential_id: String,
293    pub authenticator_data: String,
294    pub client_data_json: String,
295    pub signature: String,
296    pub user_handle: Option<String>,
297}
298
299impl std::fmt::Debug for WebAuthnAuthenticationCompleteRequest {
300    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
301        let mut d = f.debug_struct("WebAuthnAuthenticationCompleteRequest");
302        d.field(
303            "session_id",
304            &crate::utils::redact::redacted(&self.session_id),
305        );
306        d.field("credential_id", &self.credential_id);
307        d.field("authenticator_data", &self.authenticator_data);
308        d.field("client_data_json", &self.client_data_json);
309        d.field("signature", &self.signature);
310        d.field("user_handle", &self.user_handle);
311        d.finish()
312    }
313}
314
315/// Supporting structures
316#[derive(Debug, Serialize, Deserialize)]
317pub struct PublicKeyCredentialRpEntity {
318    pub id: String,
319    pub name: String,
320}
321
322#[derive(Debug, Serialize, Deserialize)]
323pub struct PublicKeyCredentialUserEntity {
324    pub id: String,
325    pub name: String,
326    pub display_name: String,
327}
328
329#[derive(Debug, Serialize, Deserialize)]
330pub struct PublicKeyCredentialParameters {
331    #[serde(rename = "type")]
332    pub type_field: String,
333    pub alg: i32,
334}
335
336impl PublicKeyCredentialParameters {
337    /// ES256 (ECDSA P-256) — COSE algorithm −7.
338    pub fn es256() -> Self {
339        Self {
340            type_field: "public-key".to_string(),
341            alg: -7,
342        }
343    }
344
345    /// RS256 (RSASSA-PKCS1-v1_5 with SHA-256) — COSE algorithm −257.
346    pub fn rs256() -> Self {
347        Self {
348            type_field: "public-key".to_string(),
349            alg: -257,
350        }
351    }
352
353    /// Default WebAuthn parameter set: ES256 + RS256.
354    pub fn defaults() -> Vec<Self> {
355        vec![Self::es256(), Self::rs256()]
356    }
357}
358
359#[derive(Debug, Serialize, Deserialize)]
360pub struct PublicKeyCredentialDescriptor {
361    #[serde(rename = "type")]
362    pub type_field: String,
363    pub id: String,
364    pub transports: Option<Vec<String>>,
365}
366
367#[derive(Debug, Serialize, Deserialize)]
368pub struct AuthenticatorSelectionCriteria {
369    pub authenticator_attachment: Option<String>,
370    pub require_resident_key: Option<bool>,
371    pub user_verification: String,
372}
373
374type SharedStorage = std::sync::Arc<dyn crate::storage::AuthStorage>;
375
376/// Resolve a username to its account id via the `user:username:{name}`
377/// index every registration path maintains.
378async fn resolve_user_id(storage: &SharedStorage, username: &str) -> Option<String> {
379    let bytes = storage
380        .get_kv(&format!("user:username:{username}"))
381        .await
382        .ok()
383        .flatten()?;
384    String::from_utf8(bytes).ok().filter(|id| !id.is_empty())
385}
386
387/// `true` when `user:{id}` exists, parses, and is not deactivated.
388async fn account_is_active(storage: &SharedStorage, user_id: &str) -> bool {
389    match storage.get_kv(&format!("user:{user_id}")).await {
390        Ok(Some(bytes)) => serde_json::from_slice::<serde_json::Value>(&bytes)
391            .map(|record| record["active"].as_bool() != Some(false))
392            .unwrap_or(false),
393        _ => false,
394    }
395}
396
397/// Authenticate the caller from the `Authorization: Bearer` header.
398///
399/// Returns the `(code, message)` of the error response on failure.
400async fn require_caller(
401    state: &ApiState,
402    headers: &HeaderMap,
403) -> Result<crate::tokens::AuthToken, (&'static str, &'static str)> {
404    let token = extract_bearer_token(headers).ok_or(("UNAUTHORIZED", "Authentication required"))?;
405    validate_api_token(&state.auth_framework, &token)
406        .await
407        .map_err(|_| ("UNAUTHORIZED", "Invalid or expired token"))
408}
409
410/// A caller may manage an account's passkeys if it is that account, or an admin.
411fn may_manage(caller: &crate::tokens::AuthToken, target_user_id: &str) -> bool {
412    caller.user_id == target_user_id || caller.roles.contains("admin")
413}
414
415/// Credentials are stored per ACCOUNT ID, never per caller-supplied name.
416fn credential_key(user_id: &str, credential_id: &str) -> String {
417    format!("webauthn_credential:{user_id}:{credential_id}")
418}
419
420fn credential_index_key(user_id: &str) -> String {
421    format!("webauthn_creds_index:{user_id}")
422}
423
424/// `scheme://host[:port]` of an http(s) URL, with default ports elided; `None` otherwise.
425fn normalize_origin(origin: &str) -> Option<String> {
426    let url = url::Url::parse(origin).ok()?;
427    if !matches!(url.scheme(), "http" | "https") {
428        return None;
429    }
430    // An origin is scheme://host[:port] and nothing else: no credentials, path, query or
431    // fragment (`Url::origin()` would silently discard them).
432    if !url.username().is_empty()
433        || url.password().is_some()
434        || url.query().is_some()
435        || url.fragment().is_some()
436        || url.path() != "/"
437    {
438        return None;
439    }
440    Some(url.origin().ascii_serialization())
441}
442
443/// Check the client-data `origin` against the configured origins: scheme, host and port must
444/// all match. A missing origin is a refusal: the origin binding is what ties the ceremony to
445/// this site, so it cannot be optional.
446fn check_origin(
447    client_data: &serde_json::Value,
448    config: &WebAuthnConfig,
449) -> Result<(), &'static str> {
450    const MISMATCH: &str = "Origin mismatch: does not match the relying party's origin";
451    let origin = client_data
452        .get("origin")
453        .and_then(|o| o.as_str())
454        .ok_or("Missing origin in client data")?;
455    match normalize_origin(origin) {
456        Some(normalized) if config.expected_origins().contains(&normalized) => Ok(()),
457        _ => Err(MISMATCH),
458    }
459}
460
461/// Check the authenticator data of an assertion (WebAuthn section 7.2): it must be for this
462/// relying party (`rpIdHash`), the user must have been present (UP), and verified (UV) when
463/// the server requires it.
464fn check_authenticator_data(
465    auth_data: &[u8],
466    rp_id: &str,
467    require_user_verification: bool,
468) -> Result<(), &'static str> {
469    if auth_data.len() < 37 {
470        return Err("Authenticator data is too short");
471    }
472    if auth_data[..32] != Sha256::digest(rp_id.as_bytes())[..] {
473        return Err("Authenticator data is for a different relying party");
474    }
475    let flags = auth_data[32];
476    if flags & 0x01 == 0 {
477        return Err("User presence flag is not set");
478    }
479    if require_user_verification && flags & 0x04 == 0 {
480        return Err("User verification is required but was not performed");
481    }
482    Ok(())
483}
484
485/// Initiate WebAuthn registration process.
486///
487/// Requires a bearer token. The caller must be the account named by
488/// `username`, or an admin: registering a credential gives the holder of
489/// its private key the ability to sign in as the account.
490pub async fn webauthn_registration_init(
491    State(state): State<ApiState>,
492    headers: HeaderMap,
493    Json(request): Json<WebAuthnRegistrationInitRequest>,
494) -> Json<ApiResponse<WebAuthnRegistrationResponse>> {
495    let caller = match require_caller(&state, &headers).await {
496        Ok(caller) => caller,
497        Err((code, message)) => return Json(ApiResponse::error_typed(code, message)),
498    };
499
500    // Validate username format before processing
501    if let Err(e) = crate::utils::validation::validate_username(&request.username) {
502        return Json(ApiResponse::error_typed("VALIDATION_ERROR", format!("{e}")));
503    }
504
505    let webauthn_cfg = WebAuthnConfig::from_env();
506    if !attestation_supported(&webauthn_cfg.attestation) {
507        return Json(ApiResponse::error_typed(
508            "ATTESTATION_UNSUPPORTED",
509            "This server cannot verify attestation statements; set WEBAUTHN_ATTESTATION=none",
510        ));
511    }
512
513    // Same answer whether the account is missing or belongs to someone
514    // else, so this cannot be used to probe which usernames exist.
515    let storage = state.auth_framework.storage();
516    let target_user_id = match resolve_user_id(&storage, &request.username).await {
517        Some(id) if may_manage(&caller, &id) && account_is_active(&storage, &id).await => id,
518        _ => {
519            return Json(ApiResponse::error_typed(
520                "FORBIDDEN",
521                "You can only register credentials for your own account",
522            ));
523        }
524    };
525
526    // Generate a secure challenge
527    let mut challenge_bytes = [0u8; 32];
528    rand::rng().fill_bytes(&mut challenge_bytes);
529    let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(challenge_bytes);
530
531    // The WebAuthn user handle is the opaque account id, not the username.
532    let user_handle =
533        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(target_user_id.as_bytes());
534
535    // Create session ID for tracking this registration
536    let session_id = format!("webauthn_{}", uuid::Uuid::new_v4());
537
538    let response = WebAuthnRegistrationResponse {
539        challenge: challenge.clone(),
540        rp: PublicKeyCredentialRpEntity {
541            id: webauthn_cfg.rp_id,
542            name: webauthn_cfg.rp_name,
543        },
544        user: PublicKeyCredentialUserEntity {
545            id: user_handle,
546            name: request.username.clone(),
547            display_name: request.display_name.unwrap_or(request.username.clone()),
548        },
549        pubkey_cred_params: PublicKeyCredentialParameters::defaults(),
550        timeout: Some(webauthn_cfg.timeout_ms),
551        exclude_credentials: None,
552        authenticator_selection: Some(AuthenticatorSelectionCriteria {
553            authenticator_attachment: request.authenticator_attachment,
554            require_resident_key: Some(false),
555            user_verification: webauthn_cfg.user_verification.clone(),
556        }),
557        // The server does not verify attestation statements, so it only
558        // ever asks for "none" (see `attestation_supported`).
559        attestation: webauthn_cfg.attestation,
560        session_id: session_id.clone(),
561    };
562
563    // Store the challenge, the target account and the authenticated
564    // caller with a 5-minute TTL. The caller is bound so the session id
565    // alone is not a capability.
566    let session_key = format!("webauthn_reg_session:{}", session_id);
567    let session_data = serde_json::json!({
568        "challenge": challenge,
569        "user_id": target_user_id,
570        "caller_id": caller.user_id,
571        "timestamp": chrono::Utc::now().timestamp()
572    });
573    if let Err(e) = storage
574        .store_kv(
575            &session_key,
576            session_data.to_string().as_bytes(),
577            Some(std::time::Duration::from_secs(300)),
578        )
579        .await
580    {
581        tracing::error!("Failed to store WebAuthn registration session: {}", e);
582        return Json(ApiResponse::error_typed(
583            "INTERNAL_ERROR",
584            "Failed to start registration",
585        ));
586    }
587
588    Json(ApiResponse::success_with_message(
589        response,
590        "WebAuthn registration challenge generated",
591    ))
592}
593
594/// Complete WebAuthn registration process.
595///
596/// Requires the same bearer token that started the ceremony. The server
597/// does not verify attestation statements (see [`attestation_supported`]):
598/// the credential is trusted because an authenticated session for the
599/// account registered it, not because of what the authenticator claims.
600pub async fn webauthn_registration_complete(
601    State(state): State<ApiState>,
602    headers: HeaderMap,
603    Json(request): Json<WebAuthnRegistrationCompleteRequest>,
604) -> Json<ApiResponse<()>> {
605    let caller = match require_caller(&state, &headers).await {
606        Ok(caller) => caller,
607        Err((code, message)) => return Json(ApiResponse::error_typed(code, message)),
608    };
609
610    // Retrieve the stored session to validate the challenge
611    let session_key = format!("webauthn_reg_session:{}", request.session_id);
612    let storage = state.auth_framework.storage();
613
614    let (user_id, session_caller, stored_challenge) = match storage.get_kv(&session_key).await {
615        Ok(Some(data)) => {
616            let session: serde_json::Value =
617                serde_json::from_slice(&data).unwrap_or(serde_json::Value::Null);
618            let field = |name: &str| {
619                session
620                    .get(name)
621                    .and_then(|v| v.as_str())
622                    .unwrap_or("")
623                    .to_string()
624            };
625            (field("user_id"), field("caller_id"), field("challenge"))
626        }
627        _ => {
628            return Json(ApiResponse::validation_error(
629                "Session not found or expired",
630            ));
631        }
632    };
633    if user_id.is_empty() || stored_challenge.is_empty() {
634        return Json(ApiResponse::validation_error(
635            "Session not found or expired",
636        ));
637    }
638
639    // Only the caller that started the ceremony may finish it. Checked
640    // before the session is consumed so a stranger cannot burn it.
641    if session_caller != caller.user_id {
642        return Json(ApiResponse::error_typed(
643            "FORBIDDEN",
644            "This registration session belongs to another account",
645        ));
646    }
647
648    // Claim the session atomically, then delete it (see the authentication handler).
649    match storage
650        .store_kv_if_absent(
651            &format!("webauthn_session_claimed:{}", request.session_id),
652            b"1",
653            Some(std::time::Duration::from_secs(600)),
654        )
655        .await
656    {
657        Ok(true) => {}
658        Ok(false) | Err(_) => {
659            return Json(ApiResponse::error_typed(
660                "SESSION_EXPIRED",
661                "Registration session not found or expired",
662            ));
663        }
664    }
665    if let Err(e) = storage.delete_kv(&session_key).await {
666        tracing::warn!("Failed to delete WebAuthn registration session: {}", e);
667    }
668
669    // The account may have been deactivated since the ceremony began.
670    if !account_is_active(&storage, &user_id).await {
671        return Json(ApiResponse::error_typed(
672            "FORBIDDEN",
673            "You can only register credentials for your own account",
674        ));
675    }
676
677    // Basic validation of credential data
678    if request.credential_id.is_empty() || request.attestation_object.is_empty() {
679        return Json(ApiResponse::validation_error("Invalid credential data"));
680    }
681    let key_ok = base64::engine::general_purpose::URL_SAFE_NO_PAD
682        .decode(&request.credential_public_key)
683        .or_else(|_| {
684            base64::engine::general_purpose::STANDARD.decode(&request.credential_public_key)
685        })
686        .map(|key| !key.is_empty() && key.len() <= 1024)
687        .unwrap_or(false);
688    if !key_ok {
689        return Json(ApiResponse::validation_error(
690            "Invalid credential public key",
691        ));
692    }
693
694    // Verify client_data_json: challenge, origin, and type
695    let client_data_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
696        .decode(&request.client_data_json)
697        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.client_data_json))
698    {
699        Ok(b) => b,
700        Err(_) => {
701            return Json(ApiResponse::validation_error(
702                "Invalid client_data_json encoding",
703            ));
704        }
705    };
706
707    let client_data: serde_json::Value = match serde_json::from_slice(&client_data_bytes) {
708        Ok(v) => v,
709        Err(_) => {
710            return Json(ApiResponse::validation_error(
711                "Invalid client_data_json format",
712            ));
713        }
714    };
715
716    // Verify type is "webauthn.create"
717    if client_data.get("type").and_then(|t| t.as_str()) != Some("webauthn.create") {
718        return Json(ApiResponse::validation_error(
719            "Invalid ceremony type: expected webauthn.create",
720        ));
721    }
722
723    // Verify challenge matches the one we stored
724    if let Some(received_challenge) = client_data.get("challenge").and_then(|c| c.as_str()) {
725        if received_challenge != stored_challenge {
726            return Json(ApiResponse::validation_error(
727                "Challenge mismatch: possible replay attack",
728            ));
729        }
730    } else {
731        return Json(ApiResponse::validation_error(
732            "Missing challenge in client data",
733        ));
734    }
735
736    // Verify origin matches the configured RP ID (a missing origin is refused)
737    if let Err(message) = check_origin(&client_data, &WebAuthnConfig::from_env()) {
738        return Json(ApiResponse::validation_error(message));
739    }
740
741    // Store the registered credential (including initial signature counter)
742    let credential_key = credential_key(&user_id, &request.credential_id);
743    let credential_data = serde_json::json!({
744        "credential_id": request.credential_id,
745        "credential_public_key": request.credential_public_key,
746        "user_id": user_id,
747        "registered_at": chrono::Utc::now().timestamp(),
748        "sign_count": 0u64
749    });
750    if let Err(e) = storage
751        .store_kv(
752            &credential_key,
753            credential_data.to_string().as_bytes(),
754            None,
755        )
756        .await
757    {
758        tracing::error!("Failed to store WebAuthn credential: {}", e);
759        return Json(ApiResponse::error_typed(
760            "INTERNAL_ERROR",
761            "Failed to store credential",
762        ));
763    }
764
765    // Update the user's credential index so authentication can enumerate them
766    let index_key = credential_index_key(&user_id);
767    let mut existing_ids: Vec<String> = match storage.get_kv(&index_key).await {
768        Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
769        _ => Vec::new(),
770    };
771    if !existing_ids.contains(&request.credential_id) {
772        existing_ids.push(request.credential_id.clone());
773        if let Err(e) = storage
774            .store_kv(
775                &index_key,
776                serde_json::to_string(&existing_ids)
777                    .unwrap_or_default()
778                    .as_bytes(),
779                None,
780            )
781            .await
782        {
783            tracing::error!("Failed to update WebAuthn credential index: {}", e);
784            return Json(ApiResponse::error_typed(
785                "INTERNAL_ERROR",
786                "Failed to store credential",
787            ));
788        }
789    }
790
791    Json(ApiResponse::<()>::ok_with_message(
792        "WebAuthn credential registered successfully",
793    ))
794}
795
796/// Initiate WebAuthn authentication process
797pub async fn webauthn_authentication_init(
798    State(state): State<ApiState>,
799    Json(request): Json<WebAuthnAuthenticationRequest>,
800) -> Json<ApiResponse<WebAuthnAuthenticationResponse>> {
801    let mut challenge_bytes = [0u8; 32];
802    rand::rng().fill_bytes(&mut challenge_bytes);
803    let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(challenge_bytes);
804
805    let session_id = format!("webauthn_auth_{}", uuid::Uuid::new_v4());
806    let storage = state.auth_framework.storage();
807
808    // Retrieve the account's registered credentials from storage. An
809    // unknown username yields an empty list, exactly like an account with
810    // no credentials, so this does not reveal which usernames exist.
811    let username = request.username.as_deref().unwrap_or("");
812    let account_id = if username.is_empty() {
813        None
814    } else {
815        resolve_user_id(&storage, username).await
816    };
817    let allow_credentials = if let Some(account_id) = account_id.as_deref() {
818        // Look up registered credential IDs via the account's credential index
819        let index_key = credential_index_key(account_id);
820        match storage.get_kv(&index_key).await {
821            Ok(Some(data)) => {
822                if let Ok(ids) = serde_json::from_slice::<Vec<String>>(&data) {
823                    ids.into_iter()
824                        .map(|id| PublicKeyCredentialDescriptor {
825                            type_field: "public-key".to_string(),
826                            id,
827                            transports: Some(vec!["internal".to_string(), "usb".to_string()]),
828                        })
829                        .collect::<Vec<_>>()
830                } else {
831                    Vec::new()
832                }
833            }
834            _ => Vec::new(),
835        }
836    } else {
837        Vec::new()
838    };
839
840    // Store auth session with challenge
841    let session_key = format!("webauthn_auth_session:{}", session_id);
842    let session_data = serde_json::json!({
843        "challenge": challenge,
844        "username": request.username,
845        "timestamp": chrono::Utc::now().timestamp()
846    });
847    let _ = storage
848        .store_kv(
849            &session_key,
850            session_data.to_string().as_bytes(),
851            Some(std::time::Duration::from_secs(300)), // 5-minute session
852        )
853        .await;
854
855    let response = WebAuthnAuthenticationResponse {
856        challenge,
857        allow_credentials,
858        timeout: Some(60000),
859        // The requirement is the server's, not the caller's.
860        user_verification: WebAuthnConfig::from_env().user_verification,
861        session_id,
862    };
863
864    Json(ApiResponse::success_with_message(
865        response,
866        "WebAuthn authentication challenge generated",
867    ))
868}
869
870/// Complete WebAuthn authentication process
871pub async fn webauthn_authentication_complete(
872    State(state): State<ApiState>,
873    Json(request): Json<WebAuthnAuthenticationCompleteRequest>,
874) -> Json<ApiResponse<serde_json::Value>> {
875    let storage = state.auth_framework.storage();
876    let session_key = format!("webauthn_auth_session:{}", request.session_id);
877
878    // Retrieve and validate the stored session
879    let (username, stored_challenge) = match storage.get_kv(&session_key).await {
880        Ok(Some(data)) => {
881            let session: serde_json::Value =
882                serde_json::from_slice(&data).unwrap_or(serde_json::Value::Null);
883            let uname = session
884                .get("username")
885                .and_then(|u| u.as_str())
886                .unwrap_or("")
887                .to_string();
888            let challenge = session
889                .get("challenge")
890                .and_then(|c| c.as_str())
891                .unwrap_or("")
892                .to_string();
893            (uname, challenge)
894        }
895        _ => {
896            return Json(ApiResponse::validation_error_typed(
897                "Authentication session not found or expired",
898            ));
899        }
900    };
901
902    // Claim the session atomically, then delete it: of simultaneous completions of the same
903    // ceremony exactly one proceeds (a plain delete after a read lets several through).
904    match storage
905        .store_kv_if_absent(
906            &format!("webauthn_session_claimed:{}", request.session_id),
907            b"1",
908            Some(std::time::Duration::from_secs(600)),
909        )
910        .await
911    {
912        Ok(true) => {}
913        Ok(false) => {
914            return Json(ApiResponse::validation_error_typed(
915                "Authentication session not found or expired",
916            ));
917        }
918        Err(e) => {
919            tracing::error!("Failed to claim WebAuthn authentication session: {}", e);
920            return Json(ApiResponse::validation_error_typed(
921                "Authentication session not found or expired",
922            ));
923        }
924    }
925    if let Err(e) = storage.delete_kv(&session_key).await {
926        tracing::warn!("Failed to delete WebAuthn authentication session: {}", e);
927    }
928
929    // Verify client_data_json: challenge, origin, and type
930    let client_data_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
931        .decode(&request.client_data_json)
932        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.client_data_json))
933    {
934        Ok(b) => b,
935        Err(_) => {
936            return Json(ApiResponse::validation_error_typed(
937                "Invalid client_data_json encoding",
938            ));
939        }
940    };
941
942    let client_data: serde_json::Value = match serde_json::from_slice(&client_data_bytes) {
943        Ok(v) => v,
944        Err(_) => {
945            return Json(ApiResponse::validation_error_typed(
946                "Invalid client_data_json format",
947            ));
948        }
949    };
950
951    // Verify type is "webauthn.get"
952    if client_data.get("type").and_then(|t| t.as_str()) != Some("webauthn.get") {
953        return Json(ApiResponse::validation_error_typed(
954            "Invalid ceremony type: expected webauthn.get",
955        ));
956    }
957
958    // Verify challenge matches the one we stored
959    if let Some(received_challenge) = client_data.get("challenge").and_then(|c| c.as_str()) {
960        if received_challenge != stored_challenge {
961            return Json(ApiResponse::validation_error_typed(
962                "Challenge mismatch: possible replay attack",
963            ));
964        }
965    } else {
966        return Json(ApiResponse::validation_error_typed(
967            "Missing challenge in client data",
968        ));
969    }
970
971    // Verify origin matches the configured RP ID (a missing origin is refused)
972    let webauthn_cfg = WebAuthnConfig::from_env();
973    if let Err(message) = check_origin(&client_data, &webauthn_cfg) {
974        return Json(ApiResponse::validation_error_typed(message));
975    }
976
977    // Resolve the session's username to the REAL account, which must exist
978    // and be active, before anything is looked up or minted. This failure
979    // and "no such credential" below get the same answer, so the response
980    // cannot be used to probe which usernames exist.
981    let user_id = match resolve_user_id(&storage, &username).await {
982        Some(id) if account_is_active(&storage, &id).await => id,
983        _ => {
984            return Json(ApiResponse::validation_error_typed("Authentication failed"));
985        }
986    };
987
988    // Retrieve stored credential to verify it exists and check signature counter
989    let credential_key = credential_key(&user_id, &request.credential_id);
990    let stored_credential = match storage.get_kv(&credential_key).await {
991        Ok(Some(data)) => {
992            serde_json::from_slice::<serde_json::Value>(&data).unwrap_or(serde_json::Value::Null)
993        }
994        _ => {
995            return Json(ApiResponse::validation_error_typed("Authentication failed"));
996        }
997    };
998
999    // Check and update signature counter to detect cloned authenticators
1000    let stored_count = stored_credential
1001        .get("sign_count")
1002        .and_then(|c| c.as_u64())
1003        .unwrap_or(0);
1004    // Extract sign_count from authenticator_data (bytes 33-36 are the counter, big-endian)
1005    let new_count = base64::engine::general_purpose::URL_SAFE_NO_PAD
1006        .decode(&request.authenticator_data)
1007        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.authenticator_data))
1008        .ok()
1009        .filter(|d| d.len() >= 37)
1010        .map(|d| u32::from_be_bytes([d[33], d[34], d[35], d[36]]) as u64)
1011        .unwrap_or(0);
1012    if new_count > 0 && new_count <= stored_count {
1013        tracing::warn!(
1014            "WebAuthn signature counter regression for user {}: stored={}, received={}. Possible cloned authenticator.",
1015            username,
1016            stored_count,
1017            new_count
1018        );
1019        return Json(ApiResponse::validation_error_typed(
1020            "Signature counter regression detected: possible cloned authenticator",
1021        ));
1022    }
1023
1024    // ---- Cryptographic signature verification (WebAuthn §7.2 step 19-20) ----
1025    // 1. Decode the authenticator data and the raw client data JSON bytes
1026    let auth_data_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
1027        .decode(&request.authenticator_data)
1028        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.authenticator_data))
1029    {
1030        Ok(b) => b,
1031        Err(_) => {
1032            return Json(ApiResponse::validation_error_typed(
1033                "Invalid authenticator_data encoding",
1034            ));
1035        }
1036    };
1037
1038    // 1b. The assertion must be for this relying party, with the user present (and verified
1039    // when the server requires it): WebAuthn section 7.2.
1040    if let Err(message) = check_authenticator_data(
1041        &auth_data_bytes,
1042        &webauthn_cfg.rp_id,
1043        webauthn_cfg.user_verification == "required",
1044    ) {
1045        return Json(ApiResponse::validation_error_typed(message));
1046    }
1047
1048    // 2. Compute SHA-256 hash of the raw client_data_json bytes
1049    let client_data_hash = {
1050        let mut hasher = Sha256::new();
1051        hasher.update(&client_data_bytes);
1052        hasher.finalize()
1053    };
1054
1055    // 3. Build the signed message: authenticatorData || SHA-256(clientDataJSON)
1056    let mut signed_message = auth_data_bytes.clone();
1057    signed_message.extend_from_slice(&client_data_hash);
1058
1059    // 4. Decode the signature
1060    let signature_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
1061        .decode(&request.signature)
1062        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.signature))
1063    {
1064        Ok(b) => b,
1065        Err(_) => {
1066            return Json(ApiResponse::validation_error_typed(
1067                "Invalid signature encoding",
1068            ));
1069        }
1070    };
1071
1072    // 5. Retrieve the stored public key and verify the signature
1073    let credential_pub_key = stored_credential
1074        .get("credential_public_key")
1075        .and_then(|k| k.as_str())
1076        .unwrap_or("");
1077
1078    if credential_pub_key.is_empty() {
1079        return Json(ApiResponse::validation_error_typed(
1080            "No public key stored for this credential",
1081        ));
1082    }
1083
1084    // Decode the stored public key (base64url or standard base64)
1085    let pub_key_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
1086        .decode(credential_pub_key)
1087        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(credential_pub_key))
1088    {
1089        Ok(b) => b,
1090        Err(_) => {
1091            return Json(ApiResponse::validation_error_typed(
1092                "Failed to decode stored public key",
1093            ));
1094        }
1095    };
1096
1097    // Try ES256 (ECDSA P-256) first, then RS256 (RSA PKCS#1 v1.5 with SHA-256)
1098    let sig_valid = {
1099        // Attempt ES256 verification (COSE algorithm -7)
1100        let es256_result = ring::signature::UnparsedPublicKey::new(
1101            &ring::signature::ECDSA_P256_SHA256_ASN1,
1102            &pub_key_bytes,
1103        )
1104        .verify(&signed_message, &signature_bytes);
1105
1106        if es256_result.is_ok() {
1107            true
1108        } else {
1109            // Attempt RS256 verification (COSE algorithm -257)
1110            ring::signature::UnparsedPublicKey::new(
1111                &ring::signature::RSA_PKCS1_2048_8192_SHA256,
1112                &pub_key_bytes,
1113            )
1114            .verify(&signed_message, &signature_bytes)
1115            .is_ok()
1116        }
1117    };
1118
1119    if !sig_valid {
1120        tracing::warn!(
1121            "WebAuthn signature verification failed for user {} credential {}",
1122            username,
1123            request.credential_id
1124        );
1125        return Json(ApiResponse::validation_error_typed(
1126            "Signature verification failed: authentication assertion is not valid",
1127        ));
1128    }
1129
1130    // Update the stored counter
1131    let mut updated_cred = stored_credential.clone();
1132    if let Some(obj) = updated_cred.as_object_mut() {
1133        obj.insert("sign_count".to_string(), serde_json::json!(new_count));
1134    }
1135    if let Err(e) = storage
1136        .store_kv(
1137            &credential_key,
1138            serde_json::to_string(&updated_cred)
1139                .unwrap_or_default()
1140                .as_bytes(),
1141            None,
1142        )
1143        .await
1144    {
1145        tracing::warn!(
1146            "Failed to update WebAuthn credential counter for {}: {}",
1147            username,
1148            e
1149        );
1150    }
1151
1152    // Generate authentication token for the verified user
1153    let token_lifetime = state.auth_framework.config().token_lifetime;
1154    let token = match state.auth_framework.token_manager().create_jwt_token(
1155        &user_id,
1156        vec![],
1157        Some(token_lifetime),
1158    ) {
1159        Ok(t) => t,
1160        Err(e) => {
1161            return Json(ApiResponse::validation_error_typed(format!(
1162                "Token generation failed: {}",
1163                e
1164            )));
1165        }
1166    };
1167
1168    let auth_response = serde_json::json!({
1169        "access_token": token,
1170        "token_type": "Bearer",
1171        "expires_in": token_lifetime.as_secs(),
1172        "user_id": user_id,
1173        "authentication_method": "webauthn"
1174    });
1175
1176    Json(ApiResponse::success_with_message(
1177        auth_response,
1178        "WebAuthn authentication successful",
1179    ))
1180}
1181
1182/// List an account's registered WebAuthn credentials. `username` names the
1183/// account; the caller must be that account or an admin.
1184pub async fn list_webauthn_credentials(
1185    State(state): State<ApiState>,
1186    headers: HeaderMap,
1187    axum::extract::Path(username): axum::extract::Path<String>,
1188) -> Json<ApiResponse<Vec<serde_json::Value>>> {
1189    let caller = match require_caller(&state, &headers).await {
1190        Ok(caller) => caller,
1191        Err((code, message)) => return Json(ApiResponse::error_typed(code, message)),
1192    };
1193
1194    let storage = state.auth_framework.storage();
1195    let user_id = match resolve_user_id(&storage, &username).await {
1196        Some(id) if may_manage(&caller, &id) => id,
1197        // An admin may ask about a name that does not exist: empty, not an error.
1198        None if caller.roles.contains("admin") => {
1199            return Json(ApiResponse::success_with_message(
1200                Vec::new(),
1201                format!("WebAuthn credentials retrieved for user: {}", username),
1202            ));
1203        }
1204        _ => {
1205            return Json(ApiResponse::error_typed(
1206                "FORBIDDEN",
1207                "You can only view your own credentials",
1208            ));
1209        }
1210    };
1211
1212    let credentials = match storage.get_kv(&credential_index_key(&user_id)).await {
1213        Ok(Some(data)) => {
1214            if let Ok(ids) = serde_json::from_slice::<Vec<String>>(&data) {
1215                let mut creds = Vec::new();
1216                for id in ids {
1217                    if let Ok(Some(cred_data)) =
1218                        storage.get_kv(&credential_key(&user_id, &id)).await
1219                        && let Ok(cred) = serde_json::from_slice::<serde_json::Value>(&cred_data)
1220                    {
1221                        creds.push(cred);
1222                    }
1223                }
1224                creds
1225            } else {
1226                Vec::new()
1227            }
1228        }
1229        _ => Vec::new(),
1230    };
1231
1232    Json(ApiResponse::success_with_message(
1233        credentials,
1234        format!("WebAuthn credentials retrieved for user: {}", username),
1235    ))
1236}
1237
1238/// Delete a WebAuthn credential. `username` names the account; the caller
1239/// must be that account or an admin.
1240pub async fn delete_webauthn_credential(
1241    State(state): State<ApiState>,
1242    headers: HeaderMap,
1243    axum::extract::Path((username, credential_id)): axum::extract::Path<(String, String)>,
1244) -> Json<ApiResponse<()>> {
1245    let caller = match require_caller(&state, &headers).await {
1246        Ok(caller) => caller,
1247        Err((code, message)) => return Json(ApiResponse::error(code, message)),
1248    };
1249
1250    let storage = state.auth_framework.storage();
1251    let user_id = match resolve_user_id(&storage, &username).await {
1252        Some(id) if may_manage(&caller, &id) => id,
1253        _ => {
1254            return Json(ApiResponse::error(
1255                "FORBIDDEN",
1256                "You can only delete your own credentials",
1257            ));
1258        }
1259    };
1260    let credential_key = credential_key(&user_id, &credential_id);
1261
1262    // Check credential exists before deleting
1263    match storage.get_kv(&credential_key).await {
1264        Ok(Some(_)) => {
1265            if let Err(e) = storage.delete_kv(&credential_key).await {
1266                tracing::warn!(
1267                    "Failed to delete WebAuthn credential {}: {}",
1268                    credential_id,
1269                    e
1270                );
1271            }
1272
1273            // Update the credentials index
1274            let index_key = credential_index_key(&user_id);
1275            if let Ok(Some(idx_data)) = storage.get_kv(&index_key).await
1276                && let Ok(mut ids) = serde_json::from_slice::<Vec<String>>(&idx_data)
1277            {
1278                ids.retain(|id| id != &credential_id);
1279                if let Err(e) = storage
1280                    .store_kv(
1281                        &index_key,
1282                        serde_json::to_string(&ids).unwrap_or_default().as_bytes(),
1283                        None,
1284                    )
1285                    .await
1286                {
1287                    tracing::warn!(
1288                        "Failed to update WebAuthn credentials index for {}: {}",
1289                        username,
1290                        e
1291                    );
1292                }
1293            }
1294
1295            Json(ApiResponse::<()>::ok_with_message(
1296                "WebAuthn credential deleted successfully",
1297            ))
1298        }
1299        _ => Json(ApiResponse::validation_error("Credential not found")),
1300    }
1301}
1302
1303#[cfg(test)]
1304mod tests {
1305    use super::*;
1306
1307    #[test]
1308    fn test_webauthn_config_default() {
1309        let cfg = WebAuthnConfig::default();
1310        assert_eq!(cfg.rp_id, "localhost");
1311        assert_eq!(cfg.rp_name, "AuthFramework");
1312        assert_eq!(cfg.attestation, "none");
1313        assert_eq!(cfg.timeout_ms, 60_000);
1314    }
1315
1316    #[test]
1317    fn check_origin_matches_scheme_host_and_port() {
1318        let cfg = WebAuthnConfig::new("localhost", "x");
1319        let ok =
1320            |origin: &str| check_origin(&serde_json::json!({ "origin": origin }), &cfg).is_ok();
1321        assert!(ok("https://localhost"));
1322        assert!(
1323            ok("https://localhost:443"),
1324            "default port is the same origin"
1325        );
1326        assert!(ok("http://localhost"), "dev origin for the localhost rp id");
1327        for hostile in [
1328            "https://localhost:8443",
1329            "http://localhost:8080",
1330            "ftp://localhost",
1331            "localhost",
1332            "https://localhost.evil.com",
1333            "https://evil.com",
1334            "https://localhost@evil.com",
1335            "https://evil.com/localhost",
1336            "https://notlocalhost",
1337            "",
1338        ] {
1339            assert!(!ok(hostile), "{hostile:?} must be refused");
1340        }
1341        assert!(check_origin(&serde_json::json!({}), &cfg).is_err());
1342        assert!(check_origin(&serde_json::json!({ "origin": 5 }), &cfg).is_err());
1343    }
1344
1345    #[test]
1346    fn an_origin_is_only_scheme_host_and_port() {
1347        let cfg = WebAuthnConfig::new("auth.example.com", "x");
1348        let ok =
1349            |origin: &str| check_origin(&serde_json::json!({ "origin": origin }), &cfg).is_ok();
1350        assert!(ok("https://auth.example.com"));
1351        assert!(
1352            ok("https://AUTH.example.com"),
1353            "host case is not significant"
1354        );
1355        for sloppy in [
1356            "https://user@auth.example.com",
1357            "https://user:pw@auth.example.com",
1358            "https://auth.example.com/path",
1359            "https://auth.example.com/?q=1",
1360            "https://auth.example.com/#frag",
1361            "https://auth.example.com.",
1362        ] {
1363            assert!(!ok(sloppy), "{sloppy:?} is not an origin");
1364        }
1365    }
1366
1367    #[test]
1368    fn configured_origins_replace_the_default() {
1369        let cfg = WebAuthnConfig::new("auth.example.com", "x").origins(vec![
1370            "https://app.example.com".into(),
1371            "http://localhost:3000".into(),
1372        ]);
1373        let ok =
1374            |origin: &str| check_origin(&serde_json::json!({ "origin": origin }), &cfg).is_ok();
1375        assert!(ok("https://app.example.com"));
1376        assert!(ok("http://localhost:3000"));
1377        assert!(
1378            !ok("https://auth.example.com"),
1379            "the default no longer applies"
1380        );
1381        assert!(!ok("http://localhost:3001"));
1382        // default for a real rp id is https://{rp_id}
1383        let default = WebAuthnConfig::new("auth.example.com", "x");
1384        assert!(
1385            check_origin(
1386                &serde_json::json!({"origin": "https://auth.example.com"}),
1387                &default
1388            )
1389            .is_ok()
1390        );
1391        assert!(
1392            check_origin(
1393                &serde_json::json!({"origin": "http://auth.example.com"}),
1394                &default
1395            )
1396            .is_err()
1397        );
1398    }
1399
1400    #[test]
1401    fn authenticator_data_is_checked_for_rp_presence_and_verification() {
1402        let data = |rp: &str, flags: u8| {
1403            let mut d = vec![0u8; 37];
1404            d[..32].copy_from_slice(&Sha256::digest(rp.as_bytes()));
1405            d[32] = flags;
1406            d
1407        };
1408        assert!(check_authenticator_data(&data("localhost", 0x01), "localhost", false).is_ok());
1409        assert!(check_authenticator_data(&data("localhost", 0x05), "localhost", true).is_ok());
1410        // wrong relying party
1411        assert!(check_authenticator_data(&data("evil.com", 0x01), "localhost", false).is_err());
1412        // user not present
1413        assert!(check_authenticator_data(&data("localhost", 0x04), "localhost", false).is_err());
1414        // verification required but not performed
1415        assert!(check_authenticator_data(&data("localhost", 0x01), "localhost", true).is_err());
1416        // too short
1417        assert!(check_authenticator_data(&[0u8; 36], "localhost", false).is_err());
1418    }
1419
1420    #[test]
1421    fn test_only_attestation_none_is_supported() {
1422        assert!(attestation_supported("none"));
1423        for unsupported in ["direct", "indirect", "enterprise", ""] {
1424            assert!(!attestation_supported(unsupported), "{unsupported}");
1425        }
1426    }
1427
1428    #[test]
1429    fn test_webauthn_config_new_and_chain() {
1430        let cfg = WebAuthnConfig::new("auth.example.com", "My Service")
1431            .attestation("none")
1432            .timeout(120_000);
1433        assert_eq!(cfg.rp_id, "auth.example.com");
1434        assert_eq!(cfg.rp_name, "My Service");
1435        assert_eq!(cfg.attestation, "none");
1436        assert_eq!(cfg.timeout_ms, 120_000);
1437    }
1438
1439    #[test]
1440    fn test_pubkey_cred_params_presets() {
1441        let es = PublicKeyCredentialParameters::es256();
1442        assert_eq!(es.alg, -7);
1443        assert_eq!(es.type_field, "public-key");
1444
1445        let rs = PublicKeyCredentialParameters::rs256();
1446        assert_eq!(rs.alg, -257);
1447        assert_eq!(rs.type_field, "public-key");
1448    }
1449
1450    #[test]
1451    fn test_pubkey_cred_params_defaults_contains_both() {
1452        let params = PublicKeyCredentialParameters::defaults();
1453        assert_eq!(params.len(), 2);
1454        assert_eq!(params[0].alg, -7);
1455        assert_eq!(params[1].alg, -257);
1456    }
1457}