entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! OAuth token response parsing from JSON.
//!
//! Parses the JSON body returned by the token endpoint into a structured
//! [`TokenResponse`]. Handles both successful responses (with
//! `access_token`) and error responses (with `error` field).
//!
//! # Security
//!
//! SECURITY: The `access_token` and `refresh_token` are stored in
//! [`Zeroizing`] wrappers to clear them from memory on drop. The
//! [`Debug`] implementation redacts these values.
//!
//! [`Zeroizing`]: crate::crypto::zeroize::Zeroizing

use std::fmt;

use crate::crypto::zeroize::Zeroizing;
use crate::json::JsonValue;
use crate::util::log::{info, warn};

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// The category of token response parse failure.
#[derive(Debug, Clone, PartialEq, Eq)]
enum TokenResponseErrorKind {
    /// The JSON could not be parsed.
    InvalidJson,
    /// The response is a JSON object with an `error` field (OAuth error).
    OAuthError {
        /// The error code (e.g. `invalid_grant`).
        error: String,
        /// Optional human-readable description.
        description: Option<String>,
    },
    /// Required field `access_token` is missing.
    MissingAccessToken,
    /// Required field `token_type` is missing.
    MissingTokenType,
    /// The `expires_in` field is present but not a valid integer.
    InvalidExpiresIn,
}

/// Error returned when parsing a token endpoint response fails.
///
/// This can represent either a JSON parsing failure, a missing required
/// field, or an OAuth error response from the provider.
#[doc(alias = "token_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenResponseError {
    kind: TokenResponseErrorKind,
}

impl TokenResponseError {
    const fn new(kind: TokenResponseErrorKind) -> Self {
        Self { kind }
    }
}

impl fmt::Display for TokenResponseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            TokenResponseErrorKind::InvalidJson => {
                write!(f, "token response: invalid JSON")
            }
            TokenResponseErrorKind::OAuthError { error, description } => {
                write!(f, "token response: OAuth error: {error}")?;
                if let Some(desc) = description {
                    write!(f, " ({desc})")?;
                }
                Ok(())
            }
            TokenResponseErrorKind::MissingAccessToken => {
                write!(f, "token response: missing access_token")
            }
            TokenResponseErrorKind::MissingTokenType => {
                write!(f, "token response: missing token_type")
            }
            TokenResponseErrorKind::InvalidExpiresIn => {
                write!(f, "token response: invalid expires_in value")
            }
        }
    }
}

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

// ---------------------------------------------------------------------------
// TokenResponse
// ---------------------------------------------------------------------------

/// A parsed OAuth token endpoint response.
///
/// Contains the access token, token type, and optional fields per
/// RFC 6749 §5.1.
///
/// # Security
///
/// SECURITY: `access_token` and `refresh_token` are stored in
/// [`Zeroizing`] wrappers that clear memory on drop.
///
/// [`Zeroizing`]: crate::crypto::zeroize::Zeroizing
#[doc(alias = "token_response")]
pub struct TokenResponse {
    /// The access token issued by the authorization server.
    access_token: Zeroizing<String>,
    /// The type of the token (typically `"Bearer"`).
    token_type: String,
    /// The lifetime in seconds of the access token, if provided.
    expires_in: Option<u64>,
    /// The refresh token, if provided.
    refresh_token: Option<Zeroizing<String>>,
    /// The scope of the access token, if provided.
    scope: Option<String>,
    /// The `OpenID` Connect ID token (a signed JWT), if provided. Present when
    /// the `openid` scope was requested; carries the authenticated user's
    /// claims for the relying party to validate (see
    /// [`oidc::IdTokenValidator`](crate::oidc::IdTokenValidator)).
    id_token: Option<String>,
}

impl TokenResponse {
    /// Returns the access token.
    ///
    /// # Security
    ///
    /// SECURITY: The caller must take care not to log this value.
    #[must_use]
    #[inline]
    pub fn access_token(&self) -> &str {
        &self.access_token
    }

    /// Returns the token type (typically `"Bearer"`).
    ///
    /// The parser requires this field to be present but does **not** validate
    /// its value. Per RFC 6749 §7.1 a client must understand the token type
    /// before using the credential, so a caller that treats `access_token` as
    /// a bearer token MUST confirm this equals `"Bearer"` (case-insensitively).
    #[must_use]
    #[inline]
    pub fn token_type(&self) -> &str {
        &self.token_type
    }

    /// Returns the lifetime in seconds of the access token, if provided.
    #[must_use]
    #[inline]
    pub fn expires_in(&self) -> Option<u64> {
        self.expires_in
    }

    /// Returns the refresh token, if present.
    ///
    /// # Security
    ///
    /// SECURITY: The caller must take care not to log this value.
    #[must_use]
    #[inline]
    pub fn refresh_token(&self) -> Option<&str> {
        self.refresh_token.as_ref().map(|z| z.as_str())
    }

    /// Returns the scope of the access token, if provided.
    #[must_use]
    #[inline]
    pub fn scope(&self) -> Option<&str> {
        self.scope.as_deref()
    }

    /// Returns the `OpenID` Connect ID token (a signed JWT), if present.
    ///
    /// Validate it with [`oidc::IdTokenValidator`](crate::oidc::IdTokenValidator)
    /// — `validate_jwks` for public providers (Google, Microsoft, Okta) that
    /// sign with keys published at a JWKS endpoint.
    #[must_use]
    #[inline]
    pub fn id_token(&self) -> Option<&str> {
        self.id_token.as_deref()
    }
}

impl TokenResponse {
    /// Parses a JSON response body from the token endpoint.
    ///
    /// # OAuth error responses
    ///
    /// If the JSON contains an `error` field, this is treated as an OAuth
    /// error response per RFC 6749 §5.2 and an appropriate error is
    /// returned.
    ///
    /// # Errors
    ///
    /// Returns [`TokenResponseError`] if:
    /// - The JSON is invalid.
    /// - The response is an OAuth error.
    /// - Required fields (`access_token`, `token_type`) are missing.
    /// - The `expires_in` field is present but not a valid positive integer.
    #[must_use = "parsing may fail; handle the Result"]
    pub fn parse(json: &str) -> Result<Self, TokenResponseError> {
        let value = JsonValue::parse(json).map_err(|_| {
            warn!("oauth: token response parse failed: invalid JSON");
            TokenResponseError::new(TokenResponseErrorKind::InvalidJson)
        })?;

        // Check for OAuth error response first. RFC 6749 §5.2 defines an error
        // response by the *presence* of `error`, so gate on presence — not on
        // it being a string. A hostile endpoint returning a non-string `error`
        // (e.g. `{"error":123,"access_token":"..."}`) must not slip through as
        // a success; fall back to a placeholder code when it is not a string.
        if value.get("error").is_some() {
            let error = value.get_str("error").unwrap_or("invalid_error").to_owned();
            let description = value.get_str("error_description").map(String::from);
            // SECURITY: Log only the error code, never the token values.
            warn!(code = %error, "oauth: token endpoint error");
            return Err(TokenResponseError::new(
                TokenResponseErrorKind::OAuthError { error, description },
            ));
        }

        // SECURITY: Wrap access_token in Zeroizing immediately to minimize plaintext window.
        let access_token = Zeroizing::new(
            value
                .get_str("access_token")
                .ok_or_else(|| {
                    warn!("oauth: token response parse failed: missing access_token");
                    TokenResponseError::new(TokenResponseErrorKind::MissingAccessToken)
                })?
                .to_owned(),
        );

        let token_type = value
            .get_str("token_type")
            .ok_or_else(|| {
                warn!("oauth: token response parse failed: missing token_type");
                TokenResponseError::new(TokenResponseErrorKind::MissingTokenType)
            })?
            .to_owned();

        // Extract optional expires_in.
        let expires_in = if let Some(val) = value.get("expires_in") {
            if val.is_null() {
                None
            } else {
                let secs = val.as_i64().ok_or_else(|| {
                    warn!("oauth: token response parse failed: invalid expires_in");
                    TokenResponseError::new(TokenResponseErrorKind::InvalidExpiresIn)
                })?;
                if secs < 0 {
                    warn!("oauth: token response parse failed: invalid expires_in");
                    return Err(TokenResponseError::new(
                        TokenResponseErrorKind::InvalidExpiresIn,
                    ));
                }
                #[allow(clippy::cast_sign_loss)]
                Some(secs as u64)
            }
        } else {
            None
        };

        // Extract optional refresh_token.
        let refresh_token = value
            .get_str("refresh_token")
            .map(|s| Zeroizing::new(s.to_owned()));

        // Extract optional scope.
        let scope = value.get_str("scope").map(String::from);

        // Extract the optional OIDC ID token (present when `openid` was
        // requested). It is a signed JWT, not a bearer credential, but is
        // still treated as sensitive (PII) and kept out of logs / Debug.
        let id_token = value.get_str("id_token").map(String::from);

        // SECURITY: Never log the access_token or refresh_token.
        info!(
            token_type = %token_type,
            expires_in = ?expires_in,
            "oauth: token response parsed"
        );

        Ok(Self {
            // SECURITY: Already wrapped in Zeroizing at extraction point.
            access_token,
            token_type,
            expires_in,
            refresh_token,
            scope,
            id_token,
        })
    }
}

// SECURITY: Debug redacts access_token, refresh_token, and id_token.
impl fmt::Debug for TokenResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TokenResponse")
            .field("access_token", &"[REDACTED]")
            .field("token_type", &self.token_type)
            .field("expires_in", &self.expires_in)
            .field(
                "refresh_token",
                if self.refresh_token.is_some() {
                    &"Some([REDACTED])"
                } else {
                    &"None"
                },
            )
            .field("scope", &self.scope)
            .field(
                "id_token",
                if self.id_token.is_some() {
                    &"Some([REDACTED])"
                } else {
                    &"None"
                },
            )
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // --- Valid responses ---

    #[test]
    fn parse_minimal_response() {
        let json = r#"{"access_token":"abc123","token_type":"Bearer"}"#;
        let resp = TokenResponse::parse(json).unwrap();
        assert_eq!(resp.access_token(), "abc123");
        assert_eq!(resp.token_type(), "Bearer");
        assert_eq!(resp.expires_in(), None);
        assert!(resp.refresh_token().is_none());
        assert!(resp.scope().is_none());
        assert!(resp.id_token().is_none());
    }

    #[test]
    fn parse_oidc_response_exposes_id_token() {
        // Google-shaped token response: includes the OIDC `id_token`.
        let json = r#"{
            "access_token": "ya29.a0Af...",
            "token_type": "Bearer",
            "expires_in": 3599,
            "scope": "openid email profile",
            "id_token": "eyJhbGciOiJSUzI1Ni'...header.payload.sig"
        }"#;
        let resp = TokenResponse::parse(json).unwrap();
        assert_eq!(
            resp.id_token(),
            Some("eyJhbGciOiJSUzI1Ni'...header.payload.sig")
        );
        // Debug must not leak the id_token.
        assert!(format!("{resp:?}").contains("id_token: \"Some([REDACTED])\""));
    }

    #[test]
    fn parse_full_response() {
        let json = r#"{
            "access_token": "eyJhbGciOi...",
            "token_type": "Bearer",
            "expires_in": 3600,
            "refresh_token": "tGzv3JOk...",
            "scope": "openid profile email"
        }"#;
        let resp = TokenResponse::parse(json).unwrap();
        assert_eq!(resp.access_token(), "eyJhbGciOi...");
        assert_eq!(resp.token_type(), "Bearer");
        assert_eq!(resp.expires_in(), Some(3600));
        assert_eq!(resp.refresh_token(), Some("tGzv3JOk..."));
        assert_eq!(resp.scope(), Some("openid profile email"));
    }

    #[test]
    fn parse_response_with_zero_expires_in() {
        let json = r#"{"access_token":"tok","token_type":"Bearer","expires_in":0}"#;
        let resp = TokenResponse::parse(json).unwrap();
        assert_eq!(resp.expires_in(), Some(0));
    }

    #[test]
    fn parse_response_with_null_expires_in() {
        let json = r#"{"access_token":"tok","token_type":"Bearer","expires_in":null}"#;
        let resp = TokenResponse::parse(json).unwrap();
        assert_eq!(resp.expires_in(), None);
    }

    // --- Missing required fields ---

    #[test]
    fn parse_missing_access_token() {
        let json = r#"{"token_type":"Bearer"}"#;
        let err = TokenResponse::parse(json).unwrap_err();
        assert!(
            err.to_string().contains("missing access_token"),
            "error should mention missing access_token: {err}",
        );
    }

    #[test]
    fn parse_missing_token_type() {
        let json = r#"{"access_token":"abc"}"#;
        let err = TokenResponse::parse(json).unwrap_err();
        assert!(
            err.to_string().contains("missing token_type"),
            "error should mention missing token_type: {err}",
        );
    }

    // --- Invalid fields ---

    #[test]
    fn parse_invalid_expires_in() {
        let json = r#"{"access_token":"tok","token_type":"Bearer","expires_in":"not-a-number"}"#;
        let err = TokenResponse::parse(json).unwrap_err();
        assert!(
            err.to_string().contains("invalid expires_in"),
            "error should mention invalid expires_in: {err}",
        );
    }

    #[test]
    fn parse_negative_expires_in() {
        let json = r#"{"access_token":"tok","token_type":"Bearer","expires_in":-1}"#;
        let err = TokenResponse::parse(json).unwrap_err();
        assert!(
            err.to_string().contains("invalid expires_in"),
            "error should mention invalid expires_in: {err}",
        );
    }

    #[test]
    fn parse_fractional_expires_in() {
        // A non-integer lifetime must be rejected, not silently truncated:
        // `as_i64` requires an exact integer round-trip.
        let json = r#"{"access_token":"tok","token_type":"Bearer","expires_in":3600.5}"#;
        let err = TokenResponse::parse(json).unwrap_err();
        assert!(
            err.to_string().contains("invalid expires_in"),
            "error should mention invalid expires_in: {err}",
        );
    }

    // --- OAuth error responses ---

    #[test]
    fn parse_oauth_error() {
        let json = r#"{"error":"invalid_grant"}"#;
        let err = TokenResponse::parse(json).unwrap_err();
        assert!(
            err.to_string().contains("invalid_grant"),
            "error should contain the OAuth error code: {err}",
        );
    }

    #[test]
    fn parse_oauth_error_with_description() {
        let json = r#"{"error":"invalid_grant","error_description":"The code has expired"}"#;
        let err = TokenResponse::parse(json).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("invalid_grant"),
            "error should contain the error code: {msg}",
        );
        assert!(
            msg.contains("The code has expired"),
            "error should contain the description: {msg}",
        );
    }

    // --- Invalid JSON ---

    #[test]
    fn parse_invalid_json() {
        let err = TokenResponse::parse("not json at all").unwrap_err();
        assert!(
            err.to_string().contains("invalid JSON"),
            "error should mention invalid JSON: {err}",
        );
    }

    #[test]
    fn parse_empty_string() {
        let err = TokenResponse::parse("").unwrap_err();
        assert!(
            err.to_string().contains("invalid JSON"),
            "error should mention invalid JSON: {err}",
        );
    }

    // --- Debug redaction ---

    #[test]
    fn debug_redacts_tokens() {
        let json = r#"{
            "access_token": "secret-access-token",
            "token_type": "Bearer",
            "refresh_token": "secret-refresh-token"
        }"#;
        let resp = TokenResponse::parse(json).unwrap();
        let debug_output = format!("{resp:?}");
        assert!(
            debug_output.contains("[REDACTED]"),
            "debug should contain [REDACTED]: {debug_output}",
        );
        assert!(
            !debug_output.contains("secret-access-token"),
            "debug must not contain the access token",
        );
        assert!(
            !debug_output.contains("secret-refresh-token"),
            "debug must not contain the refresh token",
        );
    }

    // --- Error Display ---

    #[test]
    fn error_display_messages() {
        let err = TokenResponseError::new(TokenResponseErrorKind::InvalidJson);
        assert_eq!(err.to_string(), "token response: invalid JSON");

        let err = TokenResponseError::new(TokenResponseErrorKind::MissingAccessToken);
        assert_eq!(err.to_string(), "token response: missing access_token");

        let err = TokenResponseError::new(TokenResponseErrorKind::MissingTokenType);
        assert_eq!(err.to_string(), "token response: missing token_type");

        let err = TokenResponseError::new(TokenResponseErrorKind::InvalidExpiresIn);
        assert_eq!(err.to_string(), "token response: invalid expires_in value");
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(TokenResponseError::new(TokenResponseErrorKind::InvalidJson));
        let _ = err.to_string();
    }
}