jwt-verify 0.1.0

JWT verification library for AWS Cognito tokens and any OIDC-compatible IDP
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
use std::fmt;
use anyhow::{Error as AnyhowError, Result as AnyhowResult};

/// Detailed error types for JWT verification failures
#[derive(Debug)]
pub enum JwtError {
    /// Token has expired
    ExpiredToken {
        /// When the token expired (Unix timestamp)
        exp: Option<u64>,
        /// Current time when validation was performed (Unix timestamp)
        current_time: Option<u64>,
    },
    /// Token is not yet valid (nbf claim)
    TokenNotYetValid {
        /// When the token becomes valid (Unix timestamp)
        nbf: Option<u64>,
        /// Current time when validation was performed (Unix timestamp)
        current_time: Option<u64>,
    },
    /// Token signature is invalid
    InvalidSignature,
    /// A specific claim is invalid
    InvalidClaim {
        /// The name of the claim that is invalid
        claim: String,
        /// The reason why the claim is invalid
        reason: String,
        /// The value of the claim, if available
        value: Option<String>,
    },
    /// Token issuer is invalid
    InvalidIssuer {
        /// The expected issuer
        expected: String,
        /// The actual issuer in the token
        actual: String,
    },
    /// Token client ID is invalid
    InvalidClientId {
        /// The expected client ID(s)
        expected: Vec<String>,
        /// The actual client ID in the token
        actual: String,
    },
    /// Token use is invalid
    InvalidTokenUse {
        /// The expected token use
        expected: String,
        /// The actual token use in the token
        actual: String,
    },
    /// JWK key not found
    KeyNotFound(String),
    /// Error fetching JWKs
    JwksFetchError {
        /// The URL that was being fetched
        url: Option<String>,
        /// The error message
        error: String,
    },
    /// Error parsing token
    ParseError {
        /// The part of the token that failed to parse (header, payload, signature)
        part: Option<String>,
        /// The error message
        error: String,
    },
    /// Configuration error
    ConfigurationError {
        /// The parameter that has an invalid configuration
        parameter: Option<String>,
        /// The error message
        error: String,
    },
    /// Missing token
    MissingToken,
    /// Unsupported token type
    UnsupportedTokenType {
        /// The token type that was provided
        token_type: String,
    },
    /// Generic token error
    InvalidToken(String),
    /// Unexpected error
    UnexpectedError(String),
}

impl fmt::Display for JwtError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JwtError::ExpiredToken { exp, current_time } => {
                if let (Some(exp), Some(current_time)) = (exp, current_time) {
                    write!(f, "Token has expired at {} (current time: {})", exp, current_time)
                } else {
                    write!(f, "Token has expired")
                }
            },
            JwtError::TokenNotYetValid { nbf, current_time } => {
                if let (Some(nbf), Some(current_time)) = (nbf, current_time) {
                    write!(f, "Token is not yet valid until {} (current time: {})", nbf, current_time)
                } else {
                    write!(f, "Token is not yet valid")
                }
            },
            JwtError::InvalidSignature => write!(f, "Token signature is invalid"),
            JwtError::InvalidClaim { claim, reason, value } => {
                if let Some(value) = value {
                    write!(f, "Invalid claim '{}': {} (value: '{}')", claim, reason, value)
                } else {
                    write!(f, "Invalid claim '{}': {}", claim, reason)
                }
            },
            JwtError::InvalidIssuer { expected, actual } => {
                write!(f, "Invalid issuer: expected '{}', got '{}'", expected, actual)
            },
            JwtError::InvalidClientId { expected, actual } => {
                write!(f, "Invalid client ID: expected one of {:?}, got '{}'", expected, actual)
            },
            JwtError::InvalidTokenUse { expected, actual } => {
                write!(f, "Invalid token use: expected '{}', got '{}'", expected, actual)
            },
            JwtError::KeyNotFound(kid) => write!(f, "JWK not found for key ID: {}", kid),
            JwtError::JwksFetchError { url, error } => {
                if let Some(url) = url {
                    write!(f, "Failed to fetch JWKs from {}: {}", url, error)
                } else {
                    write!(f, "Failed to fetch JWKs: {}", error)
                }
            },
            JwtError::ParseError { part, error } => {
                if let Some(part) = part {
                    write!(f, "Failed to parse token {}: {}", part, error)
                } else {
                    write!(f, "Failed to parse token: {}", error)
                }
            },
            JwtError::ConfigurationError { parameter, error } => {
                if let Some(parameter) = parameter {
                    write!(f, "Configuration error for '{}': {}", parameter, error)
                } else {
                    write!(f, "Configuration error: {}", error)
                }
            },
            JwtError::MissingToken => write!(f, "Token is missing"),
            JwtError::UnsupportedTokenType { token_type } => {
                write!(f, "Unsupported token type: {}", token_type)
            },
            JwtError::InvalidToken(err) => write!(f, "Invalid token: {}", err),
            JwtError::UnexpectedError(err) => write!(f, "Unexpected error: {}", err),
        }
    }
}

impl std::error::Error for JwtError {}

impl From<jsonwebtoken::errors::Error> for JwtError {
    fn from(err: jsonwebtoken::errors::Error) -> Self {
        use jsonwebtoken::errors::ErrorKind;
        match err.kind() {
            ErrorKind::ExpiredSignature => JwtError::ExpiredToken {
                exp: None,
                current_time: None,
            },
            ErrorKind::InvalidSignature => JwtError::InvalidSignature,
            ErrorKind::InvalidToken => JwtError::InvalidToken("Token format is invalid".to_string()),
            ErrorKind::InvalidIssuer => JwtError::InvalidIssuer {
                expected: "unknown".to_string(),
                actual: "unknown".to_string(),
            },
            ErrorKind::InvalidAudience => JwtError::InvalidClaim {
                claim: "aud".to_string(),
                reason: "Audience is invalid".to_string(),
                value: None,
            },
            ErrorKind::InvalidSubject => JwtError::InvalidClaim {
                claim: "sub".to_string(),
                reason: "Subject is invalid".to_string(),
                value: None,
            },
            ErrorKind::ImmatureSignature => JwtError::TokenNotYetValid {
                nbf: None,
                current_time: None,
            },
            ErrorKind::InvalidAlgorithm => JwtError::InvalidClaim {
                claim: "alg".to_string(),
                reason: "Algorithm is invalid".to_string(),
                value: None,
            },
            _ => JwtError::ParseError {
                part: None,
                error: format!("{}", err),
            },
        }
    }
}

impl From<reqwest::Error> for JwtError {
    fn from(err: reqwest::Error) -> Self {
        let url = err.url().map(|u| u.to_string());
        JwtError::JwksFetchError {
            url,
            error: format!("{}", err),
        }
    }
}

impl From<serde_json::Error> for JwtError {
    fn from(err: serde_json::Error) -> Self {
        JwtError::ParseError {
            part: Some("payload".to_string()),
            error: format!("JSON error: {}", err),
        }
    }
}

impl From<AnyhowError> for JwtError {
    fn from(err: AnyhowError) -> Self {
        JwtError::UnexpectedError(format!("{}", err))
    }
}

impl From<std::io::Error> for JwtError {
    fn from(err: std::io::Error) -> Self {
        JwtError::UnexpectedError(format!("IO error: {}", err))
    }
}

impl From<base64::DecodeError> for JwtError {
    fn from(err: base64::DecodeError) -> Self {
        JwtError::ParseError {
            part: Some("base64".to_string()),
            error: format!("Base64 decode error: {}", err),
        }
    }
}

impl From<std::str::Utf8Error> for JwtError {
    fn from(err: std::str::Utf8Error) -> Self {
        JwtError::ParseError {
            part: Some("utf8".to_string()),
            error: format!("UTF-8 decode error: {}", err),
        }
    }
}

/// Public error type that sanitizes error details for client responses
#[derive(Debug)]
pub enum PublicJwtError {
    /// Generic invalid token error
    InvalidToken,
}

impl fmt::Display for PublicJwtError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PublicJwtError::InvalidToken => write!(f, "Invalid authentication token"),
        }
    }
}

impl std::error::Error for PublicJwtError {}

impl From<JwtError> for PublicJwtError {
    fn from(_err: JwtError) -> Self {
        // All errors map to a single generic error to avoid leaking sensitive information
        PublicJwtError::InvalidToken
    }
}

/// Error logger with configurable verbosity
#[derive(Debug)]
pub struct ErrorLogger {
    verbosity: ErrorVerbosity,
}

/// Error verbosity levels
#[derive(Debug, Clone, Copy)]
pub enum ErrorVerbosity {
    /// Only log error type
    Minimal,
    /// Log error type and general context
    Standard,
    /// Log all error details including specific claims
    Detailed,
}

impl Default for ErrorVerbosity {
    fn default() -> Self {
        Self::Standard
    }
}

impl ErrorLogger {
    /// Create a new error logger with the specified verbosity
    pub fn new(verbosity: ErrorVerbosity) -> Self {
        Self { verbosity }
    }

    /// Create a new error logger with default verbosity (Standard)
    pub fn default() -> Self {
        Self {
            verbosity: ErrorVerbosity::default(),
        }
    }

    /// Log an error with the configured verbosity
    pub fn log(&self, error: &JwtError) {
        match self.verbosity {
            ErrorVerbosity::Minimal => {
                // Minimal logging just shows the error type without details
                let error_type = match error {
                    JwtError::ExpiredToken { .. } => "ExpiredToken",
                    JwtError::TokenNotYetValid { .. } => "TokenNotYetValid",
                    JwtError::InvalidSignature => "InvalidSignature",
                    JwtError::InvalidClaim { .. } => "InvalidClaim",
                    JwtError::InvalidIssuer { .. } => "InvalidIssuer",
                    JwtError::InvalidClientId { .. } => "InvalidClientId",
                    JwtError::InvalidTokenUse { .. } => "InvalidTokenUse",
                    JwtError::KeyNotFound(_) => "KeyNotFound",
                    JwtError::JwksFetchError { .. } => "JwksFetchError",
                    JwtError::ParseError { .. } => "ParseError",
                    JwtError::ConfigurationError { .. } => "ConfigurationError",
                    JwtError::MissingToken => "MissingToken",
                    JwtError::UnsupportedTokenType { .. } => "UnsupportedTokenType",
                    JwtError::InvalidToken(_) => "InvalidToken",
                    JwtError::UnexpectedError(_) => "UnexpectedError",
                };
                tracing::error!("JWT verification error: {}", error_type);
            }
            ErrorVerbosity::Standard => {
                // Standard logging includes more context but omits sensitive values
                match error {
                    JwtError::ExpiredToken { exp, current_time } => {
                        if let (Some(exp), Some(current_time)) = (exp, current_time) {
                            tracing::error!("JWT verification error: Token expired at {} (current time: {})", exp, current_time);
                        } else {
                            tracing::error!("JWT verification error: Token has expired");
                        }
                    }
                    JwtError::TokenNotYetValid { nbf, current_time } => {
                        if let (Some(nbf), Some(current_time)) = (nbf, current_time) {
                            tracing::error!("JWT verification error: Token not valid until {} (current time: {})", nbf, current_time);
                        } else {
                            tracing::error!("JWT verification error: Token is not yet valid");
                        }
                    }
                    JwtError::InvalidSignature => {
                        tracing::error!("JWT verification error: Invalid signature");
                    }
                    JwtError::InvalidClaim { claim, reason, .. } => {
                        tracing::error!("JWT verification error: Invalid claim '{}': {}", claim, reason);
                    }
                    JwtError::InvalidIssuer { expected, actual } => {
                        tracing::error!("JWT verification error: Invalid issuer, expected '{}', got '{}'", expected, actual);
                    }
                    JwtError::InvalidClientId { expected, actual } => {
                        tracing::error!("JWT verification error: Invalid client ID, expected one of {:?}, got '{}'", expected, actual);
                    }
                    JwtError::InvalidTokenUse { expected, actual } => {
                        tracing::error!(
                            "JWT verification error: Invalid token use, expected '{}', got '{}'",
                            expected, actual
                        );
                    }
                    JwtError::KeyNotFound(kid) => {
                        tracing::error!("JWT verification error: Key not found for ID '{}'", kid);
                    }
                    JwtError::JwksFetchError { url, error } => {
                        if let Some(url) = url {
                            tracing::error!("JWT verification error: Failed to fetch JWKs from {}: {}", url, error);
                        } else {
                            tracing::error!("JWT verification error: Failed to fetch JWKs: {}", error);
                        }
                    }
                    JwtError::ParseError { part, error } => {
                        if let Some(part) = part {
                            tracing::error!("JWT verification error: Failed to parse token {}: {}", part, error);
                        } else {
                            tracing::error!("JWT verification error: Failed to parse token: {}", error);
                        }
                    }
                    JwtError::ConfigurationError { parameter, error } => {
                        if let Some(parameter) = parameter {
                            tracing::error!("JWT verification error: Configuration error for '{}': {}", parameter, error);
                        } else {
                            tracing::error!("JWT verification error: Configuration error: {}", error);
                        }
                    }
                    JwtError::MissingToken => {
                        tracing::error!("JWT verification error: Token is missing");
                    }
                    JwtError::UnsupportedTokenType { token_type } => {
                        tracing::error!("JWT verification error: Unsupported token type: {}", token_type);
                    }
                    JwtError::InvalidToken(err) => {
                        tracing::error!("JWT verification error: Invalid token: {}", err);
                    }
                    JwtError::UnexpectedError(err) => {
                        tracing::error!("JWT verification error: Unexpected error: {}", err);
                    }
                }
            }
            ErrorVerbosity::Detailed => {
                // Detailed logging includes all available information
                // This should only be used in development environments
                tracing::error!("JWT verification error: {:?}", error);
                
                // Add additional context based on error type
                match error {
                    JwtError::ExpiredToken { exp, current_time } => {
                        tracing::debug!("Token expiration details - exp: {:?}, current_time: {:?}", exp, current_time);
                    }
                    JwtError::InvalidClaim { claim, reason, value } => {
                        tracing::debug!("Invalid claim details - claim: {}, reason: {}, value: {:?}", claim, reason, value);
                    }
                    JwtError::JwksFetchError { url, error } => {
                        tracing::debug!("JWK fetch error details - url: {:?}, error: {}", url, error);
                    }
                    _ => {}
                }
            }
        }
    }

    /// Convert an internal error to a public error
    pub fn to_public_error(&self, error: JwtError) -> PublicJwtError {
        // Log the error with the configured verbosity
        self.log(&error);
        
        // All errors map to a single generic error to avoid leaking sensitive information
        PublicJwtError::InvalidToken
    }
    
    /// Sanitize an error message for public consumption
    pub fn sanitize_error_message(&self, _error: &JwtError) -> String {
        // All errors map to a single generic message to avoid leaking sensitive information
        "Invalid authentication token".to_string()
    }
    
    /// Get the appropriate HTTP status code for an error
    pub fn status_code_for_error(&self, error: &JwtError) -> u16 {
        match error {
            JwtError::KeyNotFound(_) => 500, // Internal Server Error
            JwtError::JwksFetchError { .. } => 500, // Internal Server Error
            JwtError::ConfigurationError { .. } => 500, // Internal Server Error
            JwtError::UnexpectedError(_) => 500, // Internal Server Error
            _ => 401, // Unauthorized
        }
    }
}

/// Result type for JWT verification operations
pub type Result<T> = AnyhowResult<T>;