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