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}
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 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 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 pub fn attestation(mut self, attestation: impl Into<String>) -> Self {
89 self.attestation = attestation.into();
90 self
91 }
92
93 pub fn timeout(mut self, ms: u64) -> Self {
95 self.timeout_ms = ms;
96 self
97 }
98}
99
100pub(crate) fn attestation_supported(preference: &str) -> bool {
106 preference == "none"
107}
108
109#[derive(Debug, Serialize, Deserialize)]
111pub struct WebAuthnRegistrationInitRequest {
112 pub username: String,
113 pub display_name: Option<String>,
114 pub authenticator_attachment: Option<String>, pub user_verification: Option<String>, }
117
118#[derive(Debug, Serialize, Deserialize)]
120pub struct WebAuthnRegistrationResponse {
121 pub challenge: String,
122 pub rp: PublicKeyCredentialRpEntity,
123 pub user: PublicKeyCredentialUserEntity,
124 pub pubkey_cred_params: Vec<PublicKeyCredentialParameters>,
125 pub timeout: Option<u64>,
126 #[serde(rename = "excludeCredentials")]
127 pub exclude_credentials: Option<Vec<PublicKeyCredentialDescriptor>>,
128 #[serde(rename = "authenticatorSelection")]
129 pub authenticator_selection: Option<AuthenticatorSelectionCriteria>,
130 pub attestation: String,
131 pub session_id: String,
132}
133
134#[derive(Debug, Serialize, Deserialize)]
136pub struct WebAuthnRegistrationCompleteRequest {
137 pub session_id: String,
138 pub credential_id: String,
139 pub credential_public_key: String,
140 pub attestation_object: String,
141 pub client_data_json: String,
142 pub authenticator_data: String,
143 pub signature: String,
144}
145
146#[derive(Debug, Serialize, Deserialize)]
148pub struct WebAuthnAuthenticationRequest {
149 pub username: Option<String>,
150 pub user_verification: Option<String>,
151}
152
153#[derive(Debug, Serialize, Deserialize)]
155pub struct WebAuthnAuthenticationResponse {
156 pub challenge: String,
157 pub allow_credentials: Vec<PublicKeyCredentialDescriptor>,
158 pub timeout: Option<u64>,
159 pub user_verification: String,
160 pub session_id: String,
161}
162
163#[derive(Debug, Serialize, Deserialize)]
165pub struct WebAuthnAuthenticationCompleteRequest {
166 pub session_id: String,
167 pub credential_id: String,
168 pub authenticator_data: String,
169 pub client_data_json: String,
170 pub signature: String,
171 pub user_handle: Option<String>,
172}
173
174#[derive(Debug, Serialize, Deserialize)]
176pub struct PublicKeyCredentialRpEntity {
177 pub id: String,
178 pub name: String,
179}
180
181#[derive(Debug, Serialize, Deserialize)]
182pub struct PublicKeyCredentialUserEntity {
183 pub id: String,
184 pub name: String,
185 pub display_name: String,
186}
187
188#[derive(Debug, Serialize, Deserialize)]
189pub struct PublicKeyCredentialParameters {
190 #[serde(rename = "type")]
191 pub type_field: String,
192 pub alg: i32,
193}
194
195impl PublicKeyCredentialParameters {
196 pub fn es256() -> Self {
198 Self {
199 type_field: "public-key".to_string(),
200 alg: -7,
201 }
202 }
203
204 pub fn rs256() -> Self {
206 Self {
207 type_field: "public-key".to_string(),
208 alg: -257,
209 }
210 }
211
212 pub fn defaults() -> Vec<Self> {
214 vec![Self::es256(), Self::rs256()]
215 }
216}
217
218#[derive(Debug, Serialize, Deserialize)]
219pub struct PublicKeyCredentialDescriptor {
220 #[serde(rename = "type")]
221 pub type_field: String,
222 pub id: String,
223 pub transports: Option<Vec<String>>,
224}
225
226#[derive(Debug, Serialize, Deserialize)]
227pub struct AuthenticatorSelectionCriteria {
228 pub authenticator_attachment: Option<String>,
229 pub require_resident_key: Option<bool>,
230 pub user_verification: String,
231}
232
233type SharedStorage = std::sync::Arc<dyn crate::storage::AuthStorage>;
234
235async fn resolve_user_id(storage: &SharedStorage, username: &str) -> Option<String> {
238 let bytes = storage
239 .get_kv(&format!("user:username:{username}"))
240 .await
241 .ok()
242 .flatten()?;
243 String::from_utf8(bytes).ok().filter(|id| !id.is_empty())
244}
245
246async fn account_is_active(storage: &SharedStorage, user_id: &str) -> bool {
248 match storage.get_kv(&format!("user:{user_id}")).await {
249 Ok(Some(bytes)) => serde_json::from_slice::<serde_json::Value>(&bytes)
250 .map(|record| record["active"].as_bool() != Some(false))
251 .unwrap_or(false),
252 _ => false,
253 }
254}
255
256async fn require_caller(
260 state: &ApiState,
261 headers: &HeaderMap,
262) -> Result<crate::tokens::AuthToken, (&'static str, &'static str)> {
263 let token = extract_bearer_token(headers).ok_or(("UNAUTHORIZED", "Authentication required"))?;
264 validate_api_token(&state.auth_framework, &token)
265 .await
266 .map_err(|_| ("UNAUTHORIZED", "Invalid or expired token"))
267}
268
269fn may_manage(caller: &crate::tokens::AuthToken, target_user_id: &str) -> bool {
271 caller.user_id == target_user_id || caller.roles.contains("admin")
272}
273
274fn credential_key(user_id: &str, credential_id: &str) -> String {
276 format!("webauthn_credential:{user_id}:{credential_id}")
277}
278
279fn credential_index_key(user_id: &str) -> String {
280 format!("webauthn_creds_index:{user_id}")
281}
282
283fn check_origin(client_data: &serde_json::Value, expected_rp_id: &str) -> Result<(), &'static str> {
287 const MISMATCH: &str = "Origin mismatch: does not match relying party ID";
288 let origin = client_data
289 .get("origin")
290 .and_then(|o| o.as_str())
291 .ok_or("Missing origin in client data")?;
292 match url::Url::parse(origin) {
293 Ok(origin_url) if origin_url.host_str() == Some(expected_rp_id) => Ok(()),
294 Ok(_) => Err(MISMATCH),
295 Err(_) if origin == expected_rp_id => Ok(()),
296 Err(_) => Err(MISMATCH),
297 }
298}
299
300pub async fn webauthn_registration_init(
306 State(state): State<ApiState>,
307 headers: HeaderMap,
308 Json(request): Json<WebAuthnRegistrationInitRequest>,
309) -> Json<ApiResponse<WebAuthnRegistrationResponse>> {
310 let caller = match require_caller(&state, &headers).await {
311 Ok(caller) => caller,
312 Err((code, message)) => return Json(ApiResponse::error_typed(code, message)),
313 };
314
315 if let Err(e) = crate::utils::validation::validate_username(&request.username) {
317 return Json(ApiResponse::error_typed("VALIDATION_ERROR", format!("{e}")));
318 }
319
320 let webauthn_cfg = WebAuthnConfig::from_env();
321 if !attestation_supported(&webauthn_cfg.attestation) {
322 return Json(ApiResponse::error_typed(
323 "ATTESTATION_UNSUPPORTED",
324 "This server cannot verify attestation statements; set WEBAUTHN_ATTESTATION=none",
325 ));
326 }
327
328 let storage = state.auth_framework.storage();
331 let target_user_id = match resolve_user_id(&storage, &request.username).await {
332 Some(id) if may_manage(&caller, &id) && account_is_active(&storage, &id).await => id,
333 _ => {
334 return Json(ApiResponse::error_typed(
335 "FORBIDDEN",
336 "You can only register credentials for your own account",
337 ));
338 }
339 };
340
341 let mut challenge_bytes = [0u8; 32];
343 rand::rng().fill_bytes(&mut challenge_bytes);
344 let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(challenge_bytes);
345
346 let user_handle =
348 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(target_user_id.as_bytes());
349
350 let session_id = format!("webauthn_{}", uuid::Uuid::new_v4());
352
353 let response = WebAuthnRegistrationResponse {
354 challenge: challenge.clone(),
355 rp: PublicKeyCredentialRpEntity {
356 id: webauthn_cfg.rp_id,
357 name: webauthn_cfg.rp_name,
358 },
359 user: PublicKeyCredentialUserEntity {
360 id: user_handle,
361 name: request.username.clone(),
362 display_name: request.display_name.unwrap_or(request.username.clone()),
363 },
364 pubkey_cred_params: PublicKeyCredentialParameters::defaults(),
365 timeout: Some(webauthn_cfg.timeout_ms),
366 exclude_credentials: None,
367 authenticator_selection: Some(AuthenticatorSelectionCriteria {
368 authenticator_attachment: request.authenticator_attachment,
369 require_resident_key: Some(false),
370 user_verification: request.user_verification.unwrap_or("preferred".to_string()),
371 }),
372 attestation: webauthn_cfg.attestation,
375 session_id: session_id.clone(),
376 };
377
378 let session_key = format!("webauthn_reg_session:{}", session_id);
382 let session_data = serde_json::json!({
383 "challenge": challenge,
384 "user_id": target_user_id,
385 "caller_id": caller.user_id,
386 "timestamp": chrono::Utc::now().timestamp()
387 });
388 if let Err(e) = storage
389 .store_kv(
390 &session_key,
391 session_data.to_string().as_bytes(),
392 Some(std::time::Duration::from_secs(300)),
393 )
394 .await
395 {
396 tracing::error!("Failed to store WebAuthn registration session: {}", e);
397 return Json(ApiResponse::error_typed(
398 "INTERNAL_ERROR",
399 "Failed to start registration",
400 ));
401 }
402
403 Json(ApiResponse::success_with_message(
404 response,
405 "WebAuthn registration challenge generated",
406 ))
407}
408
409pub async fn webauthn_registration_complete(
416 State(state): State<ApiState>,
417 headers: HeaderMap,
418 Json(request): Json<WebAuthnRegistrationCompleteRequest>,
419) -> Json<ApiResponse<()>> {
420 let caller = match require_caller(&state, &headers).await {
421 Ok(caller) => caller,
422 Err((code, message)) => return Json(ApiResponse::error_typed(code, message)),
423 };
424
425 let session_key = format!("webauthn_reg_session:{}", request.session_id);
427 let storage = state.auth_framework.storage();
428
429 let (user_id, session_caller, stored_challenge) = match storage.get_kv(&session_key).await {
430 Ok(Some(data)) => {
431 let session: serde_json::Value =
432 serde_json::from_slice(&data).unwrap_or(serde_json::Value::Null);
433 let field = |name: &str| {
434 session
435 .get(name)
436 .and_then(|v| v.as_str())
437 .unwrap_or("")
438 .to_string()
439 };
440 (field("user_id"), field("caller_id"), field("challenge"))
441 }
442 _ => {
443 return Json(ApiResponse::validation_error(
444 "Session not found or expired",
445 ));
446 }
447 };
448 if user_id.is_empty() || stored_challenge.is_empty() {
449 return Json(ApiResponse::validation_error(
450 "Session not found or expired",
451 ));
452 }
453
454 if session_caller != caller.user_id {
457 return Json(ApiResponse::error_typed(
458 "FORBIDDEN",
459 "This registration session belongs to another account",
460 ));
461 }
462
463 if let Err(e) = storage.delete_kv(&session_key).await {
465 tracing::warn!("Failed to delete WebAuthn registration session: {}", e);
466 }
467
468 if !account_is_active(&storage, &user_id).await {
470 return Json(ApiResponse::error_typed(
471 "FORBIDDEN",
472 "You can only register credentials for your own account",
473 ));
474 }
475
476 if request.credential_id.is_empty() || request.attestation_object.is_empty() {
478 return Json(ApiResponse::validation_error("Invalid credential data"));
479 }
480 let key_ok = base64::engine::general_purpose::URL_SAFE_NO_PAD
481 .decode(&request.credential_public_key)
482 .or_else(|_| {
483 base64::engine::general_purpose::STANDARD.decode(&request.credential_public_key)
484 })
485 .map(|key| !key.is_empty() && key.len() <= 1024)
486 .unwrap_or(false);
487 if !key_ok {
488 return Json(ApiResponse::validation_error(
489 "Invalid credential public key",
490 ));
491 }
492
493 let client_data_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
495 .decode(&request.client_data_json)
496 .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.client_data_json))
497 {
498 Ok(b) => b,
499 Err(_) => {
500 return Json(ApiResponse::validation_error(
501 "Invalid client_data_json encoding",
502 ));
503 }
504 };
505
506 let client_data: serde_json::Value = match serde_json::from_slice(&client_data_bytes) {
507 Ok(v) => v,
508 Err(_) => {
509 return Json(ApiResponse::validation_error(
510 "Invalid client_data_json format",
511 ));
512 }
513 };
514
515 if client_data.get("type").and_then(|t| t.as_str()) != Some("webauthn.create") {
517 return Json(ApiResponse::validation_error(
518 "Invalid ceremony type: expected webauthn.create",
519 ));
520 }
521
522 if let Some(received_challenge) = client_data.get("challenge").and_then(|c| c.as_str()) {
524 if received_challenge != stored_challenge {
525 return Json(ApiResponse::validation_error(
526 "Challenge mismatch: possible replay attack",
527 ));
528 }
529 } else {
530 return Json(ApiResponse::validation_error(
531 "Missing challenge in client data",
532 ));
533 }
534
535 if let Err(message) = check_origin(&client_data, &WebAuthnConfig::from_env().rp_id) {
537 return Json(ApiResponse::validation_error(message));
538 }
539
540 let credential_key = credential_key(&user_id, &request.credential_id);
542 let credential_data = serde_json::json!({
543 "credential_id": request.credential_id,
544 "credential_public_key": request.credential_public_key,
545 "user_id": user_id,
546 "registered_at": chrono::Utc::now().timestamp(),
547 "sign_count": 0u64
548 });
549 if let Err(e) = storage
550 .store_kv(
551 &credential_key,
552 credential_data.to_string().as_bytes(),
553 None,
554 )
555 .await
556 {
557 tracing::error!("Failed to store WebAuthn credential: {}", e);
558 return Json(ApiResponse::error_typed(
559 "INTERNAL_ERROR",
560 "Failed to store credential",
561 ));
562 }
563
564 let index_key = credential_index_key(&user_id);
566 let mut existing_ids: Vec<String> = match storage.get_kv(&index_key).await {
567 Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
568 _ => Vec::new(),
569 };
570 if !existing_ids.contains(&request.credential_id) {
571 existing_ids.push(request.credential_id.clone());
572 if let Err(e) = storage
573 .store_kv(
574 &index_key,
575 serde_json::to_string(&existing_ids)
576 .unwrap_or_default()
577 .as_bytes(),
578 None,
579 )
580 .await
581 {
582 tracing::error!("Failed to update WebAuthn credential index: {}", e);
583 return Json(ApiResponse::error_typed(
584 "INTERNAL_ERROR",
585 "Failed to store credential",
586 ));
587 }
588 }
589
590 Json(ApiResponse::<()>::ok_with_message(
591 "WebAuthn credential registered successfully",
592 ))
593}
594
595pub async fn webauthn_authentication_init(
597 State(state): State<ApiState>,
598 Json(request): Json<WebAuthnAuthenticationRequest>,
599) -> Json<ApiResponse<WebAuthnAuthenticationResponse>> {
600 let mut challenge_bytes = [0u8; 32];
601 rand::rng().fill_bytes(&mut challenge_bytes);
602 let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(challenge_bytes);
603
604 let session_id = format!("webauthn_auth_{}", uuid::Uuid::new_v4());
605 let storage = state.auth_framework.storage();
606
607 let username = request.username.as_deref().unwrap_or("");
611 let account_id = if username.is_empty() {
612 None
613 } else {
614 resolve_user_id(&storage, username).await
615 };
616 let allow_credentials = if let Some(account_id) = account_id.as_deref() {
617 let index_key = credential_index_key(account_id);
619 match storage.get_kv(&index_key).await {
620 Ok(Some(data)) => {
621 if let Ok(ids) = serde_json::from_slice::<Vec<String>>(&data) {
622 ids.into_iter()
623 .map(|id| PublicKeyCredentialDescriptor {
624 type_field: "public-key".to_string(),
625 id,
626 transports: Some(vec!["internal".to_string(), "usb".to_string()]),
627 })
628 .collect::<Vec<_>>()
629 } else {
630 Vec::new()
631 }
632 }
633 _ => Vec::new(),
634 }
635 } else {
636 Vec::new()
637 };
638
639 let session_key = format!("webauthn_auth_session:{}", session_id);
641 let session_data = serde_json::json!({
642 "challenge": challenge,
643 "username": request.username,
644 "timestamp": chrono::Utc::now().timestamp()
645 });
646 let _ = storage
647 .store_kv(
648 &session_key,
649 session_data.to_string().as_bytes(),
650 Some(std::time::Duration::from_secs(300)), )
652 .await;
653
654 let response = WebAuthnAuthenticationResponse {
655 challenge,
656 allow_credentials,
657 timeout: Some(60000),
658 user_verification: request.user_verification.unwrap_or("preferred".to_string()),
659 session_id,
660 };
661
662 Json(ApiResponse::success_with_message(
663 response,
664 "WebAuthn authentication challenge generated",
665 ))
666}
667
668pub async fn webauthn_authentication_complete(
670 State(state): State<ApiState>,
671 Json(request): Json<WebAuthnAuthenticationCompleteRequest>,
672) -> Json<ApiResponse<serde_json::Value>> {
673 let storage = state.auth_framework.storage();
674 let session_key = format!("webauthn_auth_session:{}", request.session_id);
675
676 let (username, stored_challenge) = match storage.get_kv(&session_key).await {
678 Ok(Some(data)) => {
679 let session: serde_json::Value =
680 serde_json::from_slice(&data).unwrap_or(serde_json::Value::Null);
681 let uname = session
682 .get("username")
683 .and_then(|u| u.as_str())
684 .unwrap_or("")
685 .to_string();
686 let challenge = session
687 .get("challenge")
688 .and_then(|c| c.as_str())
689 .unwrap_or("")
690 .to_string();
691 (uname, challenge)
692 }
693 _ => {
694 return Json(ApiResponse::validation_error_typed(
695 "Authentication session not found or expired",
696 ));
697 }
698 };
699
700 if let Err(e) = storage.delete_kv(&session_key).await {
702 tracing::warn!("Failed to delete WebAuthn authentication session: {}", e);
703 }
704
705 let client_data_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
707 .decode(&request.client_data_json)
708 .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.client_data_json))
709 {
710 Ok(b) => b,
711 Err(_) => {
712 return Json(ApiResponse::validation_error_typed(
713 "Invalid client_data_json encoding",
714 ));
715 }
716 };
717
718 let client_data: serde_json::Value = match serde_json::from_slice(&client_data_bytes) {
719 Ok(v) => v,
720 Err(_) => {
721 return Json(ApiResponse::validation_error_typed(
722 "Invalid client_data_json format",
723 ));
724 }
725 };
726
727 if client_data.get("type").and_then(|t| t.as_str()) != Some("webauthn.get") {
729 return Json(ApiResponse::validation_error_typed(
730 "Invalid ceremony type: expected webauthn.get",
731 ));
732 }
733
734 if let Some(received_challenge) = client_data.get("challenge").and_then(|c| c.as_str()) {
736 if received_challenge != stored_challenge {
737 return Json(ApiResponse::validation_error_typed(
738 "Challenge mismatch: possible replay attack",
739 ));
740 }
741 } else {
742 return Json(ApiResponse::validation_error_typed(
743 "Missing challenge in client data",
744 ));
745 }
746
747 if let Err(message) = check_origin(&client_data, &WebAuthnConfig::from_env().rp_id) {
749 return Json(ApiResponse::validation_error_typed(message));
750 }
751
752 let user_id = match resolve_user_id(&storage, &username).await {
757 Some(id) if account_is_active(&storage, &id).await => id,
758 _ => {
759 return Json(ApiResponse::validation_error_typed("Authentication failed"));
760 }
761 };
762
763 let credential_key = credential_key(&user_id, &request.credential_id);
765 let stored_credential = match storage.get_kv(&credential_key).await {
766 Ok(Some(data)) => {
767 serde_json::from_slice::<serde_json::Value>(&data).unwrap_or(serde_json::Value::Null)
768 }
769 _ => {
770 return Json(ApiResponse::validation_error_typed("Authentication failed"));
771 }
772 };
773
774 let stored_count = stored_credential
776 .get("sign_count")
777 .and_then(|c| c.as_u64())
778 .unwrap_or(0);
779 let new_count = base64::engine::general_purpose::URL_SAFE_NO_PAD
781 .decode(&request.authenticator_data)
782 .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.authenticator_data))
783 .ok()
784 .filter(|d| d.len() >= 37)
785 .map(|d| u32::from_be_bytes([d[33], d[34], d[35], d[36]]) as u64)
786 .unwrap_or(0);
787 if new_count > 0 && new_count <= stored_count {
788 tracing::warn!(
789 "WebAuthn signature counter regression for user {}: stored={}, received={}. Possible cloned authenticator.",
790 username,
791 stored_count,
792 new_count
793 );
794 return Json(ApiResponse::validation_error_typed(
795 "Signature counter regression detected: possible cloned authenticator",
796 ));
797 }
798
799 let auth_data_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
802 .decode(&request.authenticator_data)
803 .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.authenticator_data))
804 {
805 Ok(b) => b,
806 Err(_) => {
807 return Json(ApiResponse::validation_error_typed(
808 "Invalid authenticator_data encoding",
809 ));
810 }
811 };
812
813 let client_data_hash = {
815 let mut hasher = Sha256::new();
816 hasher.update(&client_data_bytes);
817 hasher.finalize()
818 };
819
820 let mut signed_message = auth_data_bytes.clone();
822 signed_message.extend_from_slice(&client_data_hash);
823
824 let signature_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
826 .decode(&request.signature)
827 .or_else(|_| base64::engine::general_purpose::STANDARD.decode(&request.signature))
828 {
829 Ok(b) => b,
830 Err(_) => {
831 return Json(ApiResponse::validation_error_typed(
832 "Invalid signature encoding",
833 ));
834 }
835 };
836
837 let credential_pub_key = stored_credential
839 .get("credential_public_key")
840 .and_then(|k| k.as_str())
841 .unwrap_or("");
842
843 if credential_pub_key.is_empty() {
844 return Json(ApiResponse::validation_error_typed(
845 "No public key stored for this credential",
846 ));
847 }
848
849 let pub_key_bytes = match base64::engine::general_purpose::URL_SAFE_NO_PAD
851 .decode(credential_pub_key)
852 .or_else(|_| base64::engine::general_purpose::STANDARD.decode(credential_pub_key))
853 {
854 Ok(b) => b,
855 Err(_) => {
856 return Json(ApiResponse::validation_error_typed(
857 "Failed to decode stored public key",
858 ));
859 }
860 };
861
862 let sig_valid = {
864 let es256_result = ring::signature::UnparsedPublicKey::new(
866 &ring::signature::ECDSA_P256_SHA256_ASN1,
867 &pub_key_bytes,
868 )
869 .verify(&signed_message, &signature_bytes);
870
871 if es256_result.is_ok() {
872 true
873 } else {
874 ring::signature::UnparsedPublicKey::new(
876 &ring::signature::RSA_PKCS1_2048_8192_SHA256,
877 &pub_key_bytes,
878 )
879 .verify(&signed_message, &signature_bytes)
880 .is_ok()
881 }
882 };
883
884 if !sig_valid {
885 tracing::warn!(
886 "WebAuthn signature verification failed for user {} credential {}",
887 username,
888 request.credential_id
889 );
890 return Json(ApiResponse::validation_error_typed(
891 "Signature verification failed: authentication assertion is not valid",
892 ));
893 }
894
895 let mut updated_cred = stored_credential.clone();
897 if let Some(obj) = updated_cred.as_object_mut() {
898 obj.insert("sign_count".to_string(), serde_json::json!(new_count));
899 }
900 if let Err(e) = storage
901 .store_kv(
902 &credential_key,
903 serde_json::to_string(&updated_cred)
904 .unwrap_or_default()
905 .as_bytes(),
906 None,
907 )
908 .await
909 {
910 tracing::warn!(
911 "Failed to update WebAuthn credential counter for {}: {}",
912 username,
913 e
914 );
915 }
916
917 let token_lifetime = state.auth_framework.config().token_lifetime;
919 let token = match state.auth_framework.token_manager().create_jwt_token(
920 &user_id,
921 vec![],
922 Some(token_lifetime),
923 ) {
924 Ok(t) => t,
925 Err(e) => {
926 return Json(ApiResponse::validation_error_typed(format!(
927 "Token generation failed: {}",
928 e
929 )));
930 }
931 };
932
933 let auth_response = serde_json::json!({
934 "access_token": token,
935 "token_type": "Bearer",
936 "expires_in": token_lifetime.as_secs(),
937 "user_id": user_id,
938 "authentication_method": "webauthn"
939 });
940
941 Json(ApiResponse::success_with_message(
942 auth_response,
943 "WebAuthn authentication successful",
944 ))
945}
946
947pub async fn list_webauthn_credentials(
950 State(state): State<ApiState>,
951 headers: HeaderMap,
952 axum::extract::Path(username): axum::extract::Path<String>,
953) -> Json<ApiResponse<Vec<serde_json::Value>>> {
954 let caller = match require_caller(&state, &headers).await {
955 Ok(caller) => caller,
956 Err((code, message)) => return Json(ApiResponse::error_typed(code, message)),
957 };
958
959 let storage = state.auth_framework.storage();
960 let user_id = match resolve_user_id(&storage, &username).await {
961 Some(id) if may_manage(&caller, &id) => id,
962 None if caller.roles.contains("admin") => {
964 return Json(ApiResponse::success_with_message(
965 Vec::new(),
966 format!("WebAuthn credentials retrieved for user: {}", username),
967 ));
968 }
969 _ => {
970 return Json(ApiResponse::error_typed(
971 "FORBIDDEN",
972 "You can only view your own credentials",
973 ));
974 }
975 };
976
977 let credentials = match storage.get_kv(&credential_index_key(&user_id)).await {
978 Ok(Some(data)) => {
979 if let Ok(ids) = serde_json::from_slice::<Vec<String>>(&data) {
980 let mut creds = Vec::new();
981 for id in ids {
982 if let Ok(Some(cred_data)) =
983 storage.get_kv(&credential_key(&user_id, &id)).await
984 && let Ok(cred) = serde_json::from_slice::<serde_json::Value>(&cred_data)
985 {
986 creds.push(cred);
987 }
988 }
989 creds
990 } else {
991 Vec::new()
992 }
993 }
994 _ => Vec::new(),
995 };
996
997 Json(ApiResponse::success_with_message(
998 credentials,
999 format!("WebAuthn credentials retrieved for user: {}", username),
1000 ))
1001}
1002
1003pub async fn delete_webauthn_credential(
1006 State(state): State<ApiState>,
1007 headers: HeaderMap,
1008 axum::extract::Path((username, credential_id)): axum::extract::Path<(String, String)>,
1009) -> Json<ApiResponse<()>> {
1010 let caller = match require_caller(&state, &headers).await {
1011 Ok(caller) => caller,
1012 Err((code, message)) => return Json(ApiResponse::error(code, message)),
1013 };
1014
1015 let storage = state.auth_framework.storage();
1016 let user_id = match resolve_user_id(&storage, &username).await {
1017 Some(id) if may_manage(&caller, &id) => id,
1018 _ => {
1019 return Json(ApiResponse::error(
1020 "FORBIDDEN",
1021 "You can only delete your own credentials",
1022 ));
1023 }
1024 };
1025 let credential_key = credential_key(&user_id, &credential_id);
1026
1027 match storage.get_kv(&credential_key).await {
1029 Ok(Some(_)) => {
1030 if let Err(e) = storage.delete_kv(&credential_key).await {
1031 tracing::warn!(
1032 "Failed to delete WebAuthn credential {}: {}",
1033 credential_id,
1034 e
1035 );
1036 }
1037
1038 let index_key = credential_index_key(&user_id);
1040 if let Ok(Some(idx_data)) = storage.get_kv(&index_key).await
1041 && let Ok(mut ids) = serde_json::from_slice::<Vec<String>>(&idx_data)
1042 {
1043 ids.retain(|id| id != &credential_id);
1044 if let Err(e) = storage
1045 .store_kv(
1046 &index_key,
1047 serde_json::to_string(&ids).unwrap_or_default().as_bytes(),
1048 None,
1049 )
1050 .await
1051 {
1052 tracing::warn!(
1053 "Failed to update WebAuthn credentials index for {}: {}",
1054 username,
1055 e
1056 );
1057 }
1058 }
1059
1060 Json(ApiResponse::<()>::ok_with_message(
1061 "WebAuthn credential deleted successfully",
1062 ))
1063 }
1064 _ => Json(ApiResponse::validation_error("Credential not found")),
1065 }
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070 use super::*;
1071
1072 #[test]
1073 fn test_webauthn_config_default() {
1074 let cfg = WebAuthnConfig::default();
1075 assert_eq!(cfg.rp_id, "localhost");
1076 assert_eq!(cfg.rp_name, "AuthFramework");
1077 assert_eq!(cfg.attestation, "none");
1078 assert_eq!(cfg.timeout_ms, 60_000);
1079 }
1080
1081 #[test]
1082 fn check_origin_accepts_only_the_relying_party_host() {
1083 let ok = |origin: &str| {
1084 check_origin(&serde_json::json!({ "origin": origin }), "localhost").is_ok()
1085 };
1086 assert!(ok("https://localhost"));
1087 assert!(ok("https://localhost:8443"));
1088 assert!(ok("localhost"), "non-URL equal to the rp id");
1089 for hostile in [
1090 "https://localhost.evil.com",
1091 "https://evil.com",
1092 "https://localhost@evil.com",
1093 "https://evil.com/localhost",
1094 "https://notlocalhost",
1095 "",
1096 ] {
1097 assert!(!ok(hostile), "{hostile:?} must be refused");
1098 }
1099 assert!(check_origin(&serde_json::json!({}), "localhost").is_err());
1100 assert!(check_origin(&serde_json::json!({ "origin": 5 }), "localhost").is_err());
1101 }
1102
1103 #[test]
1104 fn test_only_attestation_none_is_supported() {
1105 assert!(attestation_supported("none"));
1106 for unsupported in ["direct", "indirect", "enterprise", ""] {
1107 assert!(!attestation_supported(unsupported), "{unsupported}");
1108 }
1109 }
1110
1111 #[test]
1112 fn test_webauthn_config_new_and_chain() {
1113 let cfg = WebAuthnConfig::new("auth.example.com", "My Service")
1114 .attestation("none")
1115 .timeout(120_000);
1116 assert_eq!(cfg.rp_id, "auth.example.com");
1117 assert_eq!(cfg.rp_name, "My Service");
1118 assert_eq!(cfg.attestation, "none");
1119 assert_eq!(cfg.timeout_ms, 120_000);
1120 }
1121
1122 #[test]
1123 fn test_pubkey_cred_params_presets() {
1124 let es = PublicKeyCredentialParameters::es256();
1125 assert_eq!(es.alg, -7);
1126 assert_eq!(es.type_field, "public-key");
1127
1128 let rs = PublicKeyCredentialParameters::rs256();
1129 assert_eq!(rs.alg, -257);
1130 assert_eq!(rs.type_field, "public-key");
1131 }
1132
1133 #[test]
1134 fn test_pubkey_cred_params_defaults_contains_both() {
1135 let params = PublicKeyCredentialParameters::defaults();
1136 assert_eq!(params.len(), 2);
1137 assert_eq!(params[0].alg, -7);
1138 assert_eq!(params[1].alg, -257);
1139 }
1140}