pas-external 0.18.0

Ppoppo Accounts System (PAS) external SDK — OAuth2 PKCE, JWT verification port, Axum middleware, session liveness
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
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
681
682
683
684
685
686
687
688
689
690
691
692
693
//! Native-app OAuth composition root — the non-OIDC sibling of
//! [`RelyingParty`](crate::oidc::RelyingParty).
//!
//! [`NativeAuthFlow<S>`] runs the authorization-code + PKCE flow for a
//! **native client** (RFC 8252): a desktop or CLI program that opens the
//! system browser and receives the redirect on a loopback socket it owns.
//! It requests *resource scopes* — `chat.read`, `contact.read`, … — and no
//! `openid`, so the authorization server mints no id_token.
//!
//! # Why `RelyingParty` cannot serve this
//!
//! The OIDC RP is welded to OIDC in three independent places, and a native
//! resource client breaks all three:
//!
//! | `RelyingParty` requires | A native client |
//! |---|---|
//! | `S: RequestedScope`, whose every impl is an `openid …` marker | requests resource atoms, never `openid` |
//! | a `nonce` on every authorize request | has no id_token for a nonce to bind |
//! | a verified id_token in the token response | receives none — PAS mints one only for `openid` |
//!
//! Loosening any of them would weaken the contract CWC / RCW / CTW depend
//! on. So this is a sibling composition root, not a relaxation — and the
//! two share their machinery (PKCE, discovery, the OAuth client) rather
//! than their contract.
//!
//! # Shape
//!
//! Three calls, and the SDK holds every invariant that is easy to get
//! wrong:
//!
//! ```no_run
//! # use pas_external::{NativeAuthFlow, NativeConfig, MemoryTokenStore};
//! # use ppoppo_sdk_core::scopes::ConsentScopes;
//! # async fn run<S: ConsentScopes>() -> Result<(), Box<dyn std::error::Error>> {
//! let flow = NativeAuthFlow::<S>::new(
//!     NativeConfig::new("https://accounts.ppoppo.com".parse()?, "my_app_id")
//!         .with_resource("https://api.ppoppo.com/grpc"),
//! )
//! .await?;
//!
//! // 1. Bind your loopback listener, then hand its address to `start`.
//! let url = flow.start("http://127.0.0.1:54321/callback");
//! //    …open `url` in the browser, wait for the redirect…
//! # let raw_query = "";
//!
//! // 2. Hand back the raw query string. State verification, the code
//! //    exchange, and the grant check all happen inside.
//! let source = flow.complete(raw_query, MemoryTokenStore::new()).await?;
//! # Ok(()) }
//! ```
//!
//! `source` is a [`ScopedTokenSource<S>`](ppoppo_sdk_core::scopes::ScopedTokenSource)
//! — feed it straight to a resource client built at the same `S`, and the
//! credential's tier and the client's tier cannot disagree.
//!
//! On a later run there is no code to exchange: the refresh token is
//! already in the keystore. [`token_source`](NativeAuthFlow::token_source)
//! is that path, and `complete` is defined in terms of it.
//!
//! # What the consumer still owns
//!
//! The loopback listener — a socket in the consumer's process, which no
//! library can hold for it. Everything else (state generation, single-use
//! state verification, PKCE, callback parsing, the grant check) is here, on
//! purpose: each is a security invariant that would otherwise be
//! re-implemented, slightly differently, by every native consumer.

use std::marker::PhantomData;
use std::sync::Mutex;

use ppoppo_sdk_core::discovery::{Discovery, DiscoveryError, fetch_discovery};
use ppoppo_sdk_core::scopes::ConsentScopes;
use url::Url;

use crate::oauth::{AuthClient, OAuthConfig};
use crate::pkce;
use crate::refresh_source::{RefreshTokenSource, TokenStore};
use crate::scope_grant::{ScopeNotCovered, ensure_covers};

// ────────────────────────────────────────────────────────────────────────
// Config
// ────────────────────────────────────────────────────────────────────────

/// Boot configuration for a [`NativeAuthFlow`].
///
/// Deliberately carries **no redirect URI**: a loopback client binds an
/// ephemeral port at run time (RFC 8252 §7.3 requires the server to accept
/// any port on `127.0.0.1` / `[::1]`), so the redirect is not knowable when
/// the flow is constructed. It is supplied per attempt, to
/// [`NativeAuthFlow::start`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct NativeConfig {
    /// The authorization server's issuer URL; discovery hangs off it.
    pub issuer: Url,
    /// The registered public-client identifier. No client secret — a native
    /// app cannot keep one (RFC 8252 §8.5), which is why PKCE is mandatory.
    pub client_id: String,
    /// RFC 8707 resource indicator, verbatim. See
    /// [`Self::with_resource`].
    pub resource: Option<String>,
}

impl NativeConfig {
    /// A config for `client_id` against the authorization server at
    /// `issuer`.
    #[must_use]
    pub fn new(issuer: Url, client_id: impl Into<String>) -> Self {
        Self { issuer, client_id: client_id.into(), resource: None }
    }

    /// Bind the token to a specific resource server (RFC 8707), so the
    /// minted `aud` clears that server's perimeter instead of defaulting to
    /// the client id.
    ///
    /// **Pass the value exactly as registered.** It is matched
    /// byte-for-byte and never parsed, because parsing is what breaks it:
    /// round-tripping a host-only URI through `Url` appends a trailing
    /// slash (`http://localhost:3200` → `http://localhost:3200/`), and PAS
    /// rejects the slashed form outright with `invalid_target` — verified
    /// live, 2026-07-21.
    #[must_use]
    pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
        self.resource = Some(resource.into());
        self
    }
}

// ────────────────────────────────────────────────────────────────────────
// Errors
// ────────────────────────────────────────────────────────────────────────

/// [`NativeAuthFlow::new`] failure surface.
#[derive(Debug, thiserror::Error)]
pub enum NativeAuthInitError {
    /// The authorization server's discovery document could not be fetched
    /// or did not validate.
    #[error("discovery fetch failed: {0}")]
    Discovery(#[from] DiscoveryError),
    /// The HTTP client could not be constructed (TLS init, resource
    /// exhaustion).
    #[error("OAuth client construction failed: {0}")]
    OAuthClient(String),
}

/// [`NativeAuthFlow::complete`] failure surface.
///
/// Every variant is terminal for the attempt that produced it; none is
/// retryable with the same callback.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CallbackError {
    /// No authorization was pending — `complete` ran without a preceding
    /// `start`, or a second callback arrived for an attempt already
    /// consumed.
    ///
    /// Load-bearing: the pending slot is taken **unconditionally**, before
    /// the state is compared, so a replayed callback lands here regardless
    /// of whether the first attempt succeeded. Single-use is the property;
    /// this variant is what it looks like from outside.
    #[error("no authorization is pending (never started, or already consumed)")]
    NoPendingAuthorization,

    /// The returned `state` did not match the pending one — the CSRF
    /// defense (RFC 6749 §10.12). The attempt is consumed either way.
    #[error("state mismatch (CSRF defense triggered)")]
    StateMismatch,

    /// The authorization server redirected with an error instead of a code
    /// (RFC 6749 §4.1.2.1) — most commonly `access_denied`, the user
    /// declining at the consent screen.
    #[error("authorization denied by the server: {error}{}", .description.as_deref().map(|d| format!(" — {d}")).unwrap_or_default())]
    AuthorizationDenied {
        /// The RFC 6749 §4.1.2.1 error code, verbatim.
        error: String,
        /// The server's human-readable elaboration, when present.
        description: Option<String>,
    },

    /// The redirect query was neither a valid success nor a valid error
    /// response — no `code`, no `error`, or no `state`.
    #[error("malformed callback: {0}")]
    MalformedCallback(&'static str),

    /// The token endpoint rejected the exchange.
    #[error("token exchange failed: {0}")]
    TokenExchange(String),

    /// The exchange succeeded but the granted scope does not cover the
    /// requested tier. Fails here, at sign-in, rather than an hour later on
    /// the first call that needs the missing atom.
    #[error(transparent)]
    ScopeNotCovered(#[from] ScopeNotCovered),

    /// The token response carried no `refresh_token`, so no durable
    /// credential can be built from it. A native client that cannot renew
    /// would silently sign the user out within the hour.
    #[error("token response carried no refresh_token — cannot build a renewable credential")]
    MissingRefreshToken,

    /// The keystore rejected the write.
    #[error("token store failure: {0}")]
    TokenStore(String),
}

// ────────────────────────────────────────────────────────────────────────
// The flow
// ────────────────────────────────────────────────────────────────────────

/// One in-flight authorization attempt.
///
/// Held inline rather than behind a port. A `StateStore` seam exists on the
/// OIDC RP because a web relying party is multi-user and multi-request — it
/// must correlate a callback arriving on any process against state written
/// by any other. A native client has one user and at most one attempt in
/// flight, so a port here would model a reality this client does not have.
struct PendingAuthorization {
    state: String,
    code_verifier: String,
    /// Captured at `start` because RFC 6749 §4.1.3 requires the token-leg
    /// `redirect_uri` to be identical to the authorize-leg one — and with an
    /// ephemeral loopback port, only this attempt knows what that was.
    redirect_uri: String,
}

/// Native-app OAuth composition root. See the [module docs](self).
///
/// `S` is the scope tier: it determines what goes on the authorize wire,
/// what the grant is checked against, and what the yielded token source is
/// witnessed for — one type parameter across the whole credential story.
pub struct NativeAuthFlow<S: ConsentScopes> {
    config: NativeConfig,
    discovery: Discovery,
    pending: Mutex<Option<PendingAuthorization>>,
    _scope: PhantomData<S>,
}

impl<S: ConsentScopes> std::fmt::Debug for NativeAuthFlow<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Never the pending attempt: it holds the PKCE code_verifier.
        f.debug_struct("NativeAuthFlow")
            .field("config", &self.config)
            .field("discovery", &self.discovery)
            .finish_non_exhaustive()
    }
}

impl<S: ConsentScopes> NativeAuthFlow<S> {
    /// Construct a flow, fetching the authorization server's discovery
    /// document once.
    ///
    /// No OAuth client is built here — a native client's redirect URI does
    /// not exist until a loopback socket is bound, so the client is
    /// assembled per use from the discovered endpoints.
    ///
    /// # Errors
    ///
    /// [`NativeAuthInitError::Discovery`] if the document cannot be fetched
    /// or fails RFC 8414 §3.3 issuer validation.
    pub async fn new(config: NativeConfig) -> Result<Self, NativeAuthInitError> {
        let discovery = fetch_discovery(&config.issuer).await?;
        Ok(Self { config, discovery, pending: Mutex::new(None), _scope: PhantomData })
    }

    /// Begin an authorization attempt; returns the URL to open in the
    /// browser.
    ///
    /// `redirect_uri` is the loopback address the consumer has **already
    /// bound**, forwarded verbatim to both legs of the flow. Pass it
    /// exactly as the listener reports it — it is never parsed, for the
    /// same byte-identity reason as
    /// [`NativeConfig::with_resource`], and RFC 6749 §4.1.3 requires the
    /// token leg to repeat it unchanged.
    ///
    /// Any attempt already pending is **discarded**: at most one
    /// authorization can be in flight, and the newest supersedes it. The
    /// abandoned attempt's state can then never be completed, which is the
    /// correct outcome for a flow the user restarted.
    ///
    /// Emits **no `nonce`** — there is no id_token for one to bind to.
    #[must_use]
    pub fn start(&self, redirect_uri: &str) -> Url {
        let state = pkce::generate_state();
        let code_verifier = pkce::generate_code_verifier();
        let code_challenge = pkce::generate_code_challenge(&code_verifier);

        let url = build_native_authorize_url(
            &self.discovery.authorization_endpoint,
            &self.config.client_id,
            redirect_uri,
            &state,
            &code_challenge,
            &S::scope_line(),
            self.config.resource.as_deref(),
        );

        // Poisoning can only happen if a panic unwound while the slot was
        // held; the slot holds no invariant worth preserving across that, so
        // recover rather than propagate a panic into a sign-in path.
        let mut slot = self.pending.lock().unwrap_or_else(|e| e.into_inner());
        *slot = Some(PendingAuthorization {
            state,
            code_verifier,
            redirect_uri: redirect_uri.to_owned(),
        });

        url
    }

    /// A renewing token source over an **already-held** refresh token.
    ///
    /// This is the restart path: a native app relaunching with a credential
    /// in its keystore has no authorization code to exchange, and needs no
    /// browser round trip. `store` must already hold the refresh token.
    ///
    /// The returned source is witnessed for `S` on the same terms as
    /// [`complete`](Self::complete)'s — the guarantee attaches to *use*, and
    /// every renewal re-checks the grant. So this constructor needs no proof
    /// from its caller and still cannot yield an unchecked token.
    ///
    /// # Errors
    ///
    /// [`NativeAuthInitError::OAuthClient`] if the HTTP client cannot be
    /// built.
    pub fn token_source<T: TokenStore>(
        &self,
        store: T,
    ) -> Result<RefreshTokenSource<AuthClient, T, S>, NativeAuthInitError> {
        let client = AuthClient::try_new(self.oauth_config())
            .map_err(|e| NativeAuthInitError::OAuthClient(e.to_string()))?;
        Ok(RefreshTokenSource::new(client, store))
    }

    /// Complete an attempt from the raw redirect query string.
    ///
    /// `callback_query` is everything after the `?` in the redirect the
    /// loopback listener received — passed through untouched. This method
    /// parses it, enforces single-use `state`, exchanges the code with the
    /// stored PKCE verifier, checks the granted scope covers `S`, persists
    /// the refresh token into `store`, and returns the renewing source.
    ///
    /// # Errors
    ///
    /// See [`CallbackError`]. Note that
    /// [`AuthorizationDenied`](CallbackError::AuthorizationDenied) is the
    /// ordinary "user said no" outcome, not a defect.
    pub async fn complete<T: TokenStore>(
        &self,
        callback_query: &str,
        store: T,
    ) -> Result<RefreshTokenSource<AuthClient, T, S>, CallbackError> {
        // 1. Consume the attempt FIRST, unconditionally. Taking before
        //    comparing is what makes `state` single-use: a replayed callback
        //    finds an empty slot no matter how the first one ended. It also
        //    removes any oracle in the comparison below — by the time we
        //    compare, there is nothing left to probe for.
        let pending = {
            let mut slot = self.pending.lock().unwrap_or_else(|e| e.into_inner());
            slot.take()
        }
        .ok_or(CallbackError::NoPendingAuthorization)?;

        let callback = CallbackParams::parse(callback_query)?;

        // 2. CSRF: the returned state must be the one we issued. Checked
        //    before the error branch too — an unsolicited `error=` redirect
        //    is as forgeable as an unsolicited `code=` one.
        if callback.state != pending.state {
            return Err(CallbackError::StateMismatch);
        }

        // 3. RFC 6749 §4.1.2.1 — the server may redirect with an error
        //    instead of a code. `access_denied` is the consent screen being
        //    declined, which is a normal outcome and must not read as a bug.
        let code = match callback.outcome {
            CallbackOutcome::Code(code) => code,
            CallbackOutcome::Error { error, description } => {
                return Err(CallbackError::AuthorizationDenied { error, description });
            }
        };

        // 4. Exchange, with the redirect_uri this attempt used (§4.1.3).
        let exchange_client = AuthClient::try_new(
            self.oauth_config().with_redirect_uri(pending.redirect_uri),
        )
        .map_err(|e| CallbackError::TokenExchange(e.to_string()))?;

        let tokens = exchange_client
            .exchange_code(&code, &pending.code_verifier)
            .await
            .map_err(|e| CallbackError::TokenExchange(e.to_string()))?;

        // 5. The acquisition-leg grant check. Runs before anything is
        //    persisted: a credential at the wrong tier should not reach the
        //    keystore at all.
        ensure_covers::<S>(tokens.scope.as_deref())?;

        let refresh_token = tokens.refresh_token.ok_or(CallbackError::MissingRefreshToken)?;
        store
            .save(&refresh_token)
            .await
            .map_err(|e| CallbackError::TokenStore(e.to_string()))?;

        // ponytail: the access token just minted is discarded, so the first
        // use costs one extra refresh round trip (and one RTR rotation).
        // Priming the source with it would buy that back, but adds a
        // serve-once-then-refresh branch to `fetch_token` — the exact
        // function carrying the yanked-0.5.2 `Send` footgun — and cannot
        // seed the downstream TokenCache anyway, which is built later by the
        // resource client. Prime it here if sign-in latency ever matters.
        self.token_source(store)
            .map_err(|e| CallbackError::TokenExchange(e.to_string()))
    }

    /// The endpoints + client identity shared by every client this flow
    /// builds. Carries no `redirect_uri`: only the code-exchange leg needs
    /// one, and it supplies its own from the pending attempt.
    fn oauth_config(&self) -> OAuthConfig {
        let mut config = OAuthConfig::new(self.config.client_id.clone())
            .with_auth_url(self.discovery.authorization_endpoint.clone())
            .with_token_url(self.discovery.token_endpoint.clone());
        if let Some(resource) = &self.config.resource {
            config = config.with_resource(resource.clone());
        }
        config
    }
}

// ────────────────────────────────────────────────────────────────────────
// Callback parsing
// ────────────────────────────────────────────────────────────────────────

enum CallbackOutcome {
    Code(String),
    Error { error: String, description: Option<String> },
}

struct CallbackParams {
    state: String,
    outcome: CallbackOutcome,
}

impl CallbackParams {
    /// Parse a redirect query string into a success or an error response.
    ///
    /// `state` is required in both shapes — PAS echoes it on the error
    /// redirect too (RFC 6749 §4.1.2.1), and without it an attacker could
    /// cancel an in-flight sign-in with an unsolicited `error=` redirect.
    fn parse(query: &str) -> Result<Self, CallbackError> {
        let mut state = None;
        let mut code = None;
        let mut error = None;
        let mut description = None;

        for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
            // First occurrence wins: a duplicated parameter is a smuggling
            // attempt, and taking the last would let an appended copy
            // override the one the server sent.
            match key.as_ref() {
                "state" if state.is_none() => state = Some(value.into_owned()),
                "code" if code.is_none() => code = Some(value.into_owned()),
                "error" if error.is_none() => error = Some(value.into_owned()),
                "error_description" if description.is_none() => {
                    description = Some(value.into_owned());
                }
                _ => {}
            }
        }

        let state = state.ok_or(CallbackError::MalformedCallback("no `state` parameter"))?;

        let outcome = match (code, error) {
            // A redirect carrying both is ambiguous; refuse rather than pick.
            (Some(_), Some(_)) => {
                return Err(CallbackError::MalformedCallback(
                    "carries both `code` and `error`",
                ));
            }
            (Some(code), None) => CallbackOutcome::Code(code),
            (None, Some(error)) => CallbackOutcome::Error { error, description },
            (None, None) => {
                return Err(CallbackError::MalformedCallback(
                    "carries neither `code` nor `error`",
                ));
            }
        };

        Ok(Self { state, outcome })
    }
}

// ────────────────────────────────────────────────────────────────────────
// URL builder — extracted for boundary-test introspection
// ────────────────────────────────────────────────────────────────────────

/// Build the native authorize URL.
///
/// A free function, mirroring the OIDC sibling, so the boundary test can
/// assert the exact wire parameters without the randomness `start`
/// generates on every call.
///
/// Distinct from `oidc::build_authorize_url` in exactly one way that
/// matters: **no `nonce`**. That parameter is unconditional on the OIDC
/// side, and emitting it here would be a request for an id_token this flow
/// neither asks for nor could verify.
fn build_native_authorize_url(
    authorization_endpoint: &Url,
    client_id: &str,
    redirect_uri: &str,
    state: &str,
    code_challenge: &str,
    scope: &str,
    resource: Option<&str>,
) -> Url {
    let mut url = authorization_endpoint.clone();
    {
        let mut pairs = url.query_pairs_mut();
        pairs
            .append_pair("response_type", "code")
            .append_pair("client_id", client_id)
            .append_pair("redirect_uri", redirect_uri)
            .append_pair("state", state)
            .append_pair("code_challenge", code_challenge)
            .append_pair("code_challenge_method", "S256")
            .append_pair("scope", scope);
        // RFC 8707 §2 — bind the resource at authorize so the code carries it
        // and the token-leg `aud` is minted against it.
        if let Some(r) = resource {
            pairs.append_pair("resource", r);
        }
    }
    url
}

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

    struct Notify;
    impl ConsentScopes for Notify {
        const SCOPES: &'static [&'static str] = &["chat.read", "contact.read", "chat.ack"];
    }

    fn authorize(resource: Option<&str>) -> String {
        build_native_authorize_url(
            &"http://localhost:3100/oauth/authorize".parse().unwrap(),
            "cnc_01ky26fzxzjvzpy3",
            "http://127.0.0.1:54321/callback",
            "st",
            "chal",
            &Notify::scope_line(),
            resource,
        )
        .into()
    }

    /// The invariant this whole flow exists for. `RelyingParty` emits a
    /// nonce unconditionally; PAS mints no id_token without `openid`, so a
    /// nonce here would request something that can never come back.
    #[test]
    fn authorize_url_emits_no_nonce() {
        assert!(!authorize(None).contains("nonce"), "native flow must not request an id_token");
    }

    #[test]
    fn authorize_url_carries_the_tier_scope_line() {
        // Space-separated per RFC 6749 §3.3; form-encoded as `+`.
        assert!(
            authorize(None).contains("scope=chat.read+contact.read+chat.ack"),
            "{}",
            authorize(None)
        );
    }

    #[test]
    fn authorize_url_carries_pkce_s256_and_no_secret() {
        let url = authorize(None);
        assert!(url.contains("code_challenge=chal"));
        assert!(url.contains("code_challenge_method=S256"));
        assert!(!url.contains("client_secret"), "a native client is a public client");
    }

    /// The live-verified trap: PAS rejects `http://localhost:3200/` — one
    /// trailing slash — with `invalid_target`. The value must reach the wire
    /// exactly as configured.
    #[test]
    fn authorize_url_carries_the_resource_byte_identically() {
        let url = authorize(Some("http://localhost:3200"));
        // Decode the parameter back and compare to the input — asserting on
        // the encoded form would pass for a value that merely *contains* the
        // right prefix.
        let got = Url::parse(&url)
            .unwrap()
            .query_pairs()
            .find(|(k, _)| k == "resource")
            .map(|(_, v)| v.into_owned());
        assert_eq!(
            got.as_deref(),
            Some("http://localhost:3200"),
            "the resource must reach the wire byte-identically — PAS rejects \
             the trailing-slash form with `invalid_target` (verified live)"
        );
    }

    #[test]
    fn authorize_url_carries_the_redirect_uri_byte_identically() {
        // Same discipline as `resource`, and RFC 6749 §4.1.3 additionally
        // requires the token leg to repeat this value unchanged — which is
        // why `start` stores the raw string rather than a parsed `Url`.
        let raw = "http://127.0.0.1:54321/callback";
        let got = Url::parse(&authorize(None))
            .unwrap()
            .query_pairs()
            .find(|(k, _)| k == "redirect_uri")
            .map(|(_, v)| v.into_owned());
        assert_eq!(got.as_deref(), Some(raw));
    }

    #[test]
    fn authorize_url_omits_resource_when_absent() {
        assert!(!authorize(None).contains("resource="));
    }

    #[test]
    fn callback_parses_a_success_redirect() {
        let p = CallbackParams::parse("code=abc&state=xyz").unwrap();
        assert_eq!(p.state, "xyz");
        assert!(matches!(p.outcome, CallbackOutcome::Code(c) if c == "abc"));
    }

    /// RFC 6749 §4.1.2.1 — the user declining consent is a redirect, not a
    /// transport failure, and must not read as a malformed callback.
    #[test]
    fn callback_parses_an_error_redirect() {
        let p = CallbackParams::parse(
            "error=access_denied&error_description=User+declined&state=xyz",
        )
        .unwrap();
        match p.outcome {
            CallbackOutcome::Error { error, description } => {
                assert_eq!(error, "access_denied");
                assert_eq!(description.as_deref(), Some("User declined"));
            }
            CallbackOutcome::Code(_) => panic!("must parse as an error redirect"),
        }
    }

    #[test]
    fn callback_without_state_is_malformed() {
        // Required on BOTH shapes: without it, an unsolicited `error=`
        // redirect could cancel someone else's in-flight sign-in.
        assert!(matches!(
            CallbackParams::parse("code=abc"),
            Err(CallbackError::MalformedCallback(_))
        ));
        assert!(matches!(
            CallbackParams::parse("error=access_denied"),
            Err(CallbackError::MalformedCallback(_))
        ));
    }

    #[test]
    fn callback_with_neither_code_nor_error_is_malformed() {
        assert!(matches!(
            CallbackParams::parse("state=xyz"),
            Err(CallbackError::MalformedCallback(_))
        ));
    }

    #[test]
    fn callback_with_both_code_and_error_is_refused() {
        // Ambiguous. Picking either one is a decision the server did not make.
        assert!(matches!(
            CallbackParams::parse("code=abc&error=access_denied&state=xyz"),
            Err(CallbackError::MalformedCallback(_))
        ));
    }

    #[test]
    fn duplicate_parameters_take_the_first_occurrence() {
        // An appended copy must not override what the server sent.
        let p = CallbackParams::parse("code=real&state=xyz&code=injected").unwrap();
        assert!(matches!(p.outcome, CallbackOutcome::Code(c) if c == "real"));
    }

    #[test]
    fn callback_values_are_percent_decoded() {
        let p = CallbackParams::parse("code=a%2Fb%2Bc&state=s%20t").unwrap();
        assert_eq!(p.state, "s t");
        assert!(matches!(p.outcome, CallbackOutcome::Code(c) if c == "a/b+c"));
    }
}