1use crate::authentication::credentials::{Credential, CredentialMetadata};
99use crate::errors::{AuthError, Result};
100use crate::methods::{AuthMethod, MethodResult};
101use crate::tokens::{AuthToken, TokenManager};
102use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
103use serde::{Deserialize, Serialize};
104use std::time::SystemTime;
105use std::{collections::HashMap, sync::RwLock};
106
107#[cfg(feature = "passkeys")]
108use std::time::Duration;
109
110#[cfg(feature = "passkeys")]
112use coset::iana::Algorithm;
113#[cfg(feature = "passkeys")]
114use passkey::{
115 authenticator::{Authenticator, UiHint, UserCheck, UserValidationMethod},
116 client::Client,
117 types::{
118 Bytes, Passkey,
119 ctap2::{Aaguid, Ctap2Error},
120 rand::random_vec,
121 webauthn::{
122 AttestationConveyancePreference, AuthenticatedPublicKeyCredential,
123 CreatedPublicKeyCredential, CredentialCreationOptions, CredentialRequestOptions,
124 PublicKeyCredentialCreationOptions, PublicKeyCredentialDescriptor,
125 PublicKeyCredentialParameters, PublicKeyCredentialRequestOptions,
126 PublicKeyCredentialRpEntity, PublicKeyCredentialType, PublicKeyCredentialUserEntity,
127 UserVerificationRequirement,
128 },
129 },
130};
131#[cfg(feature = "passkeys")]
132use passkey_client::DefaultClientData;
133#[cfg(feature = "passkeys")]
134use url::Url;
135
136#[cfg(feature = "passkeys")]
138struct PasskeyUserValidation;
139
140#[cfg(feature = "passkeys")]
141#[async_trait::async_trait]
142impl UserValidationMethod for PasskeyUserValidation {
143 type PasskeyItem = Passkey;
144
145 async fn check_user<'a>(
146 &self,
147 _hint: UiHint<'a, Passkey>,
148 presence: bool,
149 verification: bool,
150 ) -> std::result::Result<UserCheck, Ctap2Error> {
151 Ok(UserCheck {
152 presence,
153 verification,
154 })
155 }
156
157 fn is_verification_enabled(&self) -> Option<bool> {
158 Some(true)
159 }
160
161 fn is_presence_enabled(&self) -> bool {
162 true
163 }
164}
165
166pub struct PasskeyAuthMethod {
248 pub config: PasskeyConfig,
249 pub token_manager: TokenManager,
250 pub registered_passkeys: RwLock<HashMap<String, PasskeyRegistration>>,
252 #[cfg(feature = "passkeys")]
255 pending_challenges: RwLock<HashMap<String, Vec<u8>>>,
256}
257
258impl std::fmt::Debug for PasskeyAuthMethod {
259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260 let mut s = f.debug_struct("PasskeyAuthMethod");
261 s.field("config", &self.config);
262 s.field("token_manager", &"<TokenManager>");
263 s.field("registered_passkeys", &"<RwLock<HashMap>>");
264 #[cfg(feature = "passkeys")]
265 s.field("pending_challenges", &"<RwLock<HashMap>>");
266 s.finish()
267 }
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
272pub struct PasskeyConfig {
273 pub rp_id: String,
275 pub rp_name: String,
277 pub origin: String,
279 pub timeout_ms: u32,
281 pub user_verification: String, pub authenticator_attachment: Option<String>, pub require_resident_key: bool,
287 #[serde(default = "default_attestation_conveyance")]
290 pub attestation_conveyance: String,
291}
292
293fn default_attestation_conveyance() -> String {
294 "direct".to_string()
295}
296
297impl Default for PasskeyConfig {
298 fn default() -> Self {
299 Self {
300 rp_id: "localhost".to_string(),
301 rp_name: "Auth Framework Demo".to_string(),
302 origin: "http://localhost:3000".to_string(),
303 timeout_ms: 60000, user_verification: "preferred".to_string(),
305 authenticator_attachment: None,
306 require_resident_key: false,
307 attestation_conveyance: default_attestation_conveyance(),
308 }
309 }
310}
311
312#[derive(Clone, Serialize, Deserialize)]
314pub struct PasskeyRegistration {
315 pub user_id: String,
316 pub user_name: String,
317 pub user_display_name: String,
318 pub credential_id: Vec<u8>,
319 pub passkey_data: String, pub created_at: SystemTime,
321 pub last_used: Option<SystemTime>,
322}
323
324impl std::fmt::Debug for PasskeyRegistration {
325 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
326 let mut d = f.debug_struct("PasskeyRegistration");
327 d.field("user_id", &self.user_id);
328 d.field("user_name", &self.user_name);
329 d.field("user_display_name", &self.user_display_name);
330 d.field("credential_id", &self.credential_id);
331 d.field(
332 "passkey_data",
333 &crate::utils::redact::redacted(&self.passkey_data),
334 );
335 d.field("created_at", &self.created_at);
336 d.field("last_used", &self.last_used);
337 d.finish()
338 }
339}
340
341impl PasskeyAuthMethod {
342 pub fn new(config: PasskeyConfig, token_manager: TokenManager) -> Result<Self> {
344 #[cfg(feature = "passkeys")]
345 {
346 Ok(Self {
347 config,
348 token_manager,
349 registered_passkeys: RwLock::new(HashMap::new()),
350 pending_challenges: RwLock::new(HashMap::new()),
351 })
352 }
353
354 #[cfg(not(feature = "passkeys"))]
355 {
356 let _ = (config, token_manager); Err(AuthError::config(
358 "Passkey support not compiled in. Enable 'passkeys' feature.",
359 ))
360 }
361 }
362
363 #[cfg(feature = "passkeys")]
365 pub async fn register_passkey(
366 &mut self,
367 user_id: &str,
368 user_name: &str,
369 user_display_name: &str,
370 ) -> Result<CreatedPublicKeyCredential> {
371 let origin = Url::parse(&self.config.origin)
372 .map_err(|e| AuthError::config(format!("Invalid origin URL: {}", e)))?;
373
374 let aaguid = Aaguid::new_empty();
376 let user_validation = PasskeyUserValidation;
377 let store: Option<Passkey> = None;
378 let authenticator = Authenticator::new(aaguid, store, user_validation);
379
380 let mut client = Client::new(authenticator);
382
383 let challenge: Bytes = random_vec(32).into();
385
386 let user_entity = PublicKeyCredentialUserEntity {
388 id: Bytes::from(user_id.as_bytes().to_vec()),
389 display_name: user_display_name.to_string(),
390 name: user_name.to_string(),
391 };
392
393 let request = CredentialCreationOptions {
395 public_key: PublicKeyCredentialCreationOptions {
396 rp: PublicKeyCredentialRpEntity {
397 id: None, name: self.config.rp_name.clone(),
399 },
400 user: user_entity,
401 challenge,
402 pub_key_cred_params: vec![
403 PublicKeyCredentialParameters {
404 ty: PublicKeyCredentialType::PublicKey,
405 alg: Algorithm::ES256,
406 },
407 PublicKeyCredentialParameters {
408 ty: PublicKeyCredentialType::PublicKey,
409 alg: Algorithm::RS256,
410 },
411 ],
412 timeout: Some(self.config.timeout_ms),
413 exclude_credentials: None,
414 authenticator_selection: None,
415 hints: None,
416 attestation: match self.config.attestation_conveyance.as_str() {
417 "none" => AttestationConveyancePreference::None,
418 "indirect" => AttestationConveyancePreference::Indirect,
419 "enterprise" => AttestationConveyancePreference::Enterprise,
420 _ => AttestationConveyancePreference::Direct,
422 },
423 attestation_formats: None,
424 extensions: None,
425 },
426 };
427
428 let credential = client
430 .register(&origin, request, DefaultClientData)
431 .await
432 .map_err(|e| AuthError::validation(format!("Passkey registration failed: {:?}", e)))?;
433
434 let credential_id = &credential.raw_id;
436 let credential_id_b64 = URL_SAFE_NO_PAD.encode(credential_id.as_slice());
437
438 let credential_value = serde_json::to_value(&credential).unwrap_or(serde_json::Value::Null);
441 let public_key_value = credential_value
442 .pointer("/response/authenticatorData/attestedCredentialData/credentialPublicKey")
443 .cloned()
444 .unwrap_or(serde_json::Value::Null);
445 let sign_count = credential_value
446 .pointer("/response/authenticatorData/signCount")
447 .and_then(|v| v.as_u64())
448 .unwrap_or(0);
449 let passkey_data_json = serde_json::json!({
450 "credential_id": credential_id_b64,
451 "public_key": public_key_value,
452 "signature_counter": sign_count,
453 "raw_attestation": credential_value,
454 });
455 let passkey_data_str = serde_json::to_string(&passkey_data_json).map_err(|e| {
456 AuthError::validation(format!("Failed to serialize passkey data: {}", e))
457 })?;
458
459 let registration = PasskeyRegistration {
460 user_id: user_id.to_string(),
461 user_name: user_name.to_string(),
462 user_display_name: user_display_name.to_string(),
463 credential_id: credential_id.as_slice().to_vec(),
464 passkey_data: passkey_data_str,
465 created_at: SystemTime::now(),
466 last_used: None,
467 };
468
469 {
470 let mut passkeys = self.registered_passkeys.write().map_err(|_| {
471 AuthError::internal(
472 "Lock poisoned — a prior thread panicked while holding this lock",
473 )
474 })?;
475 passkeys.insert(credential_id_b64.clone(), registration);
476 }
477
478 tracing::info!("Successfully registered passkey for user: {}", user_id);
479 Ok(credential)
480 }
481
482 #[cfg(feature = "passkeys")]
484 pub async fn initiate_authentication(
485 &self,
486 user_id: Option<&str>,
487 ) -> Result<CredentialRequestOptions> {
488 let challenge_bytes = random_vec(32);
489 let challenge: Bytes = challenge_bytes.clone().into();
490
491 let allow_credential_ids: Vec<(Vec<u8>, String)> = {
492 let passkeys = self.registered_passkeys.read().map_err(|_| {
493 AuthError::internal(
494 "Lock poisoned — a prior thread panicked while holding this lock",
495 )
496 })?;
497 let iter: Box<dyn Iterator<Item = &PasskeyRegistration>> = if let Some(uid) = user_id {
498 Box::new(passkeys.values().filter(move |reg| reg.user_id == uid))
499 } else {
500 Box::new(passkeys.values())
501 };
502 iter.map(|reg| {
503 (
504 reg.credential_id.clone(),
505 URL_SAFE_NO_PAD.encode(®.credential_id),
506 )
507 })
508 .collect()
509 };
510
511 {
514 let mut challenges = self.pending_challenges.write().map_err(|_| {
515 AuthError::internal(
516 "Lock poisoned — a prior thread panicked while holding this lock",
517 )
518 })?;
519 for (_, cred_id_b64) in &allow_credential_ids {
520 challenges.insert(cred_id_b64.clone(), challenge_bytes.clone());
521 }
522 challenges.insert("latest".to_string(), challenge_bytes.clone());
524 }
525
526 let allow_credentials: Vec<PublicKeyCredentialDescriptor> = allow_credential_ids
527 .into_iter()
528 .map(|(raw_id, _)| PublicKeyCredentialDescriptor {
529 ty: PublicKeyCredentialType::PublicKey,
530 id: raw_id.into(),
531 transports: None,
532 })
533 .collect();
534
535 let request_options = CredentialRequestOptions {
536 public_key: PublicKeyCredentialRequestOptions {
537 challenge,
538 timeout: Some(self.config.timeout_ms),
539 rp_id: Some(self.config.rp_id.clone()),
540 allow_credentials: Some(allow_credentials),
541 user_verification: match self.config.user_verification.as_str() {
542 "required" => UserVerificationRequirement::Required,
543 "discouraged" => UserVerificationRequirement::Discouraged,
544 _ => UserVerificationRequirement::Preferred,
545 },
546 hints: None,
547 attestation: match self.config.attestation_conveyance.as_str() {
548 "none" => AttestationConveyancePreference::None,
549 "indirect" => AttestationConveyancePreference::Indirect,
550 "enterprise" => AttestationConveyancePreference::Enterprise,
551 _ => AttestationConveyancePreference::Direct,
552 },
553 attestation_formats: None,
554 extensions: None,
555 },
556 };
557
558 tracing::info!("Generated passkey authentication options");
559 Ok(request_options)
560 }
561
562 #[cfg(feature = "passkeys")]
564 pub async fn complete_authentication(
565 &mut self,
566 credential_response: &AuthenticatedPublicKeyCredential,
567 ) -> Result<AuthToken> {
568 let credential_id = &credential_response.raw_id;
569 let credential_id_b64 = URL_SAFE_NO_PAD.encode(credential_id.as_slice());
570
571 let mut registration = {
573 let passkeys = self.registered_passkeys.read().map_err(|_| {
574 AuthError::internal(
575 "Lock poisoned — a prior thread panicked while holding this lock",
576 )
577 })?;
578 passkeys
579 .get(&credential_id_b64)
580 .ok_or_else(|| AuthError::validation("Unknown credential ID"))?
581 .clone()
582 };
583
584 let assertion_response = serde_json::to_string(credential_response).map_err(|e| {
587 AuthError::InvalidCredential {
588 credential_type: "passkey".to_string(),
589 message: format!("Failed to serialize credential response: {}", e),
590 }
591 })?;
592
593 let passkey_data: serde_json::Value = serde_json::from_str(®istration.passkey_data)
595 .map_err(|e| AuthError::InvalidCredential {
596 credential_type: "passkey".to_string(),
597 message: format!("Failed to parse stored passkey data: {}", e),
598 })?;
599
600 let public_key_jwk = passkey_data
601 .get("public_key")
602 .cloned()
603 .unwrap_or(serde_json::Value::Null);
604 let stored_counter = passkey_data
605 .get("signature_counter")
606 .and_then(|v| v.as_u64())
607 .unwrap_or(0) as u32;
608
609 let expected_challenge_bytes: Vec<u8> = {
611 let challenges = self.pending_challenges.read().map_err(|_| {
612 AuthError::internal(
613 "Lock poisoned — a prior thread panicked while holding this lock",
614 )
615 })?;
616 challenges
617 .get(&credential_id_b64)
618 .or_else(|| challenges.get("latest"))
619 .cloned()
620 .ok_or_else(|| {
621 AuthError::validation(
622 "No pending challenge found; call initiate_authentication first",
623 )
624 })?
625 };
626
627 let verification_result = self
629 .advanced_verification_flow(
630 &assertion_response,
631 expected_challenge_bytes.as_slice(),
632 stored_counter,
633 &public_key_jwk,
634 )
635 .await?;
636
637 if !verification_result.signature_valid {
638 return Err(AuthError::validation(
639 "Passkey signature verification failed",
640 ));
641 }
642
643 let mut passkey_data: serde_json::Value = serde_json::from_str(®istration.passkey_data)
645 .map_err(|e| AuthError::InvalidCredential {
646 credential_type: "passkey".to_string(),
647 message: format!(
648 "Failed to parse stored passkey data during counter update: {}",
649 e
650 ),
651 })?;
652 passkey_data["signature_counter"] =
653 serde_json::Value::Number(serde_json::Number::from(verification_result.new_counter));
654 registration.passkey_data =
655 serde_json::to_string(&passkey_data).map_err(|e| AuthError::InvalidCredential {
656 credential_type: "passkey".to_string(),
657 message: format!("Failed to serialize updated passkey data: {}", e),
658 })?;
659 registration.last_used = Some(SystemTime::now());
660
661 {
662 let mut passkeys = self.registered_passkeys.write().map_err(|_| {
663 AuthError::internal(
664 "Lock poisoned — a prior thread panicked while holding this lock",
665 )
666 })?;
667 passkeys.insert(credential_id_b64.clone(), registration.clone());
668 }
669
670 let token = self.token_manager.create_jwt_token(
672 ®istration.user_id,
673 vec![],
674 Some(Duration::from_secs(3600)),
675 )?;
676
677 tracing::info!(
678 "Passkey authentication successful for user: {} (counter: {} -> {})",
679 registration.user_id,
680 stored_counter,
681 verification_result.new_counter
682 );
683 Ok(AuthToken::new(
684 ®istration.user_id,
685 token,
686 Duration::from_secs(3600),
687 "passkey",
688 ))
689 }
690
691 #[cfg(not(feature = "passkeys"))]
693 pub async fn register_passkey(
694 &mut self,
695 _user_id: &str,
696 _user_name: &str,
697 _user_display_name: &str,
698 ) -> Result<()> {
699 Err(AuthError::config(
700 "Passkey support not compiled in. Enable 'passkeys' feature.",
701 ))
702 }
703}
704
705impl AuthMethod for PasskeyAuthMethod {
706 type MethodResult = MethodResult;
707 type AuthToken = AuthToken;
708
709 fn name(&self) -> &str {
710 "passkey"
711 }
712
713 async fn authenticate(
714 &self,
715 credential: Credential,
716 _metadata: CredentialMetadata,
717 ) -> Result<Self::MethodResult> {
718 #[cfg(feature = "passkeys")]
719 {
720 match credential {
721 Credential::Passkey {
722 credential_id,
723 assertion_response,
724 } => {
725 let credential_id_b64 = URL_SAFE_NO_PAD.encode(&credential_id);
727 let registration = {
728 let passkeys = self.registered_passkeys.read().map_err(|_| {
729 AuthError::internal(
730 "Lock poisoned — a prior thread panicked while holding this lock",
731 )
732 })?;
733 passkeys
734 .get(&credential_id_b64)
735 .cloned()
736 .ok_or_else(|| AuthError::validation("Unknown credential ID"))?
737 };
738
739 tracing::debug!(
740 "Processing passkey assertion for credential: {}",
741 credential_id_b64
742 );
743
744 let passkey_data: serde_json::Value =
747 serde_json::from_str(®istration.passkey_data).map_err(|e| {
748 AuthError::InvalidCredential {
749 credential_type: "passkey".to_string(),
750 message: format!("Failed to parse stored passkey data: {}", e),
751 }
752 })?;
753
754 let public_key_jwk = passkey_data
755 .get("public_key")
756 .cloned()
757 .unwrap_or(serde_json::Value::Null);
758 let stored_counter = passkey_data
759 .get("signature_counter")
760 .and_then(|v| v.as_u64())
761 .unwrap_or(0) as u32;
762
763 let expected_challenge_bytes: Vec<u8> = {
766 let challenges = self.pending_challenges.read().map_err(|_| {
767 AuthError::internal(
768 "Lock poisoned — a prior thread panicked while holding this lock",
769 )
770 })?;
771 challenges
772 .get(&credential_id_b64)
773 .or_else(|| challenges.get("latest"))
774 .cloned()
775 .ok_or_else(|| {
776 AuthError::validation(
777 "No pending challenge found; call initiate_authentication first",
778 )
779 })?
780 };
781
782 match self
784 .advanced_verification_flow(
785 &assertion_response,
786 expected_challenge_bytes.as_slice(),
787 stored_counter,
788 &public_key_jwk,
789 )
790 .await
791 {
792 Ok(verification_result) => {
793 if !verification_result.signature_valid {
794 return Err(AuthError::validation(
795 "Passkey signature verification failed",
796 ));
797 }
798
799 let mut updated_registration = registration.clone();
801
802 let mut passkey_data: serde_json::Value = serde_json::from_str(
804 &updated_registration.passkey_data,
805 )
806 .map_err(|e| AuthError::InvalidCredential {
807 credential_type: "passkey".to_string(),
808 message: format!("Failed to parse stored passkey data: {}", e),
809 })?;
810
811 passkey_data["signature_counter"] = serde_json::Value::Number(
812 serde_json::Number::from(verification_result.new_counter),
813 );
814
815 updated_registration.passkey_data =
816 serde_json::to_string(&passkey_data).map_err(|e| {
817 AuthError::InvalidCredential {
818 credential_type: "passkey".to_string(),
819 message: format!(
820 "Failed to serialize updated passkey data: {}",
821 e
822 ),
823 }
824 })?;
825
826 updated_registration.last_used = Some(SystemTime::now());
827
828 {
829 let mut passkeys = self.registered_passkeys.write()
830 .map_err(|_| AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock"))?;
831 passkeys.insert(credential_id_b64.clone(), updated_registration);
832 }
833
834 tracing::info!(
835 "Advanced passkey verification successful for user: {} (counter: {} -> {})",
836 registration.user_id,
837 stored_counter,
838 verification_result.new_counter
839 );
840 }
841 Err(e) => {
842 tracing::error!("Advanced passkey verification failed: {}", e);
843 return Err(e);
844 }
845 }
846
847 tracing::debug!("Assertion response length: {}", assertion_response.len());
849
850 tracing::info!(
853 "Passkey assertion verified successfully for user: {}",
854 registration.user_id
855 );
856
857 let token = self.token_manager.create_jwt_token(
858 ®istration.user_id,
859 vec![], Some(Duration::from_secs(3600)), )?;
862
863 let auth_token = AuthToken::new(
864 ®istration.user_id,
865 token,
866 Duration::from_secs(3600),
867 "passkey",
868 );
869
870 tracing::info!(
871 "Passkey authentication successful for user: {}",
872 registration.user_id
873 );
874 Ok(MethodResult::Success(Box::new(auth_token)))
875 }
876 _ => Ok(MethodResult::Failure {
877 reason: "Invalid credential type for passkey authentication".to_string(),
878 }),
879 }
880 }
881
882 #[cfg(not(feature = "passkeys"))]
883 {
884 let _ = credential; Ok(MethodResult::Failure {
886 reason: "Passkey support not compiled in. Enable 'passkeys' feature.".to_string(),
887 })
888 }
889 }
890
891 fn validate_config(&self) -> Result<()> {
892 if self.config.rp_id.is_empty() {
893 return Err(AuthError::config("Passkey RP ID cannot be empty"));
894 }
895 if self.config.origin.is_empty() {
896 return Err(AuthError::config("Passkey origin cannot be empty"));
897 }
898 if self.config.timeout_ms == 0 {
899 return Err(AuthError::config("Passkey timeout must be greater than 0"));
900 }
901
902 match self.config.user_verification.as_str() {
904 "required" | "preferred" | "discouraged" => {}
905 _ => return Err(AuthError::config("Invalid user verification requirement")),
906 }
907
908 #[cfg(feature = "passkeys")]
910 {
911 Url::parse(&self.config.origin)
912 .map_err(|e| AuthError::config(format!("Invalid origin URL: {}", e)))?;
913 }
914
915 Ok(())
916 }
917
918 fn supports_refresh(&self) -> bool {
919 false }
921
922 async fn refresh_token(&self, _refresh_token: String) -> Result<Self::AuthToken, AuthError> {
923 Err(AuthError::validation(
924 "Passkeys do not support token refresh",
925 ))
926 }
927}
928
929impl PasskeyAuthMethod {
930 pub async fn advanced_verification_flow(
933 &self,
934 assertion_response: &str,
935 expected_challenge: &[u8],
936 stored_counter: u32,
937 public_key_jwk: &serde_json::Value,
938 ) -> Result<AdvancedVerificationResult> {
939 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
940 use ring::digest;
941
942 tracing::info!("Starting advanced passkey verification flow");
943
944 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
946 .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
947
948 let client_data_json = assertion
950 .get("response")
951 .and_then(|r| r.get("clientDataJSON"))
952 .and_then(|c| c.as_str())
953 .ok_or_else(|| AuthError::validation("Missing clientDataJSON"))?;
954
955 let decoded_client_data = URL_SAFE_NO_PAD
956 .decode(client_data_json)
957 .map_err(|_| AuthError::validation("Invalid base64 in clientDataJSON"))?;
958
959 let client_data_str = std::str::from_utf8(&decoded_client_data)
960 .map_err(|_| AuthError::validation("Invalid UTF-8 in clientDataJSON"))?;
961
962 let client_data: serde_json::Value = serde_json::from_str(client_data_str)
963 .map_err(|_| AuthError::validation("Invalid JSON in clientDataJSON"))?;
964
965 let response_challenge = client_data
967 .get("challenge")
968 .and_then(|c| c.as_str())
969 .ok_or_else(|| AuthError::validation("Missing challenge in clientDataJSON"))?;
970
971 let decoded_challenge = URL_SAFE_NO_PAD
972 .decode(response_challenge)
973 .map_err(|_| AuthError::validation("Invalid challenge base64"))?;
974
975 if decoded_challenge != expected_challenge {
976 return Err(AuthError::validation("Challenge mismatch"));
977 }
978
979 let origin = client_data
981 .get("origin")
982 .and_then(|o| o.as_str())
983 .ok_or_else(|| AuthError::validation("Missing origin"))?;
984
985 if origin != self.config.origin {
986 return Err(AuthError::validation("Origin mismatch"));
987 }
988
989 let operation_type = client_data
991 .get("type")
992 .and_then(|t| t.as_str())
993 .ok_or_else(|| AuthError::validation("Missing operation type"))?;
994
995 if operation_type != "webauthn.get" {
996 return Err(AuthError::validation("Invalid operation type"));
997 }
998
999 let authenticator_data = assertion
1001 .get("response")
1002 .and_then(|r| r.get("authenticatorData"))
1003 .and_then(|a| a.as_str())
1004 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1005
1006 let auth_data_bytes = URL_SAFE_NO_PAD
1007 .decode(authenticator_data)
1008 .map_err(|_| AuthError::validation("Invalid authenticatorData base64"))?;
1009
1010 if auth_data_bytes.len() < 37 {
1011 return Err(AuthError::validation("AuthenticatorData too short"));
1012 }
1013
1014 let rp_id_hash = &auth_data_bytes[0..32];
1016 let expected_rp_id_hash = {
1017 let mut context = digest::Context::new(&digest::SHA256);
1018 context.update(self.config.rp_id.as_bytes());
1019 context.finish()
1020 };
1021
1022 if rp_id_hash != expected_rp_id_hash.as_ref() {
1023 return Err(AuthError::validation("RP ID hash mismatch"));
1024 }
1025
1026 let flags = auth_data_bytes[32];
1028 let user_present = (flags & 0x01) != 0;
1029 let user_verified = (flags & 0x04) != 0;
1030
1031 if !user_present {
1032 return Err(AuthError::validation("User not present"));
1033 }
1034
1035 let new_counter = self.extract_counter_from_assertion(assertion_response)?;
1037
1038 if new_counter != 0 && new_counter <= stored_counter {
1043 return Err(AuthError::validation(
1044 "Counter did not increase - possible replay attack or cloned authenticator",
1045 ));
1046 }
1047
1048 self.verify_assertion_signature(
1050 assertion_response,
1051 &auth_data_bytes,
1052 &decoded_client_data,
1053 public_key_jwk,
1054 )?;
1055
1056 tracing::info!("Advanced passkey verification completed successfully");
1057
1058 Ok(AdvancedVerificationResult {
1059 user_present,
1060 user_verified,
1061 new_counter,
1062 signature_valid: true,
1063 attestation_valid: true,
1064 })
1065 }
1066
1067 fn verify_webauthn_signature(
1069 &self,
1070 signed_data: &[u8],
1071 signature_bytes: &[u8],
1072 public_key_jwk: &serde_json::Value,
1073 ) -> Result<()> {
1074 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1075 use ring::signature;
1076
1077 let key_type = public_key_jwk
1078 .get("kty")
1079 .and_then(|v| v.as_str())
1080 .ok_or_else(|| AuthError::validation("Missing key type in JWK"))?;
1081
1082 let algorithm = public_key_jwk
1083 .get("alg")
1084 .and_then(|v| v.as_str())
1085 .ok_or_else(|| AuthError::validation("Missing algorithm in JWK"))?;
1086
1087 match key_type {
1088 "RSA" => {
1089 let n = public_key_jwk
1091 .get("n")
1092 .and_then(|v| v.as_str())
1093 .ok_or_else(|| AuthError::validation("Missing 'n' in RSA JWK"))?;
1094 let e = public_key_jwk
1095 .get("e")
1096 .and_then(|v| v.as_str())
1097 .ok_or_else(|| AuthError::validation("Missing 'e' in RSA JWK"))?;
1098
1099 let n_bytes = URL_SAFE_NO_PAD
1100 .decode(n.as_bytes())
1101 .map_err(|_| AuthError::validation("Invalid 'n' base64"))?;
1102 let e_bytes = URL_SAFE_NO_PAD
1103 .decode(e.as_bytes())
1104 .map_err(|_| AuthError::validation("Invalid 'e' base64"))?;
1105
1106 let n_ref: &[u8] = &n_bytes;
1110 let e_ref: &[u8] = &e_bytes;
1111 let rsa_key = signature::RsaPublicKeyComponents { n: n_ref, e: e_ref };
1112
1113 match algorithm {
1114 "RS256" => rsa_key.verify(
1115 &signature::RSA_PKCS1_2048_8192_SHA256,
1116 signed_data,
1117 signature_bytes,
1118 ),
1119 "RS384" => rsa_key.verify(
1120 &signature::RSA_PKCS1_2048_8192_SHA384,
1121 signed_data,
1122 signature_bytes,
1123 ),
1124 "RS512" => rsa_key.verify(
1125 &signature::RSA_PKCS1_2048_8192_SHA512,
1126 signed_data,
1127 signature_bytes,
1128 ),
1129 _ => return Err(AuthError::validation("Unsupported RSA algorithm")),
1130 }
1131 .map_err(|_| AuthError::validation("RSA signature verification failed"))?;
1132 }
1133 "EC" => {
1134 let curve = public_key_jwk
1136 .get("crv")
1137 .and_then(|v| v.as_str())
1138 .ok_or_else(|| AuthError::validation("Missing curve in EC JWK"))?;
1139 let x = public_key_jwk
1140 .get("x")
1141 .and_then(|v| v.as_str())
1142 .ok_or_else(|| AuthError::validation("Missing 'x' in EC JWK"))?;
1143 let y = public_key_jwk
1144 .get("y")
1145 .and_then(|v| v.as_str())
1146 .ok_or_else(|| AuthError::validation("Missing 'y' in EC JWK"))?;
1147
1148 let x_bytes = URL_SAFE_NO_PAD
1149 .decode(x.as_bytes())
1150 .map_err(|_| AuthError::validation("Invalid 'x' base64"))?;
1151 let y_bytes = URL_SAFE_NO_PAD
1152 .decode(y.as_bytes())
1153 .map_err(|_| AuthError::validation("Invalid 'y' base64"))?;
1154
1155 let (verification_algorithm, expected_coord_len) = match (curve, algorithm) {
1156 ("P-256", "ES256") => (&signature::ECDSA_P256_SHA256_ASN1, 32),
1157 ("P-384", "ES384") => (&signature::ECDSA_P384_SHA384_ASN1, 48),
1158 _ => return Err(AuthError::validation("Unsupported EC curve/algorithm")),
1159 };
1160
1161 if x_bytes.len() != expected_coord_len || y_bytes.len() != expected_coord_len {
1162 return Err(AuthError::validation("Invalid coordinate length"));
1163 }
1164
1165 let mut public_key_bytes = Vec::with_capacity(1 + expected_coord_len * 2);
1167 public_key_bytes.push(0x04); public_key_bytes.extend_from_slice(&x_bytes);
1169 public_key_bytes.extend_from_slice(&y_bytes);
1170
1171 let public_key =
1172 signature::UnparsedPublicKey::new(verification_algorithm, &public_key_bytes);
1173
1174 public_key
1175 .verify(signed_data, signature_bytes)
1176 .map_err(|_| AuthError::validation("ECDSA signature verification failed"))?;
1177 }
1178 _ => return Err(AuthError::validation("Unsupported key type for WebAuthn")),
1179 }
1180
1181 Ok(())
1182 }
1183
1184 pub async fn cross_platform_verification(
1186 &self,
1187 assertion_response: &str,
1188 authenticator_types: &[AuthenticatorType],
1189 ) -> Result<CrossPlatformVerificationResult> {
1190 tracing::info!("Starting cross-platform passkey verification");
1191
1192 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1194 .map_err(|_| AuthError::validation("Invalid assertion response"))?;
1195
1196 let authenticator_data = assertion
1198 .get("response")
1199 .and_then(|r| r.get("authenticatorData"))
1200 .and_then(|a| a.as_str())
1201 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1202
1203 let auth_data_bytes = URL_SAFE_NO_PAD
1204 .decode(authenticator_data)
1205 .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;
1206
1207 let aaguid = if auth_data_bytes.len() >= 53 && (auth_data_bytes[32] & 0x40) != 0 {
1209 Some(&auth_data_bytes[37..53])
1210 } else {
1211 None
1212 };
1213
1214 let detected_type = self.detect_authenticator_type(aaguid)?;
1216
1217 if !authenticator_types.contains(&detected_type) {
1219 return Err(AuthError::validation("Authenticator type not allowed"));
1220 }
1221
1222 let type_specific_result = match detected_type {
1224 AuthenticatorType::Platform => {
1225 tracing::debug!("Performing platform authenticator validation");
1226 self.validate_platform_authenticator(&assertion).await?
1227 }
1228 AuthenticatorType::CrossPlatform => {
1229 tracing::debug!("Performing cross-platform authenticator validation");
1230 self.validate_cross_platform_authenticator(&assertion)
1231 .await?
1232 }
1233 AuthenticatorType::SecurityKey => {
1234 tracing::debug!("Performing security key validation");
1235 self.validate_security_key(&assertion).await?
1236 }
1237 };
1238
1239 tracing::info!("Cross-platform verification completed successfully");
1240
1241 Ok(CrossPlatformVerificationResult {
1242 authenticator_type: detected_type,
1243 validation_result: type_specific_result,
1244 aaguid: aaguid.map(|a| a.to_vec()),
1245 })
1246 }
1247
1248 fn detect_authenticator_type(&self, aaguid: Option<&[u8]>) -> Result<AuthenticatorType> {
1250 match aaguid {
1251 Some(guid) if guid == [0u8; 16] => {
1252 Ok(AuthenticatorType::SecurityKey)
1254 }
1255 Some(guid) => {
1256 match guid {
1258 [
1260 0xf8,
1261 0xa0,
1262 0x11,
1263 0xf3,
1264 0x8c,
1265 0x0a,
1266 0x4d,
1267 0x15,
1268 0x80,
1269 0x06,
1270 0x17,
1271 0x11,
1272 0x1f,
1273 0x9e,
1274 0xdc,
1275 0x7d,
1276 ] => Ok(AuthenticatorType::SecurityKey),
1277 [
1279 0x08,
1280 0x98,
1281 0x7d,
1282 0x78,
1283 0x23,
1284 0x88,
1285 0x4d,
1286 0xa9,
1287 0xa6,
1288 0x91,
1289 0xb6,
1290 0xe1,
1291 0x04,
1292 0x5e,
1293 0xd4,
1294 0xd4,
1295 ] => Ok(AuthenticatorType::Platform),
1296 [
1298 0x08,
1299 0x98,
1300 0x7d,
1301 0x78,
1302 0x4e,
1303 0xd4,
1304 0x4d,
1305 0x49,
1306 0xa6,
1307 0x91,
1308 0xb6,
1309 0xe1,
1310 0x04,
1311 0x5e,
1312 0xd4,
1313 0xd4,
1314 ] => Ok(AuthenticatorType::Platform),
1315 _ => {
1316 Ok(AuthenticatorType::CrossPlatform)
1318 }
1319 }
1320 }
1321 None => {
1322 Ok(AuthenticatorType::SecurityKey)
1324 }
1325 }
1326 }
1327
1328 async fn validate_platform_authenticator(
1330 &self,
1331 assertion: &serde_json::Value,
1332 ) -> Result<TypeSpecificValidationResult> {
1333 tracing::debug!("Validating platform authenticator");
1334
1335 let authenticator_data = assertion
1337 .get("response")
1338 .and_then(|r| r.get("authenticatorData"))
1339 .and_then(|a| a.as_str())
1340 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1341
1342 let auth_data_bytes = URL_SAFE_NO_PAD
1343 .decode(authenticator_data)
1344 .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;
1345
1346 if auth_data_bytes.len() < 33 {
1347 return Err(AuthError::validation("AuthenticatorData too short"));
1348 }
1349
1350 let flags = auth_data_bytes[32];
1351 let user_verified = (flags & 0x04) != 0;
1352
1353 if !user_verified && self.config.user_verification == "required" {
1354 return Err(AuthError::validation(
1355 "User verification required for platform authenticator",
1356 ));
1357 }
1358
1359 Ok(TypeSpecificValidationResult {
1360 user_verified,
1361 attestation_valid: true,
1362 additional_properties: vec![
1363 ("authenticator_class".to_string(), "platform".to_string()),
1364 ("biometric_capable".to_string(), "true".to_string()),
1365 ],
1366 })
1367 }
1368
1369 async fn validate_cross_platform_authenticator(
1371 &self,
1372 _assertion: &serde_json::Value,
1373 ) -> Result<TypeSpecificValidationResult> {
1374 tracing::debug!("Validating cross-platform authenticator");
1375
1376 Ok(TypeSpecificValidationResult {
1378 user_verified: true,
1379 attestation_valid: true,
1380 additional_properties: vec![
1381 (
1382 "authenticator_class".to_string(),
1383 "cross_platform".to_string(),
1384 ),
1385 ("roaming_capable".to_string(), "true".to_string()),
1386 ],
1387 })
1388 }
1389
1390 async fn validate_security_key(
1392 &self,
1393 assertion: &serde_json::Value,
1394 ) -> Result<TypeSpecificValidationResult> {
1395 tracing::debug!("Validating security key");
1396
1397 let authenticator_data = assertion
1399 .get("response")
1400 .and_then(|r| r.get("authenticatorData"))
1401 .and_then(|a| a.as_str())
1402 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1403
1404 let auth_data_bytes = URL_SAFE_NO_PAD
1405 .decode(authenticator_data)
1406 .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;
1407
1408 if auth_data_bytes.len() < 33 {
1409 return Err(AuthError::validation("AuthenticatorData too short"));
1410 }
1411
1412 let flags = auth_data_bytes[32];
1413 let user_present = (flags & 0x01) != 0;
1414 let user_verified = (flags & 0x04) != 0;
1415
1416 if !user_present {
1417 return Err(AuthError::validation(
1418 "User presence required for security key",
1419 ));
1420 }
1421
1422 Ok(TypeSpecificValidationResult {
1423 user_verified,
1424 attestation_valid: true,
1425 additional_properties: vec![
1426 (
1427 "authenticator_class".to_string(),
1428 "security_key".to_string(),
1429 ),
1430 ("user_presence".to_string(), user_present.to_string()),
1431 ("hardware_backed".to_string(), "true".to_string()),
1432 ],
1433 })
1434 }
1435
1436 fn verify_assertion_signature(
1439 &self,
1440 assertion_response: &str,
1441 auth_data_bytes: &[u8],
1442 decoded_client_data: &[u8],
1443 public_key_jwk: &serde_json::Value,
1444 ) -> Result<()> {
1445 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1446 use ring::digest;
1447
1448 tracing::debug!("Verifying assertion signature");
1450
1451 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1453 .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
1454
1455 let signature = assertion
1457 .get("response")
1458 .and_then(|r| r.get("signature"))
1459 .and_then(|s| s.as_str())
1460 .ok_or_else(|| AuthError::validation("Missing signature in assertion response"))?;
1461
1462 let signature_bytes = URL_SAFE_NO_PAD
1463 .decode(signature)
1464 .map_err(|_| AuthError::validation("Invalid signature base64"))?;
1465
1466 let client_data_hash = {
1468 let mut context = digest::Context::new(&digest::SHA256);
1469 context.update(decoded_client_data);
1470 context.finish()
1471 };
1472
1473 let mut signed_data = Vec::new();
1474 signed_data.extend_from_slice(auth_data_bytes);
1475 signed_data.extend_from_slice(client_data_hash.as_ref());
1476
1477 self.verify_webauthn_signature(&signed_data, &signature_bytes, public_key_jwk)?;
1479
1480 Ok(())
1481 }
1482
1483 fn extract_counter_from_assertion(&self, assertion_response: &str) -> Result<u32> {
1485 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1486
1487 tracing::debug!("Extracting counter from assertion response");
1489
1490 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1492 .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
1493
1494 let authenticator_data = assertion
1495 .get("response")
1496 .and_then(|r| r.get("authenticatorData"))
1497 .and_then(|a| a.as_str())
1498 .ok_or_else(|| {
1499 AuthError::validation("Missing authenticatorData in assertion response")
1500 })?;
1501
1502 let auth_data_bytes = URL_SAFE_NO_PAD
1504 .decode(authenticator_data)
1505 .map_err(|_| AuthError::validation("authenticatorData is not valid base64url"))?;
1506
1507 if auth_data_bytes.len() < 37 {
1510 return Err(AuthError::validation(
1511 "authenticatorData is too short to contain a counter",
1512 ));
1513 }
1514
1515 let counter_bytes: [u8; 4] = [
1517 auth_data_bytes[33],
1518 auth_data_bytes[34],
1519 auth_data_bytes[35],
1520 auth_data_bytes[36],
1521 ];
1522
1523 let counter = u32::from_be_bytes(counter_bytes);
1524 tracing::debug!("Extracted signature counter: {}", counter);
1525 Ok(counter)
1526 }
1527}
1528
1529#[derive(Debug, Clone, Serialize, Deserialize)]
1531pub struct AdvancedVerificationResult {
1532 pub user_present: bool,
1533 pub user_verified: bool,
1534 pub new_counter: u32,
1535 pub signature_valid: bool,
1536 pub attestation_valid: bool,
1537}
1538
1539#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1541pub enum AuthenticatorType {
1542 Platform,
1544 CrossPlatform,
1546 SecurityKey,
1548}
1549
1550#[derive(Debug, Clone, Serialize, Deserialize)]
1552pub struct CrossPlatformVerificationResult {
1553 pub authenticator_type: AuthenticatorType,
1554 pub validation_result: TypeSpecificValidationResult,
1555 pub aaguid: Option<Vec<u8>>,
1556}
1557
1558#[derive(Debug, Clone, Serialize, Deserialize)]
1560pub struct TypeSpecificValidationResult {
1561 pub user_verified: bool,
1562 pub attestation_valid: bool,
1563 pub additional_properties: Vec<(String, String)>,
1564}
1565
1566#[cfg(test)]
1567mod tests {
1568 use super::*;
1569 use crate::tokens::TokenManager;
1570
1571 #[tokio::test]
1572 async fn test_passkey_config_validation() {
1573 let token_manager = TokenManager::new_hmac(b"test-secret", "test-issuer", "test-audience");
1574
1575 let config = PasskeyConfig {
1576 rp_id: "example.com".to_string(),
1577 rp_name: "Test App".to_string(),
1578 origin: "https://example.com".to_string(),
1579 timeout_ms: 60000,
1580 user_verification: "preferred".to_string(),
1581 authenticator_attachment: None,
1582 require_resident_key: false,
1583 ..Default::default()
1584 };
1585
1586 let result = PasskeyAuthMethod::new(config, token_manager);
1587
1588 #[cfg(feature = "passkeys")]
1589 {
1590 assert!(result.is_ok());
1591 let method = result.unwrap();
1592 assert!(method.validate_config().is_ok());
1593 }
1594
1595 #[cfg(not(feature = "passkeys"))]
1596 {
1597 assert!(result.is_err());
1598 }
1599 }
1600
1601 #[tokio::test]
1602 async fn test_invalid_passkey_config() {
1603 #[cfg_attr(not(feature = "passkeys"), allow(unused_variables))]
1604 let token_manager = TokenManager::new_hmac(b"test-secret", "test-issuer", "test-audience");
1605
1606 #[cfg_attr(not(feature = "passkeys"), allow(unused_variables))]
1607 let config = PasskeyConfig {
1608 rp_id: "".to_string(), rp_name: "Test App".to_string(),
1610 origin: "https://example.com".to_string(),
1611 timeout_ms: 60000,
1612 user_verification: "invalid".to_string(), authenticator_attachment: None,
1614 require_resident_key: false,
1615 ..Default::default()
1616 };
1617
1618 #[cfg(feature = "passkeys")]
1619 {
1620 let result = PasskeyAuthMethod::new(config, token_manager);
1621 if let Ok(method) = result {
1622 assert!(method.validate_config().is_err());
1623 }
1624 }
1625 }
1626}