auth-framework 0.4.2

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
//! 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()
            .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(())
            }
            _ => Ok(()), // Allow other token types
        }
    }

    /// 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
/// use auth_framework::server::core::common_validation::collect_validation_errors;
///
/// 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("; ")))
    }
}