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;
113#[cfg(feature = "passkeys")]
114use passkey::{
115 authenticator::{Authenticator, UiHint, UserCheck, UserValidationMethod},
116 client::Client,
117 crypto::rust_crypto::RustCryptoBackend,
118 types::{
119 Bytes, Passkey,
120 ctap2::{Aaguid, Ctap2Error},
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")]
138fn random_challenge() -> Result<Vec<u8>> {
139 use ring::rand::SecureRandom;
140 let mut challenge = vec![0u8; 32];
141 ring::rand::SystemRandom::new()
142 .fill(&mut challenge)
143 .map_err(|_| AuthError::internal("Failed to generate a passkey challenge"))?;
144 Ok(challenge)
145}
146
147fn json_bytes(value: &serde_json::Value) -> Option<Vec<u8>> {
151 match value {
152 serde_json::Value::String(s) => URL_SAFE_NO_PAD.decode(s).ok(),
153 serde_json::Value::Array(items) => items
154 .iter()
155 .map(|b| b.as_u64().and_then(|n| u8::try_from(n).ok()))
156 .collect(),
157 _ => None,
158 }
159}
160
161#[cfg(feature = "passkeys")]
163fn der_element(input: &[u8]) -> Option<(u8, &[u8], &[u8])> {
164 let (&tag, rest) = input.split_first()?;
165 let (&first, rest) = rest.split_first()?;
166 let (len, rest) = if first < 0x80 {
167 (usize::from(first), rest)
168 } else {
169 let count = usize::from(first & 0x7f);
170 if count == 0 || count > 4 || rest.len() < count {
171 return None;
172 }
173 let len = rest[..count]
174 .iter()
175 .fold(0usize, |acc, &b| (acc << 8) | usize::from(b));
176 (len, &rest[count..])
177 };
178 if rest.len() < len {
179 return None;
180 }
181 Some((tag, &rest[..len], &rest[len..]))
182}
183
184#[cfg(feature = "passkeys")]
187fn jwk_from_spki(spki: &[u8], algorithm: i64) -> Result<serde_json::Value> {
188 const BAD: &str = "Passkey public key is not a valid SubjectPublicKeyInfo";
189 const EC_PUBLIC_KEY: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01];
190 const P256: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07];
191 const P384: &[u8] = &[0x2b, 0x81, 0x04, 0x00, 0x22];
192 const RSA: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01];
193
194 let bad = || AuthError::validation(BAD);
195 let (tag, spki_body, trailing) = der_element(spki).ok_or_else(bad)?;
196 if tag != 0x30 || !trailing.is_empty() {
197 return Err(bad());
198 }
199 let (tag, alg_id, rest) = der_element(spki_body).ok_or_else(bad)?;
200 if tag != 0x30 {
201 return Err(bad());
202 }
203 let (tag, key_bits, trailing) = der_element(rest).ok_or_else(bad)?;
204 if tag != 0x03 || !trailing.is_empty() || key_bits.first() != Some(&0) {
205 return Err(bad());
206 }
207 let key = &key_bits[1..];
208 let (tag, key_oid, alg_params) = der_element(alg_id).ok_or_else(bad)?;
209 if tag != 0x06 {
210 return Err(bad());
211 }
212
213 match (algorithm, key_oid) {
214 (-7 | -35, oid) if oid == EC_PUBLIC_KEY => {
215 let (tag, curve, _) = der_element(alg_params).ok_or_else(bad)?;
216 let (crv, alg, size) = match (algorithm, curve) {
217 (-7, c) if tag == 0x06 && c == P256 => ("P-256", "ES256", 32),
218 (-35, c) if tag == 0x06 && c == P384 => ("P-384", "ES384", 48),
219 _ => return Err(AuthError::validation("Unsupported passkey curve")),
220 };
221 if key.len() != 1 + 2 * size || key[0] != 0x04 {
222 return Err(bad());
223 }
224 Ok(serde_json::json!({
225 "kty": "EC",
226 "crv": crv,
227 "alg": alg,
228 "x": URL_SAFE_NO_PAD.encode(&key[1..1 + size]),
229 "y": URL_SAFE_NO_PAD.encode(&key[1 + size..]),
230 }))
231 }
232 (-257, oid) if oid == RSA => {
233 let (tag, rsa_key, trailing) = der_element(key).ok_or_else(bad)?;
234 if tag != 0x30 || !trailing.is_empty() {
235 return Err(bad());
236 }
237 let (tag, n, rest) = der_element(rsa_key).ok_or_else(bad)?;
238 let (tag_e, e, trailing) = der_element(rest).ok_or_else(bad)?;
239 if tag != 0x02 || tag_e != 0x02 || !trailing.is_empty() {
240 return Err(bad());
241 }
242 let strip = |v: &[u8]| -> Vec<u8> {
243 let skip = v.iter().take_while(|&&b| b == 0).count();
244 v[skip..].to_vec()
245 };
246 Ok(serde_json::json!({
247 "kty": "RSA",
248 "alg": "RS256",
249 "n": URL_SAFE_NO_PAD.encode(strip(n)),
250 "e": URL_SAFE_NO_PAD.encode(strip(e)),
251 }))
252 }
253 _ => Err(AuthError::validation("Unsupported passkey key algorithm")),
254 }
255}
256
257#[cfg(feature = "passkeys")]
259struct PasskeyUserValidation;
260
261#[cfg(feature = "passkeys")]
262#[async_trait::async_trait]
263impl UserValidationMethod for PasskeyUserValidation {
264 type PasskeyItem = Passkey;
265
266 async fn check_user<'a>(
267 &self,
268 _hint: UiHint<'a, Passkey>,
269 presence: bool,
270 verification: bool,
271 ) -> std::result::Result<UserCheck, Ctap2Error> {
272 Ok(UserCheck {
273 presence,
274 verification,
275 })
276 }
277
278 fn is_verification_enabled(&self) -> Option<bool> {
279 Some(true)
280 }
281
282 fn is_presence_enabled(&self) -> bool {
283 true
284 }
285}
286
287pub struct PasskeyAuthMethod {
369 pub config: PasskeyConfig,
370 pub token_manager: TokenManager,
371 pub registered_passkeys: RwLock<HashMap<String, PasskeyRegistration>>,
373 #[cfg(feature = "passkeys")]
376 pending_challenges: RwLock<HashMap<String, Vec<u8>>>,
377}
378
379impl std::fmt::Debug for PasskeyAuthMethod {
380 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
381 let mut s = f.debug_struct("PasskeyAuthMethod");
382 s.field("config", &self.config);
383 s.field("token_manager", &"<TokenManager>");
384 s.field("registered_passkeys", &"<RwLock<HashMap>>");
385 #[cfg(feature = "passkeys")]
386 s.field("pending_challenges", &"<RwLock<HashMap>>");
387 s.finish()
388 }
389}
390
391#[derive(Debug, Clone, Serialize, Deserialize)]
393pub struct PasskeyConfig {
394 pub rp_id: String,
396 pub rp_name: String,
398 pub origin: String,
400 pub timeout_ms: u32,
402 pub user_verification: String, pub authenticator_attachment: Option<String>, pub require_resident_key: bool,
408 #[serde(default = "default_attestation_conveyance")]
411 pub attestation_conveyance: String,
412}
413
414fn default_attestation_conveyance() -> String {
415 "direct".to_string()
416}
417
418impl Default for PasskeyConfig {
419 fn default() -> Self {
420 Self {
421 rp_id: "localhost".to_string(),
422 rp_name: "Auth Framework Demo".to_string(),
423 origin: "http://localhost:3000".to_string(),
424 timeout_ms: 60000, user_verification: "preferred".to_string(),
426 authenticator_attachment: None,
427 require_resident_key: false,
428 attestation_conveyance: default_attestation_conveyance(),
429 }
430 }
431}
432
433#[derive(Clone, Serialize, Deserialize)]
435pub struct PasskeyRegistration {
436 pub user_id: String,
437 pub user_name: String,
438 pub user_display_name: String,
439 pub credential_id: Vec<u8>,
440 pub passkey_data: String, pub created_at: SystemTime,
442 pub last_used: Option<SystemTime>,
443}
444
445impl std::fmt::Debug for PasskeyRegistration {
446 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
447 let mut d = f.debug_struct("PasskeyRegistration");
448 d.field("user_id", &self.user_id);
449 d.field("user_name", &self.user_name);
450 d.field("user_display_name", &self.user_display_name);
451 d.field("credential_id", &self.credential_id);
452 d.field(
453 "passkey_data",
454 &crate::utils::redact::redacted(&self.passkey_data),
455 );
456 d.field("created_at", &self.created_at);
457 d.field("last_used", &self.last_used);
458 d.finish()
459 }
460}
461
462impl PasskeyAuthMethod {
463 pub fn new(config: PasskeyConfig, token_manager: TokenManager) -> Result<Self> {
465 #[cfg(feature = "passkeys")]
466 {
467 Ok(Self {
468 config,
469 token_manager,
470 registered_passkeys: RwLock::new(HashMap::new()),
471 pending_challenges: RwLock::new(HashMap::new()),
472 })
473 }
474
475 #[cfg(not(feature = "passkeys"))]
476 {
477 let _ = (config, token_manager); Err(AuthError::config(
479 "Passkey support not compiled in. Enable 'passkeys' feature.",
480 ))
481 }
482 }
483
484 #[cfg(feature = "passkeys")]
486 pub async fn register_passkey(
487 &mut self,
488 user_id: &str,
489 user_name: &str,
490 user_display_name: &str,
491 ) -> Result<CreatedPublicKeyCredential> {
492 let origin = Url::parse(&self.config.origin)
493 .map_err(|e| AuthError::config(format!("Invalid origin URL: {}", e)))?;
494
495 let aaguid = Aaguid::new_empty();
497 let user_validation = PasskeyUserValidation;
498 let store: Option<Passkey> = None;
499 let authenticator = Authenticator::new(aaguid, store, user_validation, RustCryptoBackend);
500
501 let mut client = Client::new(authenticator);
503
504 let challenge: Bytes = random_challenge()?.into();
506
507 let user_entity = PublicKeyCredentialUserEntity {
509 id: Bytes::from(user_id.as_bytes().to_vec()),
510 display_name: user_display_name.to_string(),
511 name: user_name.to_string(),
512 };
513
514 let request = CredentialCreationOptions {
516 public_key: PublicKeyCredentialCreationOptions {
517 rp: PublicKeyCredentialRpEntity {
518 id: None, name: self.config.rp_name.clone(),
520 },
521 user: user_entity,
522 challenge,
523 pub_key_cred_params: vec![
524 PublicKeyCredentialParameters {
525 ty: PublicKeyCredentialType::PublicKey,
526 alg: iana::Algorithm::ES256,
527 },
528 PublicKeyCredentialParameters {
529 ty: PublicKeyCredentialType::PublicKey,
530 alg: iana::Algorithm::RS256,
531 },
532 ],
533 timeout: Some(self.config.timeout_ms),
534 exclude_credentials: None,
535 authenticator_selection: None,
536 hints: None,
537 attestation: match self.config.attestation_conveyance.as_str() {
538 "none" => AttestationConveyancePreference::None,
539 "indirect" => AttestationConveyancePreference::Indirect,
540 "enterprise" => AttestationConveyancePreference::Enterprise,
541 _ => AttestationConveyancePreference::Direct,
543 },
544 attestation_formats: None,
545 extensions: None,
546 },
547 };
548
549 let credential = client
551 .register(&origin, request, DefaultClientData)
552 .await
553 .map_err(|e| AuthError::validation(format!("Passkey registration failed: {:?}", e)))?;
554
555 self.register_credential(user_id, user_name, user_display_name, &credential)?;
556 Ok(credential)
557 }
558
559 #[cfg(feature = "passkeys")]
565 pub fn register_credential(
566 &mut self,
567 user_id: &str,
568 user_name: &str,
569 user_display_name: &str,
570 credential: &CreatedPublicKeyCredential,
571 ) -> Result<()> {
572 let credential_id = &credential.raw_id;
573 let credential_id_b64 = URL_SAFE_NO_PAD.encode(credential_id.as_slice());
574
575 let credential_value = serde_json::to_value(credential)
576 .map_err(|e| AuthError::validation(format!("Unreadable passkey credential: {e}")))?;
577 let response = credential_value
578 .get("response")
579 .ok_or_else(|| AuthError::validation("Passkey credential has no response"))?;
580 let spki = response
581 .get("publicKey")
582 .and_then(json_bytes)
583 .ok_or_else(|| AuthError::validation("Passkey credential has no public key"))?;
584 let algorithm = response
585 .get("publicKeyAlgorithm")
586 .and_then(serde_json::Value::as_i64)
587 .ok_or_else(|| AuthError::validation("Passkey credential has no key algorithm"))?;
588 let public_key_jwk = jwk_from_spki(&spki, algorithm)?;
589 let sign_count = response
590 .get("authenticatorData")
591 .and_then(json_bytes)
592 .and_then(|d| {
593 d.get(33..37)
594 .map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]]))
595 })
596 .ok_or_else(|| AuthError::validation("Passkey credential has no authenticator data"))?;
597
598 let passkey_data_json = serde_json::json!({
599 "credential_id": credential_id_b64,
600 "public_key": public_key_jwk,
601 "signature_counter": sign_count,
602 "raw_attestation": credential_value,
603 });
604 let passkey_data_str = serde_json::to_string(&passkey_data_json).map_err(|e| {
605 AuthError::validation(format!("Failed to serialize passkey data: {}", e))
606 })?;
607
608 let registration = PasskeyRegistration {
609 user_id: user_id.to_string(),
610 user_name: user_name.to_string(),
611 user_display_name: user_display_name.to_string(),
612 credential_id: credential_id.as_slice().to_vec(),
613 passkey_data: passkey_data_str,
614 created_at: SystemTime::now(),
615 last_used: None,
616 };
617
618 {
619 let mut passkeys = self.registered_passkeys.write().map_err(|_| {
620 AuthError::internal(
621 "Lock poisoned — a prior thread panicked while holding this lock",
622 )
623 })?;
624 passkeys.insert(credential_id_b64, registration);
625 }
626
627 tracing::info!("Successfully registered passkey for user: {}", user_id);
628 Ok(())
629 }
630
631 #[cfg(feature = "passkeys")]
633 pub fn registered_passkey(&self, credential_id: &[u8]) -> Option<PasskeyRegistration> {
634 let key = URL_SAFE_NO_PAD.encode(credential_id);
635 self.registered_passkeys.read().ok()?.get(&key).cloned()
636 }
637
638 #[cfg(feature = "passkeys")]
640 pub async fn initiate_authentication(
641 &self,
642 user_id: Option<&str>,
643 ) -> Result<CredentialRequestOptions> {
644 let challenge_bytes = random_challenge()?;
645 let challenge: Bytes = challenge_bytes.clone().into();
646
647 let allow_credential_ids: Vec<(Vec<u8>, String)> = {
648 let passkeys = self.registered_passkeys.read().map_err(|_| {
649 AuthError::internal(
650 "Lock poisoned — a prior thread panicked while holding this lock",
651 )
652 })?;
653 let iter: Box<dyn Iterator<Item = &PasskeyRegistration>> = if let Some(uid) = user_id {
654 Box::new(passkeys.values().filter(move |reg| reg.user_id == uid))
655 } else {
656 Box::new(passkeys.values())
657 };
658 iter.map(|reg| {
659 (
660 reg.credential_id.clone(),
661 URL_SAFE_NO_PAD.encode(®.credential_id),
662 )
663 })
664 .collect()
665 };
666
667 {
670 let mut challenges = self.pending_challenges.write().map_err(|_| {
671 AuthError::internal(
672 "Lock poisoned — a prior thread panicked while holding this lock",
673 )
674 })?;
675 for (_, cred_id_b64) in &allow_credential_ids {
676 challenges.insert(cred_id_b64.clone(), challenge_bytes.clone());
677 }
678 challenges.insert("latest".to_string(), challenge_bytes.clone());
680 }
681
682 let allow_credentials: Vec<PublicKeyCredentialDescriptor> = allow_credential_ids
683 .into_iter()
684 .map(|(raw_id, _)| PublicKeyCredentialDescriptor {
685 ty: PublicKeyCredentialType::PublicKey,
686 id: raw_id.into(),
687 transports: None,
688 })
689 .collect();
690
691 let request_options = CredentialRequestOptions {
692 public_key: PublicKeyCredentialRequestOptions {
693 challenge,
694 timeout: Some(self.config.timeout_ms),
695 rp_id: Some(self.config.rp_id.clone()),
696 allow_credentials: Some(allow_credentials),
697 user_verification: match self.config.user_verification.as_str() {
698 "required" => UserVerificationRequirement::Required,
699 "discouraged" => UserVerificationRequirement::Discouraged,
700 _ => UserVerificationRequirement::Preferred,
701 },
702 hints: None,
703 attestation: match self.config.attestation_conveyance.as_str() {
704 "none" => AttestationConveyancePreference::None,
705 "indirect" => AttestationConveyancePreference::Indirect,
706 "enterprise" => AttestationConveyancePreference::Enterprise,
707 _ => AttestationConveyancePreference::Direct,
708 },
709 attestation_formats: None,
710 extensions: None,
711 },
712 };
713
714 tracing::info!("Generated passkey authentication options");
715 Ok(request_options)
716 }
717
718 #[cfg(feature = "passkeys")]
720 pub async fn complete_authentication(
721 &mut self,
722 credential_response: &AuthenticatedPublicKeyCredential,
723 ) -> Result<AuthToken> {
724 let credential_id = &credential_response.raw_id;
725 let credential_id_b64 = URL_SAFE_NO_PAD.encode(credential_id.as_slice());
726
727 let mut registration = {
729 let passkeys = self.registered_passkeys.read().map_err(|_| {
730 AuthError::internal(
731 "Lock poisoned — a prior thread panicked while holding this lock",
732 )
733 })?;
734 passkeys
735 .get(&credential_id_b64)
736 .ok_or_else(|| AuthError::validation("Unknown credential ID"))?
737 .clone()
738 };
739
740 let assertion_response = serde_json::to_string(credential_response).map_err(|e| {
743 AuthError::InvalidCredential {
744 credential_type: "passkey".to_string(),
745 message: format!("Failed to serialize credential response: {}", e),
746 }
747 })?;
748
749 let passkey_data: serde_json::Value = serde_json::from_str(®istration.passkey_data)
751 .map_err(|e| AuthError::InvalidCredential {
752 credential_type: "passkey".to_string(),
753 message: format!("Failed to parse stored passkey data: {}", e),
754 })?;
755
756 let public_key_jwk = passkey_data
757 .get("public_key")
758 .cloned()
759 .unwrap_or(serde_json::Value::Null);
760 let stored_counter = passkey_data
761 .get("signature_counter")
762 .and_then(|v| v.as_u64())
763 .unwrap_or(0) as u32;
764
765 let expected_challenge_bytes: Vec<u8> = {
768 let mut challenges = self.pending_challenges.write().map_err(|_| {
769 AuthError::internal(
770 "Lock poisoned — a prior thread panicked while holding this lock",
771 )
772 })?;
773 let own = challenges.remove(&credential_id_b64);
774 let taken = match own {
777 Some(own) => {
778 if challenges.get("latest") == Some(&own) {
779 challenges.remove("latest");
780 }
781 Some(own)
782 }
783 None => challenges.remove("latest"),
784 };
785 taken.ok_or_else(|| {
786 AuthError::validation(
787 "No pending challenge found; call initiate_authentication first",
788 )
789 })?
790 };
791
792 let verification_result = self
794 .advanced_verification_flow(
795 &assertion_response,
796 expected_challenge_bytes.as_slice(),
797 stored_counter,
798 &public_key_jwk,
799 )
800 .await?;
801
802 if !verification_result.signature_valid {
803 return Err(AuthError::validation(
804 "Passkey signature verification failed",
805 ));
806 }
807
808 let mut passkey_data: serde_json::Value = serde_json::from_str(®istration.passkey_data)
810 .map_err(|e| AuthError::InvalidCredential {
811 credential_type: "passkey".to_string(),
812 message: format!(
813 "Failed to parse stored passkey data during counter update: {}",
814 e
815 ),
816 })?;
817 passkey_data["signature_counter"] =
818 serde_json::Value::Number(serde_json::Number::from(verification_result.new_counter));
819 registration.passkey_data =
820 serde_json::to_string(&passkey_data).map_err(|e| AuthError::InvalidCredential {
821 credential_type: "passkey".to_string(),
822 message: format!("Failed to serialize updated passkey data: {}", e),
823 })?;
824 registration.last_used = Some(SystemTime::now());
825
826 {
827 let mut passkeys = self.registered_passkeys.write().map_err(|_| {
828 AuthError::internal(
829 "Lock poisoned — a prior thread panicked while holding this lock",
830 )
831 })?;
832 passkeys.insert(credential_id_b64.clone(), registration.clone());
833 }
834
835 let token = self.token_manager.create_jwt_token(
837 ®istration.user_id,
838 vec![],
839 Some(Duration::from_secs(3600)),
840 )?;
841
842 tracing::info!(
843 "Passkey authentication successful for user: {} (counter: {} -> {})",
844 registration.user_id,
845 stored_counter,
846 verification_result.new_counter
847 );
848 Ok(AuthToken::new(
849 ®istration.user_id,
850 token,
851 Duration::from_secs(3600),
852 "passkey",
853 ))
854 }
855
856 #[cfg(not(feature = "passkeys"))]
858 pub async fn register_passkey(
859 &mut self,
860 _user_id: &str,
861 _user_name: &str,
862 _user_display_name: &str,
863 ) -> Result<()> {
864 Err(AuthError::config(
865 "Passkey support not compiled in. Enable 'passkeys' feature.",
866 ))
867 }
868}
869
870impl AuthMethod for PasskeyAuthMethod {
871 type MethodResult = MethodResult;
872 type AuthToken = AuthToken;
873
874 fn name(&self) -> &str {
875 "passkey"
876 }
877
878 async fn authenticate(
879 &self,
880 credential: Credential,
881 _metadata: CredentialMetadata,
882 ) -> Result<Self::MethodResult> {
883 #[cfg(feature = "passkeys")]
884 {
885 match credential {
886 Credential::Passkey {
887 credential_id,
888 assertion_response,
889 } => {
890 let credential_id_b64 = URL_SAFE_NO_PAD.encode(&credential_id);
892 let registration = {
893 let passkeys = self.registered_passkeys.read().map_err(|_| {
894 AuthError::internal(
895 "Lock poisoned — a prior thread panicked while holding this lock",
896 )
897 })?;
898 passkeys
899 .get(&credential_id_b64)
900 .cloned()
901 .ok_or_else(|| AuthError::validation("Unknown credential ID"))?
902 };
903
904 tracing::debug!(
905 "Processing passkey assertion for credential: {}",
906 credential_id_b64
907 );
908
909 let passkey_data: serde_json::Value =
912 serde_json::from_str(®istration.passkey_data).map_err(|e| {
913 AuthError::InvalidCredential {
914 credential_type: "passkey".to_string(),
915 message: format!("Failed to parse stored passkey data: {}", e),
916 }
917 })?;
918
919 let public_key_jwk = passkey_data
920 .get("public_key")
921 .cloned()
922 .unwrap_or(serde_json::Value::Null);
923 let stored_counter = passkey_data
924 .get("signature_counter")
925 .and_then(|v| v.as_u64())
926 .unwrap_or(0) as u32;
927
928 let expected_challenge_bytes: Vec<u8> = {
931 let challenges = self.pending_challenges.read().map_err(|_| {
932 AuthError::internal(
933 "Lock poisoned — a prior thread panicked while holding this lock",
934 )
935 })?;
936 challenges
937 .get(&credential_id_b64)
938 .or_else(|| challenges.get("latest"))
939 .cloned()
940 .ok_or_else(|| {
941 AuthError::validation(
942 "No pending challenge found; call initiate_authentication first",
943 )
944 })?
945 };
946
947 match self
949 .advanced_verification_flow(
950 &assertion_response,
951 expected_challenge_bytes.as_slice(),
952 stored_counter,
953 &public_key_jwk,
954 )
955 .await
956 {
957 Ok(verification_result) => {
958 if !verification_result.signature_valid {
959 return Err(AuthError::validation(
960 "Passkey signature verification failed",
961 ));
962 }
963
964 let mut updated_registration = registration.clone();
966
967 let mut passkey_data: serde_json::Value = serde_json::from_str(
969 &updated_registration.passkey_data,
970 )
971 .map_err(|e| AuthError::InvalidCredential {
972 credential_type: "passkey".to_string(),
973 message: format!("Failed to parse stored passkey data: {}", e),
974 })?;
975
976 passkey_data["signature_counter"] = serde_json::Value::Number(
977 serde_json::Number::from(verification_result.new_counter),
978 );
979
980 updated_registration.passkey_data =
981 serde_json::to_string(&passkey_data).map_err(|e| {
982 AuthError::InvalidCredential {
983 credential_type: "passkey".to_string(),
984 message: format!(
985 "Failed to serialize updated passkey data: {}",
986 e
987 ),
988 }
989 })?;
990
991 updated_registration.last_used = Some(SystemTime::now());
992
993 {
994 let mut passkeys = self.registered_passkeys.write()
995 .map_err(|_| AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock"))?;
996 passkeys.insert(credential_id_b64.clone(), updated_registration);
997 }
998
999 tracing::info!(
1000 "Advanced passkey verification successful for user: {} (counter: {} -> {})",
1001 registration.user_id,
1002 stored_counter,
1003 verification_result.new_counter
1004 );
1005 }
1006 Err(e) => {
1007 tracing::error!("Advanced passkey verification failed: {}", e);
1008 return Err(e);
1009 }
1010 }
1011
1012 tracing::debug!("Assertion response length: {}", assertion_response.len());
1014
1015 tracing::info!(
1018 "Passkey assertion verified successfully for user: {}",
1019 registration.user_id
1020 );
1021
1022 let token = self.token_manager.create_jwt_token(
1023 ®istration.user_id,
1024 vec![], Some(Duration::from_secs(3600)), )?;
1027
1028 let auth_token = AuthToken::new(
1029 ®istration.user_id,
1030 token,
1031 Duration::from_secs(3600),
1032 "passkey",
1033 );
1034
1035 tracing::info!(
1036 "Passkey authentication successful for user: {}",
1037 registration.user_id
1038 );
1039 Ok(MethodResult::Success(Box::new(auth_token)))
1040 }
1041 _ => Ok(MethodResult::Failure {
1042 reason: "Invalid credential type for passkey authentication".to_string(),
1043 }),
1044 }
1045 }
1046
1047 #[cfg(not(feature = "passkeys"))]
1048 {
1049 let _ = credential; Ok(MethodResult::Failure {
1051 reason: "Passkey support not compiled in. Enable 'passkeys' feature.".to_string(),
1052 })
1053 }
1054 }
1055
1056 fn validate_config(&self) -> Result<()> {
1057 if self.config.rp_id.is_empty() {
1058 return Err(AuthError::config("Passkey RP ID cannot be empty"));
1059 }
1060 if self.config.origin.is_empty() {
1061 return Err(AuthError::config("Passkey origin cannot be empty"));
1062 }
1063 if self.config.timeout_ms == 0 {
1064 return Err(AuthError::config("Passkey timeout must be greater than 0"));
1065 }
1066
1067 match self.config.user_verification.as_str() {
1069 "required" | "preferred" | "discouraged" => {}
1070 _ => return Err(AuthError::config("Invalid user verification requirement")),
1071 }
1072
1073 #[cfg(feature = "passkeys")]
1075 {
1076 Url::parse(&self.config.origin)
1077 .map_err(|e| AuthError::config(format!("Invalid origin URL: {}", e)))?;
1078 }
1079
1080 Ok(())
1081 }
1082
1083 fn supports_refresh(&self) -> bool {
1084 false }
1086
1087 async fn refresh_token(&self, _refresh_token: String) -> Result<Self::AuthToken, AuthError> {
1088 Err(AuthError::validation(
1089 "Passkeys do not support token refresh",
1090 ))
1091 }
1092}
1093
1094impl PasskeyAuthMethod {
1095 pub async fn advanced_verification_flow(
1098 &self,
1099 assertion_response: &str,
1100 expected_challenge: &[u8],
1101 stored_counter: u32,
1102 public_key_jwk: &serde_json::Value,
1103 ) -> Result<AdvancedVerificationResult> {
1104 use ring::digest;
1105
1106 tracing::info!("Starting advanced passkey verification flow");
1107
1108 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1110 .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
1111
1112 let client_data_json = assertion
1114 .get("response")
1115 .and_then(|r| r.get("clientDataJSON"))
1116 .ok_or_else(|| AuthError::validation("Missing clientDataJSON"))?;
1117
1118 let decoded_client_data = json_bytes(client_data_json)
1119 .ok_or_else(|| AuthError::validation("Invalid encoding of clientDataJSON"))?;
1120
1121 let client_data_str = std::str::from_utf8(&decoded_client_data)
1122 .map_err(|_| AuthError::validation("Invalid UTF-8 in clientDataJSON"))?;
1123
1124 let client_data: serde_json::Value = serde_json::from_str(client_data_str)
1125 .map_err(|_| AuthError::validation("Invalid JSON in clientDataJSON"))?;
1126
1127 let response_challenge = client_data
1129 .get("challenge")
1130 .and_then(|c| c.as_str())
1131 .ok_or_else(|| AuthError::validation("Missing challenge in clientDataJSON"))?;
1132
1133 let decoded_challenge = URL_SAFE_NO_PAD
1134 .decode(response_challenge)
1135 .map_err(|_| AuthError::validation("Invalid challenge base64"))?;
1136
1137 if decoded_challenge != expected_challenge {
1138 return Err(AuthError::validation("Challenge mismatch"));
1139 }
1140
1141 let origin = client_data
1143 .get("origin")
1144 .and_then(|o| o.as_str())
1145 .ok_or_else(|| AuthError::validation("Missing origin"))?;
1146
1147 if origin != self.config.origin {
1148 return Err(AuthError::validation("Origin mismatch"));
1149 }
1150
1151 let operation_type = client_data
1153 .get("type")
1154 .and_then(|t| t.as_str())
1155 .ok_or_else(|| AuthError::validation("Missing operation type"))?;
1156
1157 if operation_type != "webauthn.get" {
1158 return Err(AuthError::validation("Invalid operation type"));
1159 }
1160
1161 let authenticator_data = assertion
1163 .get("response")
1164 .and_then(|r| r.get("authenticatorData"))
1165 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1166
1167 let auth_data_bytes = json_bytes(authenticator_data)
1168 .ok_or_else(|| AuthError::validation("Invalid authenticatorData encoding"))?;
1169
1170 if auth_data_bytes.len() < 37 {
1171 return Err(AuthError::validation("AuthenticatorData too short"));
1172 }
1173
1174 let rp_id_hash = &auth_data_bytes[0..32];
1176 let expected_rp_id_hash = {
1177 let mut context = digest::Context::new(&digest::SHA256);
1178 context.update(self.config.rp_id.as_bytes());
1179 context.finish()
1180 };
1181
1182 if rp_id_hash != expected_rp_id_hash.as_ref() {
1183 return Err(AuthError::validation("RP ID hash mismatch"));
1184 }
1185
1186 let flags = auth_data_bytes[32];
1188 let user_present = (flags & 0x01) != 0;
1189 let user_verified = (flags & 0x04) != 0;
1190
1191 if !user_present {
1192 return Err(AuthError::validation("User not present"));
1193 }
1194
1195 let new_counter = self.extract_counter_from_assertion(assertion_response)?;
1197
1198 if new_counter != 0 && new_counter <= stored_counter {
1203 return Err(AuthError::validation(
1204 "Counter did not increase - possible replay attack or cloned authenticator",
1205 ));
1206 }
1207
1208 self.verify_assertion_signature(
1210 assertion_response,
1211 &auth_data_bytes,
1212 &decoded_client_data,
1213 public_key_jwk,
1214 )?;
1215
1216 tracing::info!("Advanced passkey verification completed successfully");
1217
1218 Ok(AdvancedVerificationResult {
1219 user_present,
1220 user_verified,
1221 new_counter,
1222 signature_valid: true,
1223 attestation_valid: true,
1224 })
1225 }
1226
1227 fn verify_webauthn_signature(
1229 &self,
1230 signed_data: &[u8],
1231 signature_bytes: &[u8],
1232 public_key_jwk: &serde_json::Value,
1233 ) -> Result<()> {
1234 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1235 use ring::signature;
1236
1237 let key_type = public_key_jwk
1238 .get("kty")
1239 .and_then(|v| v.as_str())
1240 .ok_or_else(|| AuthError::validation("Missing key type in JWK"))?;
1241
1242 let algorithm = public_key_jwk
1243 .get("alg")
1244 .and_then(|v| v.as_str())
1245 .ok_or_else(|| AuthError::validation("Missing algorithm in JWK"))?;
1246
1247 match key_type {
1248 "RSA" => {
1249 let n = public_key_jwk
1251 .get("n")
1252 .and_then(|v| v.as_str())
1253 .ok_or_else(|| AuthError::validation("Missing 'n' in RSA JWK"))?;
1254 let e = public_key_jwk
1255 .get("e")
1256 .and_then(|v| v.as_str())
1257 .ok_or_else(|| AuthError::validation("Missing 'e' in RSA JWK"))?;
1258
1259 let n_bytes = URL_SAFE_NO_PAD
1260 .decode(n.as_bytes())
1261 .map_err(|_| AuthError::validation("Invalid 'n' base64"))?;
1262 let e_bytes = URL_SAFE_NO_PAD
1263 .decode(e.as_bytes())
1264 .map_err(|_| AuthError::validation("Invalid 'e' base64"))?;
1265
1266 let n_ref: &[u8] = &n_bytes;
1270 let e_ref: &[u8] = &e_bytes;
1271 let rsa_key = signature::RsaPublicKeyComponents { n: n_ref, e: e_ref };
1272
1273 match algorithm {
1274 "RS256" => rsa_key.verify(
1275 &signature::RSA_PKCS1_2048_8192_SHA256,
1276 signed_data,
1277 signature_bytes,
1278 ),
1279 "RS384" => rsa_key.verify(
1280 &signature::RSA_PKCS1_2048_8192_SHA384,
1281 signed_data,
1282 signature_bytes,
1283 ),
1284 "RS512" => rsa_key.verify(
1285 &signature::RSA_PKCS1_2048_8192_SHA512,
1286 signed_data,
1287 signature_bytes,
1288 ),
1289 _ => return Err(AuthError::validation("Unsupported RSA algorithm")),
1290 }
1291 .map_err(|_| AuthError::validation("RSA signature verification failed"))?;
1292 }
1293 "EC" => {
1294 let curve = public_key_jwk
1296 .get("crv")
1297 .and_then(|v| v.as_str())
1298 .ok_or_else(|| AuthError::validation("Missing curve in EC JWK"))?;
1299 let x = public_key_jwk
1300 .get("x")
1301 .and_then(|v| v.as_str())
1302 .ok_or_else(|| AuthError::validation("Missing 'x' in EC JWK"))?;
1303 let y = public_key_jwk
1304 .get("y")
1305 .and_then(|v| v.as_str())
1306 .ok_or_else(|| AuthError::validation("Missing 'y' in EC JWK"))?;
1307
1308 let x_bytes = URL_SAFE_NO_PAD
1309 .decode(x.as_bytes())
1310 .map_err(|_| AuthError::validation("Invalid 'x' base64"))?;
1311 let y_bytes = URL_SAFE_NO_PAD
1312 .decode(y.as_bytes())
1313 .map_err(|_| AuthError::validation("Invalid 'y' base64"))?;
1314
1315 let (verification_algorithm, expected_coord_len) = match (curve, algorithm) {
1316 ("P-256", "ES256") => (&signature::ECDSA_P256_SHA256_ASN1, 32),
1317 ("P-384", "ES384") => (&signature::ECDSA_P384_SHA384_ASN1, 48),
1318 _ => return Err(AuthError::validation("Unsupported EC curve/algorithm")),
1319 };
1320
1321 if x_bytes.len() != expected_coord_len || y_bytes.len() != expected_coord_len {
1322 return Err(AuthError::validation("Invalid coordinate length"));
1323 }
1324
1325 let mut public_key_bytes = Vec::with_capacity(1 + expected_coord_len * 2);
1327 public_key_bytes.push(0x04); public_key_bytes.extend_from_slice(&x_bytes);
1329 public_key_bytes.extend_from_slice(&y_bytes);
1330
1331 let public_key =
1332 signature::UnparsedPublicKey::new(verification_algorithm, &public_key_bytes);
1333
1334 public_key
1335 .verify(signed_data, signature_bytes)
1336 .map_err(|_| AuthError::validation("ECDSA signature verification failed"))?;
1337 }
1338 _ => return Err(AuthError::validation("Unsupported key type for WebAuthn")),
1339 }
1340
1341 Ok(())
1342 }
1343
1344 pub async fn cross_platform_verification(
1346 &self,
1347 assertion_response: &str,
1348 authenticator_types: &[AuthenticatorType],
1349 ) -> Result<CrossPlatformVerificationResult> {
1350 tracing::info!("Starting cross-platform passkey verification");
1351
1352 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1354 .map_err(|_| AuthError::validation("Invalid assertion response"))?;
1355
1356 let authenticator_data = assertion
1358 .get("response")
1359 .and_then(|r| r.get("authenticatorData"))
1360 .and_then(|a| a.as_str())
1361 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1362
1363 let auth_data_bytes = URL_SAFE_NO_PAD
1364 .decode(authenticator_data)
1365 .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;
1366
1367 let aaguid = if auth_data_bytes.len() >= 53 && (auth_data_bytes[32] & 0x40) != 0 {
1369 Some(&auth_data_bytes[37..53])
1370 } else {
1371 None
1372 };
1373
1374 let detected_type = self.detect_authenticator_type(aaguid)?;
1376
1377 if !authenticator_types.contains(&detected_type) {
1379 return Err(AuthError::validation("Authenticator type not allowed"));
1380 }
1381
1382 let type_specific_result = match detected_type {
1384 AuthenticatorType::Platform => {
1385 tracing::debug!("Performing platform authenticator validation");
1386 self.validate_platform_authenticator(&assertion).await?
1387 }
1388 AuthenticatorType::CrossPlatform => {
1389 tracing::debug!("Performing cross-platform authenticator validation");
1390 self.validate_cross_platform_authenticator(&assertion)
1391 .await?
1392 }
1393 AuthenticatorType::SecurityKey => {
1394 tracing::debug!("Performing security key validation");
1395 self.validate_security_key(&assertion).await?
1396 }
1397 };
1398
1399 tracing::info!("Cross-platform verification completed successfully");
1400
1401 Ok(CrossPlatformVerificationResult {
1402 authenticator_type: detected_type,
1403 validation_result: type_specific_result,
1404 aaguid: aaguid.map(|a| a.to_vec()),
1405 })
1406 }
1407
1408 fn detect_authenticator_type(&self, aaguid: Option<&[u8]>) -> Result<AuthenticatorType> {
1410 match aaguid {
1411 Some(guid) if guid == [0u8; 16] => {
1412 Ok(AuthenticatorType::SecurityKey)
1414 }
1415 Some(guid) => {
1416 match guid {
1418 [
1420 0xf8,
1421 0xa0,
1422 0x11,
1423 0xf3,
1424 0x8c,
1425 0x0a,
1426 0x4d,
1427 0x15,
1428 0x80,
1429 0x06,
1430 0x17,
1431 0x11,
1432 0x1f,
1433 0x9e,
1434 0xdc,
1435 0x7d,
1436 ] => Ok(AuthenticatorType::SecurityKey),
1437 [
1439 0x08,
1440 0x98,
1441 0x7d,
1442 0x78,
1443 0x23,
1444 0x88,
1445 0x4d,
1446 0xa9,
1447 0xa6,
1448 0x91,
1449 0xb6,
1450 0xe1,
1451 0x04,
1452 0x5e,
1453 0xd4,
1454 0xd4,
1455 ] => Ok(AuthenticatorType::Platform),
1456 [
1458 0x08,
1459 0x98,
1460 0x7d,
1461 0x78,
1462 0x4e,
1463 0xd4,
1464 0x4d,
1465 0x49,
1466 0xa6,
1467 0x91,
1468 0xb6,
1469 0xe1,
1470 0x04,
1471 0x5e,
1472 0xd4,
1473 0xd4,
1474 ] => Ok(AuthenticatorType::Platform),
1475 _ => {
1476 Ok(AuthenticatorType::CrossPlatform)
1478 }
1479 }
1480 }
1481 None => {
1482 Ok(AuthenticatorType::SecurityKey)
1484 }
1485 }
1486 }
1487
1488 async fn validate_platform_authenticator(
1490 &self,
1491 assertion: &serde_json::Value,
1492 ) -> Result<TypeSpecificValidationResult> {
1493 tracing::debug!("Validating platform authenticator");
1494
1495 let authenticator_data = assertion
1497 .get("response")
1498 .and_then(|r| r.get("authenticatorData"))
1499 .and_then(|a| a.as_str())
1500 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1501
1502 let auth_data_bytes = URL_SAFE_NO_PAD
1503 .decode(authenticator_data)
1504 .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;
1505
1506 if auth_data_bytes.len() < 33 {
1507 return Err(AuthError::validation("AuthenticatorData too short"));
1508 }
1509
1510 let flags = auth_data_bytes[32];
1511 let user_verified = (flags & 0x04) != 0;
1512
1513 if !user_verified && self.config.user_verification == "required" {
1514 return Err(AuthError::validation(
1515 "User verification required for platform authenticator",
1516 ));
1517 }
1518
1519 Ok(TypeSpecificValidationResult {
1520 user_verified,
1521 attestation_valid: true,
1522 additional_properties: vec![
1523 ("authenticator_class".to_string(), "platform".to_string()),
1524 ("biometric_capable".to_string(), "true".to_string()),
1525 ],
1526 })
1527 }
1528
1529 async fn validate_cross_platform_authenticator(
1531 &self,
1532 _assertion: &serde_json::Value,
1533 ) -> Result<TypeSpecificValidationResult> {
1534 tracing::debug!("Validating cross-platform authenticator");
1535
1536 Ok(TypeSpecificValidationResult {
1538 user_verified: true,
1539 attestation_valid: true,
1540 additional_properties: vec![
1541 (
1542 "authenticator_class".to_string(),
1543 "cross_platform".to_string(),
1544 ),
1545 ("roaming_capable".to_string(), "true".to_string()),
1546 ],
1547 })
1548 }
1549
1550 async fn validate_security_key(
1552 &self,
1553 assertion: &serde_json::Value,
1554 ) -> Result<TypeSpecificValidationResult> {
1555 tracing::debug!("Validating security key");
1556
1557 let authenticator_data = assertion
1559 .get("response")
1560 .and_then(|r| r.get("authenticatorData"))
1561 .and_then(|a| a.as_str())
1562 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1563
1564 let auth_data_bytes = URL_SAFE_NO_PAD
1565 .decode(authenticator_data)
1566 .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;
1567
1568 if auth_data_bytes.len() < 33 {
1569 return Err(AuthError::validation("AuthenticatorData too short"));
1570 }
1571
1572 let flags = auth_data_bytes[32];
1573 let user_present = (flags & 0x01) != 0;
1574 let user_verified = (flags & 0x04) != 0;
1575
1576 if !user_present {
1577 return Err(AuthError::validation(
1578 "User presence required for security key",
1579 ));
1580 }
1581
1582 Ok(TypeSpecificValidationResult {
1583 user_verified,
1584 attestation_valid: true,
1585 additional_properties: vec![
1586 (
1587 "authenticator_class".to_string(),
1588 "security_key".to_string(),
1589 ),
1590 ("user_presence".to_string(), user_present.to_string()),
1591 ("hardware_backed".to_string(), "true".to_string()),
1592 ],
1593 })
1594 }
1595
1596 fn verify_assertion_signature(
1599 &self,
1600 assertion_response: &str,
1601 auth_data_bytes: &[u8],
1602 decoded_client_data: &[u8],
1603 public_key_jwk: &serde_json::Value,
1604 ) -> Result<()> {
1605 use ring::digest;
1606
1607 tracing::debug!("Verifying assertion signature");
1609
1610 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1612 .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
1613
1614 let signature = assertion
1616 .get("response")
1617 .and_then(|r| r.get("signature"))
1618 .ok_or_else(|| AuthError::validation("Missing signature in assertion response"))?;
1619
1620 let signature_bytes = json_bytes(signature)
1621 .ok_or_else(|| AuthError::validation("Invalid signature encoding"))?;
1622
1623 let client_data_hash = {
1625 let mut context = digest::Context::new(&digest::SHA256);
1626 context.update(decoded_client_data);
1627 context.finish()
1628 };
1629
1630 let mut signed_data = Vec::new();
1631 signed_data.extend_from_slice(auth_data_bytes);
1632 signed_data.extend_from_slice(client_data_hash.as_ref());
1633
1634 self.verify_webauthn_signature(&signed_data, &signature_bytes, public_key_jwk)?;
1636
1637 Ok(())
1638 }
1639
1640 fn extract_counter_from_assertion(&self, assertion_response: &str) -> Result<u32> {
1642 tracing::debug!("Extracting counter from assertion response");
1644
1645 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1647 .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
1648
1649 let authenticator_data = assertion
1650 .get("response")
1651 .and_then(|r| r.get("authenticatorData"))
1652 .ok_or_else(|| {
1653 AuthError::validation("Missing authenticatorData in assertion response")
1654 })?;
1655
1656 let auth_data_bytes = json_bytes(authenticator_data).ok_or_else(|| {
1657 AuthError::validation("authenticatorData is neither base64url nor a byte array")
1658 })?;
1659
1660 if auth_data_bytes.len() < 37 {
1663 return Err(AuthError::validation(
1664 "authenticatorData is too short to contain a counter",
1665 ));
1666 }
1667
1668 let counter_bytes: [u8; 4] = [
1670 auth_data_bytes[33],
1671 auth_data_bytes[34],
1672 auth_data_bytes[35],
1673 auth_data_bytes[36],
1674 ];
1675
1676 let counter = u32::from_be_bytes(counter_bytes);
1677 tracing::debug!("Extracted signature counter: {}", counter);
1678 Ok(counter)
1679 }
1680}
1681
1682#[derive(Debug, Clone, Serialize, Deserialize)]
1684pub struct AdvancedVerificationResult {
1685 pub user_present: bool,
1686 pub user_verified: bool,
1687 pub new_counter: u32,
1688 pub signature_valid: bool,
1689 pub attestation_valid: bool,
1690}
1691
1692#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1694pub enum AuthenticatorType {
1695 Platform,
1697 CrossPlatform,
1699 SecurityKey,
1701}
1702
1703#[derive(Debug, Clone, Serialize, Deserialize)]
1705pub struct CrossPlatformVerificationResult {
1706 pub authenticator_type: AuthenticatorType,
1707 pub validation_result: TypeSpecificValidationResult,
1708 pub aaguid: Option<Vec<u8>>,
1709}
1710
1711#[derive(Debug, Clone, Serialize, Deserialize)]
1713pub struct TypeSpecificValidationResult {
1714 pub user_verified: bool,
1715 pub attestation_valid: bool,
1716 pub additional_properties: Vec<(String, String)>,
1717}
1718
1719#[cfg(test)]
1720mod tests {
1721 use super::*;
1722 use crate::tokens::TokenManager;
1723
1724 #[tokio::test]
1725 async fn test_passkey_config_validation() {
1726 let token_manager = TokenManager::new_hmac(b"test-secret", "test-issuer", "test-audience");
1727
1728 let config = PasskeyConfig {
1729 rp_id: "example.com".to_string(),
1730 rp_name: "Test App".to_string(),
1731 origin: "https://example.com".to_string(),
1732 timeout_ms: 60000,
1733 user_verification: "preferred".to_string(),
1734 authenticator_attachment: None,
1735 require_resident_key: false,
1736 ..Default::default()
1737 };
1738
1739 let result = PasskeyAuthMethod::new(config, token_manager);
1740
1741 #[cfg(feature = "passkeys")]
1742 {
1743 assert!(result.is_ok());
1744 let method = result.unwrap();
1745 assert!(method.validate_config().is_ok());
1746 }
1747
1748 #[cfg(not(feature = "passkeys"))]
1749 {
1750 assert!(result.is_err());
1751 }
1752 }
1753
1754 #[tokio::test]
1755 async fn test_invalid_passkey_config() {
1756 #[cfg_attr(not(feature = "passkeys"), allow(unused_variables))]
1757 let token_manager = TokenManager::new_hmac(b"test-secret", "test-issuer", "test-audience");
1758
1759 #[cfg_attr(not(feature = "passkeys"), allow(unused_variables))]
1760 let config = PasskeyConfig {
1761 rp_id: "".to_string(), rp_name: "Test App".to_string(),
1763 origin: "https://example.com".to_string(),
1764 timeout_ms: 60000,
1765 user_verification: "invalid".to_string(), authenticator_attachment: None,
1767 require_resident_key: false,
1768 ..Default::default()
1769 };
1770
1771 #[cfg(feature = "passkeys")]
1772 {
1773 let result = PasskeyAuthMethod::new(config, token_manager);
1774 if let Ok(method) = result {
1775 assert!(method.validate_config().is_err());
1776 }
1777 }
1778 }
1779}