auth-framework 0.5.0-rc18

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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Common Validation Utilities
//!
//! This module provides shared validation functions to eliminate
//! duplication across server modules.

use crate::errors::{AuthError, Result};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

/// Common JWT validation utilities
pub mod jwt {
    use super::*;
    use jsonwebtoken::decode_header;

    /// Validate JWT structure and format
    pub fn validate_jwt_format(token: &str) -> Result<()> {
        if token.is_empty() {
            return Err(AuthError::validation("JWT token is empty"));
        }

        let parts: Vec<&str> = token.split('.').collect();
        if parts.len() != 3 {
            return Err(AuthError::validation(
                "Invalid JWT format: must have 3 parts",
            ));
        }

        // Validate header can be decoded
        decode_header(token)
            .map_err(|e| AuthError::validation(format!("Invalid JWT header: {}", e)))?;

        Ok(())
    }

    /// Extract claims without signature validation (for inspection ONLY)
    ///
    /// # Security Warning
    /// This function does NOT validate the JWT signature, making it vulnerable to:
    /// - Token forgery
    /// - Data tampering
    /// - Man-in-the-middle attacks
    ///
    /// Only use for:
    /// - Token inspection/debugging
    /// - Extracting metadata before validation
    /// - Non-security-critical operations
    ///
    /// Never use for authentication or authorization decisions!
    pub fn extract_claims_unsafe(token: &str) -> Result<serde_json::Value> {
        validate_jwt_format(token)?;

        let parts: Vec<&str> = token.split('.').collect();
        let payload = parts[1];

        use base64::Engine as _;
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;

        let decoded = URL_SAFE_NO_PAD
            .decode(payload)
            .map_err(|e| AuthError::validation(format!("Invalid JWT payload encoding: {}", e)))?;

        let claims: serde_json::Value = serde_json::from_slice(&decoded)
            .map_err(|e| AuthError::validation(format!("Invalid JWT payload JSON: {}", e)))?;

        Ok(claims)
    }

    /// Validate JWT timestamp claims (exp, iat, nbf)
    pub fn validate_time_claims(claims: &serde_json::Value) -> Result<()> {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64;

        // Check expiration
        if let Some(exp) = claims.get("exp").and_then(|v| v.as_i64())
            && now >= exp
        {
            return Err(AuthError::validation("Token has expired"));
        }

        // Check not before
        if let Some(nbf) = claims.get("nbf").and_then(|v| v.as_i64())
            && now < nbf
        {
            return Err(AuthError::validation("Token not yet valid (nbf)"));
        }

        // Check issued at (reasonable bounds)
        if let Some(iat) = claims.get("iat").and_then(|v| v.as_i64()) {
            let max_age = 24 * 60 * 60; // 24 hours
            if now - iat > max_age {
                return Err(AuthError::validation("Token too old"));
            }
        }

        Ok(())
    }

    /// Validate required JWT claims
    pub fn validate_required_claims(claims: &serde_json::Value, required: &[&str]) -> Result<()> {
        for claim in required {
            if claims.get(claim).is_none() {
                return Err(AuthError::validation(format!(
                    "Missing required claim: {}",
                    claim
                )));
            }
        }
        Ok(())
    }
}

/// Common token validation utilities
pub mod token {
    use super::*;

    /// Token type validation
    pub fn validate_token_type(token_type: &str, allowed_types: &[&str]) -> Result<()> {
        if !allowed_types.contains(&token_type) {
            return Err(AuthError::validation(format!(
                "Unsupported token type: {}",
                token_type
            )));
        }
        Ok(())
    }

    /// Validate token format (basic structure)
    pub fn validate_token_format(token: &str, token_type: &str) -> Result<()> {
        if token.is_empty() {
            return Err(AuthError::validation("Token is empty"));
        }

        match token_type {
            "urn:ietf:params:oauth:token-type:jwt" => jwt::validate_jwt_format(token),
            "urn:ietf:params:oauth:token-type:access_token" => {
                // Bearer token validation
                if token.len() < 10 {
                    return Err(AuthError::validation("Access token too short"));
                }
                Ok(())
            }
            "urn:ietf:params:oauth:token-type:refresh_token" => {
                // Refresh token validation
                if token.len() < 20 {
                    return Err(AuthError::validation("Refresh token too short"));
                }
                Ok(())
            }
            _ => {
                // Reject unrecognized token types rather than silently accepting them.
                Err(AuthError::validation(format!(
                    "Unsupported token type: {}",
                    token_type
                )))
            }
        }
    }

    /// Validate scope format
    pub fn validate_scope(scope: &str) -> Result<Vec<String>> {
        if scope.is_empty() {
            return Ok(vec![]);
        }

        let scopes: Vec<String> = scope.split_whitespace().map(|s| s.to_string()).collect();

        // Validate each scope
        for scope in &scopes {
            if scope.is_empty() {
                return Err(AuthError::validation("Empty scope value"));
            }

            // Basic scope format validation
            if !scope.chars().all(|c| {
                c.is_alphanumeric() || c == ':' || c == '/' || c == '.' || c == '-' || c == '_'
            }) {
                return Err(AuthError::validation(format!(
                    "Invalid scope format: {}",
                    scope
                )));
            }
        }

        Ok(scopes)
    }
}

/// Common client validation utilities
pub mod client {
    use super::*;

    /// Validate client ID format
    pub fn validate_client_id(client_id: &str) -> Result<()> {
        if client_id.is_empty() {
            return Err(AuthError::validation("Client ID is empty"));
        }

        if client_id.len() < 3 {
            return Err(AuthError::validation("Client ID too short"));
        }

        if client_id.len() > 255 {
            return Err(AuthError::validation("Client ID too long"));
        }

        // Validate character set
        if !client_id
            .chars()
            .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.')
        {
            return Err(AuthError::validation(
                "Client ID contains invalid characters",
            ));
        }

        Ok(())
    }

    /// Validate redirect URI
    pub fn validate_redirect_uri(uri: &str) -> Result<()> {
        if uri.is_empty() {
            return Err(AuthError::validation("Redirect URI is empty"));
        }

        // Must be absolute URI
        if !uri.starts_with("http://")
            && !uri.starts_with("https://")
            && !uri.starts_with("custom://")
        {
            return Err(AuthError::validation("Redirect URI must be absolute"));
        }

        // No fragments allowed
        if uri.contains('#') {
            return Err(AuthError::validation(
                "Redirect URI cannot contain fragments",
            ));
        }

        Ok(())
    }

    /// Validate grant type
    pub fn validate_grant_type(grant_type: &str, allowed_grants: &[&str]) -> Result<()> {
        if !allowed_grants.contains(&grant_type) {
            return Err(AuthError::validation(format!(
                "Unsupported grant type: {}",
                grant_type
            )));
        }
        Ok(())
    }
}

/// Common request validation utilities
pub mod request {
    use super::*;

    /// Validate required parameters
    pub fn validate_required_params(
        params: &HashMap<String, String>,
        required: &[&str],
    ) -> Result<()> {
        for param in required {
            if !params.contains_key(*param) || params[*param].trim().is_empty() {
                return Err(AuthError::validation(format!(
                    "Missing parameter: {}",
                    param
                )));
            }
        }
        Ok(())
    }

    /// Validate parameter format
    pub fn validate_param_format(value: &str, param_name: &str, pattern: &str) -> Result<()> {
        // Basic validation without regex for now
        if value.is_empty() {
            return Err(AuthError::validation(format!(
                "Parameter {} cannot be empty",
                param_name
            )));
        }

        // Basic pattern checks
        match pattern {
            "alphanum" => {
                if !value.chars().all(|c| c.is_alphanumeric()) {
                    return Err(AuthError::validation(format!(
                        "Parameter {} must be alphanumeric",
                        param_name
                    )));
                }
            }
            _ => {
                // For now, just check it's not empty
                if value.trim().is_empty() {
                    return Err(AuthError::validation(format!(
                        "Parameter {} has invalid format",
                        param_name
                    )));
                }
            }
        }

        Ok(())
    }

    /// Validate code challenge method
    pub fn validate_code_challenge_method(method: &str) -> Result<()> {
        match method {
            "plain" | "S256" => Ok(()),
            _ => Err(AuthError::validation("Invalid code challenge method")),
        }
    }

    /// Validate response type
    pub fn validate_response_type(response_type: &str, allowed_types: &[&str]) -> Result<()> {
        let types: Vec<&str> = response_type.split_whitespace().collect();

        for response_type in &types {
            if !allowed_types.contains(response_type) {
                return Err(AuthError::validation(format!(
                    "Unsupported response type: {}",
                    response_type
                )));
            }
        }

        Ok(())
    }
}

/// Common URL validation utilities
pub mod url {
    use super::*;

    /// Validate URL format and accessibility
    pub fn validate_url_format(url: &str) -> Result<()> {
        if url.is_empty() {
            return Err(AuthError::validation("URL is empty"));
        }

        if !url.starts_with("http://") && !url.starts_with("https://") {
            return Err(AuthError::validation("URL must use HTTP or HTTPS scheme"));
        }

        // Basic URL parsing validation - simplified without url crate for now
        if !url.contains("://") {
            return Err(AuthError::validation("Invalid URL format"));
        }

        Ok(())
    }

    /// Validate HTTPS requirement
    pub fn validate_https_required(url: &str) -> Result<()> {
        validate_url_format(url)?;

        if !url.starts_with("https://") {
            return Err(AuthError::validation("HTTPS is required"));
        }

        Ok(())
    }
}

/// Collects and aggregates validation errors from multiple validation operations.
///
/// This function takes a vector of validation results and combines any errors
/// into a single error message. If all validations pass, returns Ok(()).
/// If any validations fail, returns an error containing all error messages.
///
/// # Arguments
///
/// * `validations` - A vector of validation results to aggregate
///
/// # Returns
///
/// * `Ok(())` if all validations passed
/// * `Err(AuthError)` containing aggregated error messages if any validations failed
///
/// # Example
///
/// ```rust,no_run
/// use auth_framework::server::core::common_validation::collect_validation_errors;
/// use auth_framework::errors::Result;
///
/// # fn validate_client_id(_: &str) -> Result<()> { Ok(()) }
/// # fn validate_scope(_: &str) -> Result<()> { Ok(()) }
/// # fn validate_redirect_uri(_: &str) -> Result<()> { Ok(()) }
/// let validations = vec![
///     validate_client_id("valid_client"),
///     validate_scope("read write"),
///     validate_redirect_uri("https://example.com/callback"),
/// ];
///
/// let result = collect_validation_errors(validations);
/// match result {
///     Ok(()) => println!("All validations passed"),
///     Err(e) => println!("Validation errors: {}", e),
/// }
/// ```
pub fn collect_validation_errors(validations: Vec<Result<()>>) -> Result<()> {
    let errors: Vec<String> = validations
        .into_iter()
        .filter_map(|result| result.err())
        .map(|e| format!("{}", e))
        .collect();

    if errors.is_empty() {
        Ok(())
    } else {
        Err(AuthError::validation(errors.join("; ")))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    // ── JWT validation ──────────────────────────────────────────────────

    #[test]
    fn test_validate_jwt_format_empty() {
        assert!(jwt::validate_jwt_format("").is_err());
    }

    #[test]
    fn test_validate_jwt_format_wrong_parts() {
        assert!(jwt::validate_jwt_format("one.two").is_err());
        assert!(jwt::validate_jwt_format("a.b.c.d").is_err());
    }

    #[test]
    fn test_validate_required_claims_missing() {
        let claims = json!({"sub": "user1"});
        assert!(jwt::validate_required_claims(&claims, &["sub"]).is_ok());
        assert!(jwt::validate_required_claims(&claims, &["aud"]).is_err());
    }

    #[test]
    fn test_validate_time_claims_expired() {
        let claims = json!({"exp": 1000000});
        assert!(jwt::validate_time_claims(&claims).is_err());
    }

    #[test]
    fn test_validate_time_claims_future_nbf() {
        let far_future = (SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 999999) as i64;
        let claims = json!({"nbf": far_future});
        assert!(jwt::validate_time_claims(&claims).is_err());
    }

    #[test]
    fn test_validate_time_claims_valid_no_claims() {
        let claims = json!({});
        assert!(jwt::validate_time_claims(&claims).is_ok());
    }

    // ── Token validation ────────────────────────────────────────────────

    #[test]
    fn test_validate_token_type_success() {
        assert!(token::validate_token_type("bearer", &["bearer", "dpop"]).is_ok());
    }

    #[test]
    fn test_validate_token_type_unsupported() {
        assert!(token::validate_token_type("mac", &["bearer"]).is_err());
    }

    #[test]
    fn test_validate_token_format_empty() {
        assert!(token::validate_token_format("", "anything").is_err());
    }

    #[test]
    fn test_validate_token_format_access_token_too_short() {
        assert!(
            token::validate_token_format("short", "urn:ietf:params:oauth:token-type:access_token")
                .is_err()
        );
    }

    #[test]
    fn test_validate_token_format_refresh_token_too_short() {
        assert!(
            token::validate_token_format(
                "shorttoken",
                "urn:ietf:params:oauth:token-type:refresh_token"
            )
            .is_err()
        );
    }

    #[test]
    fn test_validate_scope_empty() {
        let scopes = token::validate_scope("").unwrap();
        assert!(scopes.is_empty());
    }

    #[test]
    fn test_validate_scope_valid() {
        let scopes = token::validate_scope("read write openid").unwrap();
        assert_eq!(scopes, vec!["read", "write", "openid"]);
    }

    #[test]
    fn test_validate_scope_invalid_chars() {
        assert!(token::validate_scope("read <script>").is_err());
    }

    // ── Client validation ───────────────────────────────────────────────

    #[test]
    fn test_validate_client_id_valid() {
        assert!(client::validate_client_id("my-client.app_01").is_ok());
    }

    #[test]
    fn test_validate_client_id_empty() {
        assert!(client::validate_client_id("").is_err());
    }

    #[test]
    fn test_validate_client_id_too_short() {
        assert!(client::validate_client_id("ab").is_err());
    }

    #[test]
    fn test_validate_client_id_too_long() {
        let long_id = "a".repeat(256);
        assert!(client::validate_client_id(&long_id).is_err());
    }

    #[test]
    fn test_validate_client_id_invalid_chars() {
        assert!(client::validate_client_id("my client!").is_err());
    }

    #[test]
    fn test_validate_redirect_uri_valid() {
        assert!(client::validate_redirect_uri("https://example.com/callback").is_ok());
        assert!(client::validate_redirect_uri("http://localhost:8080/cb").is_ok());
        assert!(client::validate_redirect_uri("custom://app/callback").is_ok());
    }

    #[test]
    fn test_validate_redirect_uri_empty() {
        assert!(client::validate_redirect_uri("").is_err());
    }

    #[test]
    fn test_validate_redirect_uri_not_absolute() {
        assert!(client::validate_redirect_uri("/callback").is_err());
    }

    #[test]
    fn test_validate_redirect_uri_with_fragment() {
        assert!(client::validate_redirect_uri("https://example.com/cb#section").is_err());
    }

    #[test]
    fn test_validate_grant_type_success() {
        assert!(
            client::validate_grant_type(
                "authorization_code",
                &["authorization_code", "refresh_token"]
            )
            .is_ok()
        );
    }

    #[test]
    fn test_validate_grant_type_unsupported() {
        assert!(client::validate_grant_type("implicit", &["authorization_code"]).is_err());
    }

    // ── Request validation ──────────────────────────────────────────────

    #[test]
    fn test_validate_required_params() {
        let mut params = HashMap::new();
        params.insert("code".to_string(), "abc123".to_string());
        assert!(request::validate_required_params(&params, &["code"]).is_ok());
        assert!(request::validate_required_params(&params, &["code", "state"]).is_err());
    }

    #[test]
    fn test_validate_required_params_empty_value() {
        let mut params = HashMap::new();
        params.insert("code".to_string(), "  ".to_string());
        assert!(request::validate_required_params(&params, &["code"]).is_err());
    }

    #[test]
    fn test_validate_param_format_alphanum() {
        assert!(request::validate_param_format("abc123", "nonce", "alphanum").is_ok());
        assert!(request::validate_param_format("abc-123", "nonce", "alphanum").is_err());
    }

    #[test]
    fn test_validate_param_format_empty() {
        assert!(request::validate_param_format("", "nonce", "alphanum").is_err());
    }

    #[test]
    fn test_validate_code_challenge_method() {
        assert!(request::validate_code_challenge_method("S256").is_ok());
        assert!(request::validate_code_challenge_method("plain").is_ok());
        assert!(request::validate_code_challenge_method("S512").is_err());
    }

    #[test]
    fn test_validate_response_type() {
        assert!(request::validate_response_type("code", &["code", "token"]).is_ok());
        assert!(request::validate_response_type("id_token", &["code"]).is_err());
    }

    // ── URL validation ──────────────────────────────────────────────────

    #[test]
    fn test_validate_url_format_valid() {
        assert!(url::validate_url_format("https://example.com").is_ok());
        assert!(url::validate_url_format("http://localhost:8080").is_ok());
    }

    #[test]
    fn test_validate_url_format_empty() {
        assert!(url::validate_url_format("").is_err());
    }

    #[test]
    fn test_validate_url_format_no_scheme() {
        assert!(url::validate_url_format("example.com").is_err());
    }

    #[test]
    fn test_validate_https_required() {
        assert!(url::validate_https_required("https://example.com").is_ok());
        assert!(url::validate_https_required("http://example.com").is_err());
    }

    // ── collect_validation_errors ────────────────────────────────────────

    #[test]
    fn test_collect_validation_errors_all_ok() {
        let validations = vec![Ok(()), Ok(())];
        assert!(collect_validation_errors(validations).is_ok());
    }

    #[test]
    fn test_collect_validation_errors_some_fail() {
        let validations = vec![
            Ok(()),
            Err(AuthError::validation("err1")),
            Err(AuthError::validation("err2")),
        ];
        let err = collect_validation_errors(validations).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("err1"));
        assert!(msg.contains("err2"));
    }
}