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
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
//! Authorization-code redemption verdict (RFC 6749 §4.1.3, RFC 7636 §4.6).
//!
//! [`evaluate_code_redemption`] is the storage-free decision an
//! authorization server makes at the token endpoint when a client presents
//! an authorization code: given the code's stored state and the parameters
//! of the token request, decide whether the code may be exchanged for
//! tokens.
//!
//! The function performs no I/O and mutates no state. The caller loads the
//! stored code row, builds [`StoredAuthCode`], evaluates, and — only on an
//! `Accepted` verdict — marks the code consumed and issues tokens. Marking
//! the code consumed (single-use enforcement) is the caller's transaction;
//! this function merely reports whether the *currently stored* state
//! permits redemption.
//!
//! # Checks (in order)
//!
//! 1. **Client binding** — the authenticating client matches the client the
//!    code was issued to, and that client authenticated successfully.
//! 2. **Single use** — the code has not already been consumed (RFC 6749
//!    §4.1.2: codes MUST be single-use; reuse is a replay attack signal).
//! 3. **Expiry** — the code has not expired (short TTL, §4.1.2).
//! 4. **Redirect-URI match** — the `redirect_uri` in the token request is
//!    identical to the one in the authorization request (§4.1.3).
//! 5. **PKCE** — when the code was bound to a `code_challenge`, the presented
//!    `code_verifier` produces that challenge under S256 (RFC 7636 §4.6).
//!
//! # Security
//!
//! * PKCE verification recomputes `base64url(SHA-256(verifier))` and
//!   compares it to the stored challenge with [`constant_time_eq`].
//! * The redirect-URI comparison is constant-time.

use core::fmt;

use crate::crypto::Sha256;
use crate::crypto::constant_time::constant_time_eq;
use crate::encoding::base64url_encode;
use crate::util::timestamp::Timestamp;

// ---------------------------------------------------------------------------
// Client authentication result
// ---------------------------------------------------------------------------

/// The result of authenticating the client at the token endpoint.
///
/// Client authentication itself (HTTP Basic, `client_secret_post`, or
/// "public client, no secret") is the caller's concern — secrets live in the
/// caller's database. This enum reports only the *verdict* so the code
/// redemption logic can reason about it without touching secret material.
#[doc(alias = "client_auth")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ClientAuthResult {
    /// The client authenticated successfully (confidential client) or is a
    /// public client for which PKCE is the binding (RFC 6749 §3.2.1).
    Authenticated,
    /// Client authentication failed (bad secret, unknown client, …).
    Failed,
}

// ---------------------------------------------------------------------------
// Stored code state
// ---------------------------------------------------------------------------

/// The persisted state of an issued authorization code, as the server
/// stored it at the authorize step.
///
/// A borrowed view — the caller owns the row. `code_challenge` is `None`
/// only for codes issued to clients that did not use PKCE.
#[derive(Debug, Clone, Copy)]
pub struct StoredAuthCode<'a> {
    /// The `client_id` the code was issued to.
    pub client_id: &'a str,
    /// The exact `redirect_uri` from the authorization request.
    pub redirect_uri: &'a str,
    /// The S256 `code_challenge` bound to the code, if PKCE was used.
    pub code_challenge: Option<&'a str>,
    /// Whether the issuing client mandates PKCE (public client, or an
    /// explicit `require_pkce`). When `true`, a code that carries no
    /// `code_challenge` is a downgrade and is rejected (OAuth 2.1 §7.5.1).
    pub require_pkce: bool,
    /// The code's expiry time.
    pub expires_at: Timestamp,
    /// Whether the code has already been redeemed.
    pub consumed: bool,
}

/// The token-request parameters a client presented when redeeming a code.
#[derive(Debug, Clone, Copy)]
pub struct TokenRequestPresented<'a> {
    /// The authenticated `client_id` (whichever client the request
    /// authenticated as).
    pub client_id: &'a str,
    /// The outcome of authenticating that client.
    pub client_auth: ClientAuthResult,
    /// The `redirect_uri` sent in the token request.
    pub redirect_uri: &'a str,
    /// The PKCE `code_verifier`, if supplied.
    pub code_verifier: Option<&'a str>,
}

// ---------------------------------------------------------------------------
// Verdict
// ---------------------------------------------------------------------------

/// The reason an authorization code may not be redeemed.
#[doc(alias = "redemption_error")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CodeRedemptionDenied {
    /// Client authentication failed (RFC 6749 §5.2 `invalid_client`).
    ClientAuthenticationFailed,
    /// The authenticating client is not the client the code was issued to
    /// (§4.1.3 `invalid_grant`).
    ClientMismatch,
    /// The code has already been consumed — a replay (§4.1.2).
    ///
    /// SECURITY: per RFC 6749 §4.1.2 the server SHOULD revoke all tokens
    /// previously issued from this code when a consumed code is replayed.
    AlreadyConsumed,
    /// The code has expired (§4.1.2 `invalid_grant`).
    Expired,
    /// The token-request `redirect_uri` does not match the one bound to the
    /// code (§4.1.3 `invalid_grant`).
    RedirectUriMismatch,
    /// A PKCE `code_verifier` was required (the code is bound to a
    /// challenge) but none was presented (RFC 7636 §4.6 `invalid_grant`).
    MissingCodeVerifier,
    /// The presented `code_verifier` does not match the stored challenge
    /// (RFC 7636 §4.6 `invalid_grant`).
    PkceVerificationFailed,
    /// The client mandates PKCE, or a `code_verifier` was presented, but the
    /// code carries no bound `code_challenge` — a PKCE downgrade attempt
    /// (OAuth 2.1 §7.5.1 `invalid_grant`).
    PkceDowngrade,
}

impl CodeRedemptionDenied {
    /// A short, non-secret diagnostic string for operator logs.
    #[must_use]
    #[inline]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ClientAuthenticationFailed => "client authentication failed",
            Self::ClientMismatch => "code was issued to a different client",
            Self::AlreadyConsumed => "code already consumed (replay)",
            Self::Expired => "code expired",
            Self::RedirectUriMismatch => "redirect_uri mismatch",
            Self::MissingCodeVerifier => "missing PKCE code_verifier",
            Self::PkceVerificationFailed => "PKCE verification failed",
            Self::PkceDowngrade => "PKCE downgrade (no challenge bound to code)",
        }
    }

    /// Returns `true` if this denial indicates an authorization-code replay,
    /// which per RFC 6749 §4.1.2 SHOULD trigger revocation of any tokens
    /// already issued from the code.
    #[must_use]
    #[inline]
    pub fn is_replay(self) -> bool {
        matches!(self, Self::AlreadyConsumed)
    }
}

impl fmt::Display for CodeRedemptionDenied {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "code redemption denied: {}", self.as_str())
    }
}

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

/// The verdict of evaluating an authorization-code redemption.
#[doc(alias = "code_verdict")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CodeRedemptionVerdict {
    /// The code may be redeemed. The caller MUST now atomically mark the
    /// code consumed and issue tokens.
    Accepted,
    /// The code must not be redeemed; the variant carries the reason.
    Denied(CodeRedemptionDenied),
}

// ---------------------------------------------------------------------------
// Evaluation
// ---------------------------------------------------------------------------

/// Evaluates whether a presented token request may redeem the stored
/// authorization code, as of `now`.
///
/// Returns [`CodeRedemptionVerdict::Accepted`] only when every check in the
/// module-level list passes; otherwise a [`CodeRedemptionVerdict::Denied`]
/// carrying the first failing reason. Pure and side-effect-free.
#[must_use]
pub fn evaluate_code_redemption(
    stored: &StoredAuthCode<'_>,
    presented: &TokenRequestPresented<'_>,
    now: Timestamp,
) -> CodeRedemptionVerdict {
    use CodeRedemptionDenied as D;
    use CodeRedemptionVerdict::{Accepted, Denied};

    // 1. Client authentication must have succeeded.
    if presented.client_auth != ClientAuthResult::Authenticated {
        return Denied(D::ClientAuthenticationFailed);
    }

    // 1b. The authenticating client must be the one the code was issued to.
    //     SECURITY: constant-time to avoid leaking the bound client id.
    if !constant_time_eq(stored.client_id.as_bytes(), presented.client_id.as_bytes()) {
        return Denied(D::ClientMismatch);
    }

    // 2. Single-use: a consumed code is a replay.
    if stored.consumed {
        return Denied(D::AlreadyConsumed);
    }

    // 3. Expiry.
    if stored.expires_at.is_expired(&now) {
        return Denied(D::Expired);
    }

    // 4. Redirect-URI binding (constant-time exact match).
    if !constant_time_eq(
        stored.redirect_uri.as_bytes(),
        presented.redirect_uri.as_bytes(),
    ) {
        return Denied(D::RedirectUriMismatch);
    }

    // 5. PKCE.
    match stored.code_challenge {
        Some(challenge) => {
            let Some(verifier) = presented.code_verifier else {
                return Denied(D::MissingCodeVerifier);
            };
            if !verify_s256(verifier, challenge) {
                return Denied(D::PkceVerificationFailed);
            }
        }
        None => {
            // No challenge was bound at authorize time. Either is a downgrade:
            //   * the client mandates PKCE (authorize.rs always binds a
            //     challenge for such clients, so this is defence in depth), or
            //   * a verifier was presented anyway — reject it rather than
            //     silently ignore the mismatch (OAuth 2.1 §7.5.1).
            if stored.require_pkce || presented.code_verifier.is_some() {
                return Denied(D::PkceDowngrade);
            }
        }
    }

    Accepted
}

/// Verifies a PKCE S256 `code_verifier` against a stored `code_challenge`.
///
/// Recomputes `base64url(SHA-256(ASCII(verifier)))` (RFC 7636 §4.6) and
/// compares it to `challenge` in constant time.
fn verify_s256(verifier: &str, challenge: &str) -> bool {
    let computed = base64url_encode(&Sha256::digest(verifier.as_bytes()));
    constant_time_eq(computed.as_bytes(), challenge.as_bytes())
}

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

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

    fn now() -> Timestamp {
        Timestamp::from_unix_secs(1_000_000)
    }

    fn future() -> Timestamp {
        Timestamp::from_unix_secs(1_000_060)
    }

    fn past() -> Timestamp {
        Timestamp::from_unix_secs(999_999)
    }

    fn accepted(v: CodeRedemptionVerdict) -> bool {
        matches!(v, CodeRedemptionVerdict::Accepted)
    }

    fn denied_reason(v: CodeRedemptionVerdict) -> CodeRedemptionDenied {
        match v {
            CodeRedemptionVerdict::Denied(d) => d,
            CodeRedemptionVerdict::Accepted => panic!("expected denial, got accepted"),
        }
    }

    #[test]
    fn accepts_valid_redemption_with_pkce() {
        let pkce = PkceChallenge::generate().unwrap();
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: Some(pkce.challenge()),
            require_pkce: true,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: Some(pkce.verifier()),
        };
        assert!(accepted(evaluate_code_redemption(
            &stored,
            &presented,
            now()
        )));
    }

    #[test]
    fn accepts_valid_redemption_without_pkce() {
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: None,
            require_pkce: false,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: None,
        };
        assert!(accepted(evaluate_code_redemption(
            &stored,
            &presented,
            now()
        )));
    }

    #[test]
    fn redirect_uri_mismatch_reported_before_pkce_failure() {
        // When both the redirect_uri AND the PKCE verifier are wrong, the
        // redirect-URI check (earlier in the fixed order) must be the reported
        // reason. Pins first-failure ordering so a reordering refactor can't
        // silently change which denial surfaces.
        let pkce = PkceChallenge::generate().unwrap();
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: Some(pkce.challenge()),
            require_pkce: true,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://attacker.example.com/cb", // wrong
            code_verifier: Some("the-wrong-verifier"),       // also wrong
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::RedirectUriMismatch,
        );
    }

    #[test]
    fn rejects_failed_client_auth() {
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: None,
            require_pkce: false,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Failed,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: None,
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::ClientAuthenticationFailed,
        );
    }

    #[test]
    fn rejects_client_mismatch() {
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: None,
            require_pkce: false,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c2",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: None,
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::ClientMismatch,
        );
    }

    #[test]
    fn rejects_consumed_code_as_replay() {
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: None,
            require_pkce: false,
            expires_at: future(),
            consumed: true,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: None,
        };
        let reason = denied_reason(evaluate_code_redemption(&stored, &presented, now()));
        assert_eq!(reason, CodeRedemptionDenied::AlreadyConsumed);
        assert!(reason.is_replay());
    }

    #[test]
    fn rejects_expired_code() {
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: None,
            require_pkce: false,
            expires_at: past(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: None,
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::Expired,
        );
    }

    #[test]
    fn rejects_redirect_uri_mismatch() {
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: None,
            require_pkce: false,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/other",
            code_verifier: None,
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::RedirectUriMismatch,
        );
    }

    #[test]
    fn rejects_missing_verifier_when_challenge_present() {
        let pkce = PkceChallenge::generate().unwrap();
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: Some(pkce.challenge()),
            require_pkce: true,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: None,
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::MissingCodeVerifier,
        );
    }

    #[test]
    fn rejects_wrong_verifier() {
        let pkce = PkceChallenge::generate().unwrap();
        let other = PkceChallenge::generate().unwrap();
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: Some(pkce.challenge()),
            require_pkce: true,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: Some(other.verifier()),
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::PkceVerificationFailed,
        );
    }

    #[test]
    fn pkce_s256_matches_known_rfc7636_vector() {
        // RFC 7636 Appendix B: verifier and its S256 challenge.
        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
        assert!(verify_s256(verifier, challenge));
        assert!(!verify_s256(verifier, "wrong-challenge"));
    }

    #[test]
    fn rejects_pkce_downgrade_when_client_requires_pkce() {
        // Client mandates PKCE but the stored code carries no challenge.
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: None,
            require_pkce: true,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: None,
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::PkceDowngrade,
        );
    }

    #[test]
    fn rejects_stray_verifier_on_non_pkce_code() {
        // A verifier presented against a code with no bound challenge is a
        // downgrade attempt, not silently ignored.
        let pkce = PkceChallenge::generate().unwrap();
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: None,
            require_pkce: false,
            expires_at: future(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: Some(pkce.verifier()),
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::PkceDowngrade,
        );
    }

    #[test]
    fn exactly_expired_is_rejected() {
        // Timestamp::is_expired treats equality as expired.
        let stored = StoredAuthCode {
            client_id: "c1",
            redirect_uri: "https://app.example.com/cb",
            code_challenge: None,
            require_pkce: false,
            expires_at: now(),
            consumed: false,
        };
        let presented = TokenRequestPresented {
            client_id: "c1",
            client_auth: ClientAuthResult::Authenticated,
            redirect_uri: "https://app.example.com/cb",
            code_verifier: None,
        };
        assert_eq!(
            denied_reason(evaluate_code_redemption(&stored, &presented, now())),
            CodeRedemptionDenied::Expired,
        );
    }
}