volga-oauth-client 0.9.7

OAuth 2.1/OIDC client for Volga Web Framework
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
//! OAuth 2.1 client
//!
//! [`OAuthClient`] implements the Authorization Code flow with mandatory
//! PKCE, refresh tokens and resource indicators (RFC 8707) on top of
//! server metadata - typically discovered with
//! [`DiscoveryClient`](crate::DiscoveryClient).

use base64::{Engine, engine::general_purpose::STANDARD};
use http::HeaderValue;
use std::{sync::Arc, time::Duration};

use serde::{Deserialize, Serialize};
use volga_oauth_core::{AuthorizationServerMetadata, OAuthErrorCode};

use crate::{
    ClientConfig, ClientError, Pkce, TokenResponse, TokenSet, TokenStore,
    pkce::{PKCE_METHOD, random_urlsafe},
    transport::Transport,
};

/// How early before its expiration a stored access token is considered
/// stale by [`OAuthClient::token`] and refreshed
const EXPIRY_LEEWAY: Duration = Duration::from_secs(30);

const TOKEN_STORE_NOT_CONFIGURED: &str =
    "OAuth client: token store is not configured; attach one with with_token_store(..)";

/// How a confidential client authenticates to the token endpoint
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClientAuthMethod {
    /// `client_secret_basic` - HTTP Basic authentication (RFC 6749
    /// Section 2.3.1), the default and the method servers are required to support
    #[default]
    Basic,

    /// `client_secret_post` - credentials in the request body, for
    /// servers that do not accept HTTP Basic authentication
    Post,
}

/// OAuth 2.1 client for the Authorization Code + PKCE flow
///
/// Without a secret the client acts as a public client (PKCE is the
/// protection, as OAuth 2.1 prescribes); with one it authenticates to the
/// token endpoint per the configured [`ClientAuthMethod`].
///
/// # Example
/// ```no_run
/// use std::sync::Arc;
/// use volga_oauth_client::{DiscoveryClient, InMemoryTokenStore, OAuthClient};
///
/// # async fn run() -> Result<(), volga_oauth_client::ClientError> {
/// let metadata = DiscoveryClient::new()
///     .fetch_server_metadata("https://auth.example.com")
///     .await?;
///
/// let client = OAuthClient::new("my-client")
///     .with_redirect_uri("https://app.example.com/callback")
///     .with_token_store(Arc::new(InMemoryTokenStore::new()));
///
/// let auth = client
///     .authorization_request(&metadata)
///     .with_scopes(["read"])
///     .with_resource("https://api.example.com")
///     .build()?;
///
/// // send the user to `auth.url`; then, in the redirect callback:
/// # let (code, state) = ("code", "state");
/// assert!(auth.matches_state(state));
/// let tokens = client.exchange_code(&metadata, code, &auth).await?;
/// client.store_tokens("alice", &tokens);
///
/// // later - served from the store, transparently refreshed when stale:
/// let tokens = client.token("alice", &metadata).await?;
/// # Ok(())
/// # }
/// ```
pub struct OAuthClient {
    transport: Transport,
    client_id: String,
    client_secret: Option<String>,
    auth_method: ClientAuthMethod,
    redirect_uri: Option<String>,
    store: Option<Arc<dyn TokenStore>>,
}

impl OAuthClient {
    /// Creates a public client with the given `client_id` and the default
    /// [`ClientConfig`]
    pub fn new(client_id: impl Into<String>) -> Self {
        Self {
            transport: Transport::new(ClientConfig::new()),
            client_id: client_id.into(),
            client_secret: None,
            auth_method: ClientAuthMethod::default(),
            redirect_uri: None,
            store: None,
        }
    }

    /// Creates a client from a Dynamic Client Registration response
    /// (RFC 7591), adopting the issued credentials
    ///
    /// The registered `token_endpoint_auth_method` selects the
    /// [`ClientAuthMethod`] (`client_secret_basic` when omitted, per
    /// RFC 7591 Section 2) and, when exactly one `redirect_uri` was registered,
    /// it becomes the client's redirect URI.
    ///
    /// Fails with [`ClientError::Validation`] when the registered method
    /// is one this client cannot perform (e.g. `client_secret_jwt`) -
    /// authenticating differently from the registration would only yield
    /// `invalid_client` at the token endpoint. A registration with `none`
    /// produces a public client; a secret issued alongside it is ignored,
    /// since that method sends no credentials.
    pub fn from_registration(
        response: &volga_oauth_core::ClientRegistrationResponse,
    ) -> Result<Self, ClientError> {
        let mut client = Self::new(response.client_id.clone());

        // an omitted method defaults to client_secret_basic (RFC 7591 Section 2)
        match response
            .metadata
            .token_endpoint_auth_method
            .as_deref()
            .unwrap_or("client_secret_basic")
        {
            "none" => {}
            "client_secret_basic" => {
                if let Some(secret) = &response.client_secret {
                    client = client.with_secret(secret.clone());
                }
            }
            "client_secret_post" => {
                if let Some(secret) = &response.client_secret {
                    client = client
                        .with_secret(secret.clone())
                        .with_auth_method(ClientAuthMethod::Post);
                }
            }
            unsupported => {
                return Err(ClientError::validation(format!(
                    "registered token_endpoint_auth_method '{unsupported}' is not supported; \
                     this client supports client_secret_basic, client_secret_post and none"
                )));
            }
        }

        if let [redirect_uri] = response.metadata.redirect_uris.as_slice() {
            client = client.with_redirect_uri(redirect_uri.clone());
        }

        Ok(client)
    }

    /// Replaces the transport configuration
    pub fn with_config(mut self, config: ClientConfig) -> Self {
        self.transport = Transport::new(config);
        self
    }

    /// Makes this a confidential client authenticating to the token
    /// endpoint with `client_secret`
    pub fn with_secret(mut self, client_secret: impl Into<String>) -> Self {
        self.client_secret = Some(client_secret.into());
        self
    }

    /// Sets how the client secret is presented to the token endpoint;
    /// [`ClientAuthMethod::Basic`] by default, ignored without a secret
    pub fn with_auth_method(mut self, method: ClientAuthMethod) -> Self {
        self.auth_method = method;
        self
    }

    /// Sets the `redirect_uri` sent in authorization and token requests
    pub fn with_redirect_uri(mut self, redirect_uri: impl Into<String>) -> Self {
        self.redirect_uri = Some(redirect_uri.into());
        self
    }

    /// Attaches a [`TokenStore`] enabling [`token`](Self::token) and
    /// [`store_tokens`](Self::store_tokens)
    pub fn with_token_store(mut self, store: Arc<dyn TokenStore>) -> Self {
        self.store = Some(store);
        self
    }

    /// Starts building an authorization request against `metadata`
    ///
    /// [`AuthorizationRequestBuilder::build`] produces the URL to send the
    /// user to, along with the generated `state` and PKCE pair.
    pub fn authorization_request<'a>(
        &'a self,
        metadata: &'a AuthorizationServerMetadata,
    ) -> AuthorizationRequestBuilder<'a> {
        AuthorizationRequestBuilder {
            client: self,
            metadata,
            scopes: Vec::new(),
            resources: Vec::new(),
            state: None,
            extra: Vec::new(),
        }
    }

    /// Exchanges an authorization `code` for tokens (RFC 6749 Section 4.1.3)
    ///
    /// `request` is the [`AuthorizationRequest`] the code was obtained
    /// with: it supplies the PKCE verifier and repeats the requested
    /// resource indicators. Verify the callback `state` with
    /// [`AuthorizationRequest::matches_state`] before calling this.
    pub async fn exchange_code(
        &self,
        metadata: &AuthorizationServerMetadata,
        code: &str,
        request: &AuthorizationRequest,
    ) -> Result<TokenSet, ClientError> {
        let endpoint = token_endpoint(metadata)?;
        // the serializer is not `Sync`: scoping it keeps it out of the
        // future's state, so this future stays `Send` (see `refresh`)
        let (body, authorization) = {
            let mut form = form_urlencoded::Serializer::new(String::new());

            form.append_pair("grant_type", "authorization_code")
                .append_pair("code", code)
                .append_pair("code_verifier", request.pkce.verifier());

            if let Some(redirect_uri) = &self.redirect_uri {
                form.append_pair("redirect_uri", redirect_uri);
            }

            for resource in &request.resources {
                form.append_pair("resource", resource);
            }

            let authorization = self.apply_client_auth(&mut form);
            (form.finish(), authorization)
        };

        self.request_tokens(endpoint, body, authorization).await
    }

    /// Obtains fresh tokens with a refresh token (RFC 6749 Section 6)
    ///
    /// The server may rotate the refresh token; when the response carries
    /// none, the one passed in remains valid - [`token`](Self::token)
    /// handles that carry-over automatically.
    pub async fn refresh(
        &self,
        metadata: &AuthorizationServerMetadata,
        refresh_token: &str,
    ) -> Result<TokenSet, ClientError> {
        let endpoint = token_endpoint(metadata)?;
        // scoped so the non-`Sync` serializer is dropped before the await:
        // a future holding it would be `!Send` and could not be spawned
        let (body, authorization) = {
            let mut form = form_urlencoded::Serializer::new(String::new());

            form.append_pair("grant_type", "refresh_token")
                .append_pair("refresh_token", refresh_token);

            let authorization = self.apply_client_auth(&mut form);
            (form.finish(), authorization)
        };

        self.request_tokens(endpoint, body, authorization).await
    }

    /// Returns valid tokens stored under `key`, refreshing a stale access
    /// token transparently
    ///
    /// `Ok(None)` means interactive authorization is required: nothing is
    /// stored, the stored entry has no refresh token to renew it with, or
    /// the server rejected the refresh token (`invalid_grant`) - in the
    /// latter cases the dead entry is removed from the store.
    ///
    /// # Panics
    /// Panics when no [`TokenStore`] is attached
    /// (see [`with_token_store`](Self::with_token_store)).
    pub async fn token(
        &self,
        key: &str,
        metadata: &AuthorizationServerMetadata,
    ) -> Result<Option<TokenSet>, ClientError> {
        let store = self.store.as_deref().expect(TOKEN_STORE_NOT_CONFIGURED);
        let Some(tokens) = store.get(key) else {
            return Ok(None);
        };

        if !tokens.expires_within(EXPIRY_LEEWAY) {
            return Ok(Some(tokens));
        }

        let Some(refresh_token) = tokens.refresh_token else {
            store.remove(key);
            return Ok(None);
        };

        match self.refresh(metadata, &refresh_token).await {
            Ok(mut fresh) => {
                // no rotation in the response - the old token stays valid
                if fresh.refresh_token.is_none() {
                    fresh.refresh_token = Some(refresh_token);
                }
                store.put(key, &fresh);
                Ok(Some(fresh))
            }
            Err(ClientError::Protocol(err)) if err.error == OAuthErrorCode::InvalidGrant => {
                store.remove(key);
                Ok(None)
            }
            Err(err) => Err(err),
        }
    }

    /// Stores `tokens` under `key` - typically right after
    /// [`exchange_code`](Self::exchange_code)
    ///
    /// # Panics
    /// Panics when no [`TokenStore`] is attached
    /// (see [`with_token_store`](Self::with_token_store)).
    pub fn store_tokens(&self, key: &str, tokens: &TokenSet) {
        self.store
            .as_deref()
            .expect(TOKEN_STORE_NOT_CONFIGURED)
            .put(key, tokens);
    }

    async fn request_tokens(
        &self,
        endpoint: &str,
        body: String,
        authorization: Option<HeaderValue>,
    ) -> Result<TokenSet, ClientError> {
        let value = self
            .transport
            .post_form(endpoint, body, authorization)
            .await?;

        let response: TokenResponse = serde_json::from_value(value)?;
        Ok(response.into())
    }

    /// Applies client authentication to a token request: either an HTTP
    /// Basic header or credentials appended to `form`, per the configured
    /// method. Public clients identify themselves with `client_id` alone.
    fn apply_client_auth(
        &self,
        form: &mut form_urlencoded::Serializer<'_, String>,
    ) -> Option<HeaderValue> {
        match (&self.client_secret, self.auth_method) {
            (Some(secret), ClientAuthMethod::Basic) => {
                Some(basic_credentials(&self.client_id, secret))
            }
            (Some(secret), ClientAuthMethod::Post) => {
                form.append_pair("client_id", &self.client_id)
                    .append_pair("client_secret", secret);
                None
            }
            (None, _) => {
                form.append_pair("client_id", &self.client_id);
                None
            }
        }
    }
}

impl std::fmt::Debug for OAuthClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OAuthClient")
            .field("transport", &self.transport)
            .field("client_id", &self.client_id)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "[redacted]"),
            )
            .field("auth_method", &self.auth_method)
            .field("redirect_uri", &self.redirect_uri)
            .field("store", &self.store.as_ref().map(|_| "dyn TokenStore"))
            .finish()
    }
}

/// Builder for an authorization request, created by
/// [`OAuthClient::authorization_request`]
pub struct AuthorizationRequestBuilder<'a> {
    client: &'a OAuthClient,
    metadata: &'a AuthorizationServerMetadata,
    scopes: Vec<String>,
    resources: Vec<String>,
    state: Option<String>,
    extra: Vec<(String, String)>,
}

impl AuthorizationRequestBuilder<'_> {
    /// Sets the requested scopes, joined into the `scope` parameter
    pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.scopes = scopes.into_iter().map(Into::into).collect();
        self
    }

    /// Adds a resource indicator (RFC 8707), repeatable; it is also sent
    /// with the token request by [`OAuthClient::exchange_code`]
    pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
        self.resources.push(resource.into());
        self
    }

    /// Overrides the `state` parameter; a random value is generated when
    /// not set
    pub fn with_state(mut self, state: impl Into<String>) -> Self {
        self.state = Some(state.into());
        self
    }

    /// Adds an extra query parameter (e.g. the OIDC `nonce` or `prompt`),
    /// repeatable
    pub fn with_param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.push((name.into(), value.into()));
        self
    }

    /// Builds the authorization URL together with the `state` and PKCE
    /// pair the application must keep for the callback
    ///
    /// Fails with [`ClientError::Validation`] when the metadata declares
    /// no `authorization_endpoint` or advertises PKCE methods without
    /// `S256` (OAuth 2.1 requires it).
    pub fn build(self) -> Result<AuthorizationRequest, ClientError> {
        let endpoint = self
            .metadata
            .authorization_endpoint
            .as_deref()
            .ok_or_else(|| {
                ClientError::validation("server metadata declares no authorization_endpoint")
            })?;

        self.client.transport.check_scheme(endpoint)?;

        let methods = &self.metadata.code_challenge_methods_supported;
        if !methods.is_empty() && !methods.iter().any(|method| method == PKCE_METHOD) {
            return Err(ClientError::validation(format!(
                "authorization server does not support the {PKCE_METHOD} PKCE method"
            )));
        }

        let pkce = Pkce::new();
        let state = self.state.unwrap_or_else(|| random_urlsafe(16));

        let mut query = form_urlencoded::Serializer::new(String::new());
        query
            .append_pair("response_type", "code")
            .append_pair("client_id", &self.client.client_id)
            .append_pair("state", &state)
            .append_pair("code_challenge", pkce.challenge())
            .append_pair("code_challenge_method", PKCE_METHOD);

        if let Some(redirect_uri) = &self.client.redirect_uri {
            query.append_pair("redirect_uri", redirect_uri);
        }

        if !self.scopes.is_empty() {
            query.append_pair("scope", &self.scopes.join(" "));
        }

        for resource in &self.resources {
            query.append_pair("resource", resource);
        }

        for (name, value) in &self.extra {
            query.append_pair(name, value);
        }

        let query = query.finish();

        let separator = if endpoint.contains('?') { '&' } else { '?' };
        Ok(AuthorizationRequest {
            url: format!("{endpoint}{separator}{query}"),
            state,
            pkce,
            resources: self.resources,
        })
    }
}

impl std::fmt::Debug for AuthorizationRequestBuilder<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthorizationRequestBuilder")
            .field("scopes", &self.scopes)
            .field("resources", &self.resources)
            .field("state", &self.state)
            .field("extra", &self.extra)
            .finish_non_exhaustive()
    }
}

/// A prepared authorization request
///
/// Everything the application must keep between redirecting the user to
/// [`url`](Self::url) and exchanging the callback code; serializable so a
/// web application can stash it in the session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthorizationRequest {
    /// The authorization URL to send the user to
    pub url: String,

    /// The `state` parameter embedded in the URL; the callback must echo
    /// it back (checked with [`matches_state`](Self::matches_state))
    pub state: String,

    /// The PKCE pair; the verifier is sent with the token request
    pub pkce: Pkce,

    /// The requested resource indicators, repeated in the token request
    /// per RFC 8707
    pub resources: Vec<String>,
}

impl AuthorizationRequest {
    /// Returns `true` when the `state` returned by the callback matches
    /// the one this request was built with - always verify it before
    /// exchanging the code (CSRF protection)
    #[inline]
    pub fn matches_state(&self, state: &str) -> bool {
        self.state == state
    }

    /// Validates the parameters of the authorization callback before the
    /// code is exchanged: the `state` (CSRF) and the RFC 9207 `iss`
    /// (authorization server mix-up).
    ///
    /// `iss` is the callback's `iss` query parameter, `None` when the
    /// response carried none. It must match the issuer whenever it is
    /// present, and it is *required* when the metadata advertises
    /// [`authorization_response_iss_parameter_supported`] - a response
    /// missing it there may come from a different, possibly malicious,
    /// authorization server.
    ///
    /// ```no_run
    /// # use volga_oauth_client::{
    /// #     AuthorizationRequest, AuthorizationServerMetadata, ClientError,
    /// # };
    /// # fn check(
    /// #     request: &AuthorizationRequest,
    /// #     metadata: &AuthorizationServerMetadata,
    /// #     state: &str,
    /// #     iss: Option<&str>,
    /// # ) -> Result<(), ClientError> {
    /// request.validate_callback(metadata, state, iss)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`authorization_response_iss_parameter_supported`]: AuthorizationServerMetadata::authorization_response_iss_parameter_supported
    pub fn validate_callback(
        &self,
        metadata: &AuthorizationServerMetadata,
        state: &str,
        iss: Option<&str>,
    ) -> Result<(), ClientError> {
        if !self.matches_state(state) {
            return Err(ClientError::validation(
                "authorization response `state` does not match the request",
            ));
        }

        match (iss, metadata.authorization_response_iss_parameter_supported) {
            (Some(iss), _) if iss != metadata.issuer => Err(ClientError::validation(format!(
                "authorization response `iss` mismatch: expected {}, got {iss}",
                metadata.issuer
            ))),
            (None, true) => Err(ClientError::validation(
                "authorization server advertises RFC 9207 but the response carries no `iss`",
            )),
            _ => Ok(()),
        }
    }
}

/// Builds an RFC 6749 Section 2.3.1 HTTP Basic authorization header: identifier
/// and secret are form-urlencoded before being joined and base64-encoded.
fn basic_credentials(client_id: &str, client_secret: &str) -> HeaderValue {
    let encode =
        |value: &str| -> String { form_urlencoded::byte_serialize(value.as_bytes()).collect() };

    let credentials = STANDARD.encode(format!("{}:{}", encode(client_id), encode(client_secret)));

    HeaderValue::from_str(&format!("Basic {credentials}"))
        .expect("base64 output is always a valid header value")
}

fn token_endpoint(metadata: &AuthorizationServerMetadata) -> Result<&str, ClientError> {
    metadata
        .token_endpoint
        .as_deref()
        .ok_or_else(|| ClientError::validation("server metadata declares no token_endpoint"))
}

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

    fn metadata() -> AuthorizationServerMetadata {
        let mut metadata = AuthorizationServerMetadata::new("https://auth.example.com");
        metadata.authorization_endpoint = Some("https://auth.example.com/authorize".into());
        metadata.token_endpoint = Some("https://auth.example.com/token".into());
        metadata
    }

    fn query_pairs(url: &str) -> Vec<(String, String)> {
        let query = url.split_once('?').unwrap().1;
        form_urlencoded::parse(query.as_bytes())
            .into_owned()
            .collect()
    }

    #[test]
    fn it_builds_a_spec_compliant_authorization_url() {
        let client =
            OAuthClient::new("my-client").with_redirect_uri("https://app.example.com/callback");
        let request = client
            .authorization_request(&metadata())
            .with_scopes(["read", "write"])
            .with_resource("https://api.example.com")
            .with_param("nonce", "n-1")
            .build()
            .unwrap();

        assert!(
            request
                .url
                .starts_with("https://auth.example.com/authorize?")
        );
        let pairs = query_pairs(&request.url);
        let get = |name: &str| {
            pairs
                .iter()
                .find(|(key, _)| key == name)
                .map(|(_, value)| value.as_str())
        };
        assert_eq!(get("response_type"), Some("code"));
        assert_eq!(get("client_id"), Some("my-client"));
        assert_eq!(
            get("redirect_uri"),
            Some("https://app.example.com/callback")
        );
        assert_eq!(get("scope"), Some("read write"));
        assert_eq!(get("resource"), Some("https://api.example.com"));
        assert_eq!(get("code_challenge"), Some(request.pkce.challenge()));
        assert_eq!(get("code_challenge_method"), Some("S256"));
        assert_eq!(get("state"), Some(request.state.as_str()));
        assert_eq!(get("nonce"), Some("n-1"));
        assert!(request.matches_state(&request.state.clone()));
        assert!(!request.matches_state("other"));
    }

    #[test]
    fn it_appends_to_an_existing_query_and_respects_custom_state() {
        let mut metadata = metadata();
        metadata.authorization_endpoint =
            Some("https://auth.example.com/authorize?tenant=t1".into());
        let request = OAuthClient::new("my-client")
            .authorization_request(&metadata)
            .with_state("custom-state")
            .build()
            .unwrap();
        assert!(request.url.contains("tenant=t1&response_type=code"));
        assert_eq!(request.state, "custom-state");
    }

    #[test]
    fn it_validates_metadata_before_building_requests() {
        let client = OAuthClient::new("my-client");

        let mut incomplete = metadata();
        incomplete.authorization_endpoint = None;
        assert!(matches!(
            client.authorization_request(&incomplete).build(),
            Err(ClientError::Validation(reason)) if reason.contains("authorization_endpoint")
        ));

        let mut plain_only = metadata();
        plain_only.code_challenge_methods_supported = vec!["plain".into()];
        assert!(matches!(
            client.authorization_request(&plain_only).build(),
            Err(ClientError::Validation(reason)) if reason.contains("S256")
        ));

        // https enforcement applies to the authorization endpoint too
        let mut insecure = metadata();
        insecure.authorization_endpoint = Some("http://auth.example.com/authorize".into());
        assert!(matches!(
            client.authorization_request(&insecure).build(),
            Err(ClientError::InsecureUrl(_))
        ));
    }

    #[test]
    fn it_encodes_basic_credentials_per_rfc6749() {
        // RFC 6749 Section 2.3.1: form-urlencode the id and secret first
        let header = basic_credentials("client with space", "s&cret");
        let encoded = header
            .to_str()
            .unwrap()
            .strip_prefix("Basic ")
            .unwrap()
            .to_owned();
        let decoded = String::from_utf8(STANDARD.decode(encoded).unwrap()).unwrap();
        assert_eq!(decoded, "client+with+space:s%26cret");
    }

    #[test]
    fn it_applies_the_configured_client_authentication() {
        let public = OAuthClient::new("my-client");
        let mut form = form_urlencoded::Serializer::new(String::new());
        assert!(public.apply_client_auth(&mut form).is_none());
        assert_eq!(form.finish(), "client_id=my-client");

        let basic = OAuthClient::new("my-client").with_secret("s3cret");
        let mut form = form_urlencoded::Serializer::new(String::new());
        assert!(basic.apply_client_auth(&mut form).is_some());
        assert_eq!(form.finish(), "");

        let post = OAuthClient::new("my-client")
            .with_secret("s3cret")
            .with_auth_method(ClientAuthMethod::Post);
        let mut form = form_urlencoded::Serializer::new(String::new());
        assert!(post.apply_client_auth(&mut form).is_none());
        assert_eq!(form.finish(), "client_id=my-client&client_secret=s3cret");
    }

    #[test]
    fn it_adopts_registered_credentials_per_auth_method() {
        let registration = |auth_method: serde_json::Value| {
            serde_json::from_value::<volga_oauth_core::ClientRegistrationResponse>(
                serde_json::json!({
                    "client_id": "generated-id",
                    "client_secret": "generated-secret",
                    "token_endpoint_auth_method": auth_method,
                    "redirect_uris": ["https://app.example.com/callback"]
                }),
            )
            .unwrap()
        };

        // an omitted method defaults to client_secret_basic
        let client =
            OAuthClient::from_registration(&registration(serde_json::Value::Null)).unwrap();
        assert_eq!(client.auth_method, ClientAuthMethod::Basic);
        assert_eq!(client.client_secret.as_deref(), Some("generated-secret"));
        assert_eq!(
            client.redirect_uri.as_deref(),
            Some("https://app.example.com/callback")
        );

        let client =
            OAuthClient::from_registration(&registration("client_secret_post".into())).unwrap();
        assert_eq!(client.auth_method, ClientAuthMethod::Post);
        assert_eq!(client.client_secret.as_deref(), Some("generated-secret"));

        // `none` sends no credentials - the client stays public even
        // though the server issued a secret
        let client = OAuthClient::from_registration(&registration("none".into())).unwrap();
        assert_eq!(client.client_secret, None);

        // a method this client cannot perform is rejected upfront rather
        // than failing with invalid_client at the token endpoint
        let err =
            OAuthClient::from_registration(&registration("client_secret_jwt".into())).unwrap_err();
        assert!(matches!(
            err,
            ClientError::Validation(reason) if reason.contains("client_secret_jwt")
        ));
    }

    #[test]
    fn it_returns_send_token_endpoint_futures() {
        // the token-endpoint futures must be spawnable onto a multi-thread
        // runtime: nothing non-`Sync` (the form serializer) may be held
        // across their awaits
        fn assert_send(_: impl Send) {}

        let client = OAuthClient::new("my-client")
            .with_token_store(Arc::new(crate::InMemoryTokenStore::default()));
        let metadata = metadata();
        let request = client.authorization_request(&metadata).build().unwrap();

        assert_send(client.exchange_code(&metadata, "the-code", &request));
        assert_send(client.refresh(&metadata, "the-refresh-token"));
        assert_send(client.token("alice", &metadata));
    }

    #[test]
    fn it_validates_the_authorization_callback() {
        let client = OAuthClient::new("my-client");
        let metadata = metadata();
        let request = client.authorization_request(&metadata).build().unwrap();
        let state = request.state.clone();

        // no `iss` and no advertisement - nothing more to check
        assert!(request.validate_callback(&metadata, &state, None).is_ok());
        assert!(
            request
                .validate_callback(&metadata, &state, Some(&metadata.issuer))
                .is_ok()
        );

        // CSRF: a foreign `state` never reaches the token endpoint
        let err = request
            .validate_callback(&metadata, "forged", None)
            .unwrap_err();
        assert!(matches!(err, ClientError::Validation(reason) if reason.contains("state")));

        // mix-up: a present `iss` must match the issuer, advertised or not
        let err = request
            .validate_callback(&metadata, &state, Some("https://evil.example.com"))
            .unwrap_err();
        assert!(
            matches!(err, ClientError::Validation(reason) if reason.contains("`iss` mismatch"))
        );

        // ...and it is mandatory once the server advertises RFC 9207
        let advertised = metadata.with_authorization_response_iss_parameter(true);
        assert!(
            request
                .validate_callback(&advertised, &state, Some(&advertised.issuer))
                .is_ok()
        );
        let err = request
            .validate_callback(&advertised, &state, None)
            .unwrap_err();
        assert!(matches!(err, ClientError::Validation(reason) if reason.contains("RFC 9207")));
    }

    #[test]
    #[should_panic(expected = "token store is not configured")]
    fn it_panics_on_store_access_without_a_store() {
        OAuthClient::new("my-client").store_tokens(
            "alice",
            &TokenSet {
                access_token: "at".into(),
                token_type: "Bearer".into(),
                refresh_token: None,
                scope: None,
                id_token: None,
                expires_at: None,
            },
        );
    }
}