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