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