Skip to main content

auth_framework/security/
secure_jwt.rs

1use crate::errors::Result;
2use jsonwebtoken::{Algorithm, DecodingKey};
3use serde::{Deserialize, Serialize};
4use std::collections::HashSet;
5use std::time::Duration;
6
7#[derive(Clone, Serialize, Deserialize)]
8pub struct SecureJwtClaims {
9    pub sub: String,
10    pub iss: String,
11    pub aud: String,
12    pub exp: i64,
13    pub nbf: i64,
14    pub iat: i64,
15    pub jti: String,
16    pub scope: String,
17    pub typ: String,
18    pub sid: Option<String>,
19    pub client_id: Option<String>,
20    pub auth_ctx_hash: Option<String>,
21}
22
23impl std::fmt::Debug for SecureJwtClaims {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        let mut d = f.debug_struct("SecureJwtClaims");
26        d.field("sub", &self.sub);
27        d.field("iss", &self.iss);
28        d.field("aud", &self.aud);
29        d.field("exp", &self.exp);
30        d.field("nbf", &self.nbf);
31        d.field("iat", &self.iat);
32        d.field("jti", &self.jti);
33        d.field("scope", &self.scope);
34        d.field("typ", &self.typ);
35        d.field("sid", &crate::utils::redact::redacted(&self.sid));
36        d.field("client_id", &self.client_id);
37        d.field("auth_ctx_hash", &self.auth_ctx_hash);
38        d.finish()
39    }
40}
41
42#[derive(Clone)]
43pub struct SecureJwtConfig {
44    pub allowed_algorithms: Vec<Algorithm>,
45    pub required_issuers: HashSet<String>,
46    pub required_audiences: HashSet<String>,
47    pub max_token_lifetime: Duration,
48    pub clock_skew: Duration,
49    pub require_jti: bool,
50    pub validate_nbf: bool,
51    pub allowed_token_types: HashSet<String>,
52    pub require_secure_transport: bool,
53    /// JWT signing/validation key
54    pub jwt_secret: String,
55}
56
57impl std::fmt::Debug for SecureJwtConfig {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        let mut d = f.debug_struct("SecureJwtConfig");
60        d.field("allowed_algorithms", &self.allowed_algorithms);
61        d.field("required_issuers", &self.required_issuers);
62        d.field("required_audiences", &self.required_audiences);
63        d.field("max_token_lifetime", &self.max_token_lifetime);
64        d.field("clock_skew", &self.clock_skew);
65        d.field("require_jti", &self.require_jti);
66        d.field("validate_nbf", &self.validate_nbf);
67        d.field("allowed_token_types", &self.allowed_token_types);
68        d.field("require_secure_transport", &self.require_secure_transport);
69        d.field(
70            "jwt_secret",
71            &crate::utils::redact::redacted(&self.jwt_secret),
72        );
73        d.finish()
74    }
75}
76
77impl Default for SecureJwtConfig {
78    fn default() -> Self {
79        let mut allowed_token_types = HashSet::new();
80        allowed_token_types.insert("access".to_string());
81        allowed_token_types.insert("refresh".to_string());
82        allowed_token_types.insert("JARM".to_string());
83
84        let mut required_issuers = HashSet::new();
85        required_issuers.insert("auth-framework".to_string());
86
87        Self {
88            allowed_algorithms: vec![Algorithm::HS256, Algorithm::RS256, Algorithm::ES256],
89            required_issuers,
90            required_audiences: HashSet::new(),
91            max_token_lifetime: Duration::from_secs(3600),
92            clock_skew: Duration::from_secs(30),
93            require_jti: true,
94            validate_nbf: true,
95            allowed_token_types,
96            require_secure_transport: false,
97            jwt_secret: "CHANGE_THIS_IN_PRODUCTION_USE_PROPER_KEY_MANAGEMENT".to_string(),
98        }
99    }
100}
101
102pub struct SecureJwtValidator {
103    config: SecureJwtConfig,
104    revoked_tokens: std::sync::Mutex<std::collections::HashSet<String>>,
105}
106
107impl std::fmt::Debug for SecureJwtValidator {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        let mut d = f.debug_struct("SecureJwtValidator");
110        d.field("config", &self.config);
111        d.field(
112            "revoked_tokens",
113            &crate::utils::redact::redacted(&self.revoked_tokens),
114        );
115        d.finish()
116    }
117}
118
119impl SecureJwtValidator {
120    pub fn new(config: SecureJwtConfig) -> Self {
121        Self {
122            config,
123            revoked_tokens: std::sync::Mutex::new(std::collections::HashSet::new()),
124        }
125    }
126
127    /// Get decoding key for JWT validation
128    pub fn get_decoding_key(&self) -> jsonwebtoken::DecodingKey {
129        jsonwebtoken::DecodingKey::from_secret(self.config.jwt_secret.as_bytes())
130    }
131
132    pub fn validate_token(
133        &self,
134        token: &str,
135        decoding_key: &DecodingKey,
136        verify_signature: bool,
137    ) -> Result<SecureJwtClaims> {
138        use jsonwebtoken::{Algorithm, Validation, decode};
139
140        // Create validation with signature verification
141        let mut validation = Validation::new(Algorithm::HS256);
142        validation.validate_exp = false; // Let our custom validation handle expiry
143        validation.validate_aud = false; // Let our custom validation handle audience
144        validation.validate_nbf = false; // Let our custom validation handle not before
145
146        if !verify_signature {
147            validation.insecure_disable_signature_validation();
148        }
149
150        // Decode and validate the JWT
151        match decode::<SecureJwtClaims>(token, decoding_key, &validation) {
152            Ok(token_data) => {
153                let claims = token_data.claims;
154
155                // Check if token is revoked
156                if self.is_token_revoked(&claims.jti)? {
157                    return Err(crate::errors::AuthError::Unauthorized(
158                        "Token is revoked".to_string(),
159                    ));
160                }
161
162                // Additional custom validations can be added here
163
164                Ok(claims)
165            }
166            Err(e) => Err(crate::errors::AuthError::Unauthorized(format!(
167                "JWT validation failed: {}",
168                e
169            ))),
170        }
171    }
172
173    pub fn is_token_revoked(&self, jti: &str) -> Result<bool> {
174        let revoked_tokens = self.revoked_tokens.lock().unwrap();
175        Ok(revoked_tokens.contains(jti))
176    }
177
178    pub fn revoke_token(&self, jti: &str) -> Result<()> {
179        let mut revoked_tokens = self.revoked_tokens.lock().unwrap();
180        revoked_tokens.insert(jti.to_string());
181        Ok(())
182    }
183
184    pub fn cleanup_revoked_tokens(&self, _expired_cutoff: std::time::SystemTime) -> Result<()> {
185        // For production, this would actually clean up expired tokens
186        // For testing, we'll just keep them all for simplicity
187        Ok(())
188    }
189}