auth-framework 0.4.42

A comprehensive, production-ready authentication and authorization framework for Rust 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Enhanced OAuth2 token and code storage with proper validation

use crate::errors::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::SystemTime;
use uuid::Uuid;

/// Stored refresh token with validation metadata
#[derive(Clone, Serialize, Deserialize)]
pub struct RefreshToken {
    pub token_id: String,
    pub client_id: String,
    pub user_id: String,
    pub scopes: Vec<String>,
    pub issued_at: SystemTime,
    pub expires_at: SystemTime,
    pub is_revoked: bool,
}

impl std::fmt::Debug for RefreshToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("RefreshToken");
        d.field("token_id", &crate::utils::redact::redacted(&self.token_id));
        d.field("client_id", &self.client_id);
        d.field("user_id", &self.user_id);
        d.field("scopes", &self.scopes);
        d.field("issued_at", &self.issued_at);
        d.field("expires_at", &self.expires_at);
        d.field("is_revoked", &self.is_revoked);
        d.finish()
    }
}

impl RefreshToken {
    pub fn new(
        client_id: String,
        user_id: String,
        scopes: Vec<String>,
        lifetime: std::time::Duration,
    ) -> Self {
        let now = SystemTime::now();
        Self {
            token_id: Uuid::new_v4().to_string(),
            client_id,
            user_id,
            scopes,
            issued_at: now,
            expires_at: now + lifetime,
            is_revoked: false,
        }
    }

    pub fn is_expired(&self) -> bool {
        SystemTime::now() > self.expires_at
    }

    pub fn is_valid(&self) -> bool {
        !self.is_revoked && !self.is_expired()
    }

    pub fn revoke(&mut self) {
        self.is_revoked = true;
    }
}

/// Enhanced authorization code with user context
#[derive(Clone, Serialize, Deserialize)]
pub struct EnhancedAuthorizationCode {
    pub code: String,
    pub client_id: String,
    pub user_id: String,
    pub redirect_uri: String,
    pub scopes: Vec<String>,
    pub code_challenge: Option<String>,
    pub code_challenge_method: Option<String>,
    pub issued_at: SystemTime,
    pub expires_at: SystemTime,
    pub is_used: bool,
}

impl std::fmt::Debug for EnhancedAuthorizationCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("EnhancedAuthorizationCode");
        d.field("code", &crate::utils::redact::redacted(&self.code));
        d.field("client_id", &self.client_id);
        d.field("user_id", &self.user_id);
        d.field("redirect_uri", &self.redirect_uri);
        d.field("scopes", &self.scopes);
        d.field("code_challenge", &self.code_challenge);
        d.field("code_challenge_method", &self.code_challenge_method);
        d.field("issued_at", &self.issued_at);
        d.field("expires_at", &self.expires_at);
        d.field("is_used", &self.is_used);
        d.finish()
    }
}

impl EnhancedAuthorizationCode {
    pub fn new(
        client_id: String,
        user_id: String,
        redirect_uri: String,
        scopes: Vec<String>,
        code_challenge: Option<String>,
        code_challenge_method: Option<String>,
        lifetime: std::time::Duration,
    ) -> Self {
        let now = SystemTime::now();
        Self {
            code: Uuid::new_v4().to_string(),
            client_id,
            user_id,
            redirect_uri,
            scopes,
            code_challenge,
            code_challenge_method,
            issued_at: now,
            expires_at: now + lifetime,
            is_used: false,
        }
    }

    pub fn is_expired(&self) -> bool {
        SystemTime::now() > self.expires_at
    }

    pub fn is_valid(&self) -> bool {
        !self.is_used && !self.is_expired()
    }

    pub fn mark_used(&mut self) {
        self.is_used = true;
    }
}

/// Enhanced client credentials with proper secret validation
#[derive(Clone, Serialize, Deserialize)]
pub struct EnhancedClientCredentials {
    pub client_id: String,
    pub client_secret_hash: String,
    pub client_type: ClientType,
    pub redirect_uris: Vec<String>,
    pub allowed_scopes: Vec<String>,
    pub grant_types: Vec<String>,
    pub created_at: SystemTime,
    pub is_active: bool,
}

impl std::fmt::Debug for EnhancedClientCredentials {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("EnhancedClientCredentials");
        d.field("client_id", &self.client_id);
        d.field(
            "client_secret_hash",
            &crate::utils::redact::redacted(&self.client_secret_hash),
        );
        d.field("client_type", &self.client_type);
        d.field("redirect_uris", &self.redirect_uris);
        d.field("allowed_scopes", &self.allowed_scopes);
        d.field("grant_types", &self.grant_types);
        d.field("created_at", &self.created_at);
        d.field("is_active", &self.is_active);
        d.finish()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ClientType {
    Confidential,
    Public,
}

impl EnhancedClientCredentials {
    pub fn new_confidential(
        client_id: String,
        client_secret: &str,
        redirect_uris: Vec<String>,
        allowed_scopes: Vec<String>,
        grant_types: Vec<String>,
    ) -> Result<Self> {
        use crate::security::secure_utils::hash_password;

        Ok(Self {
            client_id,
            client_secret_hash: hash_password(client_secret)?,
            client_type: ClientType::Confidential,
            redirect_uris,
            allowed_scopes,
            grant_types,
            created_at: SystemTime::now(),
            is_active: true,
        })
    }

    pub fn new_public(
        client_id: String,
        redirect_uris: Vec<String>,
        allowed_scopes: Vec<String>,
        grant_types: Vec<String>,
    ) -> Self {
        Self {
            client_id,
            client_secret_hash: String::new(), // Public clients don't have secrets
            client_type: ClientType::Public,
            redirect_uris,
            allowed_scopes,
            grant_types,
            created_at: SystemTime::now(),
            is_active: true,
        }
    }

    pub fn validate_secret(&self, provided_secret: &str) -> Result<bool> {
        match self.client_type {
            ClientType::Public => Ok(true), // Public clients don't need secret validation
            ClientType::Confidential => {
                use crate::security::secure_utils::verify_password;
                verify_password(provided_secret, &self.client_secret_hash)
            }
        }
    }

    pub fn requires_secret(&self) -> bool {
        matches!(self.client_type, ClientType::Confidential)
    }

    pub fn has_scope(&self, scope: &str) -> bool {
        self.allowed_scopes.contains(&scope.to_string())
    }

    pub fn supports_grant_type(&self, grant_type: &str) -> bool {
        self.grant_types.contains(&grant_type.to_string())
    }
}

/// Enhanced token storage with proper validation
#[derive(Clone)]
pub struct EnhancedTokenStorage {
    refresh_tokens: HashMap<String, RefreshToken>,
    authorization_codes: HashMap<String, EnhancedAuthorizationCode>,
    client_credentials: HashMap<String, EnhancedClientCredentials>,
}

impl std::fmt::Debug for EnhancedTokenStorage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("EnhancedTokenStorage");
        d.field(
            "refresh_tokens",
            &crate::utils::redact::redacted(&self.refresh_tokens),
        );
        d.field(
            "authorization_codes",
            &crate::utils::redact::redacted(&self.authorization_codes),
        );
        d.field(
            "client_credentials",
            &crate::utils::redact::redacted(&self.client_credentials),
        );
        d.finish()
    }
}

impl EnhancedTokenStorage {
    pub fn new() -> Self {
        Self {
            refresh_tokens: HashMap::new(),
            authorization_codes: HashMap::new(),
            client_credentials: HashMap::new(),
        }
    }

    // Refresh token operations
    pub async fn store_refresh_token(&mut self, token: RefreshToken) -> Result<String> {
        let token_id = token.token_id.clone();
        self.refresh_tokens.insert(token_id.clone(), token);
        Ok(token_id)
    }

    pub async fn get_refresh_token(&self, token_id: &str) -> Result<Option<RefreshToken>> {
        Ok(self.refresh_tokens.get(token_id).cloned())
    }

    pub async fn validate_refresh_token(&self, token_id: &str) -> Result<bool> {
        match self.refresh_tokens.get(token_id) {
            Some(token) => Ok(token.is_valid()),
            None => Ok(false),
        }
    }

    pub async fn revoke_refresh_token(&mut self, token_id: &str) -> Result<bool> {
        match self.refresh_tokens.get_mut(token_id) {
            Some(token) => {
                token.revoke();
                Ok(true)
            }
            None => Ok(false),
        }
    }

    // Authorization code operations
    pub async fn store_authorization_code(
        &mut self,
        code: EnhancedAuthorizationCode,
    ) -> Result<String> {
        let code_value = code.code.clone();
        self.authorization_codes.insert(code_value.clone(), code);
        Ok(code_value)
    }

    pub async fn get_authorization_code(
        &self,
        code: &str,
    ) -> Result<Option<EnhancedAuthorizationCode>> {
        Ok(self.authorization_codes.get(code).cloned())
    }

    pub async fn consume_authorization_code(
        &mut self,
        code: &str,
    ) -> Result<Option<EnhancedAuthorizationCode>> {
        match self.authorization_codes.get_mut(code) {
            Some(auth_code) if auth_code.is_valid() => {
                auth_code.mark_used();
                Ok(Some(auth_code.clone()))
            }
            _ => Ok(None),
        }
    }

    // Client credentials operations
    pub async fn store_client_credentials(
        &mut self,
        credentials: EnhancedClientCredentials,
    ) -> Result<()> {
        let client_id = credentials.client_id.clone();
        self.client_credentials.insert(client_id, credentials);
        Ok(())
    }

    pub async fn get_client_credentials(
        &self,
        client_id: &str,
    ) -> Result<Option<EnhancedClientCredentials>> {
        Ok(self.client_credentials.get(client_id).cloned())
    }

    pub async fn validate_client_credentials(
        &self,
        client_id: &str,
        client_secret: Option<&str>,
    ) -> Result<bool> {
        match self.client_credentials.get(client_id) {
            Some(credentials) if credentials.is_active => {
                if credentials.requires_secret() {
                    match client_secret {
                        Some(secret) => credentials.validate_secret(secret),
                        None => Ok(false), // Secret required but not provided
                    }
                } else {
                    Ok(true) // Public client, no secret required
                }
            }
            _ => Ok(false), // Client not found or inactive
        }
    }

    // Cleanup operations
    pub async fn cleanup_expired_tokens(&mut self) -> Result<usize> {
        let initial_count = self.refresh_tokens.len() + self.authorization_codes.len();

        // Remove expired refresh tokens
        self.refresh_tokens.retain(|_, token| token.is_valid());

        // Remove expired authorization codes
        self.authorization_codes.retain(|_, code| code.is_valid());

        let final_count = self.refresh_tokens.len() + self.authorization_codes.len();
        Ok(initial_count - final_count)
    }

    // User credential management methods

    /// Get user credentials for authentication
    pub async fn get_user_credentials(&self, username: &str) -> Result<Option<UserCredentials>> {
        // For demo purposes, use pre-computed bcrypt hashes for known users
        // In production, this would query a database with pre-hashed passwords
        let demo_users = [
            (
                "admin",
                "$2b$12$UfM9FwL8dbLOFTOmL8kAVOUe8.mFYGsqtaEjpMrS6yOGhN6SHL6me", // hash of "admin_password_123456789"
                vec!["read", "write", "admin", "delete"],
            ),
            (
                "user",
                "$2b$12$3Jb05MyZ7QDS81DJkt3QLeyR9z.S9yQqULr42kZ5F5crUYbwJaXdW", // hash of "user_password_123456789"
                vec!["read", "write"],
            ),
            (
                "test",
                "$2b$12$bM6NV4EQdo8kJHUhhZGpIuIsalt4eD9J8co0KyO6pzEPX0ClONwTy", // hash of "test_password_123456789"
                vec!["read"],
            ),
        ];

        for (demo_user, password_hash, demo_scopes) in &demo_users {
            if username == *demo_user {
                return Ok(Some(UserCredentials {
                    username: username.to_string(),
                    password_hash: password_hash.to_string(),
                    scopes: demo_scopes.iter().map(|s| s.to_string()).collect(),
                    is_active: true,
                }));
            }
        }

        Ok(None)
    }

    /// Get user permissions/scopes
    pub async fn get_user_permissions(&self, username: &str) -> Result<Option<UserPermissions>> {
        // Get credentials which include permissions
        if let Some(credentials) = self.get_user_credentials(username).await? {
            Ok(Some(UserPermissions {
                username: credentials.username,
                scopes: credentials.scopes,
                is_active: credentials.is_active,
            }))
        } else {
            Ok(None)
        }
    }
}

/// User credentials stored in the system
#[derive(Clone, Serialize, Deserialize)]
pub struct UserCredentials {
    pub username: String,
    pub password_hash: String, // In production: bcrypt/argon2 hash
    pub scopes: Vec<String>,
    pub is_active: bool,
}

impl std::fmt::Debug for UserCredentials {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("UserCredentials");
        d.field("username", &self.username);
        d.field(
            "password_hash",
            &crate::utils::redact::redacted(&self.password_hash),
        );
        d.field("scopes", &self.scopes);
        d.field("is_active", &self.is_active);
        d.finish()
    }
}

/// User permissions/scopes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserPermissions {
    pub username: String,
    pub scopes: Vec<String>,
    pub is_active: bool,
}

impl Default for EnhancedTokenStorage {
    fn default() -> Self {
        Self::new()
    }
}