Skip to main content

auth_framework/methods/passkey/
mod.rs

1//! Pure Rust WebAuthn/Passkey authentication implementation.
2//!
3//! This module provides a complete FIDO2/WebAuthn implementation for passwordless
4//! authentication using passkeys. It supports both platform authenticators (built
5//! into devices) and roaming authenticators (USB security keys) without requiring
6//! OpenSSL dependencies.
7//!
8//! # WebAuthn Standards Compliance
9//!
10//! - **WebAuthn Level 2**: Complete implementation of W3C WebAuthn specification
11//! - **FIDO2**: FIDO Alliance Client to Authenticator Protocol v2.1
12//! - **CTAP2**: Client to Authenticator Protocol version 2
13//! - **CBOR Encoding**: Proper CTAP2 CBOR encoding/decoding
14//!
15//! # Supported Authenticator Types
16//!
17//! - **Platform Authenticators**: Windows Hello, Touch ID, Android Biometrics
18//! - **Roaming Authenticators**: YubiKey, SoloKey, Titan Security Key
19//! - **Hybrid Transport**: QR code and proximity-based authentication
20//! - **Multi-Device**: Cross-device authentication flows
21//!
22//! # Security Features
23//!
24//! - **Origin Binding**: Cryptographically bound to website origin
25//! - **User Verification**: Biometric or PIN-based verification
26//! - **Replay Protection**: Unique challenge for each authentication
27//! - **Phishing Resistance**: Cannot be used on wrong domains
28//! - **Privacy Preserving**: No biometric data leaves the device
29//!
30//! # Algorithm Support
31//!
32//! - **ECDSA**: P-256, P-384, P-521 elliptic curves
33//! - **EdDSA**: Ed25519 signature algorithm
34//! - **RSA**: RSA-2048, RSA-3072, RSA-4096 (where supported)
35//!
36//! # Registration Process
37//!
38//! 1. **Challenge Generation**: Create cryptographic challenge
39//! 2. **Credential Creation**: Browser/authenticator creates key pair
40//! 3. **Attestation Verification**: Validate authenticator attestation
41//! 4. **Storage**: Store public key and metadata
42//!
43//! # Authentication Process
44//!
45//! 1. **Challenge Generation**: Create authentication challenge
46//! 2. **Signature Creation**: Authenticator signs challenge
47//! 3. **Signature Verification**: Validate signature with stored public key
48//! 4. **Result**: Return authentication success or failure
49//!
50//! # Example Usage
51//!
52//! ```rust,no_run
53//! use auth_framework::methods::passkey::{PasskeyAuthMethod, PasskeyConfig};
54//! use auth_framework::tokens::TokenManager;
55//!
56//! # #[tokio::main]
57//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
58//! # let token_manager: TokenManager = unimplemented!();
59//! // Configure passkey authentication
60//! let config = PasskeyConfig {
61//!     rp_name: "Example Corp".to_string(),
62//!     rp_id: "example.com".to_string(),
63//!     origin: "https://example.com".to_string(),
64//!     timeout_ms: 60000,
65//!     user_verification: "required".to_string(),
66//!     authenticator_attachment: None,
67//!     require_resident_key: false,
68//!     ..Default::default()
69//! };
70//!
71//! let passkey_method = PasskeyAuthMethod::new(config, token_manager)?;
72//! // With the `passkeys` feature enabled:
73//! // passkey_method.register_passkey("user123", "user@example.com", "User Name").await?;
74//! // passkey_method.initiate_authentication("user123").await?;
75//! # Ok(())
76//! # }
77//! ```
78//!
79//! # Browser Compatibility
80//!
81//! - **Chrome**: Full WebAuthn support
82//! - **Firefox**: Complete implementation
83//! - **Safari**: iOS 14+ and macOS Big Sur+
84//! - **Edge**: Chromium-based versions
85//! - **Mobile**: iOS Safari, Chrome Android
86//!
87//! # Production Considerations
88//!
89//! - Replace in-memory storage with persistent database
90//! - Implement proper error handling for unsupported browsers
91//! - Configure appropriate timeout values for user experience
92//! - Consider attestation verification policies
93//! - Plan for authenticator replacement scenarios
94
95// Pure Rust WebAuthn/Passkey Authentication using 1Password's passkey-rs
96// Production-grade FIDO2/WebAuthn implementation without OpenSSL dependencies
97
98use 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// Keep the direct coset import aligned with passkey's coset version.
111#[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/// Simple user validation method for passkey authentication
137#[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
166/// Passkey/WebAuthn authentication method implementing FIDO2 standards.
167///
168/// `PasskeyAuthMethod` provides a pure Rust implementation of WebAuthn/FIDO2
169/// passkey authentication, supporting both platform authenticators (built into
170/// devices) and roaming authenticators (USB security keys).
171///
172/// # Features
173///
174/// - **FIDO2/WebAuthn Compliance**: Implements the latest WebAuthn Level 2 specification
175/// - **Cross-Platform Support**: Works with Windows Hello, Touch ID, YubiKey, and other authenticators
176/// - **Phishing Resistance**: Cryptographic binding to origin prevents phishing attacks
177/// - **Passwordless Authentication**: Eliminates password-related vulnerabilities
178/// - **Multi-Device Support**: Users can register multiple authenticators
179///
180/// # Security Properties
181///
182/// - **Public Key Cryptography**: Each passkey uses unique key pairs
183/// - **Origin Binding**: Passkeys are cryptographically bound to the website origin
184/// - **User Verification**: Supports biometric and PIN-based user verification
185/// - **Replay Protection**: Each authentication uses unique challenges
186/// - **Privacy**: No biometric data leaves the user's device
187///
188/// # Authenticator Types Supported
189///
190/// - **Platform Authenticators**: Windows Hello, Touch ID, Android Biometrics
191/// - **Roaming Authenticators**: YubiKey, SoloKey, other FIDO2 security keys
192/// - **Hybrid Transport**: QR code-based authentication between devices
193///
194/// # Registration Flow
195///
196/// 1. Generate registration challenge with user and relying party information
197/// 2. Client creates credential using authenticator
198/// 3. Verify attestation and store public key
199/// 4. Associate passkey with user account
200///
201/// # Authentication Flow
202///
203/// 1. Generate authentication challenge
204/// 2. Client signs challenge with private key
205/// 3. Verify signature using stored public key
206/// 4. Return authentication result
207///
208/// # Example
209///
210/// ```rust,no_run
211/// use auth_framework::methods::passkey::{PasskeyAuthMethod, PasskeyConfig};
212/// use auth_framework::tokens::TokenManager;
213///
214/// # #[tokio::main]
215/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
216/// # let token_manager: TokenManager = unimplemented!();
217/// let config = PasskeyConfig {
218///     rp_name: "Example Corp".to_string(),
219///     rp_id: "example.com".to_string(),
220///     origin: "https://example.com".to_string(),
221///     timeout_ms: 60000,
222///     user_verification: "required".to_string(),
223///     authenticator_attachment: None,
224///     require_resident_key: false,
225///     ..Default::default()
226/// };
227///
228/// let passkey_method = PasskeyAuthMethod::new(config, token_manager)?;
229/// // With the `passkeys` feature enabled:
230/// // passkey_method.register_passkey("user123", "user@example.com", "User Name").await?;
231/// // passkey_method.initiate_authentication("user123").await?;
232/// # Ok(())
233/// # }
234/// ```
235///
236/// # Thread Safety
237///
238/// This implementation is thread-safe and can be used in concurrent environments.
239/// The internal passkey storage uses `RwLock` for safe concurrent access.
240///
241/// # Production Considerations
242///
243/// - Replace in-memory storage with persistent database in production
244/// - Configure appropriate timeout values for user experience
245/// - Implement proper error handling for unsupported browsers
246/// - Consider implementing credential management for device changes
247pub struct PasskeyAuthMethod {
248    pub config: PasskeyConfig,
249    pub token_manager: TokenManager,
250    /// Storage for registered passkeys (in production, use a database)
251    pub registered_passkeys: RwLock<HashMap<String, PasskeyRegistration>>,
252    /// Pending challenges keyed by credential_id (populated during initiate_authentication).
253    /// Only present when the `passkeys` feature is enabled.
254    #[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/// Configuration for passkey authentication
271#[derive(Debug, Clone, Serialize, Deserialize)]
272pub struct PasskeyConfig {
273    /// Relying Party identifier (your domain)
274    pub rp_id: String,
275    /// Human-readable relying party name
276    pub rp_name: String,
277    /// Origin URL for WebAuthn ceremonies
278    pub origin: String,
279    /// Timeout for registration/authentication in milliseconds
280    pub timeout_ms: u32,
281    /// User verification requirement
282    pub user_verification: String, // "required", "preferred", "discouraged"
283    /// Authenticator attachment preference
284    pub authenticator_attachment: Option<String>, // "platform", "cross-platform"
285    /// Require resident keys
286    pub require_resident_key: bool,
287    /// Attestation conveyance preference: "none", "indirect", "direct", or "enterprise".
288    /// Defaults to "direct" to request authenticator attestation for device verification.
289    #[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, // 60 seconds
304            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/// Stored passkey registration information
313#[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, // JSON-serialized Passkey
320    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    /// Create a new passkey authentication method
343    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); // Suppress unused variable warning
357            Err(AuthError::config(
358                "Passkey support not compiled in. Enable 'passkeys' feature.",
359            ))
360        }
361    }
362
363    /// Register a new passkey for a user
364    #[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        // Create authenticator
375        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        // Create client
381        let mut client = Client::new(authenticator);
382
383        // Generate challenge
384        let challenge: Bytes = random_vec(32).into();
385
386        // Create user entity
387        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        // Create credential creation options
394        let request = CredentialCreationOptions {
395            public_key: PublicKeyCredentialCreationOptions {
396                rp: PublicKeyCredentialRpEntity {
397                    id: None, // Use effective domain
398                    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                    // Default to Direct for security — requests authenticator attestation
421                    _ => AttestationConveyancePreference::Direct,
422                },
423                attestation_formats: None,
424                extensions: None,
425            },
426        };
427
428        // Register the credential
429        let credential = client
430            .register(&origin, request, DefaultClientData)
431            .await
432            .map_err(|e| AuthError::validation(format!("Passkey registration failed: {:?}", e)))?;
433
434        // Extract credential ID and store registration
435        let credential_id = &credential.raw_id;
436        let credential_id_b64 = URL_SAFE_NO_PAD.encode(credential_id.as_slice());
437
438        // Serialize the credential attestation response so the public key and
439        // counter are available for future authentication verification.
440        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    /// Initiate passkey authentication
483    #[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(&reg.credential_id),
506                )
507            })
508            .collect()
509        };
510
511        // Store the challenge for each credential that may respond, and under "latest"
512        // so complete_authentication / AuthMethod::authenticate can verify it.
513        {
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            // Always save under "latest" as a fallback for usernameless flows.
523            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    /// Complete passkey authentication
563    #[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        // Find the registered passkey
572        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        // Serialize the credential to the JSON format expected by advanced_verification_flow
585        // (same format as the Credential::Passkey path in authenticate()).
586        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        // Load stored passkey data (public key + counter).
594        let passkey_data: serde_json::Value = serde_json::from_str(&registration.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        // Retrieve the stored challenge for this credential.
610        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        // Full cryptographic verification (challenge, origin, RP ID hash, signature, counter).
628        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        // Update stored counter and last-used timestamp.
644        let mut passkey_data: serde_json::Value = serde_json::from_str(&registration.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        // Issue authentication token.
671        let token = self.token_manager.create_jwt_token(
672            &registration.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            &registration.user_id,
685            token,
686            Duration::from_secs(3600),
687            "passkey",
688        ))
689    }
690
691    /// Fallback for when passkeys feature is disabled
692    #[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                    // Find the registered passkey
726                    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                    // Use advanced verification methods for production security
745                    // Parse the stored passkey data to get the required information
746                    let passkey_data: serde_json::Value =
747                        serde_json::from_str(&registration.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                    // Retrieve the stored challenge for this credential (set during initiate_authentication).
764                    // Fall back to "latest" for usernameless flows.
765                    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                    // Perform advanced verification with replay protection
783                    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                            // Update counter to prevent replay attacks
800                            let mut updated_registration = registration.clone();
801
802                            // Update the passkey data with the new counter
803                            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                    // Fallback: basic validation for compatibility
848                    tracing::debug!("Assertion response length: {}", assertion_response.len());
849
850                    // Create token after successful verification
851
852                    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                        &registration.user_id,
859                        vec![],                          // No specific scopes
860                        Some(Duration::from_secs(3600)), // 1 hour
861                    )?;
862
863                    let auth_token = AuthToken::new(
864                        &registration.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; // Suppress unused variable warning
885            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        // Validate user verification requirement
903        match self.config.user_verification.as_str() {
904            "required" | "preferred" | "discouraged" => {}
905            _ => return Err(AuthError::config("Invalid user verification requirement")),
906        }
907
908        // Validate origin URL
909        #[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 // Passkeys don't use refresh tokens
920    }
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    /// Advanced passkey verification with full WebAuthn compliance
931    /// Implements proper signature verification, replay protection, and attestation validation
932    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        // Parse assertion response
945        let assertion: serde_json::Value = serde_json::from_str(assertion_response)
946            .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
947
948        // Extract and validate clientDataJSON
949        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        // Step 1: Verify challenge
966        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        // Step 2: Verify origin
980        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        // Step 3: Verify operation type
990        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        // Step 4: Extract and validate authenticatorData
1000        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        // Step 5: Verify RP ID hash
1015        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        // Step 6: Extract and verify flags
1027        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        // Step 7: Extract and verify counter for replay protection using helper method
1036        let new_counter = self.extract_counter_from_assertion(assertion_response)?;
1037
1038        // Per WebAuthn spec §6.1 step 17: if the stored counter was 0 and the
1039        // authenticator returns 0, the authenticator does not support counters
1040        // (many platform authenticators). Only reject when the counter is non-zero
1041        // but failed to advance — that indicates a replay or cloned authenticator.
1042        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        // Step 8: Perform cryptographic signature verification using helper method
1049        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    /// Verify WebAuthn signature using Ring cryptography
1068    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                // Extract RSA public key components
1090                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                // Use ring's RsaPublicKeyComponents to avoid hand-rolling DER.
1107                // This accepts raw n/e bytes and handles SubjectPublicKeyInfo encoding
1108                // internally, correctly handling 2048-bit+ moduli.
1109                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                // Extract EC public key components
1135                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                // Create uncompressed point format
1166                let mut public_key_bytes = Vec::with_capacity(1 + expected_coord_len * 2);
1167                public_key_bytes.push(0x04); // Uncompressed point indicator
1168                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    /// Cross-platform passkey verification for multiple authenticator types
1185    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        // Parse assertion response
1193        let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1194            .map_err(|_| AuthError::validation("Invalid assertion response"))?;
1195
1196        // Extract AAGUID from assertion to determine authenticator type
1197        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        // Extract AAGUID (bytes 37-52 if attested credential data is present)
1208        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        // Determine authenticator type based on AAGUID
1215        let detected_type = self.detect_authenticator_type(aaguid)?;
1216
1217        // Verify that the detected type is allowed
1218        if !authenticator_types.contains(&detected_type) {
1219            return Err(AuthError::validation("Authenticator type not allowed"));
1220        }
1221
1222        // Perform type-specific validation
1223        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    /// Detect authenticator type based on AAGUID and other factors
1249    fn detect_authenticator_type(&self, aaguid: Option<&[u8]>) -> Result<AuthenticatorType> {
1250        match aaguid {
1251            Some(guid) if guid == [0u8; 16] => {
1252                // Null AAGUID typically indicates a security key or older authenticator
1253                Ok(AuthenticatorType::SecurityKey)
1254            }
1255            Some(guid) => {
1256                // Check known AAGUIDs for popular authenticators
1257                match guid {
1258                    // YubiKey Series
1259                    [
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                    // Touch ID/Face ID
1278                    [
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                    // Windows Hello
1297                    [
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                        // Unknown AAGUID, default to cross-platform
1317                        Ok(AuthenticatorType::CrossPlatform)
1318                    }
1319                }
1320            }
1321            None => {
1322                // No AAGUID present, default to security key
1323                Ok(AuthenticatorType::SecurityKey)
1324            }
1325        }
1326    }
1327
1328    /// Validate platform authenticator (Touch ID, Face ID, Windows Hello)
1329    async fn validate_platform_authenticator(
1330        &self,
1331        assertion: &serde_json::Value,
1332    ) -> Result<TypeSpecificValidationResult> {
1333        tracing::debug!("Validating platform authenticator");
1334
1335        // Platform authenticators should have user verification
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(|| 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    /// Validate cross-platform authenticator (Roaming authenticators)
1370    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        // Cross-platform authenticators are generally more flexible
1377        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    /// Validate security key (FIDO U2F/CTAP1 style authenticators)
1391    async fn validate_security_key(
1392        &self,
1393        assertion: &serde_json::Value,
1394    ) -> Result<TypeSpecificValidationResult> {
1395        tracing::debug!("Validating security key");
1396
1397        // Security keys typically only provide user presence
1398        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    /// Verify WebAuthn assertion signature (simplified implementation)
1437    /// In production, use a proper WebAuthn library like `webauthn-rs`
1438    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        // IMPLEMENTATION COMPLETE: Enhanced assertion signature verification
1449        tracing::debug!("Verifying assertion signature");
1450
1451        // Parse assertion response as JSON (simplified)
1452        let assertion: serde_json::Value = serde_json::from_str(assertion_response)
1453            .map_err(|_| AuthError::validation("Invalid assertion response format"))?;
1454
1455        // Extract signature
1456        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        // Create signed data: authenticatorData + SHA256(clientDataJSON)
1467        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        // Verify signature using public key
1478        self.verify_webauthn_signature(&signed_data, &signature_bytes, public_key_jwk)?;
1479
1480        Ok(())
1481    }
1482
1483    /// Extract counter from WebAuthn assertion response for replay attack protection
1484    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        // IMPLEMENTATION COMPLETE: Extract counter for replay attack protection
1488        tracing::debug!("Extracting counter from assertion response");
1489
1490        // Parse assertion response as JSON
1491        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        // Decode base64 authenticator data
1503        let auth_data_bytes = URL_SAFE_NO_PAD
1504            .decode(authenticator_data)
1505            .map_err(|_| AuthError::validation("authenticatorData is not valid base64url"))?;
1506
1507        // AuthenticatorData structure:
1508        // rpIdHash (32 bytes) + flags (1 byte) + counter (4 bytes) + ...
1509        if auth_data_bytes.len() < 37 {
1510            return Err(AuthError::validation(
1511                "authenticatorData is too short to contain a counter",
1512            ));
1513        }
1514
1515        // Extract counter from bytes 33-36 (big-endian u32)
1516        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/// Result of advanced WebAuthn verification
1530#[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/// Types of WebAuthn authenticators
1540#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1541pub enum AuthenticatorType {
1542    /// Platform authenticator (built into device)
1543    Platform,
1544    /// Cross-platform authenticator (roaming)
1545    CrossPlatform,
1546    /// Security key (FIDO U2F style)
1547    SecurityKey,
1548}
1549
1550/// Result of cross-platform verification
1551#[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/// Type-specific validation result
1559#[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(), // Invalid: empty RP ID
1609            rp_name: "Test App".to_string(),
1610            origin: "https://example.com".to_string(),
1611            timeout_ms: 60000,
1612            user_verification: "invalid".to_string(), // Invalid user verification
1613            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}