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}
43
44impl Default for WebAuthnConfig {
45    fn default() -> Self {
46        Self {
47            rp_id: "localhost".to_string(),
48            rp_name: "AuthFramework".to_string(),
49            attestation: "none".to_string(),
50            timeout_ms: 60_000,
51        }
52    }
53}
54
55impl WebAuthnConfig {
56    /// Create a config with the given RP id and name.
57    pub fn new(rp_id: impl Into<String>, rp_name: impl Into<String>) -> Self {
58        Self {
59            rp_id: rp_id.into(),
60            rp_name: rp_name.into(),
61            ..Self::default()
62        }
63    }
64
65    /// Build a config from environment variables.
66    ///
67    /// | Variable | Default |
68    /// |----------|---------|
69    /// | `WEBAUTHN_RP_ID` | `"localhost"` |
70    /// | `WEBAUTHN_RP_NAME` | `"AuthFramework"` |
71    /// | `WEBAUTHN_ATTESTATION` | `"none"` |
72    /// | `WEBAUTHN_TIMEOUT_MS` | `60000` |
73    pub fn from_env() -> Self {
74        Self {
75            rp_id: std::env::var("WEBAUTHN_RP_ID").unwrap_or_else(|_| "localhost".to_string()),
76            rp_name: std::env::var("WEBAUTHN_RP_NAME")
77                .unwrap_or_else(|_| "AuthFramework".to_string()),
78            attestation: std::env::var("WEBAUTHN_ATTESTATION")
79                .unwrap_or_else(|_| "none".to_string()),
80            timeout_ms: std::env::var("WEBAUTHN_TIMEOUT_MS")
81                .ok()
82                .and_then(|v| v.parse().ok())
83                .unwrap_or(60_000),
84        }
85    }
86
87    /// Set the attestation conveyance preference.
88    pub fn attestation(mut self, attestation: impl Into<String>) -> Self {
89        self.attestation = attestation.into();
90        self
91    }
92
93    /// Set the ceremony timeout in milliseconds.
94    pub fn timeout(mut self, ms: u64) -> Self {
95        self.timeout_ms = ms;
96        self
97    }
98}
99
100/// Whether this server can honour an attestation conveyance preference.
101///
102/// The server does not verify attestation statements, so it only accepts
103/// `"none"`: asking an authenticator for an attestation it then ignores
104/// would look like provenance checking while providing none.
105pub(crate) fn attestation_supported(preference: &str) -> bool {
106    preference == "none"
107}
108
109/// Request to initiate WebAuthn registration
110#[derive(Debug, Serialize, Deserialize)]
111pub struct WebAuthnRegistrationInitRequest {
112    pub username: String,
113    pub display_name: Option<String>,
114    pub authenticator_attachment: Option<String>, // "platform" or "cross-platform"
115    pub user_verification: Option<String>,        // "required", "preferred", "discouraged"
116}
117
118/// WebAuthn registration challenge response
119#[derive(Debug, Serialize, Deserialize)]
120pub struct WebAuthnRegistrationResponse {
121    pub challenge: String,
122    pub rp: PublicKeyCredentialRpEntity,
123    pub user: PublicKeyCredentialUserEntity,
124    pub pubkey_cred_params: Vec<PublicKeyCredentialParameters>,
125    pub timeout: Option<u64>,
126    #[serde(rename = "excludeCredentials")]
127    pub exclude_credentials: Option<Vec<PublicKeyCredentialDescriptor>>,
128    #[serde(rename = "authenticatorSelection")]
129    pub authenticator_selection: Option<AuthenticatorSelectionCriteria>,
130    pub attestation: String,
131    pub session_id: String,
132}
133
134/// Complete WebAuthn registration
135#[derive(Debug, Serialize, Deserialize)]
136pub struct WebAuthnRegistrationCompleteRequest {
137    pub session_id: String,
138    pub credential_id: String,
139    pub credential_public_key: String,
140    pub attestation_object: String,
141    pub client_data_json: String,
142    pub authenticator_data: String,
143    pub signature: String,
144}
145
146/// WebAuthn authentication initiation request
147#[derive(Debug, Serialize, Deserialize)]
148pub struct WebAuthnAuthenticationRequest {
149    pub username: Option<String>,
150    pub user_verification: Option<String>,
151}
152
153/// WebAuthn authentication challenge response
154#[derive(Debug, Serialize, Deserialize)]
155pub struct WebAuthnAuthenticationResponse {
156    pub challenge: String,
157    pub allow_credentials: Vec<PublicKeyCredentialDescriptor>,
158    pub timeout: Option<u64>,
159    pub user_verification: String,
160    pub session_id: String,
161}
162
163/// Complete WebAuthn authentication
164#[derive(Debug, Serialize, Deserialize)]
165pub struct WebAuthnAuthenticationCompleteRequest {
166    pub session_id: String,
167    pub credential_id: String,
168    pub authenticator_data: String,
169    pub client_data_json: String,
170    pub signature: String,
171    pub user_handle: Option<String>,
172}
173
174/// Supporting structures
175#[derive(Debug, Serialize, Deserialize)]
176pub struct PublicKeyCredentialRpEntity {
177    pub id: String,
178    pub name: String,
179}
180
181#[derive(Debug, Serialize, Deserialize)]
182pub struct PublicKeyCredentialUserEntity {
183    pub id: String,
184    pub name: String,
185    pub display_name: String,
186}
187
188#[derive(Debug, Serialize, Deserialize)]
189pub struct PublicKeyCredentialParameters {
190    #[serde(rename = "type")]
191    pub type_field: String,
192    pub alg: i32,
193}
194
195impl PublicKeyCredentialParameters {
196    /// ES256 (ECDSA P-256) — COSE algorithm −7.
197    pub fn es256() -> Self {
198        Self {
199            type_field: "public-key".to_string(),
200            alg: -7,
201        }
202    }
203
204    /// RS256 (RSASSA-PKCS1-v1_5 with SHA-256) — COSE algorithm −257.
205    pub fn rs256() -> Self {
206        Self {
207            type_field: "public-key".to_string(),
208            alg: -257,
209        }
210    }
211
212    /// Default WebAuthn parameter set: ES256 + RS256.
213    pub fn defaults() -> Vec<Self> {
214        vec![Self::es256(), Self::rs256()]
215    }
216}
217
218#[derive(Debug, Serialize, Deserialize)]
219pub struct PublicKeyCredentialDescriptor {
220    #[serde(rename = "type")]
221    pub type_field: String,
222    pub id: String,
223    pub transports: Option<Vec<String>>,
224}
225
226#[derive(Debug, Serialize, Deserialize)]
227pub struct AuthenticatorSelectionCriteria {
228    pub authenticator_attachment: Option<String>,
229    pub require_resident_key: Option<bool>,
230    pub user_verification: String,
231}
232
233type SharedStorage = std::sync::Arc<dyn crate::storage::AuthStorage>;
234
235/// Resolve a username to its account id via the `user:username:{name}`
236/// index every registration path maintains.
237async fn resolve_user_id(storage: &SharedStorage, username: &str) -> Option<String> {
238    let bytes = storage
239        .get_kv(&format!("user:username:{username}"))
240        .await
241        .ok()
242        .flatten()?;
243    String::from_utf8(bytes).ok().filter(|id| !id.is_empty())
244}
245
246/// `true` when `user:{id}` exists, parses, and is not deactivated.
247async fn account_is_active(storage: &SharedStorage, user_id: &str) -> bool {
248    match storage.get_kv(&format!("user:{user_id}")).await {
249        Ok(Some(bytes)) => serde_json::from_slice::<serde_json::Value>(&bytes)
250            .map(|record| record["active"].as_bool() != Some(false))
251            .unwrap_or(false),
252        _ => false,
253    }
254}
255
256/// Authenticate the caller from the `Authorization: Bearer` header.
257///
258/// Returns the `(code, message)` of the error response on failure.
259async fn require_caller(
260    state: &ApiState,
261    headers: &HeaderMap,
262) -> Result<crate::tokens::AuthToken, (&'static str, &'static str)> {
263    let token = extract_bearer_token(headers).ok_or(("UNAUTHORIZED", "Authentication required"))?;
264    validate_api_token(&state.auth_framework, &token)
265        .await
266        .map_err(|_| ("UNAUTHORIZED", "Invalid or expired token"))
267}
268
269/// A caller may manage an account's passkeys if it is that account, or an admin.
270fn may_manage(caller: &crate::tokens::AuthToken, target_user_id: &str) -> bool {
271    caller.user_id == target_user_id || caller.roles.contains("admin")
272}
273
274/// Credentials are stored per ACCOUNT ID, never per caller-supplied name.
275fn credential_key(user_id: &str, credential_id: &str) -> String {
276    format!("webauthn_credential:{user_id}:{credential_id}")
277}
278
279fn credential_index_key(user_id: &str) -> String {
280    format!("webauthn_creds_index:{user_id}")
281}
282
283/// Check the client-data `origin` against the relying-party id. A missing
284/// origin is a refusal: the origin binding is what ties the ceremony to
285/// this site, so it cannot be optional.
286fn check_origin(client_data: &serde_json::Value, expected_rp_id: &str) -> Result<(), &'static str> {
287    const MISMATCH: &str = "Origin mismatch: does not match relying party ID";
288    let origin = client_data
289        .get("origin")
290        .and_then(|o| o.as_str())
291        .ok_or("Missing origin in client data")?;
292    match url::Url::parse(origin) {
293        Ok(origin_url) if origin_url.host_str() == Some(expected_rp_id) => Ok(()),
294        Ok(_) => Err(MISMATCH),
295        Err(_) if origin == expected_rp_id => Ok(()),
296        Err(_) => Err(MISMATCH),
297    }
298}
299
300/// Initiate WebAuthn registration process.
301///
302/// Requires a bearer token. The caller must be the account named by
303/// `username`, or an admin: registering a credential gives the holder of
304/// its private key the ability to sign in as the account.
305pub async fn webauthn_registration_init(
306    State(state): State<ApiState>,
307    headers: HeaderMap,
308    Json(request): Json<WebAuthnRegistrationInitRequest>,
309) -> Json<ApiResponse<WebAuthnRegistrationResponse>> {
310    let caller = match require_caller(&state, &headers).await {
311        Ok(caller) => caller,
312        Err((code, message)) => return Json(ApiResponse::error_typed(code, message)),
313    };
314
315    // Validate username format before processing
316    if let Err(e) = crate::utils::validation::validate_username(&request.username) {
317        return Json(ApiResponse::error_typed("VALIDATION_ERROR", format!("{e}")));
318    }
319
320    let webauthn_cfg = WebAuthnConfig::from_env();
321    if !attestation_supported(&webauthn_cfg.attestation) {
322        return Json(ApiResponse::error_typed(
323            "ATTESTATION_UNSUPPORTED",
324            "This server cannot verify attestation statements; set WEBAUTHN_ATTESTATION=none",
325        ));
326    }
327
328    // Same answer whether the account is missing or belongs to someone
329    // else, so this cannot be used to probe which usernames exist.
330    let storage = state.auth_framework.storage();
331    let target_user_id = match resolve_user_id(&storage, &request.username).await {
332        Some(id) if may_manage(&caller, &id) && account_is_active(&storage, &id).await => id,
333        _ => {
334            return Json(ApiResponse::error_typed(
335                "FORBIDDEN",
336                "You can only register credentials for your own account",
337            ));
338        }
339    };
340
341    // Generate a secure challenge
342    let mut challenge_bytes = [0u8; 32];
343    rand::rng().fill_bytes(&mut challenge_bytes);
344    let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(challenge_bytes);
345
346    // The WebAuthn user handle is the opaque account id, not the username.
347    let user_handle =
348        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(target_user_id.as_bytes());
349
350    // Create session ID for tracking this registration
351    let session_id = format!("webauthn_{}", uuid::Uuid::new_v4());
352
353    let response = WebAuthnRegistrationResponse {
354        challenge: challenge.clone(),
355        rp: PublicKeyCredentialRpEntity {
356            id: webauthn_cfg.rp_id,
357            name: webauthn_cfg.rp_name,
358        },
359        user: PublicKeyCredentialUserEntity {
360            id: user_handle,
361            name: request.username.clone(),
362            display_name: request.display_name.unwrap_or(request.username.clone()),
363        },
364        pubkey_cred_params: PublicKeyCredentialParameters::defaults(),
365        timeout: Some(webauthn_cfg.timeout_ms),
366        exclude_credentials: None,
367        authenticator_selection: Some(AuthenticatorSelectionCriteria {
368            authenticator_attachment: request.authenticator_attachment,
369            require_resident_key: Some(false),
370            user_verification: request.user_verification.unwrap_or("preferred".to_string()),
371        }),
372        // The server does not verify attestation statements, so it only
373        // ever asks for "none" (see `attestation_supported`).
374        attestation: webauthn_cfg.attestation,
375        session_id: session_id.clone(),
376    };
377
378    // Store the challenge, the target account and the authenticated
379    // caller with a 5-minute TTL. The caller is bound so the session id
380    // alone is not a capability.
381    let session_key = format!("webauthn_reg_session:{}", session_id);
382    let session_data = serde_json::json!({
383        "challenge": challenge,
384        "user_id": target_user_id,
385        "caller_id": caller.user_id,
386        "timestamp": chrono::Utc::now().timestamp()
387    });
388    if let Err(e) = storage
389        .store_kv(
390            &session_key,
391            session_data.to_string().as_bytes(),
392            Some(std::time::Duration::from_secs(300)),
393        )
394        .await
395    {
396        tracing::error!("Failed to store WebAuthn registration session: {}", e);
397        return Json(ApiResponse::error_typed(
398            "INTERNAL_ERROR",
399            "Failed to start registration",
400        ));
401    }
402
403    Json(ApiResponse::success_with_message(
404        response,
405        "WebAuthn registration challenge generated",
406    ))
407}
408
409/// Complete WebAuthn registration process.
410///
411/// Requires the same bearer token that started the ceremony. The server
412/// does not verify attestation statements (see [`attestation_supported`]):
413/// the credential is trusted because an authenticated session for the
414/// account registered it, not because of what the authenticator claims.
415pub async fn webauthn_registration_complete(
416    State(state): State<ApiState>,
417    headers: HeaderMap,
418    Json(request): Json<WebAuthnRegistrationCompleteRequest>,
419) -> Json<ApiResponse<()>> {
420    let caller = match require_caller(&state, &headers).await {
421        Ok(caller) => caller,
422        Err((code, message)) => return Json(ApiResponse::error_typed(code, message)),
423    };
424
425    // Retrieve the stored session to validate the challenge
426    let session_key = format!("webauthn_reg_session:{}", request.session_id);
427    let storage = state.auth_framework.storage();
428
429    let (user_id, session_caller, stored_challenge) = match storage.get_kv(&session_key).await {
430        Ok(Some(data)) => {
431            let session: serde_json::Value =
432                serde_json::from_slice(&data).unwrap_or(serde_json::Value::Null);
433            let field = |name: &str| {
434                session
435                    .get(name)
436                    .and_then(|v| v.as_str())
437                    .unwrap_or("")
438                    .to_string()
439            };
440            (field("user_id"), field("caller_id"), field("challenge"))
441        }
442        _ => {
443            return Json(ApiResponse::validation_error(
444                "Session not found or expired",
445            ));
446        }
447    };
448    if user_id.is_empty() || stored_challenge.is_empty() {
449        return Json(ApiResponse::validation_error(
450            "Session not found or expired",
451        ));
452    }
453
454    // Only the caller that started the ceremony may finish it. Checked
455    // before the session is consumed so a stranger cannot burn it.
456    if session_caller != caller.user_id {
457        return Json(ApiResponse::error_typed(
458            "FORBIDDEN",
459            "This registration session belongs to another account",
460        ));
461    }
462
463    // Delete session immediately to prevent replay attacks
464    if let Err(e) = storage.delete_kv(&session_key).await {
465        tracing::warn!("Failed to delete WebAuthn registration session: {}", e);
466    }
467
468    // The account may have been deactivated since the ceremony began.
469    if !account_is_active(&storage, &user_id).await {
470        return Json(ApiResponse::error_typed(
471            "FORBIDDEN",
472            "You can only register credentials for your own account",
473        ));
474    }
475
476    // Basic validation of credential data
477    if request.credential_id.is_empty() || request.attestation_object.is_empty() {
478        return Json(ApiResponse::validation_error("Invalid credential data"));
479    }
480    let key_ok = base64::engine::general_purpose::URL_SAFE_NO_PAD
481        .decode(&request.credential_public_key)
482        .or_else(|_| {
483            base64::engine::general_purpose::STANDARD.decode(&request.credential_public_key)
484        })
485        .map(|key| !key.is_empty() && key.len() <= 1024)
486        .unwrap_or(false);
487    if !key_ok {
488        return Json(ApiResponse::validation_error(
489            "Invalid credential public key",
490        ));
491    }
492
493    // Verify client_data_json: challenge, origin, and type
494    let client_data_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
495        .decode(&request.client_data_json)
496        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.client_data_json))
497    {
498        Ok(b) => b,
499        Err(_) => {
500            return Json(ApiResponse::validation_error(
501                "Invalid client_data_json encoding",
502            ));
503        }
504    };
505
506    let client_data: serde_json::Value = match serde_json::from_slice(&client_data_bytes) {
507        Ok(v) => v,
508        Err(_) => {
509            return Json(ApiResponse::validation_error(
510                "Invalid client_data_json format",
511            ));
512        }
513    };
514
515    // Verify type is "webauthn.create"
516    if client_data.get("type").and_then(|t| t.as_str()) != Some("webauthn.create") {
517        return Json(ApiResponse::validation_error(
518            "Invalid ceremony type: expected webauthn.create",
519        ));
520    }
521
522    // Verify challenge matches the one we stored
523    if let Some(received_challenge) = client_data.get("challenge").and_then(|c| c.as_str()) {
524        if received_challenge != stored_challenge {
525            return Json(ApiResponse::validation_error(
526                "Challenge mismatch: possible replay attack",
527            ));
528        }
529    } else {
530        return Json(ApiResponse::validation_error(
531            "Missing challenge in client data",
532        ));
533    }
534
535    // Verify origin matches the configured RP ID (a missing origin is refused)
536    if let Err(message) = check_origin(&client_data, &WebAuthnConfig::from_env().rp_id) {
537        return Json(ApiResponse::validation_error(message));
538    }
539
540    // Store the registered credential (including initial signature counter)
541    let credential_key = credential_key(&user_id, &request.credential_id);
542    let credential_data = serde_json::json!({
543        "credential_id": request.credential_id,
544        "credential_public_key": request.credential_public_key,
545        "user_id": user_id,
546        "registered_at": chrono::Utc::now().timestamp(),
547        "sign_count": 0u64
548    });
549    if let Err(e) = storage
550        .store_kv(
551            &credential_key,
552            credential_data.to_string().as_bytes(),
553            None,
554        )
555        .await
556    {
557        tracing::error!("Failed to store WebAuthn credential: {}", e);
558        return Json(ApiResponse::error_typed(
559            "INTERNAL_ERROR",
560            "Failed to store credential",
561        ));
562    }
563
564    // Update the user's credential index so authentication can enumerate them
565    let index_key = credential_index_key(&user_id);
566    let mut existing_ids: Vec<String> = match storage.get_kv(&index_key).await {
567        Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
568        _ => Vec::new(),
569    };
570    if !existing_ids.contains(&request.credential_id) {
571        existing_ids.push(request.credential_id.clone());
572        if let Err(e) = storage
573            .store_kv(
574                &index_key,
575                serde_json::to_string(&existing_ids)
576                    .unwrap_or_default()
577                    .as_bytes(),
578                None,
579            )
580            .await
581        {
582            tracing::error!("Failed to update WebAuthn credential index: {}", e);
583            return Json(ApiResponse::error_typed(
584                "INTERNAL_ERROR",
585                "Failed to store credential",
586            ));
587        }
588    }
589
590    Json(ApiResponse::<()>::ok_with_message(
591        "WebAuthn credential registered successfully",
592    ))
593}
594
595/// Initiate WebAuthn authentication process
596pub async fn webauthn_authentication_init(
597    State(state): State<ApiState>,
598    Json(request): Json<WebAuthnAuthenticationRequest>,
599) -> Json<ApiResponse<WebAuthnAuthenticationResponse>> {
600    let mut challenge_bytes = [0u8; 32];
601    rand::rng().fill_bytes(&mut challenge_bytes);
602    let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(challenge_bytes);
603
604    let session_id = format!("webauthn_auth_{}", uuid::Uuid::new_v4());
605    let storage = state.auth_framework.storage();
606
607    // Retrieve the account's registered credentials from storage. An
608    // unknown username yields an empty list, exactly like an account with
609    // no credentials, so this does not reveal which usernames exist.
610    let username = request.username.as_deref().unwrap_or("");
611    let account_id = if username.is_empty() {
612        None
613    } else {
614        resolve_user_id(&storage, username).await
615    };
616    let allow_credentials = if let Some(account_id) = account_id.as_deref() {
617        // Look up registered credential IDs via the account's credential index
618        let index_key = credential_index_key(account_id);
619        match storage.get_kv(&index_key).await {
620            Ok(Some(data)) => {
621                if let Ok(ids) = serde_json::from_slice::<Vec<String>>(&data) {
622                    ids.into_iter()
623                        .map(|id| PublicKeyCredentialDescriptor {
624                            type_field: "public-key".to_string(),
625                            id,
626                            transports: Some(vec!["internal".to_string(), "usb".to_string()]),
627                        })
628                        .collect::<Vec<_>>()
629                } else {
630                    Vec::new()
631                }
632            }
633            _ => Vec::new(),
634        }
635    } else {
636        Vec::new()
637    };
638
639    // Store auth session with challenge
640    let session_key = format!("webauthn_auth_session:{}", session_id);
641    let session_data = serde_json::json!({
642        "challenge": challenge,
643        "username": request.username,
644        "timestamp": chrono::Utc::now().timestamp()
645    });
646    let _ = storage
647        .store_kv(
648            &session_key,
649            session_data.to_string().as_bytes(),
650            Some(std::time::Duration::from_secs(300)), // 5-minute session
651        )
652        .await;
653
654    let response = WebAuthnAuthenticationResponse {
655        challenge,
656        allow_credentials,
657        timeout: Some(60000),
658        user_verification: request.user_verification.unwrap_or("preferred".to_string()),
659        session_id,
660    };
661
662    Json(ApiResponse::success_with_message(
663        response,
664        "WebAuthn authentication challenge generated",
665    ))
666}
667
668/// Complete WebAuthn authentication process
669pub async fn webauthn_authentication_complete(
670    State(state): State<ApiState>,
671    Json(request): Json<WebAuthnAuthenticationCompleteRequest>,
672) -> Json<ApiResponse<serde_json::Value>> {
673    let storage = state.auth_framework.storage();
674    let session_key = format!("webauthn_auth_session:{}", request.session_id);
675
676    // Retrieve and validate the stored session
677    let (username, stored_challenge) = match storage.get_kv(&session_key).await {
678        Ok(Some(data)) => {
679            let session: serde_json::Value =
680                serde_json::from_slice(&data).unwrap_or(serde_json::Value::Null);
681            let uname = session
682                .get("username")
683                .and_then(|u| u.as_str())
684                .unwrap_or("")
685                .to_string();
686            let challenge = session
687                .get("challenge")
688                .and_then(|c| c.as_str())
689                .unwrap_or("")
690                .to_string();
691            (uname, challenge)
692        }
693        _ => {
694            return Json(ApiResponse::validation_error_typed(
695                "Authentication session not found or expired",
696            ));
697        }
698    };
699
700    // Delete session immediately to prevent replay attacks
701    if let Err(e) = storage.delete_kv(&session_key).await {
702        tracing::warn!("Failed to delete WebAuthn authentication session: {}", e);
703    }
704
705    // Verify client_data_json: challenge, origin, and type
706    let client_data_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
707        .decode(&request.client_data_json)
708        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.client_data_json))
709    {
710        Ok(b) => b,
711        Err(_) => {
712            return Json(ApiResponse::validation_error_typed(
713                "Invalid client_data_json encoding",
714            ));
715        }
716    };
717
718    let client_data: serde_json::Value = match serde_json::from_slice(&client_data_bytes) {
719        Ok(v) => v,
720        Err(_) => {
721            return Json(ApiResponse::validation_error_typed(
722                "Invalid client_data_json format",
723            ));
724        }
725    };
726
727    // Verify type is "webauthn.get"
728    if client_data.get("type").and_then(|t| t.as_str()) != Some("webauthn.get") {
729        return Json(ApiResponse::validation_error_typed(
730            "Invalid ceremony type: expected webauthn.get",
731        ));
732    }
733
734    // Verify challenge matches the one we stored
735    if let Some(received_challenge) = client_data.get("challenge").and_then(|c| c.as_str()) {
736        if received_challenge != stored_challenge {
737            return Json(ApiResponse::validation_error_typed(
738                "Challenge mismatch: possible replay attack",
739            ));
740        }
741    } else {
742        return Json(ApiResponse::validation_error_typed(
743            "Missing challenge in client data",
744        ));
745    }
746
747    // Verify origin matches the configured RP ID (a missing origin is refused)
748    if let Err(message) = check_origin(&client_data, &WebAuthnConfig::from_env().rp_id) {
749        return Json(ApiResponse::validation_error_typed(message));
750    }
751
752    // Resolve the session's username to the REAL account, which must exist
753    // and be active, before anything is looked up or minted. This failure
754    // and "no such credential" below get the same answer, so the response
755    // cannot be used to probe which usernames exist.
756    let user_id = match resolve_user_id(&storage, &username).await {
757        Some(id) if account_is_active(&storage, &id).await => id,
758        _ => {
759            return Json(ApiResponse::validation_error_typed("Authentication failed"));
760        }
761    };
762
763    // Retrieve stored credential to verify it exists and check signature counter
764    let credential_key = credential_key(&user_id, &request.credential_id);
765    let stored_credential = match storage.get_kv(&credential_key).await {
766        Ok(Some(data)) => {
767            serde_json::from_slice::<serde_json::Value>(&data).unwrap_or(serde_json::Value::Null)
768        }
769        _ => {
770            return Json(ApiResponse::validation_error_typed("Authentication failed"));
771        }
772    };
773
774    // Check and update signature counter to detect cloned authenticators
775    let stored_count = stored_credential
776        .get("sign_count")
777        .and_then(|c| c.as_u64())
778        .unwrap_or(0);
779    // Extract sign_count from authenticator_data (bytes 33-36 are the counter, big-endian)
780    let new_count = base64::engine::general_purpose::URL_SAFE_NO_PAD
781        .decode(&request.authenticator_data)
782        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.authenticator_data))
783        .ok()
784        .filter(|d| d.len() >= 37)
785        .map(|d| u32::from_be_bytes([d[33], d[34], d[35], d[36]]) as u64)
786        .unwrap_or(0);
787    if new_count > 0 && new_count <= stored_count {
788        tracing::warn!(
789            "WebAuthn signature counter regression for user {}: stored={}, received={}. Possible cloned authenticator.",
790            username,
791            stored_count,
792            new_count
793        );
794        return Json(ApiResponse::validation_error_typed(
795            "Signature counter regression detected: possible cloned authenticator",
796        ));
797    }
798
799    // ---- Cryptographic signature verification (WebAuthn §7.2 step 19-20) ----
800    // 1. Decode the authenticator data and the raw client data JSON bytes
801    let auth_data_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
802        .decode(&request.authenticator_data)
803        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.authenticator_data))
804    {
805        Ok(b) => b,
806        Err(_) => {
807            return Json(ApiResponse::validation_error_typed(
808                "Invalid authenticator_data encoding",
809            ));
810        }
811    };
812
813    // 2. Compute SHA-256 hash of the raw client_data_json bytes
814    let client_data_hash = {
815        let mut hasher = Sha256::new();
816        hasher.update(&client_data_bytes);
817        hasher.finalize()
818    };
819
820    // 3. Build the signed message: authenticatorData || SHA-256(clientDataJSON)
821    let mut signed_message = auth_data_bytes.clone();
822    signed_message.extend_from_slice(&client_data_hash);
823
824    // 4. Decode the signature
825    let signature_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
826        .decode(&request.signature)
827        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.signature))
828    {
829        Ok(b) => b,
830        Err(_) => {
831            return Json(ApiResponse::validation_error_typed(
832                "Invalid signature encoding",
833            ));
834        }
835    };
836
837    // 5. Retrieve the stored public key and verify the signature
838    let credential_pub_key = stored_credential
839        .get("credential_public_key")
840        .and_then(|k| k.as_str())
841        .unwrap_or("");
842
843    if credential_pub_key.is_empty() {
844        return Json(ApiResponse::validation_error_typed(
845            "No public key stored for this credential",
846        ));
847    }
848
849    // Decode the stored public key (base64url or standard base64)
850    let pub_key_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
851        .decode(credential_pub_key)
852        .or_else(|_| base64::engine::general_purpose::STANDARD.decode(credential_pub_key))
853    {
854        Ok(b) => b,
855        Err(_) => {
856            return Json(ApiResponse::validation_error_typed(
857                "Failed to decode stored public key",
858            ));
859        }
860    };
861
862    // Try ES256 (ECDSA P-256) first, then RS256 (RSA PKCS#1 v1.5 with SHA-256)
863    let sig_valid = {
864        // Attempt ES256 verification (COSE algorithm -7)
865        let es256_result = ring::signature::UnparsedPublicKey::new(
866            &ring::signature::ECDSA_P256_SHA256_ASN1,
867            &pub_key_bytes,
868        )
869        .verify(&signed_message, &signature_bytes);
870
871        if es256_result.is_ok() {
872            true
873        } else {
874            // Attempt RS256 verification (COSE algorithm -257)
875            ring::signature::UnparsedPublicKey::new(
876                &ring::signature::RSA_PKCS1_2048_8192_SHA256,
877                &pub_key_bytes,
878            )
879            .verify(&signed_message, &signature_bytes)
880            .is_ok()
881        }
882    };
883
884    if !sig_valid {
885        tracing::warn!(
886            "WebAuthn signature verification failed for user {} credential {}",
887            username,
888            request.credential_id
889        );
890        return Json(ApiResponse::validation_error_typed(
891            "Signature verification failed: authentication assertion is not valid",
892        ));
893    }
894
895    // Update the stored counter
896    let mut updated_cred = stored_credential.clone();
897    if let Some(obj) = updated_cred.as_object_mut() {
898        obj.insert("sign_count".to_string(), serde_json::json!(new_count));
899    }
900    if let Err(e) = storage
901        .store_kv(
902            &credential_key,
903            serde_json::to_string(&updated_cred)
904                .unwrap_or_default()
905                .as_bytes(),
906            None,
907        )
908        .await
909    {
910        tracing::warn!(
911            "Failed to update WebAuthn credential counter for {}: {}",
912            username,
913            e
914        );
915    }
916
917    // Generate authentication token for the verified user
918    let token_lifetime = state.auth_framework.config().token_lifetime;
919    let token = match state.auth_framework.token_manager().create_jwt_token(
920        &user_id,
921        vec![],
922        Some(token_lifetime),
923    ) {
924        Ok(t) => t,
925        Err(e) => {
926            return Json(ApiResponse::validation_error_typed(format!(
927                "Token generation failed: {}",
928                e
929            )));
930        }
931    };
932
933    let auth_response = serde_json::json!({
934        "access_token": token,
935        "token_type": "Bearer",
936        "expires_in": token_lifetime.as_secs(),
937        "user_id": user_id,
938        "authentication_method": "webauthn"
939    });
940
941    Json(ApiResponse::success_with_message(
942        auth_response,
943        "WebAuthn authentication successful",
944    ))
945}
946
947/// List an account's registered WebAuthn credentials. `username` names the
948/// account; the caller must be that account or an admin.
949pub async fn list_webauthn_credentials(
950    State(state): State<ApiState>,
951    headers: HeaderMap,
952    axum::extract::Path(username): axum::extract::Path<String>,
953) -> Json<ApiResponse<Vec<serde_json::Value>>> {
954    let caller = match require_caller(&state, &headers).await {
955        Ok(caller) => caller,
956        Err((code, message)) => return Json(ApiResponse::error_typed(code, message)),
957    };
958
959    let storage = state.auth_framework.storage();
960    let user_id = match resolve_user_id(&storage, &username).await {
961        Some(id) if may_manage(&caller, &id) => id,
962        // An admin may ask about a name that does not exist: empty, not an error.
963        None if caller.roles.contains("admin") => {
964            return Json(ApiResponse::success_with_message(
965                Vec::new(),
966                format!("WebAuthn credentials retrieved for user: {}", username),
967            ));
968        }
969        _ => {
970            return Json(ApiResponse::error_typed(
971                "FORBIDDEN",
972                "You can only view your own credentials",
973            ));
974        }
975    };
976
977    let credentials = match storage.get_kv(&credential_index_key(&user_id)).await {
978        Ok(Some(data)) => {
979            if let Ok(ids) = serde_json::from_slice::<Vec<String>>(&data) {
980                let mut creds = Vec::new();
981                for id in ids {
982                    if let Ok(Some(cred_data)) =
983                        storage.get_kv(&credential_key(&user_id, &id)).await
984                        && let Ok(cred) = serde_json::from_slice::<serde_json::Value>(&cred_data)
985                    {
986                        creds.push(cred);
987                    }
988                }
989                creds
990            } else {
991                Vec::new()
992            }
993        }
994        _ => Vec::new(),
995    };
996
997    Json(ApiResponse::success_with_message(
998        credentials,
999        format!("WebAuthn credentials retrieved for user: {}", username),
1000    ))
1001}
1002
1003/// Delete a WebAuthn credential. `username` names the account; the caller
1004/// must be that account or an admin.
1005pub async fn delete_webauthn_credential(
1006    State(state): State<ApiState>,
1007    headers: HeaderMap,
1008    axum::extract::Path((username, credential_id)): axum::extract::Path<(String, String)>,
1009) -> Json<ApiResponse<()>> {
1010    let caller = match require_caller(&state, &headers).await {
1011        Ok(caller) => caller,
1012        Err((code, message)) => return Json(ApiResponse::error(code, message)),
1013    };
1014
1015    let storage = state.auth_framework.storage();
1016    let user_id = match resolve_user_id(&storage, &username).await {
1017        Some(id) if may_manage(&caller, &id) => id,
1018        _ => {
1019            return Json(ApiResponse::error(
1020                "FORBIDDEN",
1021                "You can only delete your own credentials",
1022            ));
1023        }
1024    };
1025    let credential_key = credential_key(&user_id, &credential_id);
1026
1027    // Check credential exists before deleting
1028    match storage.get_kv(&credential_key).await {
1029        Ok(Some(_)) => {
1030            if let Err(e) = storage.delete_kv(&credential_key).await {
1031                tracing::warn!(
1032                    "Failed to delete WebAuthn credential {}: {}",
1033                    credential_id,
1034                    e
1035                );
1036            }
1037
1038            // Update the credentials index
1039            let index_key = credential_index_key(&user_id);
1040            if let Ok(Some(idx_data)) = storage.get_kv(&index_key).await
1041                && let Ok(mut ids) = serde_json::from_slice::<Vec<String>>(&idx_data)
1042            {
1043                ids.retain(|id| id != &credential_id);
1044                if let Err(e) = storage
1045                    .store_kv(
1046                        &index_key,
1047                        serde_json::to_string(&ids).unwrap_or_default().as_bytes(),
1048                        None,
1049                    )
1050                    .await
1051                {
1052                    tracing::warn!(
1053                        "Failed to update WebAuthn credentials index for {}: {}",
1054                        username,
1055                        e
1056                    );
1057                }
1058            }
1059
1060            Json(ApiResponse::<()>::ok_with_message(
1061                "WebAuthn credential deleted successfully",
1062            ))
1063        }
1064        _ => Json(ApiResponse::validation_error("Credential not found")),
1065    }
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070    use super::*;
1071
1072    #[test]
1073    fn test_webauthn_config_default() {
1074        let cfg = WebAuthnConfig::default();
1075        assert_eq!(cfg.rp_id, "localhost");
1076        assert_eq!(cfg.rp_name, "AuthFramework");
1077        assert_eq!(cfg.attestation, "none");
1078        assert_eq!(cfg.timeout_ms, 60_000);
1079    }
1080
1081    #[test]
1082    fn check_origin_accepts_only_the_relying_party_host() {
1083        let ok = |origin: &str| {
1084            check_origin(&serde_json::json!({ "origin": origin }), "localhost").is_ok()
1085        };
1086        assert!(ok("https://localhost"));
1087        assert!(ok("https://localhost:8443"));
1088        assert!(ok("localhost"), "non-URL equal to the rp id");
1089        for hostile in [
1090            "https://localhost.evil.com",
1091            "https://evil.com",
1092            "https://localhost@evil.com",
1093            "https://evil.com/localhost",
1094            "https://notlocalhost",
1095            "",
1096        ] {
1097            assert!(!ok(hostile), "{hostile:?} must be refused");
1098        }
1099        assert!(check_origin(&serde_json::json!({}), "localhost").is_err());
1100        assert!(check_origin(&serde_json::json!({ "origin": 5 }), "localhost").is_err());
1101    }
1102
1103    #[test]
1104    fn test_only_attestation_none_is_supported() {
1105        assert!(attestation_supported("none"));
1106        for unsupported in ["direct", "indirect", "enterprise", ""] {
1107            assert!(!attestation_supported(unsupported), "{unsupported}");
1108        }
1109    }
1110
1111    #[test]
1112    fn test_webauthn_config_new_and_chain() {
1113        let cfg = WebAuthnConfig::new("auth.example.com", "My Service")
1114            .attestation("none")
1115            .timeout(120_000);
1116        assert_eq!(cfg.rp_id, "auth.example.com");
1117        assert_eq!(cfg.rp_name, "My Service");
1118        assert_eq!(cfg.attestation, "none");
1119        assert_eq!(cfg.timeout_ms, 120_000);
1120    }
1121
1122    #[test]
1123    fn test_pubkey_cred_params_presets() {
1124        let es = PublicKeyCredentialParameters::es256();
1125        assert_eq!(es.alg, -7);
1126        assert_eq!(es.type_field, "public-key");
1127
1128        let rs = PublicKeyCredentialParameters::rs256();
1129        assert_eq!(rs.alg, -257);
1130        assert_eq!(rs.type_field, "public-key");
1131    }
1132
1133    #[test]
1134    fn test_pubkey_cred_params_defaults_contains_both() {
1135        let params = PublicKeyCredentialParameters::defaults();
1136        assert_eq!(params.len(), 2);
1137        assert_eq!(params[0].alg, -7);
1138        assert_eq!(params[1].alg, -257);
1139    }
1140}