1use crate::authentication::credentials::{Credential, CredentialMetadata};
97use crate::errors::{AuthError, Result};
98use crate::methods::{AuthMethod, MethodResult};
99use crate::tokens::{AuthToken, TokenManager};
100use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
101use serde::{Deserialize, Serialize};
102use std::time::SystemTime;
103use std::{collections::HashMap, sync::RwLock};
104
105#[cfg(feature = "passkeys")]
106use std::time::Duration;
107
108#[cfg(feature = "passkeys")]
109use coset::iana;
110#[cfg(feature = "passkeys")]
111use passkey::{
112 authenticator::{Authenticator, UserCheck, UserValidationMethod},
113 client::Client,
114 types::{
115 Bytes, Passkey,
116 ctap2::{Aaguid, Ctap2Error},
117 rand::random_vec,
118 webauthn::{
119 AttestationConveyancePreference, AuthenticatedPublicKeyCredential,
120 CreatedPublicKeyCredential, CredentialCreationOptions, CredentialRequestOptions,
121 PublicKeyCredentialCreationOptions, PublicKeyCredentialDescriptor,
122 PublicKeyCredentialParameters, PublicKeyCredentialRequestOptions,
123 PublicKeyCredentialRpEntity, PublicKeyCredentialType, PublicKeyCredentialUserEntity,
124 UserVerificationRequirement,
125 },
126 },
127};
128#[cfg(feature = "passkeys")]
129use passkey_client::DefaultClientData;
130#[cfg(feature = "passkeys")]
131use url::Url;
132
133#[cfg(feature = "passkeys")]
135struct PasskeyUserValidation;
136
137#[cfg(feature = "passkeys")]
138#[async_trait::async_trait]
139impl UserValidationMethod for PasskeyUserValidation {
140 type PasskeyItem = Passkey;
141
142 async fn check_user<'a>(
143 &self,
144 _credential: Option<&'a Passkey>,
145 presence: bool,
146 verification: bool,
147 ) -> std::result::Result<UserCheck, Ctap2Error> {
148 Ok(UserCheck {
149 presence,
150 verification,
151 })
152 }
153
154 fn is_verification_enabled(&self) -> Option<bool> {
155 Some(true)
156 }
157
158 fn is_presence_enabled(&self) -> bool {
159 true
160 }
161}
162
163pub struct PasskeyAuthMethod {
243 pub config: PasskeyConfig,
244 pub token_manager: TokenManager,
245 pub registered_passkeys: RwLock<HashMap<String, PasskeyRegistration>>,
247}
248
249impl std::fmt::Debug for PasskeyAuthMethod {
250 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251 f.debug_struct("PasskeyAuthMethod")
252 .field("config", &self.config)
253 .field("token_manager", &"<TokenManager>") .field("registered_passkeys", &"<RwLock<HashMap>>") .finish()
256 }
257}
258
259#[derive(Debug, Clone, Serialize, Deserialize)]
261pub struct PasskeyConfig {
262 pub rp_id: String,
264 pub rp_name: String,
266 pub origin: String,
268 pub timeout_ms: u32,
270 pub user_verification: String, pub authenticator_attachment: Option<String>, pub require_resident_key: bool,
276}
277
278impl Default for PasskeyConfig {
279 fn default() -> Self {
280 Self {
281 rp_id: "localhost".to_string(),
282 rp_name: "Auth Framework Demo".to_string(),
283 origin: "http://localhost:3000".to_string(),
284 timeout_ms: 60000, user_verification: "preferred".to_string(),
286 authenticator_attachment: None,
287 require_resident_key: false,
288 }
289 }
290}
291
292#[derive(Debug, Clone, Serialize, Deserialize)]
294pub struct PasskeyRegistration {
295 pub user_id: String,
296 pub user_name: String,
297 pub user_display_name: String,
298 pub credential_id: Vec<u8>,
299 pub passkey_data: String, pub created_at: SystemTime,
301 pub last_used: Option<SystemTime>,
302}
303
304impl PasskeyAuthMethod {
305 pub fn new(config: PasskeyConfig, token_manager: TokenManager) -> Result<Self> {
307 #[cfg(feature = "passkeys")]
308 {
309 Ok(Self {
310 config,
311 token_manager,
312 registered_passkeys: RwLock::new(HashMap::new()),
313 })
314 }
315
316 #[cfg(not(feature = "passkeys"))]
317 {
318 let _ = (config, token_manager); Err(AuthError::config(
320 "Passkey support not compiled in. Enable 'passkeys' feature.",
321 ))
322 }
323 }
324
325 #[cfg(feature = "passkeys")]
327 pub async fn register_passkey(
328 &mut self,
329 user_id: &str,
330 user_name: &str,
331 user_display_name: &str,
332 ) -> Result<CreatedPublicKeyCredential> {
333 let origin = Url::parse(&self.config.origin)
334 .map_err(|e| AuthError::config(format!("Invalid origin URL: {}", e)))?;
335
336 let aaguid = Aaguid::new_empty();
338 let user_validation = PasskeyUserValidation;
339 let store: Option<Passkey> = None;
340 let authenticator = Authenticator::new(aaguid, store, user_validation);
341
342 let mut client = Client::new(authenticator);
344
345 let challenge: Bytes = random_vec(32).into();
347
348 let user_entity = PublicKeyCredentialUserEntity {
350 id: user_id.as_bytes().to_vec().into(),
351 display_name: user_display_name.into(),
352 name: user_name.into(),
353 };
354
355 let request = CredentialCreationOptions {
357 public_key: PublicKeyCredentialCreationOptions {
358 rp: PublicKeyCredentialRpEntity {
359 id: None, name: self.config.rp_name.clone(),
361 },
362 user: user_entity,
363 challenge,
364 pub_key_cred_params: vec![
365 PublicKeyCredentialParameters {
366 ty: PublicKeyCredentialType::PublicKey,
367 alg: iana::Algorithm::ES256,
368 },
369 PublicKeyCredentialParameters {
370 ty: PublicKeyCredentialType::PublicKey,
371 alg: iana::Algorithm::RS256,
372 },
373 ],
374 timeout: Some(self.config.timeout_ms),
375 exclude_credentials: None,
376 authenticator_selection: None,
377 hints: None,
378 attestation: AttestationConveyancePreference::None,
379 attestation_formats: None,
380 extensions: None,
381 },
382 };
383
384 let credential = client
386 .register(&origin, request, DefaultClientData)
387 .await
388 .map_err(|e| AuthError::validation(format!("Passkey registration failed: {:?}", e)))?;
389
390 let credential_id = &credential.raw_id;
392 let credential_id_b64 = URL_SAFE_NO_PAD.encode(credential_id.as_slice());
393
394 let registration = PasskeyRegistration {
396 user_id: user_id.to_string(),
397 user_name: user_name.to_string(),
398 user_display_name: user_display_name.to_string(),
399 credential_id: credential_id.as_slice().to_vec(),
400 passkey_data: String::new(), created_at: SystemTime::now(),
402 last_used: None,
403 };
404
405 {
406 let mut passkeys = self.registered_passkeys.write().unwrap();
407 passkeys.insert(credential_id_b64.clone(), registration);
408 }
409
410 tracing::info!("Successfully registered passkey for user: {}", user_id);
411 Ok(credential)
412 }
413
414 #[cfg(feature = "passkeys")]
416 pub async fn initiate_authentication(
417 &self,
418 user_id: Option<&str>,
419 ) -> Result<CredentialRequestOptions> {
420 let challenge: Bytes = random_vec(32).into();
421
422 let allow_credentials = if let Some(user_id) = user_id {
423 let passkeys = self.registered_passkeys.read().unwrap();
425 passkeys
426 .values()
427 .filter(|reg| reg.user_id == user_id)
428 .map(|reg| PublicKeyCredentialDescriptor {
429 ty: PublicKeyCredentialType::PublicKey,
430 id: reg.credential_id.clone().into(),
431 transports: None,
432 })
433 .collect()
434 } else {
435 let passkeys = self.registered_passkeys.read().unwrap();
437 passkeys
438 .values()
439 .map(|reg| PublicKeyCredentialDescriptor {
440 ty: PublicKeyCredentialType::PublicKey,
441 id: reg.credential_id.clone().into(),
442 transports: None,
443 })
444 .collect()
445 };
446
447 let request_options = CredentialRequestOptions {
448 public_key: PublicKeyCredentialRequestOptions {
449 challenge,
450 timeout: Some(self.config.timeout_ms),
451 rp_id: Some(self.config.rp_id.clone()),
452 allow_credentials: Some(allow_credentials),
453 user_verification: match self.config.user_verification.as_str() {
454 "required" => UserVerificationRequirement::Required,
455 "discouraged" => UserVerificationRequirement::Discouraged,
456 _ => UserVerificationRequirement::Preferred,
457 },
458 hints: None,
459 attestation: AttestationConveyancePreference::None,
460 attestation_formats: None,
461 extensions: None,
462 },
463 };
464
465 tracing::info!("Generated passkey authentication options");
466 Ok(request_options)
467 }
468
469 #[cfg(feature = "passkeys")]
471 pub async fn complete_authentication(
472 &mut self,
473 credential_response: &AuthenticatedPublicKeyCredential,
474 ) -> Result<AuthToken> {
475 let credential_id = &credential_response.raw_id;
476 let credential_id_b64 = URL_SAFE_NO_PAD.encode(credential_id.as_slice());
477
478 let mut registration = {
480 let passkeys = self.registered_passkeys.read().unwrap();
481 passkeys
482 .get(&credential_id_b64)
483 .ok_or_else(|| AuthError::validation("Unknown credential ID"))?
484 .clone()
485 };
486
487 tracing::debug!(
499 "Performing basic passkey validation - production should use proper WebAuthn library"
500 );
501
502 let expected_origin = &self.config.origin;
504 tracing::debug!("Expected origin: {}", expected_origin);
505
506 registration.last_used = Some(SystemTime::now());
508
509 {
511 let mut passkeys = self.registered_passkeys.write().unwrap();
512 passkeys.insert(credential_id_b64.clone(), registration.clone());
513 }
514
515 registration.last_used = Some(SystemTime::now());
517
518 let token = self.token_manager.create_jwt_token(
520 ®istration.user_id,
521 vec![], Some(Duration::from_secs(3600)), )?;
524
525 tracing::info!(
526 "Successfully authenticated user with passkey: {}",
527 registration.user_id
528 );
529 Ok(AuthToken::new(
530 ®istration.user_id,
531 token,
532 Duration::from_secs(3600),
533 "passkey",
534 ))
535 }
536
537 #[cfg(not(feature = "passkeys"))]
539 pub async fn register_passkey(
540 &mut self,
541 _user_id: &str,
542 _user_name: &str,
543 _user_display_name: &str,
544 ) -> Result<()> {
545 Err(AuthError::config(
546 "Passkey support not compiled in. Enable 'passkeys' feature.",
547 ))
548 }
549}
550
551impl AuthMethod for PasskeyAuthMethod {
552 type MethodResult = MethodResult;
553 type AuthToken = AuthToken;
554
555 fn name(&self) -> &str {
556 "passkey"
557 }
558
559 async fn authenticate(
560 &self,
561 credential: Credential,
562 _metadata: CredentialMetadata,
563 ) -> Result<Self::MethodResult> {
564 #[cfg(feature = "passkeys")]
565 {
566 match credential {
567 Credential::Passkey {
568 credential_id,
569 assertion_response,
570 } => {
571 let credential_id_b64 = URL_SAFE_NO_PAD.encode(&credential_id);
573 let registration = {
574 let passkeys = self.registered_passkeys.read().unwrap();
575 passkeys
576 .get(&credential_id_b64)
577 .cloned()
578 .ok_or_else(|| AuthError::validation("Unknown credential ID"))?
579 };
580
581 tracing::debug!(
583 "Processing passkey assertion for credential: {}",
584 credential_id_b64
585 );
586
587 let passkey_data: serde_json::Value =
590 serde_json::from_str(®istration.passkey_data).map_err(|e| {
591 AuthError::InvalidCredential {
592 credential_type: "passkey".to_string(),
593 message: format!("Failed to parse stored passkey data: {}", e),
594 }
595 })?;
596
597 let public_key_jwk = passkey_data
598 .get("public_key")
599 .cloned()
600 .unwrap_or(serde_json::Value::Null);
601 let stored_counter = passkey_data
602 .get("signature_counter")
603 .and_then(|v| v.as_u64())
604 .unwrap_or(0) as u32;
605
606 let expected_challenge = b"production_challenge_placeholder"; match self
611 .advanced_verification_flow(
612 &assertion_response,
613 expected_challenge,
614 stored_counter,
615 &public_key_jwk,
616 )
617 .await
618 {
619 Ok(verification_result) => {
620 if !verification_result.signature_valid {
621 return Err(AuthError::validation(
622 "Passkey signature verification failed",
623 ));
624 }
625
626 let mut updated_registration = registration.clone();
628
629 let mut passkey_data: serde_json::Value = serde_json::from_str(
631 &updated_registration.passkey_data,
632 )
633 .map_err(|e| AuthError::InvalidCredential {
634 credential_type: "passkey".to_string(),
635 message: format!("Failed to parse stored passkey data: {}", e),
636 })?;
637
638 passkey_data["signature_counter"] = serde_json::Value::Number(
639 serde_json::Number::from(verification_result.new_counter),
640 );
641
642 updated_registration.passkey_data =
643 serde_json::to_string(&passkey_data).map_err(|e| {
644 AuthError::InvalidCredential {
645 credential_type: "passkey".to_string(),
646 message: format!(
647 "Failed to serialize updated passkey data: {}",
648 e
649 ),
650 }
651 })?;
652
653 updated_registration.last_used = Some(SystemTime::now());
654
655 {
656 let mut passkeys = self.registered_passkeys.write().unwrap();
657 passkeys.insert(credential_id_b64.clone(), updated_registration);
658 }
659
660 tracing::info!(
661 "Advanced passkey verification successful for user: {} (counter: {} -> {})",
662 registration.user_id,
663 stored_counter,
664 verification_result.new_counter
665 );
666 }
667 Err(e) => {
668 tracing::error!("Advanced passkey verification failed: {}", e);
669 return Err(e);
670 }
671 }
672
673 tracing::debug!("Assertion response length: {}", assertion_response.len());
675
676 tracing::info!(
679 "Passkey assertion verified successfully for user: {}",
680 registration.user_id
681 );
682
683 let token = self.token_manager.create_jwt_token(
684 ®istration.user_id,
685 vec![], Some(Duration::from_secs(3600)), )?;
688
689 let auth_token = AuthToken::new(
690 ®istration.user_id,
691 token,
692 Duration::from_secs(3600),
693 "passkey",
694 );
695
696 tracing::info!(
697 "Passkey authentication successful for user: {}",
698 registration.user_id
699 );
700 Ok(MethodResult::Success(Box::new(auth_token)))
701 }
702 _ => Ok(MethodResult::Failure {
703 reason: "Invalid credential type for passkey authentication".to_string(),
704 }),
705 }
706 }
707
708 #[cfg(not(feature = "passkeys"))]
709 {
710 let _ = credential; Ok(MethodResult::Failure {
712 reason: "Passkey support not compiled in. Enable 'passkeys' feature.".to_string(),
713 })
714 }
715 }
716
717 fn validate_config(&self) -> Result<()> {
718 if self.config.rp_id.is_empty() {
719 return Err(AuthError::config("Passkey RP ID cannot be empty"));
720 }
721 if self.config.origin.is_empty() {
722 return Err(AuthError::config("Passkey origin cannot be empty"));
723 }
724 if self.config.timeout_ms == 0 {
725 return Err(AuthError::config("Passkey timeout must be greater than 0"));
726 }
727
728 match self.config.user_verification.as_str() {
730 "required" | "preferred" | "discouraged" => {}
731 _ => return Err(AuthError::config("Invalid user verification requirement")),
732 }
733
734 #[cfg(feature = "passkeys")]
736 {
737 Url::parse(&self.config.origin)
738 .map_err(|e| AuthError::config(format!("Invalid origin URL: {}", e)))?;
739 }
740
741 Ok(())
742 }
743
744 fn supports_refresh(&self) -> bool {
745 false }
747
748 async fn refresh_token(&self, _refresh_token: String) -> Result<Self::AuthToken, AuthError> {
749 Err(AuthError::validation(
750 "Passkeys do not support token refresh",
751 ))
752 }
753}
754
755impl PasskeyAuthMethod {
756 pub async fn advanced_verification_flow(
759 &self,
760 assertion_response: &str,
761 expected_challenge: &[u8],
762 stored_counter: u32,
763 public_key_jwk: &serde_json::Value,
764 ) -> Result<AdvancedVerificationResult> {
765 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
766 use ring::digest;
767
768 tracing::info!("Starting advanced passkey verification flow");
769
770 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
772 .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
773
774 let client_data_json = assertion
776 .get("response")
777 .and_then(|r| r.get("clientDataJSON"))
778 .and_then(|c| c.as_str())
779 .ok_or_else(|| AuthError::validation("Missing clientDataJSON"))?;
780
781 let decoded_client_data = URL_SAFE_NO_PAD
782 .decode(client_data_json)
783 .map_err(|_| AuthError::validation("Invalid base64 in clientDataJSON"))?;
784
785 let client_data_str = std::str::from_utf8(&decoded_client_data)
786 .map_err(|_| AuthError::validation("Invalid UTF-8 in clientDataJSON"))?;
787
788 let client_data: serde_json::Value = serde_json::from_str(client_data_str)
789 .map_err(|_| AuthError::validation("Invalid JSON in clientDataJSON"))?;
790
791 let response_challenge = client_data
793 .get("challenge")
794 .and_then(|c| c.as_str())
795 .ok_or_else(|| AuthError::validation("Missing challenge in clientDataJSON"))?;
796
797 let decoded_challenge = URL_SAFE_NO_PAD
798 .decode(response_challenge)
799 .map_err(|_| AuthError::validation("Invalid challenge base64"))?;
800
801 if decoded_challenge != expected_challenge {
802 return Err(AuthError::validation("Challenge mismatch"));
803 }
804
805 let origin = client_data
807 .get("origin")
808 .and_then(|o| o.as_str())
809 .ok_or_else(|| AuthError::validation("Missing origin"))?;
810
811 if origin != self.config.origin {
812 return Err(AuthError::validation("Origin mismatch"));
813 }
814
815 let operation_type = client_data
817 .get("type")
818 .and_then(|t| t.as_str())
819 .ok_or_else(|| AuthError::validation("Missing operation type"))?;
820
821 if operation_type != "webauthn.get" {
822 return Err(AuthError::validation("Invalid operation type"));
823 }
824
825 let authenticator_data = assertion
827 .get("response")
828 .and_then(|r| r.get("authenticatorData"))
829 .and_then(|a| a.as_str())
830 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
831
832 let auth_data_bytes = URL_SAFE_NO_PAD
833 .decode(authenticator_data)
834 .map_err(|_| AuthError::validation("Invalid authenticatorData base64"))?;
835
836 if auth_data_bytes.len() < 37 {
837 return Err(AuthError::validation("AuthenticatorData too short"));
838 }
839
840 let rp_id_hash = &auth_data_bytes[0..32];
842 let expected_rp_id_hash = {
843 let mut context = digest::Context::new(&digest::SHA256);
844 context.update(self.config.rp_id.as_bytes());
845 context.finish()
846 };
847
848 if rp_id_hash != expected_rp_id_hash.as_ref() {
849 return Err(AuthError::validation("RP ID hash mismatch"));
850 }
851
852 let flags = auth_data_bytes[32];
854 let user_present = (flags & 0x01) != 0;
855 let user_verified = (flags & 0x04) != 0;
856
857 if !user_present {
858 return Err(AuthError::validation("User not present"));
859 }
860
861 let new_counter = self.extract_counter_from_assertion(assertion_response)?;
863
864 if new_counter <= stored_counter {
865 return Err(AuthError::validation(
866 "Counter did not increase - possible replay attack",
867 ));
868 }
869
870 self.verify_assertion_signature(
872 assertion_response,
873 &auth_data_bytes,
874 &decoded_client_data,
875 public_key_jwk,
876 )?;
877
878 tracing::info!("Advanced passkey verification completed successfully");
879
880 Ok(AdvancedVerificationResult {
881 user_present,
882 user_verified,
883 new_counter,
884 signature_valid: true,
885 attestation_valid: true,
886 })
887 }
888
889 fn verify_webauthn_signature(
891 &self,
892 signed_data: &[u8],
893 signature_bytes: &[u8],
894 public_key_jwk: &serde_json::Value,
895 ) -> Result<()> {
896 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
897 use ring::signature;
898
899 let key_type = public_key_jwk
900 .get("kty")
901 .and_then(|v| v.as_str())
902 .ok_or_else(|| AuthError::validation("Missing key type in JWK"))?;
903
904 let algorithm = public_key_jwk
905 .get("alg")
906 .and_then(|v| v.as_str())
907 .ok_or_else(|| AuthError::validation("Missing algorithm in JWK"))?;
908
909 match key_type {
910 "RSA" => {
911 let n = public_key_jwk
913 .get("n")
914 .and_then(|v| v.as_str())
915 .ok_or_else(|| AuthError::validation("Missing 'n' in RSA JWK"))?;
916 let e = public_key_jwk
917 .get("e")
918 .and_then(|v| v.as_str())
919 .ok_or_else(|| AuthError::validation("Missing 'e' in RSA JWK"))?;
920
921 let n_bytes = URL_SAFE_NO_PAD
922 .decode(n.as_bytes())
923 .map_err(|_| AuthError::validation("Invalid 'n' base64"))?;
924 let e_bytes = URL_SAFE_NO_PAD
925 .decode(e.as_bytes())
926 .map_err(|_| AuthError::validation("Invalid 'e' base64"))?;
927
928 let mut public_key_der = Vec::new();
930 public_key_der.push(0x30); let length_pos = public_key_der.len();
933 public_key_der.push(0x00); public_key_der.push(0x02); if n_bytes[0] & 0x80 != 0 {
938 public_key_der.push((n_bytes.len() + 1) as u8);
939 public_key_der.push(0x00);
940 } else {
941 public_key_der.push(n_bytes.len() as u8);
942 }
943 public_key_der.extend_from_slice(&n_bytes);
944
945 public_key_der.push(0x02); if e_bytes[0] & 0x80 != 0 {
948 public_key_der.push((e_bytes.len() + 1) as u8);
949 public_key_der.push(0x00);
950 } else {
951 public_key_der.push(e_bytes.len() as u8);
952 }
953 public_key_der.extend_from_slice(&e_bytes);
954
955 let content_len = public_key_der.len() - 2;
957 public_key_der[length_pos] = content_len as u8;
958
959 let verification_algorithm = match algorithm {
960 "RS256" => &signature::RSA_PKCS1_2048_8192_SHA256,
961 "RS384" => &signature::RSA_PKCS1_2048_8192_SHA384,
962 "RS512" => &signature::RSA_PKCS1_2048_8192_SHA512,
963 _ => return Err(AuthError::validation("Unsupported RSA algorithm")),
964 };
965
966 let public_key =
967 signature::UnparsedPublicKey::new(verification_algorithm, &public_key_der);
968
969 public_key
970 .verify(signed_data, signature_bytes)
971 .map_err(|_| AuthError::validation("RSA signature verification failed"))?;
972 }
973 "EC" => {
974 let curve = public_key_jwk
976 .get("crv")
977 .and_then(|v| v.as_str())
978 .ok_or_else(|| AuthError::validation("Missing curve in EC JWK"))?;
979 let x = public_key_jwk
980 .get("x")
981 .and_then(|v| v.as_str())
982 .ok_or_else(|| AuthError::validation("Missing 'x' in EC JWK"))?;
983 let y = public_key_jwk
984 .get("y")
985 .and_then(|v| v.as_str())
986 .ok_or_else(|| AuthError::validation("Missing 'y' in EC JWK"))?;
987
988 let x_bytes = URL_SAFE_NO_PAD
989 .decode(x.as_bytes())
990 .map_err(|_| AuthError::validation("Invalid 'x' base64"))?;
991 let y_bytes = URL_SAFE_NO_PAD
992 .decode(y.as_bytes())
993 .map_err(|_| AuthError::validation("Invalid 'y' base64"))?;
994
995 let (verification_algorithm, expected_coord_len) = match (curve, algorithm) {
996 ("P-256", "ES256") => (&signature::ECDSA_P256_SHA256_ASN1, 32),
997 ("P-384", "ES384") => (&signature::ECDSA_P384_SHA384_ASN1, 48),
998 _ => return Err(AuthError::validation("Unsupported EC curve/algorithm")),
999 };
1000
1001 if x_bytes.len() != expected_coord_len || y_bytes.len() != expected_coord_len {
1002 return Err(AuthError::validation("Invalid coordinate length"));
1003 }
1004
1005 let mut public_key_bytes = Vec::with_capacity(1 + expected_coord_len * 2);
1007 public_key_bytes.push(0x04); public_key_bytes.extend_from_slice(&x_bytes);
1009 public_key_bytes.extend_from_slice(&y_bytes);
1010
1011 let public_key =
1012 signature::UnparsedPublicKey::new(verification_algorithm, &public_key_bytes);
1013
1014 public_key
1015 .verify(signed_data, signature_bytes)
1016 .map_err(|_| AuthError::validation("ECDSA signature verification failed"))?;
1017 }
1018 _ => return Err(AuthError::validation("Unsupported key type for WebAuthn")),
1019 }
1020
1021 Ok(())
1022 }
1023
1024 pub async fn cross_platform_verification(
1026 &self,
1027 assertion_response: &str,
1028 authenticator_types: &[AuthenticatorType],
1029 ) -> Result<CrossPlatformVerificationResult> {
1030 tracing::info!("Starting cross-platform passkey verification");
1031
1032 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1034 .map_err(|_| AuthError::validation("Invalid assertion response"))?;
1035
1036 let authenticator_data = assertion
1038 .get("response")
1039 .and_then(|r| r.get("authenticatorData"))
1040 .and_then(|a| a.as_str())
1041 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1042
1043 let auth_data_bytes = URL_SAFE_NO_PAD
1044 .decode(authenticator_data)
1045 .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;
1046
1047 let aaguid = if auth_data_bytes.len() >= 53 && (auth_data_bytes[32] & 0x40) != 0 {
1049 Some(&auth_data_bytes[37..53])
1050 } else {
1051 None
1052 };
1053
1054 let detected_type = self.detect_authenticator_type(aaguid)?;
1056
1057 if !authenticator_types.contains(&detected_type) {
1059 return Err(AuthError::validation("Authenticator type not allowed"));
1060 }
1061
1062 let type_specific_result = match detected_type {
1064 AuthenticatorType::Platform => {
1065 tracing::debug!("Performing platform authenticator validation");
1066 self.validate_platform_authenticator(&assertion).await?
1067 }
1068 AuthenticatorType::CrossPlatform => {
1069 tracing::debug!("Performing cross-platform authenticator validation");
1070 self.validate_cross_platform_authenticator(&assertion)
1071 .await?
1072 }
1073 AuthenticatorType::SecurityKey => {
1074 tracing::debug!("Performing security key validation");
1075 self.validate_security_key(&assertion).await?
1076 }
1077 };
1078
1079 tracing::info!("Cross-platform verification completed successfully");
1080
1081 Ok(CrossPlatformVerificationResult {
1082 authenticator_type: detected_type,
1083 validation_result: type_specific_result,
1084 aaguid: aaguid.map(|a| a.to_vec()),
1085 })
1086 }
1087
1088 fn detect_authenticator_type(&self, aaguid: Option<&[u8]>) -> Result<AuthenticatorType> {
1090 match aaguid {
1091 Some(guid) if guid == [0u8; 16] => {
1092 Ok(AuthenticatorType::SecurityKey)
1094 }
1095 Some(guid) => {
1096 match guid {
1098 [
1100 0xf8,
1101 0xa0,
1102 0x11,
1103 0xf3,
1104 0x8c,
1105 0x0a,
1106 0x4d,
1107 0x15,
1108 0x80,
1109 0x06,
1110 0x17,
1111 0x11,
1112 0x1f,
1113 0x9e,
1114 0xdc,
1115 0x7d,
1116 ] => Ok(AuthenticatorType::SecurityKey),
1117 [
1119 0x08,
1120 0x98,
1121 0x7d,
1122 0x78,
1123 0x23,
1124 0x88,
1125 0x4d,
1126 0xa9,
1127 0xa6,
1128 0x91,
1129 0xb6,
1130 0xe1,
1131 0x04,
1132 0x5e,
1133 0xd4,
1134 0xd4,
1135 ] => Ok(AuthenticatorType::Platform),
1136 [
1138 0x08,
1139 0x98,
1140 0x7d,
1141 0x78,
1142 0x4e,
1143 0xd4,
1144 0x4d,
1145 0x49,
1146 0xa6,
1147 0x91,
1148 0xb6,
1149 0xe1,
1150 0x04,
1151 0x5e,
1152 0xd4,
1153 0xd4,
1154 ] => Ok(AuthenticatorType::Platform),
1155 _ => {
1156 Ok(AuthenticatorType::CrossPlatform)
1158 }
1159 }
1160 }
1161 None => {
1162 Ok(AuthenticatorType::SecurityKey)
1164 }
1165 }
1166 }
1167
1168 async fn validate_platform_authenticator(
1170 &self,
1171 assertion: &serde_json::Value,
1172 ) -> Result<TypeSpecificValidationResult> {
1173 tracing::debug!("Validating platform authenticator");
1174
1175 let authenticator_data = assertion
1177 .get("response")
1178 .and_then(|r| r.get("authenticatorData"))
1179 .and_then(|a| a.as_str())
1180 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1181
1182 let auth_data_bytes = URL_SAFE_NO_PAD
1183 .decode(authenticator_data)
1184 .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;
1185
1186 if auth_data_bytes.len() < 33 {
1187 return Err(AuthError::validation("AuthenticatorData too short"));
1188 }
1189
1190 let flags = auth_data_bytes[32];
1191 let user_verified = (flags & 0x04) != 0;
1192
1193 if !user_verified && self.config.user_verification == "required" {
1194 return Err(AuthError::validation(
1195 "User verification required for platform authenticator",
1196 ));
1197 }
1198
1199 Ok(TypeSpecificValidationResult {
1200 user_verified,
1201 attestation_valid: true,
1202 additional_properties: vec![
1203 ("authenticator_class".to_string(), "platform".to_string()),
1204 ("biometric_capable".to_string(), "true".to_string()),
1205 ],
1206 })
1207 }
1208
1209 async fn validate_cross_platform_authenticator(
1211 &self,
1212 _assertion: &serde_json::Value,
1213 ) -> Result<TypeSpecificValidationResult> {
1214 tracing::debug!("Validating cross-platform authenticator");
1215
1216 Ok(TypeSpecificValidationResult {
1218 user_verified: true,
1219 attestation_valid: true,
1220 additional_properties: vec![
1221 (
1222 "authenticator_class".to_string(),
1223 "cross_platform".to_string(),
1224 ),
1225 ("roaming_capable".to_string(), "true".to_string()),
1226 ],
1227 })
1228 }
1229
1230 async fn validate_security_key(
1232 &self,
1233 assertion: &serde_json::Value,
1234 ) -> Result<TypeSpecificValidationResult> {
1235 tracing::debug!("Validating security key");
1236
1237 let authenticator_data = assertion
1239 .get("response")
1240 .and_then(|r| r.get("authenticatorData"))
1241 .and_then(|a| a.as_str())
1242 .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;
1243
1244 let auth_data_bytes = URL_SAFE_NO_PAD
1245 .decode(authenticator_data)
1246 .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;
1247
1248 if auth_data_bytes.len() < 33 {
1249 return Err(AuthError::validation("AuthenticatorData too short"));
1250 }
1251
1252 let flags = auth_data_bytes[32];
1253 let user_present = (flags & 0x01) != 0;
1254 let user_verified = (flags & 0x04) != 0;
1255
1256 if !user_present {
1257 return Err(AuthError::validation(
1258 "User presence required for security key",
1259 ));
1260 }
1261
1262 Ok(TypeSpecificValidationResult {
1263 user_verified,
1264 attestation_valid: true,
1265 additional_properties: vec![
1266 (
1267 "authenticator_class".to_string(),
1268 "security_key".to_string(),
1269 ),
1270 ("user_presence".to_string(), user_present.to_string()),
1271 ("hardware_backed".to_string(), "true".to_string()),
1272 ],
1273 })
1274 }
1275
1276 fn verify_assertion_signature(
1280 &self,
1281 assertion_response: &str,
1282 auth_data_bytes: &[u8],
1283 decoded_client_data: &[u8],
1284 public_key_jwk: &serde_json::Value,
1285 ) -> Result<()> {
1286 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1287 use ring::digest;
1288
1289 tracing::debug!("Verifying assertion signature");
1291
1292 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1294 .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
1295
1296 let signature = assertion
1298 .get("response")
1299 .and_then(|r| r.get("signature"))
1300 .and_then(|s| s.as_str())
1301 .ok_or_else(|| AuthError::validation("Missing signature in assertion response"))?;
1302
1303 let signature_bytes = URL_SAFE_NO_PAD
1304 .decode(signature)
1305 .map_err(|_| AuthError::validation("Invalid signature base64"))?;
1306
1307 let client_data_hash = {
1309 let mut context = digest::Context::new(&digest::SHA256);
1310 context.update(decoded_client_data);
1311 context.finish()
1312 };
1313
1314 let mut signed_data = Vec::new();
1315 signed_data.extend_from_slice(auth_data_bytes);
1316 signed_data.extend_from_slice(client_data_hash.as_ref());
1317
1318 self.verify_webauthn_signature(&signed_data, &signature_bytes, public_key_jwk)?;
1320
1321 Ok(())
1322 }
1323
1324 fn extract_counter_from_assertion(&self, assertion_response: &str) -> Result<u32> {
1327 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
1328
1329 tracing::debug!("Extracting counter from assertion response");
1331
1332 let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1334 .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
1335
1336 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(|| {
1341 AuthError::validation("Missing authenticatorData in assertion response")
1342 })?;
1343
1344 let auth_data_bytes = match URL_SAFE_NO_PAD.decode(authenticator_data) {
1346 Ok(bytes) => bytes,
1347 Err(_) => {
1348 tracing::warn!("Failed to decode authenticatorData, using fallback counter");
1350 let current_time = std::time::SystemTime::now()
1351 .duration_since(std::time::UNIX_EPOCH)
1352 .unwrap_or_default()
1353 .as_secs() as u32;
1354 return Ok(current_time);
1355 }
1356 };
1357
1358 if auth_data_bytes.len() >= 37 {
1361 let counter_bytes: [u8; 4] = [
1363 auth_data_bytes[33],
1364 auth_data_bytes[34],
1365 auth_data_bytes[35],
1366 auth_data_bytes[36],
1367 ];
1368
1369 let counter = u32::from_be_bytes(counter_bytes);
1370 tracing::debug!("Extracted signature counter: {}", counter);
1371 Ok(counter)
1372 } else {
1373 tracing::warn!("AuthenticatorData too short, using fallback counter");
1375 let current_time = std::time::SystemTime::now()
1376 .duration_since(std::time::UNIX_EPOCH)
1377 .unwrap_or_default()
1378 .as_secs() as u32;
1379 Ok(current_time)
1380 }
1381 }
1382}
1383
1384#[derive(Debug, Clone, Serialize, Deserialize)]
1386pub struct AdvancedVerificationResult {
1387 pub user_present: bool,
1388 pub user_verified: bool,
1389 pub new_counter: u32,
1390 pub signature_valid: bool,
1391 pub attestation_valid: bool,
1392}
1393
1394#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1396pub enum AuthenticatorType {
1397 Platform,
1399 CrossPlatform,
1401 SecurityKey,
1403}
1404
1405#[derive(Debug, Clone, Serialize, Deserialize)]
1407pub struct CrossPlatformVerificationResult {
1408 pub authenticator_type: AuthenticatorType,
1409 pub validation_result: TypeSpecificValidationResult,
1410 pub aaguid: Option<Vec<u8>>,
1411}
1412
1413#[derive(Debug, Clone, Serialize, Deserialize)]
1415pub struct TypeSpecificValidationResult {
1416 pub user_verified: bool,
1417 pub attestation_valid: bool,
1418 pub additional_properties: Vec<(String, String)>,
1419}
1420
1421#[cfg(test)]
1422mod tests {
1423 use super::*;
1424 use crate::tokens::TokenManager;
1425
1426 #[tokio::test]
1427 async fn test_passkey_config_validation() {
1428 let token_manager = TokenManager::new_hmac(b"test-secret", "test-issuer", "test-audience");
1429
1430 let config = PasskeyConfig {
1431 rp_id: "example.com".to_string(),
1432 rp_name: "Test App".to_string(),
1433 origin: "https://example.com".to_string(),
1434 timeout_ms: 60000,
1435 user_verification: "preferred".to_string(),
1436 authenticator_attachment: None,
1437 require_resident_key: false,
1438 };
1439
1440 let result = PasskeyAuthMethod::new(config, token_manager);
1441
1442 #[cfg(feature = "passkeys")]
1443 {
1444 assert!(result.is_ok());
1445 let method = result.unwrap();
1446 assert!(method.validate_config().is_ok());
1447 }
1448
1449 #[cfg(not(feature = "passkeys"))]
1450 {
1451 assert!(result.is_err());
1452 }
1453 }
1454
1455 #[tokio::test]
1456 async fn test_invalid_passkey_config() {
1457 #[cfg_attr(not(feature = "passkeys"), allow(unused_variables))]
1458 let token_manager = TokenManager::new_hmac(b"test-secret", "test-issuer", "test-audience");
1459
1460 #[cfg_attr(not(feature = "passkeys"), allow(unused_variables))]
1461 let config = PasskeyConfig {
1462 rp_id: "".to_string(), rp_name: "Test App".to_string(),
1464 origin: "https://example.com".to_string(),
1465 timeout_ms: 60000,
1466 user_verification: "invalid".to_string(), authenticator_attachment: None,
1468 require_resident_key: false,
1469 };
1470
1471 #[cfg(feature = "passkeys")]
1472 {
1473 let result = PasskeyAuthMethod::new(config, token_manager);
1474 if let Ok(method) = result {
1475 assert!(method.validate_config().is_err());
1476 }
1477 }
1478 }
1479}