oauth2-passkey 0.6.1

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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::session::errors::SessionError;
use crate::storage::CacheData;
use crate::userdb::User as DbUser;

/// User information stored in the session.
///
/// This struct represents authenticated user data that is stored in the session
/// and retrieved during authentication checks. It contains essential user identity
/// and permission information needed for the application.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    /// Unique identifier for the user
    pub id: String,
    /// User account name or login identifier
    pub account: String,
    /// Display name or label for the user
    pub label: String,
    /// Whether the user has administrative privileges
    pub is_admin: bool,
    /// Database-assigned sequence number (primary key), None for users not yet persisted
    pub sequence_number: Option<i64>,
    /// When the user account was created
    pub created_at: DateTime<Utc>,
    /// When the user account was last updated
    pub updated_at: DateTime<Utc>,
}

impl From<DbUser> for User {
    fn from(db_user: DbUser) -> Self {
        Self {
            id: db_user.id,
            account: db_user.account,
            label: db_user.label,
            is_admin: db_user.is_admin,
            sequence_number: db_user.sequence_number,
            created_at: db_user.created_at,
            updated_at: db_user.updated_at,
        }
    }
}

impl From<User> for DbUser {
    fn from(session_user: User) -> Self {
        Self {
            id: session_user.id,
            account: session_user.account,
            label: session_user.label,
            is_admin: session_user.is_admin,
            sequence_number: session_user.sequence_number,
            created_at: session_user.created_at,
            updated_at: session_user.updated_at,
        }
    }
}

impl User {
    /// Determines if the user has administrative privileges.
    ///
    /// A user has admin privileges if:
    /// 1. They have the `is_admin` flag set to true, OR
    /// 2. They are the first user in the system (sequence_number = 1)
    ///
    /// This method provides consistent admin privilege checking across the codebase
    /// and ensures the first user always has admin access regardless of the is_admin flag.
    ///
    /// # Returns
    /// * `true` if the user has administrative privileges
    /// * `false` otherwise
    ///
    /// # Examples
    /// ```
    /// use oauth2_passkey::SessionUser as User;
    /// use chrono::Utc;
    ///
    /// // Regular admin user
    /// let admin_user = User {
    ///     id: "user1".to_string(),
    ///     account: "admin@example.com".to_string(),
    ///     label: "Admin User".to_string(),
    ///     is_admin: true,
    ///     sequence_number: Some(5),
    ///     created_at: Utc::now(),
    ///     updated_at: Utc::now(),
    /// };
    /// assert!(admin_user.has_admin_privileges());
    ///
    /// // First user (always admin)
    /// let first_user = User {
    ///     id: "user1".to_string(),
    ///     account: "first@example.com".to_string(),
    ///     label: "First User".to_string(),
    ///     is_admin: false,
    ///     sequence_number: Some(1),
    ///     created_at: Utc::now(),
    ///     updated_at: Utc::now(),
    /// };
    /// assert!(first_user.has_admin_privileges());
    ///
    /// // Regular user
    /// let regular_user = User {
    ///     id: "user1".to_string(),
    ///     account: "user@example.com".to_string(),
    ///     label: "Regular User".to_string(),
    ///     is_admin: false,
    ///     sequence_number: Some(2),
    ///     created_at: Utc::now(),
    ///     updated_at: Utc::now(),
    /// };
    /// assert!(!regular_user.has_admin_privileges());
    /// ```
    /// IMPORTANT: This logic must stay in sync with DbUser::has_admin_privileges()
    /// and AuthUser::has_admin_privileges() implementations.
    pub fn has_admin_privileges(&self) -> bool {
        self.is_admin || self.sequence_number == Some(1)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) struct StoredSession {
    pub(super) user_id: String,
    pub(super) csrf_token: String,
    pub(super) expires_at: DateTime<Utc>,
    pub(super) ttl: u64,
}

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

impl TryFrom<CacheData> for StoredSession {
    type Error = SessionError;

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

/// CSRF (Cross-Site Request Forgery) token for request validation.
///
/// This struct represents a security token that must be included in forms
/// and state-changing requests to prevent cross-site request forgery attacks.
/// It's a newtype wrapper around a String to provide type safety and prevent
/// confusion with other string types.
#[derive(Debug, Clone)]
pub struct CsrfToken(String);

/// Indicates whether the CSRF token was verified via an HTTP header.
///
/// This is typically set by middleware or other authentication layers that have
/// already performed CSRF validation. It's used to avoid redundant validation
/// when multiple layers of authentication checks are applied.
///
/// Contains a boolean where `true` means the CSRF token was already verified.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CsrfHeaderVerified(pub bool);

/// Indicates the overall authentication status of a session.
///
/// This is a simple boolean wrapper that indicates whether a user is authenticated.
/// It's used as a return type from authentication check functions to explicitly
/// communicate the authentication state.
///
/// Contains a boolean where `true` means the user is authenticated.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AuthenticationStatus(pub bool);

impl std::fmt::Display for AuthenticationStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::fmt::Display for CsrfHeaderVerified {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl CsrfToken {
    /// Creates a new CSRF token from a string.
    ///
    /// # Arguments
    /// * `token` - The token string
    ///
    /// # Returns
    /// * A new CsrfToken instance
    pub fn new(token: String) -> Self {
        Self(token)
    }

    /// Returns the token as a string slice.
    ///
    /// This method is useful when you need to include the token in a
    /// response or use it for comparison.
    ///
    /// # Returns
    /// * A string slice containing the token
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

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

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

        // Validate ID length (reasonable bounds)
        if id.len() > 255 {
            return Err(SessionError::Validation("User ID too long".to_string()));
        }

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

        // Check for dangerous sequences
        if id.contains("..") || id.contains("--") || id.contains("__") {
            return Err(SessionError::Validation(
                "User ID contains dangerous character sequences".to_string(),
            ));
        }

        Ok(UserId(id))
    }

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

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

impl SessionId {
    /// Creates a new SessionId from a string with validation.
    ///
    /// # Arguments
    /// * `id` - The session ID string
    ///
    /// # Returns
    /// * `Ok(SessionId)` - If the ID is valid
    /// * `Err(SessionError)` - 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 whitespace
    pub fn new(id: String) -> Result<Self, crate::session::SessionError> {
        use crate::session::SessionError;

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

        // Validate ID length (session IDs need sufficient entropy)
        if id.len() < 10 {
            return Err(SessionError::Validation("Session ID too short".to_string()));
        }

        if id.len() > 256 {
            return Err(SessionError::Validation("Session ID too long".to_string()));
        }

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

        Ok(SessionId(id))
    }

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

/// Type-safe wrapper for session cookies.
///
/// This provides compile-time safety to prevent mixing up session cookies with other string types.
/// Session cookies are HTTP cookie values used for user session identification and must be
/// properly validated to prevent session hijacking and other security issues.
#[derive(Debug, Clone, PartialEq)]
pub struct SessionCookie(String);

impl SessionCookie {
    /// Creates a new SessionCookie from a string with validation.
    ///
    /// This constructor validates the session cookie format to ensure it meets
    /// security requirements for session identification.
    ///
    /// # Arguments
    /// * `cookie` - The session cookie string
    ///
    /// # Returns
    /// * `Ok(SessionCookie)` - If the cookie is valid
    /// * `Err(SessionError)` - If the cookie is invalid
    ///
    /// # Validation Rules
    /// * Must not be empty
    /// * Must contain only valid characters (alphanumeric + basic symbols)
    /// * Must be reasonable length (not too short or too long)
    pub fn new(cookie: String) -> Result<Self, crate::session::SessionError> {
        use crate::session::SessionError;

        // Validate cookie is not empty
        if cookie.is_empty() {
            return Err(SessionError::Cookie(
                "Session cookie cannot be empty".to_string(),
            ));
        }

        // Validate cookie length (reasonable bounds)
        if cookie.len() < 10 {
            return Err(SessionError::Cookie("Session cookie too short".to_string()));
        }

        if cookie.len() > 1024 {
            return Err(SessionError::Cookie("Session cookie too long".to_string()));
        }

        // Validate cookie contains only safe characters
        // Allow alphanumeric, hyphens, underscores, equals signs, and basic URL-safe characters
        if !cookie
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '=' | '.' | '+' | '/'))
        {
            return Err(SessionError::Cookie(
                "Session cookie contains invalid characters".to_string(),
            ));
        }

        Ok(SessionCookie(cookie))
    }

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

#[cfg(test)]
mod tests;