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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Authorization-endpoint request validation (RFC 6749 §4.1.1, §4.1.2.1
//! plus `OpenID` Connect Core §3.1.2).
//!
//! [`validate_authorize_request`] is the authorization server's
//! counterpart to the client-side [`AuthorizationRequest`](crate::oauth::AuthorizationRequest)
//! builder: it takes the parameters a user-agent presented at `/authorize`
//! and a [`RegisteredClient`], and decides whether the request may proceed
//! to user authentication.
//!
//! # Critical error semantics (RFC 6749 §4.1.2.1)
//!
//! The spec draws a hard line between two failure classes, and getting it
//! wrong is an open redirect:
//!
//! * If the **client is unknown** or the **`redirect_uri` is missing /
//!   invalid / unregistered**, the server MUST NOT redirect. Doing so would
//!   bounce an error (and any leaked parameters) to an attacker-controlled
//!   location. These failures surface as
//!   [`AuthorizeError::Display`] — render an error page to the user.
//! * For **every other failure** (bad `response_type`, disallowed scope,
//!   missing PKCE, …) the `redirect_uri` is already trusted, so the server
//!   MUST redirect back to it with an `error=` parameter and echo the
//!   `state`. These surface as [`AuthorizeError::Redirect`], which carries
//!   the validated redirect URI, the RFC 6749 §4.1.2.1 error code, and the
//!   `state` to echo.
//!
//! The distinction is encoded in the type system so a caller cannot
//! accidentally redirect on a display-only error.
//!
//! # Validation order
//!
//! 1. Client exists and is active.            → `Display` on failure
//! 2. `redirect_uri` present + exact match.   → `Display` on failure
//! 3. `response_type` == `code`.              → `Redirect` on failure
//! 4. Requested scope ⊆ allowed scope.        → `Redirect` on failure
//! 5. PKCE S256 challenge present + well-formed when required. → `Redirect`
//!
//! Steps 1–2 are checked first precisely so that everything after can
//! safely produce a `Redirect`.

use core::fmt;

use crate::encoding::base64url_decode;

use super::client::RegisteredClient;

/// Ceiling on the canonical granted scope. Callers persist this into a
/// fixed-width column, and duplicates made the input length unbounded.
const MAX_SCOPE_LEN: usize = 500;

// ---------------------------------------------------------------------------
// Request view
// ---------------------------------------------------------------------------

/// The authorization-request parameters presented at `/authorize`.
///
/// A borrowed view of the query parameters (RFC 6749 §4.1.1). The caller
/// parses these from the request URL; this type carries no ownership and
/// performs no decoding beyond what the validator needs.
#[derive(Debug, Clone, Copy)]
pub struct AuthorizeRequest<'a> {
    /// The `response_type` parameter — must be `"code"`.
    pub response_type: &'a str,
    /// The `client_id` parameter.
    pub client_id: &'a str,
    /// The `redirect_uri` parameter, if supplied.
    pub redirect_uri: Option<&'a str>,
    /// The space-delimited `scope` parameter, if supplied.
    pub scope: Option<&'a str>,
    /// The opaque `state` parameter, echoed back on error.
    pub state: Option<&'a str>,
    /// The PKCE `code_challenge` parameter, if supplied.
    pub code_challenge: Option<&'a str>,
    /// The PKCE `code_challenge_method` parameter, if supplied.
    pub code_challenge_method: Option<&'a str>,
}

// ---------------------------------------------------------------------------
// Success output
// ---------------------------------------------------------------------------

/// The validated, normalised parameters of an accepted authorization
/// request.
///
/// Returned by [`validate_authorize_request`] on success. The redirect URI
/// is guaranteed to be an exact match of a registered URI, the scope is
/// guaranteed to be a subset of the client's allowed scopes, and — when the
/// client requires PKCE — `code_challenge` is guaranteed present and
/// well-formed S256.
#[derive(Debug, Clone)]
pub struct ValidatedAuthorizeRequest {
    redirect_uri: String,
    scope: String,
    state: Option<String>,
    code_challenge: Option<String>,
}

impl ValidatedAuthorizeRequest {
    /// The validated redirect URI (exact match of a registered URI).
    #[must_use]
    #[inline]
    pub fn redirect_uri(&self) -> &str {
        &self.redirect_uri
    }

    /// The validated, space-delimited scope (subset of allowed scopes).
    #[must_use]
    #[inline]
    pub fn scope(&self) -> &str {
        &self.scope
    }

    /// The `state` parameter to echo back on the redirect, if any.
    #[must_use]
    #[inline]
    pub fn state(&self) -> Option<&str> {
        self.state.as_deref()
    }

    /// The PKCE S256 `code_challenge` to bind to the issued code, if
    /// present. Always present when the client requires PKCE.
    #[must_use]
    #[inline]
    pub fn code_challenge(&self) -> Option<&str> {
        self.code_challenge.as_deref()
    }
}

// ---------------------------------------------------------------------------
// Error code (RFC 6749 §4.1.2.1)
// ---------------------------------------------------------------------------

/// An RFC 6749 §4.1.2.1 authorization error code, returned in a redirect.
#[doc(alias = "error_code")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AuthorizeErrorCode {
    /// `unsupported_response_type` — the server does not support obtaining a
    /// code using this `response_type`.
    UnsupportedResponseType,
    /// `invalid_scope` — the requested scope is invalid or exceeds the
    /// client's grant.
    InvalidScope,
    /// `invalid_request` — a required parameter (e.g. the PKCE challenge) is
    /// missing or malformed.
    InvalidRequest,
}

impl AuthorizeErrorCode {
    /// Returns the wire string for this code (e.g. `"invalid_scope"`),
    /// suitable for the `error=` redirect parameter.
    #[must_use]
    #[inline]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::UnsupportedResponseType => "unsupported_response_type",
            Self::InvalidScope => "invalid_scope",
            Self::InvalidRequest => "invalid_request",
        }
    }
}

impl fmt::Display for AuthorizeErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

// ---------------------------------------------------------------------------
// The two-variant error
// ---------------------------------------------------------------------------

/// The reason a request must be shown to the user rather than redirected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DisplayErrorReason {
    /// No active client matches `client_id`.
    UnknownClient,
    /// The `redirect_uri` was missing.
    MissingRedirectUri,
    /// The `redirect_uri` did not exactly match a registered URI.
    InvalidRedirectUri,
}

impl DisplayErrorReason {
    /// A short, non-secret diagnostic string for operator logs and error
    /// pages.
    #[must_use]
    #[inline]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::UnknownClient => "unknown or inactive client",
            Self::MissingRedirectUri => "missing redirect_uri",
            Self::InvalidRedirectUri => "redirect_uri does not match a registered URI",
        }
    }
}

/// The outcome of a failed authorization-request validation.
///
/// The variant dictates how the caller must respond — see the module-level
/// "Critical error semantics" section. Confusing the two is an open-redirect
/// vulnerability, which is why they are distinct variants rather than an
/// error code plus a boolean.
#[doc(alias = "authorize_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthorizeError {
    /// The request must be shown to the user; the server MUST NOT redirect
    /// (RFC 6749 §4.1.2.1 — unknown client / bad redirect URI).
    Display(DisplayErrorReason),
    /// The request may be redirected back to the (already-validated)
    /// client `redirect_uri` carrying an `error=` parameter and the echoed
    /// `state`.
    Redirect(AuthorizeRedirectError),
}

/// A redirectable authorization error (RFC 6749 §4.1.2.1).
///
/// Carries everything the caller needs to build the error redirect: the
/// validated redirect URI, the error code, and the `state` to echo.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorizeRedirectError {
    redirect_uri: String,
    code: AuthorizeErrorCode,
    state: Option<String>,
}

impl AuthorizeRedirectError {
    /// The validated redirect URI to send the error to.
    #[must_use]
    #[inline]
    pub fn redirect_uri(&self) -> &str {
        &self.redirect_uri
    }

    /// The RFC 6749 error code.
    #[must_use]
    #[inline]
    pub fn code(&self) -> AuthorizeErrorCode {
        self.code
    }

    /// The `state` value to echo in the redirect, if the request carried
    /// one.
    #[must_use]
    #[inline]
    pub fn state(&self) -> Option<&str> {
        self.state.as_deref()
    }
}

impl fmt::Display for AuthorizeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Display(reason) => {
                write!(f, "authorize: display error: {}", reason.as_str())
            }
            Self::Redirect(err) => {
                write!(f, "authorize: redirect error: {}", err.code.as_str())
            }
        }
    }
}

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

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

/// The S256 challenge is `base64url(SHA-256(verifier))` — 32 bytes encoded
/// to 43 unpadded base64url characters (RFC 7636 §4.2).
const S256_CHALLENGE_LEN: usize = 43;

/// Validates an authorization request against a registered client.
///
/// `client` must be the active record for `request.client_id` (the caller
/// performs the lookup; pass `None` if no active client matched). See the
/// module documentation for the validation order and error semantics.
///
/// # Errors
///
/// Returns [`AuthorizeError::Display`] for unknown-client / bad-redirect-URI
/// failures (do not redirect) and [`AuthorizeError::Redirect`] for all
/// other failures (redirect with `error=`).
pub fn validate_authorize_request(
    request: &AuthorizeRequest<'_>,
    client: Option<&RegisteredClient>,
) -> Result<ValidatedAuthorizeRequest, AuthorizeError> {
    // 1. Client must exist, be active, and match by id.
    //    SECURITY: an inactive or unknown client is a display error — we
    //    have no trusted redirect target to send an error to.
    let client = match client {
        Some(c) if c.active() && c.client_id() == request.client_id => c,
        _ => return Err(AuthorizeError::Display(DisplayErrorReason::UnknownClient)),
    };

    // 2. redirect_uri must be present and an exact match of a registered URI.
    //    SECURITY: until this passes we MUST NOT redirect.
    let redirect_uri = request.redirect_uri.ok_or(AuthorizeError::Display(
        DisplayErrorReason::MissingRedirectUri,
    ))?;
    if !client.is_registered_redirect_uri(redirect_uri) {
        return Err(AuthorizeError::Display(
            DisplayErrorReason::InvalidRedirectUri,
        ));
    }

    // From here on the redirect_uri is trusted — failures redirect.
    let redirect_err = |code: AuthorizeErrorCode| {
        AuthorizeError::Redirect(AuthorizeRedirectError {
            redirect_uri: redirect_uri.to_owned(),
            code,
            state: request.state.map(ToOwned::to_owned),
        })
    };

    // 3. response_type must be exactly "code" (this server issues codes only).
    if request.response_type != "code" {
        return Err(redirect_err(AuthorizeErrorCode::UnsupportedResponseType));
    }

    // 4. Requested scope must be a subset of the client's allowed scopes.
    let scope = request.scope.unwrap_or("");
    if !client.allows_scopes(scope) {
        return Err(redirect_err(AuthorizeErrorCode::InvalidScope));
    }
    // Store the *canonical* granted scope (single-space-joined, no empty
    // tokens) rather than echoing the raw request whitespace. The raw string
    // is reflected into the issued code's bound scope and the eventual token
    // response (RFC 6749 §3.3); normalizing here keeps that downstream value
    // unambiguous and free of attacker-controlled leading/double spaces.
    // Duplicates are also collapsed and the result bounded: `allows_scopes`
    // accepts a scope repeated any number of times, so `openid openid …`
    // validated and then produced an arbitrarily long string the caller must
    // persist into a fixed-width column.
    let mut canonical: Vec<&str> = Vec::new();
    for s in scope.split(' ').filter(|s| !s.is_empty()) {
        if !canonical.contains(&s) {
            canonical.push(s);
        }
    }
    let scope: String = canonical.join(" ");
    if scope.len() > MAX_SCOPE_LEN {
        return Err(redirect_err(AuthorizeErrorCode::InvalidScope));
    }

    // 5. PKCE: when required, an S256 challenge must be present and
    //    well-formed. A `plain` method is rejected (downgrade protection).
    let code_challenge = if let Some(challenge) = request.code_challenge {
        // method defaults to "plain" when omitted (RFC 7636 §4.3); this
        // server only accepts S256.
        let method = request.code_challenge_method.unwrap_or("plain");
        if method != "S256" || !is_well_formed_s256_challenge(challenge) {
            return Err(redirect_err(AuthorizeErrorCode::InvalidRequest));
        }
        Some(challenge.to_owned())
    } else {
        // No PKCE supplied — only acceptable when the client does not
        // require it.
        if client.require_pkce() {
            return Err(redirect_err(AuthorizeErrorCode::InvalidRequest));
        }
        None
    };

    Ok(ValidatedAuthorizeRequest {
        redirect_uri: redirect_uri.to_owned(),
        scope,
        state: request.state.map(ToOwned::to_owned),
        code_challenge,
    })
}

/// Returns `true` if `challenge` is a well-formed S256 PKCE challenge:
/// exactly 43 base64url characters that decode to 32 bytes (RFC 7636 §4.2).
fn is_well_formed_s256_challenge(challenge: &str) -> bool {
    if challenge.len() != S256_CHALLENGE_LEN {
        return false;
    }
    match base64url_decode(challenge) {
        Ok(bytes) => bytes.len() == 32,
        Err(_) => false,
    }
}

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

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

    fn client() -> RegisteredClient {
        RegisteredClient::builder("c1", ClientType::Confidential)
            .redirect_uri("https://app.example.com/cb")
            .allowed_scope("openid")
            .allowed_scope("profile")
            .require_pkce(true)
            .build()
            .expect("valid test client")
    }

    fn valid_challenge() -> String {
        PkceChallenge::generate().unwrap().challenge().to_owned()
    }

    fn base_request(challenge: &str) -> AuthorizeRequest<'_> {
        AuthorizeRequest {
            response_type: "code",
            client_id: "c1",
            redirect_uri: Some("https://app.example.com/cb"),
            scope: Some("openid profile"),
            state: Some("xyz"),
            code_challenge: Some(challenge),
            code_challenge_method: Some("S256"),
        }
    }

    #[test]
    fn granted_scope_is_normalized() {
        // Irregular request whitespace (leading/double spaces) must not survive
        // into the stored/echoed scope.
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.scope = Some("  openid   profile  ");
        let v = validate_authorize_request(&req, Some(&c)).unwrap();
        assert_eq!(v.scope(), "openid profile");
    }

    #[test]
    fn accepts_valid_request() {
        let c = client();
        let chal = valid_challenge();
        let req = base_request(&chal);
        let v = validate_authorize_request(&req, Some(&c)).unwrap();
        assert_eq!(v.redirect_uri(), "https://app.example.com/cb");
        assert_eq!(v.scope(), "openid profile");
        assert_eq!(v.state(), Some("xyz"));
        assert_eq!(v.code_challenge(), Some(chal.as_str()));
    }

    // --- Display errors (never redirect) ---

    #[test]
    fn unknown_client_is_display_error() {
        let chal = valid_challenge();
        let req = base_request(&chal);
        let err = validate_authorize_request(&req, None).unwrap_err();
        assert_eq!(
            err,
            AuthorizeError::Display(DisplayErrorReason::UnknownClient)
        );
    }

    #[test]
    fn inactive_client_is_display_error() {
        let c = RegisteredClient::builder("c1", ClientType::Confidential)
            .redirect_uri("https://app.example.com/cb")
            .active(false)
            .build()
            .expect("valid test client");
        let chal = valid_challenge();
        let req = base_request(&chal);
        let err = validate_authorize_request(&req, Some(&c)).unwrap_err();
        assert_eq!(
            err,
            AuthorizeError::Display(DisplayErrorReason::UnknownClient)
        );
    }

    #[test]
    fn mismatched_client_id_is_display_error() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.client_id = "other";
        let err = validate_authorize_request(&req, Some(&c)).unwrap_err();
        assert_eq!(
            err,
            AuthorizeError::Display(DisplayErrorReason::UnknownClient)
        );
    }

    #[test]
    fn missing_redirect_uri_is_display_error() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.redirect_uri = None;
        let err = validate_authorize_request(&req, Some(&c)).unwrap_err();
        assert_eq!(
            err,
            AuthorizeError::Display(DisplayErrorReason::MissingRedirectUri)
        );
    }

    #[test]
    fn unregistered_redirect_uri_is_display_error() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.redirect_uri = Some("https://evil.example.com/cb");
        let err = validate_authorize_request(&req, Some(&c)).unwrap_err();
        assert_eq!(
            err,
            AuthorizeError::Display(DisplayErrorReason::InvalidRedirectUri)
        );
    }

    #[test]
    fn non_exact_redirect_uri_is_display_error() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.redirect_uri = Some("https://app.example.com/cb/");
        let err = validate_authorize_request(&req, Some(&c)).unwrap_err();
        assert_eq!(
            err,
            AuthorizeError::Display(DisplayErrorReason::InvalidRedirectUri)
        );
    }

    // --- Redirect errors (carry state + validated uri) ---

    fn expect_redirect(err: AuthorizeError) -> AuthorizeRedirectError {
        match err {
            AuthorizeError::Redirect(e) => e,
            AuthorizeError::Display(r) => panic!("expected redirect, got display: {r:?}"),
        }
    }

    #[test]
    fn bad_response_type_redirects() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.response_type = "token";
        let e = expect_redirect(validate_authorize_request(&req, Some(&c)).unwrap_err());
        assert_eq!(e.code(), AuthorizeErrorCode::UnsupportedResponseType);
        assert_eq!(e.redirect_uri(), "https://app.example.com/cb");
        assert_eq!(e.state(), Some("xyz"));
    }

    #[test]
    fn disallowed_scope_redirects() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.scope = Some("openid admin");
        let e = expect_redirect(validate_authorize_request(&req, Some(&c)).unwrap_err());
        assert_eq!(e.code(), AuthorizeErrorCode::InvalidScope);
        assert_eq!(e.state(), Some("xyz"));
    }

    #[test]
    fn missing_pkce_when_required_redirects() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.code_challenge = None;
        req.code_challenge_method = None;
        let e = expect_redirect(validate_authorize_request(&req, Some(&c)).unwrap_err());
        assert_eq!(e.code(), AuthorizeErrorCode::InvalidRequest);
    }

    #[test]
    fn plain_pkce_method_is_rejected() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.code_challenge_method = Some("plain");
        let e = expect_redirect(validate_authorize_request(&req, Some(&c)).unwrap_err());
        assert_eq!(e.code(), AuthorizeErrorCode::InvalidRequest);
    }

    #[test]
    fn omitted_pkce_method_defaults_to_plain_and_is_rejected() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.code_challenge_method = None;
        let e = expect_redirect(validate_authorize_request(&req, Some(&c)).unwrap_err());
        assert_eq!(e.code(), AuthorizeErrorCode::InvalidRequest);
    }

    #[test]
    fn malformed_challenge_redirects() {
        let c = client();
        // Right length but contains non-base64url characters.
        let bad = "!".repeat(S256_CHALLENGE_LEN);
        let req = base_request(&bad);
        let e = expect_redirect(validate_authorize_request(&req, Some(&c)).unwrap_err());
        assert_eq!(e.code(), AuthorizeErrorCode::InvalidRequest);
    }

    #[test]
    fn wrong_length_challenge_redirects() {
        let c = client();
        let short = "abc";
        let req = base_request(short);
        let e = expect_redirect(validate_authorize_request(&req, Some(&c)).unwrap_err());
        assert_eq!(e.code(), AuthorizeErrorCode::InvalidRequest);
    }

    #[test]
    fn non_s256_named_method_is_rejected() {
        // Only S256 is accepted; any other named method (even a well-formed
        // challenge) is rejected — the allowlist is exact, not "not plain".
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.code_challenge_method = Some("S384");
        let e = expect_redirect(validate_authorize_request(&req, Some(&c)).unwrap_err());
        assert_eq!(e.code(), AuthorizeErrorCode::InvalidRequest);
    }

    // --- Public client without PKCE requirement ---

    #[test]
    fn pkce_optional_when_not_required() {
        let c = RegisteredClient::builder("pub", ClientType::Public)
            .redirect_uri("https://spa.example.com/cb")
            .allowed_scope("openid")
            .require_pkce(false)
            .build()
            .expect("valid test client");
        let req = AuthorizeRequest {
            response_type: "code",
            client_id: "pub",
            redirect_uri: Some("https://spa.example.com/cb"),
            scope: Some("openid"),
            state: None,
            code_challenge: None,
            code_challenge_method: None,
        };
        let v = validate_authorize_request(&req, Some(&c)).unwrap();
        assert_eq!(v.code_challenge(), None);
        assert_eq!(v.state(), None);
    }

    // --- Empty / absent scope ---

    #[test]
    fn empty_scope_is_allowed() {
        let c = client();
        let chal = valid_challenge();
        let mut req = base_request(&chal);
        req.scope = None;
        let v = validate_authorize_request(&req, Some(&c)).unwrap();
        assert_eq!(v.scope(), "");
    }

    // --- Error code wire strings ---

    #[test]
    fn error_code_strings() {
        assert_eq!(
            AuthorizeErrorCode::UnsupportedResponseType.as_str(),
            "unsupported_response_type"
        );
        assert_eq!(AuthorizeErrorCode::InvalidScope.as_str(), "invalid_scope");
        assert_eq!(
            AuthorizeErrorCode::InvalidRequest.as_str(),
            "invalid_request"
        );
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(AuthorizeError::Display(DisplayErrorReason::UnknownClient));
        assert!(err.to_string().contains("display error"));
    }
}