oauth2-passkey 0.6.0

OAuth2 and Passkey authentication library for Rust web applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use super::errors::PasskeyError;
use crate::session::UserId;
use crate::storage::CacheData;

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct PublicKeyCredentialUserEntity {
    pub user_handle: String,
    pub name: String,
    #[serde(rename = "displayName")]
    pub display_name: String,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub(super) struct StoredOptions {
    pub(super) challenge: String,
    pub(super) user: PublicKeyCredentialUserEntity,
    pub(super) timestamp: u64,
    pub(super) ttl: u64,
}

/// Stored credential information for a WebAuthn/Passkey.
///
/// This struct represents a stored passkey credential that can be used for authentication.
/// It contains all the necessary information to verify subsequent authentications using
/// the same credential, including the public key, credential ID, and counter value.
///
/// The credential is associated with a specific user and includes metadata about when
/// it was created, updated, and last used.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct PasskeyCredential {
    /// Database-assigned sequential primary key (internal, not exposed in API responses)
    #[serde(skip_serializing)]
    pub sequence_number: Option<i64>,
    /// Raw credential ID bytes
    pub credential_id: String,
    /// User ID associated with this credential (database ID)
    pub user_id: String,
    /// Public key bytes for the credential
    pub public_key: String,
    /// AAGUID of the authenticator
    pub aaguid: String,
    /// Relying Party ID used when this credential was registered
    pub rp_id: String,
    /// Counter value for the credential (used to prevent replay attacks)
    pub counter: u32,
    /// User entity information
    pub user: PublicKeyCredentialUserEntity,
    /// When the credential was created
    pub created_at: DateTime<Utc>,
    /// When the credential was last updated
    pub updated_at: DateTime<Utc>,
    /// When the credential was last used
    pub last_used_at: DateTime<Utc>,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub(super) struct UserIdCredentialIdStr {
    pub(super) user_id: String,
    pub(super) credential_id: String,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub(super) struct SessionInfo {
    pub(super) user: crate::session::User,
}

/// Search field options for credential lookup.
///
/// This enum provides various ways to search for passkey credentials in storage,
/// supporting different lookup strategies based on the available identifier.
/// Each variant represents a different search parameter type with compile-time type safety.
#[allow(dead_code)]
#[derive(Debug)]
pub enum CredentialSearchField {
    /// Search by credential ID (type-safe)
    CredentialId(CredentialId),
    /// Search by user ID (database ID, type-safe)
    UserId(UserId),
    /// Search by user handle (WebAuthn user handle, type-safe)
    UserHandle(UserHandle),
    /// Search by username (type-safe)
    UserName(UserName),
}

/// Helper functions for cache store operations to improve code reuse and maintainability
impl From<SessionInfo> for CacheData {
    fn from(data: SessionInfo) -> Self {
        Self {
            value: serde_json::to_string(&data).expect("Failed to serialize SessionInfo"),
        }
    }
}

impl TryFrom<CacheData> for SessionInfo {
    type Error = PasskeyError;

    fn try_from(data: CacheData) -> Result<Self, Self::Error> {
        serde_json::from_str(&data.value).map_err(|e| PasskeyError::Storage(e.to_string()))
    }
}

impl From<StoredOptions> for CacheData {
    fn from(data: StoredOptions) -> Self {
        Self {
            value: serde_json::to_string(&data).expect("Failed to serialize StoredOptions"),
        }
    }
}

impl TryFrom<CacheData> for StoredOptions {
    type Error = PasskeyError;

    fn try_from(data: CacheData) -> Result<Self, Self::Error> {
        serde_json::from_str(&data.value).map_err(|e| PasskeyError::Storage(e.to_string()))
    }
}

/// Type-safe wrapper for credential identifiers.
///
/// This provides compile-time safety to prevent mixing up credential IDs with other string types.
/// It's used in passkey coordination functions to ensure type safety when passing credential identifiers.
#[derive(Debug, Clone, PartialEq)]
pub struct CredentialId(String);

impl CredentialId {
    /// Creates a new CredentialId from a string with validation.
    ///
    /// # Arguments
    /// * `id` - The credential ID string
    ///
    /// # Returns
    /// * `Ok(CredentialId)` - If the ID is valid
    /// * `Err(PasskeyError)` - If the ID is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must contain only safe characters (alphanumeric + URL-safe symbols)
    /// * Must not contain control characters or dangerous sequences
    pub fn new(id: String) -> Result<Self, crate::passkey::PasskeyError> {
        use crate::passkey::PasskeyError;

        // Validate ID is not empty
        if id.is_empty() {
            return Err(PasskeyError::Validation(
                "Credential ID cannot be empty".to_string(),
            ));
        }

        // Validate ID length (credential IDs need sufficient entropy and can be substantial)
        if id.len() < 10 {
            return Err(PasskeyError::Validation(
                "Credential ID too short".to_string(),
            ));
        }

        if id.len() > 1024 {
            return Err(PasskeyError::Validation(
                "Credential ID too long".to_string(),
            ));
        }

        // Validate ID contains only URL-safe characters
        if !id.chars().all(|c| {
            c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '~' | '=' | '+' | '/')
        }) {
            return Err(PasskeyError::Validation(
                "Credential ID contains invalid characters".to_string(),
            ));
        }

        Ok(CredentialId(id))
    }

    /// Returns the credential ID as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the credential ID
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-safe wrapper for WebAuthn user handles.
///
/// This provides compile-time safety to prevent mixing up user handles with other string types.
/// User handles are WebAuthn-specific identifiers that may differ from usernames or display names.
#[derive(Debug, Clone, PartialEq)]
pub struct UserHandle(String);

impl UserHandle {
    /// Creates a new UserHandle from a string.
    ///
    /// # Arguments
    /// * `handle` - The user handle string
    ///
    /// # Returns
    /// * A new UserHandle instance
    #[cfg(test)]
    pub fn new(handle: String) -> Self {
        Self(handle)
    }

    /// Returns the user handle as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the user handle
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-safe wrapper for usernames.
///
/// This provides compile-time safety to prevent mixing up usernames with other string types.
/// Usernames are user-facing identifiers that may be used for display or authentication.
#[derive(Debug, Clone, PartialEq)]
pub struct UserName(String);

impl UserName {
    /// Creates a new UserName from a string with validation.
    ///
    /// # Arguments
    /// * `name` - The username string
    ///
    /// # Returns
    /// * `Ok(UserName)` - If the name is valid
    /// * `Err(PasskeyError)` - If the name is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must not contain dangerous sequences
    /// * Must not consist only of whitespace
    pub fn new(name: String) -> Result<Self, crate::passkey::PasskeyError> {
        use crate::passkey::PasskeyError;

        // Validate name is not empty
        if name.is_empty() {
            return Err(PasskeyError::Validation(
                "Username cannot be empty".to_string(),
            ));
        }

        // Validate name length (WebAuthn username limits)
        if name.len() > 64 {
            return Err(PasskeyError::Validation("Username too long".to_string()));
        }

        // Validate name doesn't consist only of whitespace
        if name.trim().is_empty() {
            return Err(PasskeyError::Validation(
                "Username cannot consist only of whitespace".to_string(),
            ));
        }

        // Check for dangerous sequences
        if name.contains("..") || name.contains("--") || name.contains("__") {
            return Err(PasskeyError::Validation(
                "Username contains dangerous character sequences".to_string(),
            ));
        }

        Ok(UserName(name))
    }

    /// Returns the username as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the username
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Type-safe wrapper for WebAuthn challenge types.
///
/// This provides compile-time safety to prevent mixing up challenge types with other string types.
/// Challenge types identify the kind of WebAuthn operation (registration, authentication) and are
/// used as cache prefixes for storing challenge data.
#[derive(Debug, Clone, PartialEq)]
pub struct ChallengeType(String);

impl ChallengeType {
    /// Creates a new ChallengeType from a string with validation.
    ///
    /// This constructor validates the challenge type to ensure it meets
    /// requirements for cache operations and WebAuthn flow identification.
    ///
    /// # Arguments
    /// * `challenge_type` - The challenge type string
    ///
    /// # Returns
    /// * `Ok(ChallengeType)` - If the challenge type is valid
    /// * `Err(PasskeyError)` - If the challenge type is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must contain only alphanumeric characters and underscores
    /// * Must be reasonable length
    pub fn new(challenge_type: String) -> Result<Self, super::errors::PasskeyError> {
        use super::errors::PasskeyError;

        // Validate challenge type is not empty
        if challenge_type.is_empty() {
            return Err(PasskeyError::Challenge(
                "Challenge type cannot be empty".to_string(),
            ));
        }

        // Validate challenge type length (reasonable bounds)
        if challenge_type.len() > 64 {
            return Err(PasskeyError::Challenge(
                "Challenge type too long".to_string(),
            ));
        }

        // Validate challenge type contains only safe characters for cache prefixes
        if !challenge_type
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_')
        {
            return Err(PasskeyError::Challenge(
                "Challenge type contains invalid characters".to_string(),
            ));
        }

        Ok(ChallengeType(challenge_type))
    }

    /// Returns the challenge type as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the challenge type
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Creates a registration challenge type.
    ///
    /// # Returns
    /// * A ChallengeType for registration operations
    pub fn registration() -> Self {
        ChallengeType("registration".to_string())
    }

    /// Creates an authentication challenge type.
    ///
    /// # Returns
    /// * A ChallengeType for authentication operations
    pub fn authentication() -> Self {
        ChallengeType("authentication".to_string())
    }
}

/// Type-safe wrapper for WebAuthn challenge identifiers.
///
/// This provides compile-time safety to prevent mixing up challenge IDs with other string types.
/// Challenge IDs are unique identifiers for specific WebAuthn challenge instances and are used
/// as cache keys for storing and retrieving challenge data.
#[derive(Debug, Clone, PartialEq)]
pub struct ChallengeId(String);

impl ChallengeId {
    /// Creates a new ChallengeId from a string with validation.
    ///
    /// This constructor validates the challenge ID to ensure it meets
    /// requirements for cache operations and uniqueness.
    ///
    /// # Arguments
    /// * `id` - The challenge ID string
    ///
    /// # Returns
    /// * `Ok(ChallengeId)` - If the challenge ID is valid
    /// * `Err(PasskeyError)` - If the challenge ID is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must contain only safe characters for cache keys
    /// * Must be reasonable length
    pub fn new(id: String) -> Result<Self, super::errors::PasskeyError> {
        use super::errors::PasskeyError;

        // Validate ID is not empty
        if id.is_empty() {
            return Err(PasskeyError::Challenge(
                "Challenge ID cannot be empty".to_string(),
            ));
        }

        // Validate ID length (reasonable bounds)
        if id.len() < 8 {
            return Err(PasskeyError::Challenge(
                "Challenge ID too short".to_string(),
            ));
        }

        if id.len() > 256 {
            return Err(PasskeyError::Challenge("Challenge ID too long".to_string()));
        }

        // Validate ID contains only safe characters for cache keys
        if !id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '+'))
        {
            return Err(PasskeyError::Challenge(
                "Challenge ID contains invalid characters".to_string(),
            ));
        }

        Ok(ChallengeId(id))
    }

    /// Returns the challenge ID as a string slice.
    ///
    /// # Returns
    /// * A string slice containing the challenge ID
    pub fn as_str(&self) -> &str {
        &self.0
    }
}