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