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