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