Skip to main content

beyondigital_auth_sdk/
client.rs

1//! Async OAuth client for auth_service (tokio).
2//!
3//! Beside discovery, the code and refresh grants, introspection, revocation and registration, the client does the device
4//! flow (RFC 8628), token exchange (RFC 8693), pushed authorization requests (RFC 9126), RP-initiated logout URLs,
5//! `private_key_jwt` client authentication (RFC 7523) and DPoP (RFC 9449). Every request is sent once: a redirect is
6//! never followed, so a credential cannot be replayed to another origin.
7use std::fmt;
8use std::sync::Mutex;
9use std::time::Duration;
10
11use base64::Engine as _;
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15use crate::client_assertion::{
16    create_client_assertion, ClientAssertionKey, ClientAssertionOptions, CLIENT_ASSERTION_TYPE,
17};
18use crate::dpop::{
19    assert_dpop_supported, send_request, DpopKey, DpopRequest, DpopSession, HttpReply,
20};
21use crate::error::AuthError;
22use crate::flows::{
23    build_authorization_url_from_request_uri, parse_device_authorization,
24    parse_pushed_authorization, poll_for_device_token, pushed_request_params, DeviceAuthorization,
25    DevicePollOptions, PushedAuthorization, DEVICE_CODE_GRANT, TOKEN_EXCHANGE_GRANT,
26    TOKEN_TYPE_ACCESS_TOKEN,
27};
28use crate::logout::{build_end_session_url, EndSessionParams};
29use crate::wire::{credential_encode, encode_form, non_blank, origin_of};
30
31fn normalize_issuer(url: &str) -> String {
32    url.trim_end_matches('/').to_string()
33}
34
35#[derive(Debug, Clone, Deserialize, Serialize)]
36pub struct OidcMetadata {
37    pub issuer: String,
38    pub authorization_endpoint: String,
39    pub token_endpoint: String,
40    pub userinfo_endpoint: String,
41    pub registration_endpoint: String,
42    pub jwks_uri: String,
43    pub revocation_endpoint: String,
44    pub introspection_endpoint: String,
45    #[serde(default)]
46    pub scopes_supported: Vec<String>,
47    #[serde(default)]
48    pub response_types_supported: Vec<String>,
49    #[serde(default)]
50    pub grant_types_supported: Vec<String>,
51    /// OIDC RP-Initiated Logout: where to send the browser to end the session.
52    #[serde(default)]
53    pub end_session_endpoint: Option<String>,
54    /// RFC 8628.
55    #[serde(default)]
56    pub device_authorization_endpoint: Option<String>,
57    /// RFC 9126.
58    #[serde(default)]
59    pub pushed_authorization_request_endpoint: Option<String>,
60    #[serde(default)]
61    pub require_pushed_authorization_requests: Option<bool>,
62    /// RFC 9449: the proof algorithms the token endpoint accepts.
63    #[serde(default)]
64    pub dpop_signing_alg_values_supported: Option<Vec<String>>,
65    #[serde(default)]
66    pub token_endpoint_auth_signing_alg_values_supported: Option<Vec<String>>,
67}
68
69#[derive(Debug, Clone, Deserialize, Serialize)]
70pub struct TokenResponse {
71    pub access_token: String,
72    pub token_type: String,
73    pub expires_in: i64,
74    pub refresh_token: Option<String>,
75    pub id_token: Option<String>,
76    pub scope: Option<String>,
77    pub session_id: Option<String>,
78    /// RFC 8693: the type of the token a token exchange returned.
79    #[serde(default)]
80    pub issued_token_type: Option<String>,
81}
82
83#[derive(Debug, Clone, Deserialize, Serialize)]
84pub struct IntrospectionResponse {
85    pub active: bool,
86    #[serde(flatten)]
87    pub extra: serde_json::Value,
88}
89
90#[derive(Debug, Clone, Deserialize, Serialize)]
91pub struct UserInfoResponse {
92    pub sub: String,
93    pub email: String,
94    pub email_verified: bool,
95}
96
97fn validate_metadata(metadata: OidcMetadata, expected: &str) -> Result<OidcMetadata, AuthError> {
98    if metadata.issuer != expected {
99        return Err(AuthError::Config("OIDC discovery issuer mismatch".into()));
100    }
101    for value in [
102        &metadata.issuer,
103        &metadata.authorization_endpoint,
104        &metadata.token_endpoint,
105        &metadata.jwks_uri,
106    ] {
107        let url = reqwest::Url::parse(value)
108            .map_err(|_| AuthError::Config("Invalid OIDC discovery endpoint".into()))?;
109        let loopback = matches!(
110            url.host_str(),
111            Some("localhost" | "127.0.0.1" | "[::1]" | "::1")
112        );
113        if !url.username().is_empty()
114            || url.password().is_some()
115            || url.fragment().is_some()
116            || !(url.scheme() == "https" || url.scheme() == "http" && loopback)
117        {
118            return Err(AuthError::Config("Unsafe OIDC discovery endpoint".into()));
119        }
120    }
121    Ok(metadata)
122}
123
124fn parse_oauth_error(status: u16, body: &serde_json::Value) -> AuthError {
125    let err = body
126        .get("error")
127        .and_then(|v| v.as_str())
128        .or_else(|| body.get("detail").and_then(|v| v.as_str()))
129        .unwrap_or("unknown_error");
130    let desc = body
131        .get("error_description")
132        .and_then(|v| v.as_str())
133        .or_else(|| body.get("detail").and_then(|v| v.as_str()))
134        .unwrap_or(err);
135    AuthError::oauth(err, desc, status)
136}
137
138/// Match the registered token_endpoint_auth_method. Public clients use None.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum ClientAuthMethod {
141    None,
142    ClientSecretBasic,
143    ClientSecretPost,
144    /// RFC 7523: a signed assertion instead of a secret. Needs [`Client::with_client_assertion_key`]; the service
145    /// accepts it at the token and pushed authorization endpoints only.
146    PrivateKeyJwt,
147}
148
149/// The endpoints a client authenticates to. `private_key_jwt` is accepted at the first two only.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151enum Endpoint {
152    Token,
153    Par,
154    Revocation,
155    Introspection,
156    DeviceAuthorization,
157}
158
159impl Endpoint {
160    fn label(self) -> &'static str {
161        match self {
162            Self::Token => "token",
163            Self::Par => "pushed authorization",
164            Self::Revocation => "revocation",
165            Self::Introspection => "introspection",
166            Self::DeviceAuthorization => "device authorization",
167        }
168    }
169}
170
171/// How a token is presented to the userinfo endpoint (and to a resource server).
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum TokenType {
174    Bearer,
175    /// A token issued with a DPoP proof: sent under the `DPoP` scheme with a proof bound to it.
176    Dpop,
177}
178
179fn require_client_id<'a>(
180    explicit: Option<&'a str>,
181    configured: Option<&'a str>,
182) -> Result<&'a str, AuthError> {
183    explicit
184        .or(configured)
185        .filter(|id| non_blank(id))
186        .ok_or_else(|| AuthError::Config("client_id required".into()))
187}
188
189fn push_resources(params: &mut Vec<(String, String)>, resource: Option<&[String]>) {
190    for item in resource.unwrap_or_default() {
191        params.push(("resource".to_string(), item.clone()));
192    }
193}
194
195pub struct Client {
196    issuer: String,
197    client_id: Option<String>,
198    client_secret: Option<String>,
199    auth_method: Option<ClientAuthMethod>,
200    redirect_uri: Option<String>,
201    assertion_key: Option<ClientAssertionKey>,
202    dpop: Option<DpopSession>,
203    /// What `discover` last returned: the end-session endpoint and the DPoP algorithms the service advertises.
204    metadata: Mutex<Option<OidcMetadata>>,
205    http: reqwest::Client,
206}
207
208impl fmt::Debug for Client {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        f.debug_struct("Client")
211            .field("issuer", &self.issuer)
212            .field("client_id", &self.client_id)
213            .field("auth_method", &self.auth_method)
214            .finish_non_exhaustive()
215    }
216}
217
218impl Client {
219    pub fn new(issuer_url: impl Into<String>) -> Self {
220        Self {
221            issuer: normalize_issuer(&issuer_url.into()),
222            client_id: None,
223            client_secret: None,
224            auth_method: None,
225            redirect_uri: None,
226            assertion_key: None,
227            dpop: None,
228            metadata: Mutex::new(None),
229            http: reqwest::Client::builder()
230                .timeout(Duration::from_secs(10))
231                .redirect(reqwest::redirect::Policy::none())
232                .build()
233                .unwrap_or_else(|_| reqwest::Client::new()),
234        }
235    }
236    pub fn with_client_id(mut self, id: impl Into<String>) -> Self {
237        self.client_id = Some(id.into());
238        self
239    }
240    pub fn with_client_secret(mut self, s: impl Into<String>) -> Self {
241        self.client_secret = Some(s.into());
242        self
243    }
244    pub fn with_auth_method(mut self, method: ClientAuthMethod) -> Self {
245        self.auth_method = Some(method);
246        self
247    }
248    pub fn with_redirect_uri(mut self, uri: impl Into<String>) -> Self {
249        self.redirect_uri = Some(uri.into());
250        self
251    }
252    /// Authenticate with `private_key_jwt`: every token and pushed authorization request carries a new signed
253    /// assertion. Implies [`ClientAuthMethod::PrivateKeyJwt`]; a client secret or another method is refused when a
254    /// request is made.
255    pub fn with_client_assertion_key(mut self, key: ClientAssertionKey) -> Self {
256        self.assertion_key = Some(key);
257        self
258    }
259    /// Sender-constrain tokens with DPoP: `exchange_code` and `refresh` send a proof, and
260    /// [`userinfo_for`](Self::userinfo_for) and [`dpop_headers`](Self::dpop_headers) use it for a bound token.
261    pub fn with_dpop(mut self, key: DpopKey) -> Self {
262        self.dpop = Some(DpopSession::new(key));
263        self
264    }
265
266    fn remembered_metadata(&self) -> Option<OidcMetadata> {
267        self.metadata.lock().ok().and_then(|guard| guard.clone())
268    }
269
270    // ── discovery ──────────────────────────────────────────────────────
271
272    pub async fn discover(&self) -> Result<OidcMetadata, AuthError> {
273        let resp = self
274            .http
275            .get(format!("{}/.well-known/openid-configuration", self.issuer))
276            .send()
277            .await
278            .map_err(|e| AuthError::Network(e.to_string()))?;
279        if !resp.status().is_success() {
280            let status = resp.status().as_u16();
281            let body: serde_json::Value = resp.json().await.unwrap_or(serde_json::json!({}));
282            return Err(parse_oauth_error(status, &body));
283        }
284        let metadata = resp
285            .json()
286            .await
287            .map_err(|e| AuthError::Network(e.to_string()))?;
288        let metadata = validate_metadata(metadata, &self.issuer)?;
289        if let Ok(mut slot) = self.metadata.lock() {
290            *slot = Some(metadata.clone());
291        }
292        Ok(metadata)
293    }
294
295    pub async fn jwks(&self) -> Result<serde_json::Value, AuthError> {
296        let resp = self
297            .http
298            .get(format!("{}/.well-known/jwks.json", self.issuer))
299            .send()
300            .await
301            .map_err(|e| AuthError::Network(e.to_string()))?;
302        if !resp.status().is_success() {
303            return Err(AuthError::Network(format!(
304                "JWKS fetch failed: {}",
305                resp.status()
306            )));
307        }
308        resp.json()
309            .await
310            .map_err(|e| AuthError::Network(e.to_string()))
311    }
312
313    // ── authorization URL ──────────────────────────────────────────────
314
315    pub fn authorization_url(
316        &self,
317        code_challenge: &str,
318        opts: AuthorizationUrlOpts,
319    ) -> Result<String, AuthError> {
320        let cid = opts
321            .client_id
322            .as_deref()
323            .or(self.client_id.as_deref())
324            .ok_or_else(|| AuthError::Config("client_id required".into()))?;
325        let ruri = opts
326            .redirect_uri
327            .as_deref()
328            .or(self.redirect_uri.as_deref())
329            .ok_or_else(|| AuthError::Config("redirect_uri required".into()))?;
330        let mut url = reqwest::Url::parse(&format!("{}/oauth/authorize", self.issuer))
331            .map_err(|e| AuthError::Config(e.to_string()))?;
332        url.query_pairs_mut().append_pair("response_type", "code");
333        url.query_pairs_mut().append_pair("client_id", cid);
334        url.query_pairs_mut().append_pair("redirect_uri", ruri);
335        url.query_pairs_mut()
336            .append_pair("code_challenge", code_challenge);
337        url.query_pairs_mut()
338            .append_pair("code_challenge_method", "S256");
339        if let Some(s) = opts.scope {
340            url.query_pairs_mut().append_pair("scope", &s);
341        }
342        if let Some(s) = opts.state {
343            url.query_pairs_mut().append_pair("state", &s);
344        }
345        if let Some(n) = opts.nonce {
346            url.query_pairs_mut().append_pair("nonce", &n);
347        }
348        for r in opts.resource.unwrap_or_default() {
349            url.query_pairs_mut().append_pair("resource", &r);
350        }
351        Ok(url.to_string())
352    }
353
354    // ── client authentication and sending ──────────────────────────────
355
356    /// Add this client's authentication to `params` (in place) and return the request headers.
357    ///
358    /// Idempotent: whatever an earlier attempt added is removed first, so a retry carries a new `private_key_jwt`
359    /// assertion rather than the single-use one it already sent.
360    fn client_auth(
361        &self,
362        params: &mut Vec<(String, String)>,
363        client_id: &str,
364        secret: Option<&str>,
365        endpoint: Endpoint,
366    ) -> Result<Vec<(String, String)>, AuthError> {
367        let method = self.auth_method.unwrap_or(if self.assertion_key.is_some() {
368            ClientAuthMethod::PrivateKeyJwt
369        } else if secret.is_some() {
370            ClientAuthMethod::ClientSecretBasic
371        } else {
372            ClientAuthMethod::None
373        });
374        if self.assertion_key.is_some() && method != ClientAuthMethod::PrivateKeyJwt {
375            return Err(AuthError::Config(
376                "a client assertion key is only for the private_key_jwt method".into(),
377            ));
378        }
379        params.retain(|(key, _)| {
380            !matches!(
381                key.as_str(),
382                "client_id" | "client_secret" | "client_assertion" | "client_assertion_type"
383            )
384        });
385        let mut headers = vec![(
386            "Content-Type".to_string(),
387            "application/x-www-form-urlencoded".to_string(),
388        )];
389        match method {
390            ClientAuthMethod::PrivateKeyJwt => {
391                // The service verifies assertions at the token and pushed authorization endpoints only.
392                if !matches!(endpoint, Endpoint::Token | Endpoint::Par) {
393                    return Err(AuthError::Config(format!(
394                        "private_key_jwt is not accepted at the {} endpoint of the service",
395                        endpoint.label()
396                    )));
397                }
398                if secret.is_some() || self.client_secret.is_some() {
399                    return Err(AuthError::Config(
400                        "private_key_jwt does not use a client secret".into(),
401                    ));
402                }
403                let key = self.assertion_key.as_ref().ok_or_else(|| {
404                    AuthError::Config("private_key_jwt needs a client assertion key".into())
405                })?;
406                let audience = format!(
407                    "{}/oauth/{}",
408                    self.issuer,
409                    if endpoint == Endpoint::Par {
410                        "par"
411                    } else {
412                        "token"
413                    }
414                );
415                let assertion = create_client_assertion(
416                    client_id,
417                    &audience,
418                    key,
419                    ClientAssertionOptions::default(),
420                )?;
421                params.push(("client_id".into(), client_id.into()));
422                params.push(("client_assertion_type".into(), CLIENT_ASSERTION_TYPE.into()));
423                params.push(("client_assertion".into(), assertion));
424            }
425            ClientAuthMethod::None => {
426                if secret.is_some() {
427                    return Err(AuthError::Config(
428                        "public clients must not send a client secret".into(),
429                    ));
430                }
431                params.push(("client_id".into(), client_id.into()));
432            }
433            ClientAuthMethod::ClientSecretPost => {
434                let secret = secret.ok_or_else(|| {
435                    AuthError::Config("client_secret_post requires a secret".into())
436                })?;
437                params.push(("client_id".into(), client_id.into()));
438                params.push(("client_secret".into(), secret.into()));
439            }
440            ClientAuthMethod::ClientSecretBasic => {
441                let secret = secret.ok_or_else(|| {
442                    AuthError::Config("client_secret_basic requires a secret".into())
443                })?;
444                // RFC 6749 section 2.3.1 form-encodes the id and secret before Basic. A space is %20, never +: the
445                // service's Basic decoder (percent_decode in routes/oauth.rs) leaves a + as a literal plus.
446                let creds = base64::engine::general_purpose::STANDARD.encode(
447                    format!(
448                        "{}:{}",
449                        credential_encode(client_id),
450                        credential_encode(secret)
451                    )
452                    .as_bytes(),
453                );
454                headers.push(("Authorization".into(), format!("Basic {creds}")));
455            }
456        }
457        Ok(headers)
458    }
459
460    fn endpoint_url(&self, path: &str) -> String {
461        format!("{}{path}", self.issuer)
462    }
463
464    /// POST a form to `path` with this client's authentication; the request is built once.
465    async fn post_form(
466        &self,
467        path: &str,
468        mut params: Vec<(String, String)>,
469        client_id: &str,
470        secret: Option<&str>,
471        endpoint: Endpoint,
472    ) -> Result<HttpReply, AuthError> {
473        let headers = self.client_auth(&mut params, client_id, secret, endpoint)?;
474        let body = encode_form(&params).into_bytes();
475        send_request(
476            &self.http,
477            "POST",
478            &self.endpoint_url(path),
479            &headers,
480            Some(&body),
481        )
482        .await
483    }
484
485    fn oauth_error_of(reply: &HttpReply) -> AuthError {
486        parse_oauth_error(reply.status, &reply.json().unwrap_or(serde_json::json!({})))
487    }
488
489    fn decode<T: serde::de::DeserializeOwned>(reply: &HttpReply) -> Result<T, AuthError> {
490        if !reply.is_success() {
491            return Err(Self::oauth_error_of(reply));
492        }
493        serde_json::from_slice(&reply.body)
494            .map_err(|_| AuthError::Network("The service returned an unreadable response".into()))
495    }
496
497    // ── token ──────────────────────────────────────────────────────────
498
499    pub async fn exchange_code(
500        &self,
501        code: &str,
502        code_verifier: &str,
503        opts: TokenOpts,
504    ) -> Result<TokenResponse, AuthError> {
505        let cid = opts
506            .client_id
507            .as_deref()
508            .or(self.client_id.as_deref())
509            .ok_or_else(|| AuthError::Config("client_id required".into()))?;
510        let ruri = opts
511            .redirect_uri
512            .as_deref()
513            .or(self.redirect_uri.as_deref())
514            .ok_or_else(|| AuthError::Config("redirect_uri required".into()))?;
515        let mut params = vec![
516            ("grant_type".to_string(), "authorization_code".to_string()),
517            ("client_id".to_string(), cid.to_string()),
518            ("code".to_string(), code.to_string()),
519            ("code_verifier".to_string(), code_verifier.to_string()),
520            ("redirect_uri".to_string(), ruri.to_string()),
521        ];
522        push_resources(&mut params, opts.resource.as_deref());
523        self.token_request(
524            params,
525            cid,
526            opts.client_secret
527                .as_deref()
528                .or(self.client_secret.as_deref()),
529            true,
530        )
531        .await
532    }
533
534    pub async fn refresh(
535        &self,
536        refresh_token: &str,
537        opts: TokenOpts,
538    ) -> Result<TokenResponse, AuthError> {
539        let cid = opts
540            .client_id
541            .as_deref()
542            .or(self.client_id.as_deref())
543            .ok_or_else(|| AuthError::Config("client_id required".into()))?;
544        let mut params = vec![
545            ("grant_type".to_string(), "refresh_token".to_string()),
546            ("client_id".to_string(), cid.to_string()),
547            ("refresh_token".to_string(), refresh_token.to_string()),
548        ];
549        push_resources(&mut params, opts.resource.as_deref());
550        self.token_request(
551            params,
552            cid,
553            opts.client_secret
554                .as_deref()
555                .or(self.client_secret.as_deref()),
556            true,
557        )
558        .await
559    }
560
561    pub async fn client_credentials(
562        &self,
563        resource: Vec<String>,
564        scope: Option<String>,
565        opts: TokenOpts,
566    ) -> Result<TokenResponse, AuthError> {
567        let cid = opts
568            .client_id
569            .as_deref()
570            .or(self.client_id.as_deref())
571            .ok_or_else(|| AuthError::Config("client_id required".into()))?;
572        let sec = opts
573            .client_secret
574            .as_deref()
575            .or(self.client_secret.as_deref());
576        let keyed = self.assertion_key.is_some()
577            || self.auth_method == Some(ClientAuthMethod::PrivateKeyJwt);
578        if sec.is_none() && !keyed {
579            return Err(AuthError::Config(
580                "client_secret required for client_credentials".into(),
581            ));
582        }
583        let mut params = vec![
584            ("grant_type".to_string(), "client_credentials".to_string()),
585            ("client_id".to_string(), cid.to_string()),
586        ];
587        if let Some(s) = scope {
588            params.push(("scope".to_string(), s));
589        }
590        for r in resource {
591            params.push(("resource".to_string(), r));
592        }
593        self.token_request(params, cid, sec, false).await
594    }
595
596    /// POST to the token endpoint with client authentication. `dpop` adds a proof (only the code and refresh grants may
597    /// carry one). Authentication runs once per attempt, so the one retry after a `use_dpop_nonce` challenge carries a
598    /// new `private_key_jwt` assertion: the service consumes an assertion's `jti` before it looks at the proof, and
599    /// would refuse the old one as replayed.
600    async fn token_request(
601        &self,
602        params: Vec<(String, String)>,
603        client_id: &str,
604        client_secret: Option<&str>,
605        dpop: bool,
606    ) -> Result<TokenResponse, AuthError> {
607        let url = self.endpoint_url("/oauth/token");
608        let build = |_attempt: u32| -> Result<DpopRequest, AuthError> {
609            let mut attempt_params = params.clone();
610            let headers = self.client_auth(
611                &mut attempt_params,
612                client_id,
613                client_secret,
614                Endpoint::Token,
615            )?;
616            Ok(DpopRequest {
617                headers,
618                body: Some(encode_form(&attempt_params).into_bytes()),
619            })
620        };
621        let reply = match (&self.dpop, dpop) {
622            (Some(session), true) => {
623                if let Some(metadata) = self.remembered_metadata() {
624                    assert_dpop_supported(
625                        metadata.dpop_signing_alg_values_supported.as_deref(),
626                        session.key(),
627                    )?;
628                }
629                session.fetch(&self.http, "POST", &url, build, None).await?
630            }
631            _ => {
632                let request = build(0)?;
633                send_request(
634                    &self.http,
635                    "POST",
636                    &url,
637                    &request.headers,
638                    request.body.as_deref(),
639                )
640                .await?
641            }
642        };
643        Self::decode(&reply)
644    }
645
646    // ── device flow (RFC 8628) ─────────────────────────────────────────
647
648    /// Ask for a device code and a user code.
649    ///
650    /// Show `user_code` and `verification_uri` (or `verification_uri_complete`, for a QR code) to the person, then call
651    /// [`poll_device_token`](Self::poll_device_token). The client must be registered for the device_code grant; a
652    /// confidential client authenticates with its secret (`private_key_jwt` is not accepted at this endpoint by the
653    /// service).
654    pub async fn start_device_authorization(
655        &self,
656        opts: DeviceAuthorizationOpts,
657    ) -> Result<DeviceAuthorization, AuthError> {
658        let cid = require_client_id(opts.client_id.as_deref(), self.client_id.as_deref())?;
659        let mut params = Vec::new();
660        if let Some(scope) = opts.scope.as_deref().filter(|s| !s.is_empty()) {
661            params.push(("scope".to_string(), scope.to_string()));
662        }
663        push_resources(&mut params, opts.resource.as_deref());
664        let secret = opts
665            .client_secret
666            .as_deref()
667            .or(self.client_secret.as_deref());
668        let reply = self
669            .post_form(
670                "/oauth/device/code",
671                params,
672                cid,
673                secret,
674                Endpoint::DeviceAuthorization,
675            )
676            .await?;
677        if !reply.is_success() {
678            return Err(Self::oauth_error_of(&reply));
679        }
680        parse_device_authorization(&reply.json().unwrap_or(Value::Null))
681    }
682
683    /// Poll the token endpoint until the person approves.
684    ///
685    /// Waits the interval before each poll, adds five seconds after `slow_down`, and stops with the service's OAuth
686    /// error for `access_denied`, `expired_token` or anything else (and with `expired_token` once the device code's own
687    /// lifetime would pass). Cancel through the [`CancelToken`](crate::CancelToken) in `poll` to stop
688    /// ([`AuthError::Cancelled`]). A network failure is returned, not retried; call again with the same authorization
689    /// to resume.
690    pub async fn poll_device_token(
691        &self,
692        device: &DeviceAuthorization,
693        opts: TokenOpts,
694        poll: &DevicePollOptions,
695    ) -> Result<TokenResponse, AuthError> {
696        let cid = require_client_id(opts.client_id.as_deref(), self.client_id.as_deref())?;
697        let secret = opts
698            .client_secret
699            .as_deref()
700            .or(self.client_secret.as_deref());
701        poll_for_device_token(
702            device,
703            || async {
704                let params = vec![
705                    ("grant_type".to_string(), DEVICE_CODE_GRANT.to_string()),
706                    ("client_id".to_string(), cid.to_string()),
707                    ("device_code".to_string(), device.device_code.clone()),
708                ];
709                self.token_request(params, cid, secret, false).await
710            },
711            poll,
712        )
713        .await
714    }
715
716    /// [`start_device_authorization`](Self::start_device_authorization), hand the codes to `on_user_code`, then
717    /// [`poll_device_token`](Self::poll_device_token) with the same authorization.
718    pub async fn device_login<F>(
719        &self,
720        on_user_code: F,
721        opts: DeviceAuthorizationOpts,
722        poll: &DevicePollOptions,
723    ) -> Result<TokenResponse, AuthError>
724    where
725        F: FnOnce(&DeviceAuthorization),
726    {
727        let token_opts = TokenOpts {
728            client_id: opts.client_id.clone(),
729            client_secret: opts.client_secret.clone(),
730            ..Default::default()
731        };
732        let device = self.start_device_authorization(opts).await?;
733        on_user_code(&device);
734        self.poll_device_token(&device, token_opts, poll).await
735    }
736
737    // ── token exchange (RFC 8693) ──────────────────────────────────────
738
739    /// Exchange an access token for a delegated one (the service's delegation grants decide whether it may).
740    ///
741    /// `subject_token` is the delegator's access token; `opts.actor_token` the acting party's. The token types default to
742    /// the only one the service supports. Never carries a DPoP proof: the service accepts one for the code and refresh
743    /// grants only.
744    pub async fn exchange_token(
745        &self,
746        subject_token: &str,
747        opts: TokenExchangeOpts,
748    ) -> Result<TokenResponse, AuthError> {
749        let cid = require_client_id(opts.client_id.as_deref(), self.client_id.as_deref())?;
750        let blank = |value: &Option<String>| value.as_deref().is_some_and(|v| !non_blank(v));
751        if subject_token.is_empty() {
752            return Err(AuthError::Config("subject_token is required".into()));
753        }
754        for (name, value) in [
755            ("actor_token", &opts.actor_token),
756            ("subject_token_type", &opts.subject_token_type),
757            ("actor_token_type", &opts.actor_token_type),
758            ("requested_token_type", &opts.requested_token_type),
759        ] {
760            if blank(value) {
761                return Err(AuthError::Config(format!(
762                    "{name} must not be blank when given"
763                )));
764            }
765        }
766        let mut params = vec![
767            ("grant_type".to_string(), TOKEN_EXCHANGE_GRANT.to_string()),
768            ("client_id".to_string(), cid.to_string()),
769            ("subject_token".to_string(), subject_token.to_string()),
770            (
771                "subject_token_type".to_string(),
772                opts.subject_token_type
773                    .clone()
774                    .unwrap_or_else(|| TOKEN_TYPE_ACCESS_TOKEN.to_string()),
775            ),
776        ];
777        if let Some(actor) = &opts.actor_token {
778            params.push(("actor_token".to_string(), actor.clone()));
779            params.push((
780                "actor_token_type".to_string(),
781                opts.actor_token_type
782                    .clone()
783                    .unwrap_or_else(|| TOKEN_TYPE_ACCESS_TOKEN.to_string()),
784            ));
785        }
786        if let Some(requested) = opts
787            .requested_token_type
788            .as_deref()
789            .filter(|v| !v.is_empty())
790        {
791            params.push(("requested_token_type".to_string(), requested.to_string()));
792        }
793        if let Some(scope) = opts.scope.as_deref().filter(|v| !v.is_empty()) {
794            params.push(("scope".to_string(), scope.to_string()));
795        }
796        push_resources(&mut params, opts.resource.as_deref());
797        let secret = opts
798            .client_secret
799            .as_deref()
800            .or(self.client_secret.as_deref());
801        let reply = self
802            .post_form("/oauth/token", params, cid, secret, Endpoint::Token)
803            .await?;
804        Self::decode(&reply)
805    }
806
807    // ── pushed authorization requests (RFC 9126) ───────────────────────
808
809    /// Send the authorize parameters to the service directly and get a one-use `request_uri` back, so the browser
810    /// carries nothing the person could read or edit.
811    ///
812    /// Authenticates like the token endpoint. Then redirect to
813    /// [`create_authorization_url_from_request_uri`](Self::create_authorization_url_from_request_uri).
814    pub async fn push_authorization_request(
815        &self,
816        code_challenge: &str,
817        opts: PushedAuthorizationOpts,
818    ) -> Result<PushedAuthorization, AuthError> {
819        let cid = opts
820            .client_id
821            .as_deref()
822            .or(self.client_id.as_deref())
823            .filter(|id| non_blank(id))
824            .ok_or_else(|| {
825                AuthError::Config("client_id is required to push an authorization request".into())
826            })?;
827        let ruri = opts
828            .redirect_uri
829            .as_deref()
830            .or(self.redirect_uri.as_deref())
831            .filter(|uri| non_blank(uri))
832            .ok_or_else(|| {
833                AuthError::Config(
834                    "redirect_uri is required to push an authorization request".into(),
835                )
836            })?;
837        let params = pushed_request_params(
838            cid,
839            ruri,
840            code_challenge,
841            opts.state.as_deref(),
842            opts.scope.as_deref(),
843            opts.nonce.as_deref(),
844            opts.resource.as_deref().unwrap_or_default(),
845            &opts.extra,
846        )?;
847        let secret = opts
848            .client_secret
849            .as_deref()
850            .or(self.client_secret.as_deref());
851        let reply = self
852            .post_form("/oauth/par", params, cid, secret, Endpoint::Par)
853            .await?;
854        if !reply.is_success() {
855            return Err(Self::oauth_error_of(&reply));
856        }
857        parse_pushed_authorization(&reply.json().unwrap_or(Value::Null))
858    }
859
860    /// The authorize URL for a pushed request: `client_id` and `request_uri` only.
861    pub fn create_authorization_url_from_request_uri(
862        &self,
863        request_uri: &str,
864    ) -> Result<String, AuthError> {
865        let cid = self.client_id.as_deref().ok_or_else(|| {
866            AuthError::Config("client_id is required to create authorization URL".into())
867        })?;
868        build_authorization_url_from_request_uri(&self.issuer, cid, request_uri)
869    }
870
871    // ── RP-initiated logout ────────────────────────────────────────────
872
873    /// The URL to send the person's browser to in order to end their session.
874    ///
875    /// Uses the discovered `end_session_endpoint` when it is on the issuer's origin, `<issuer>/oauth/end_session`
876    /// otherwise. The service redirects to `post_logout_redirect_uri` only for an `id_token_hint` that names a client
877    /// for which that URI is registered. `params.end_session_endpoint` is ignored here: the client supplies it.
878    pub fn create_end_session_url(&self, params: &EndSessionParams) -> Result<String, AuthError> {
879        let discovered = self
880            .remembered_metadata()
881            .and_then(|metadata| metadata.end_session_endpoint);
882        let endpoint = discovered.filter(|candidate| {
883            matches!(
884                (origin_of(candidate), origin_of(&self.issuer)),
885                (Some(a), Some(b)) if a == b
886            )
887        });
888        let mut effective = params.clone();
889        effective.end_session_endpoint = endpoint;
890        build_end_session_url(&self.issuer, &effective)
891    }
892
893    // ── DPoP (RFC 9449) ────────────────────────────────────────────────
894
895    /// The `Authorization: DPoP <token>` and `DPoP: <proof>` headers for a request to any resource server, with the
896    /// proof bound to the token (`ath`), the method and the URL (query and fragment excluded). Needs the key from
897    /// [`with_dpop`](Self::with_dpop). Call once per request: a proof is single use.
898    pub fn dpop_headers(
899        &self,
900        access_token: &str,
901        method: &str,
902        url: &str,
903    ) -> Result<Vec<(String, String)>, AuthError> {
904        let session = self
905            .dpop
906            .as_ref()
907            .ok_or_else(|| AuthError::Config("a dpop key is required: use with_dpop".into()))?;
908        session.headers(method, url, Some(access_token))
909    }
910
911    // ── introspect / revoke / userinfo / register ──────────────────────
912
913    pub async fn introspect(
914        &self,
915        token: &str,
916        audience: &str,
917        client_id: Option<&str>,
918        client_secret: Option<&str>,
919    ) -> Result<IntrospectionResponse, AuthError> {
920        let cid = client_id
921            .or(self.client_id.as_deref())
922            .ok_or_else(|| AuthError::Config("client_id required for introspect".into()))?;
923        let sec = client_secret.or(self.client_secret.as_deref());
924        let keyed = self.assertion_key.is_some()
925            || self.auth_method == Some(ClientAuthMethod::PrivateKeyJwt);
926        if sec.is_none() && !keyed {
927            // A keyed client is refused by client_auth, with the reason the service gives.
928            return Err(AuthError::Config(
929                "client_secret required for introspect".into(),
930            ));
931        }
932        let params = vec![
933            ("token".to_string(), token.to_string()),
934            ("audience".to_string(), audience.to_string()),
935        ];
936        let reply = self
937            .post_form(
938                "/oauth/introspect",
939                params,
940                cid,
941                sec,
942                Endpoint::Introspection,
943            )
944            .await?;
945        Self::decode(&reply)
946    }
947
948    pub async fn revoke(&self, token: &str) -> Result<(), AuthError> {
949        let cid = self
950            .client_id
951            .as_deref()
952            .ok_or_else(|| AuthError::Config("client_id required for revocation".into()))?;
953        let params = vec![("token".to_string(), token.to_string())];
954        let reply = self
955            .post_form(
956                "/oauth/revoke",
957                params,
958                cid,
959                self.client_secret.as_deref(),
960                Endpoint::Revocation,
961            )
962            .await?;
963        if !reply.is_success() {
964            return Err(Self::oauth_error_of(&reply));
965        }
966        Ok(())
967    }
968
969    /// The userinfo endpoint with a bearer token.
970    pub async fn userinfo(&self, access_token: &str) -> Result<UserInfoResponse, AuthError> {
971        self.userinfo_for(access_token, TokenType::Bearer).await
972    }
973
974    /// The userinfo endpoint. [`TokenType::Dpop`] is for a token issued with a DPoP proof: it is sent under the `DPoP`
975    /// scheme with a proof bound to it, and needs the key from [`with_dpop`](Self::with_dpop).
976    pub async fn userinfo_for(
977        &self,
978        access_token: &str,
979        token_type: TokenType,
980    ) -> Result<UserInfoResponse, AuthError> {
981        let url = self.endpoint_url("/oauth/userinfo");
982        let reply = match token_type {
983            TokenType::Bearer => {
984                let headers = vec![(
985                    "Authorization".to_string(),
986                    format!("Bearer {access_token}"),
987                )];
988                send_request(&self.http, "GET", &url, &headers, None).await?
989            }
990            TokenType::Dpop => {
991                let session = self.dpop.as_ref().ok_or_else(|| {
992                    AuthError::Config(
993                        "a dpop key is required to use a DPoP token: use with_dpop".into(),
994                    )
995                })?;
996                if let Some(metadata) = self.remembered_metadata() {
997                    assert_dpop_supported(
998                        metadata.dpop_signing_alg_values_supported.as_deref(),
999                        session.key(),
1000                    )?;
1001                }
1002                let authorization = format!("DPoP {access_token}");
1003                reqwest::header::HeaderValue::from_str(&authorization).map_err(|_| {
1004                    AuthError::Config("The access token is not a valid header value".into())
1005                })?;
1006                session
1007                    .fetch(
1008                        &self.http,
1009                        "GET",
1010                        &url,
1011                        |_| {
1012                            Ok(DpopRequest {
1013                                headers: vec![("Authorization".to_string(), authorization.clone())],
1014                                body: None,
1015                            })
1016                        },
1017                        Some(access_token),
1018                    )
1019                    .await?
1020            }
1021        };
1022        Self::decode(&reply)
1023    }
1024
1025    pub async fn register(&self, input: serde_json::Value) -> Result<serde_json::Value, AuthError> {
1026        let resp = self
1027            .http
1028            .post(format!("{}/oauth/register", self.issuer))
1029            .json(&input)
1030            .send()
1031            .await
1032            .map_err(|e| AuthError::Network(e.to_string()))?;
1033        if !resp.status().is_success() {
1034            let status = resp.status().as_u16();
1035            let body: serde_json::Value = resp.json().await.unwrap_or(serde_json::json!({}));
1036            return Err(parse_oauth_error(status, &body));
1037        }
1038        resp.json()
1039            .await
1040            .map_err(|e| AuthError::Network(e.to_string()))
1041    }
1042}
1043
1044#[derive(Debug, Default)]
1045pub struct AuthorizationUrlOpts {
1046    pub scope: Option<String>,
1047    pub state: Option<String>,
1048    pub nonce: Option<String>,
1049    pub resource: Option<Vec<String>>,
1050    pub client_id: Option<String>,
1051    pub redirect_uri: Option<String>,
1052}
1053
1054#[derive(Debug, Default)]
1055pub struct TokenOpts {
1056    pub client_id: Option<String>,
1057    pub client_secret: Option<String>,
1058    pub redirect_uri: Option<String>,
1059    pub resource: Option<Vec<String>>,
1060}
1061
1062/// Options for [`Client::start_device_authorization`].
1063#[derive(Clone, Default)]
1064pub struct DeviceAuthorizationOpts {
1065    pub scope: Option<String>,
1066    pub resource: Option<Vec<String>>,
1067    pub client_id: Option<String>,
1068    pub client_secret: Option<String>,
1069}
1070
1071impl fmt::Debug for DeviceAuthorizationOpts {
1072    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1073        f.debug_struct("DeviceAuthorizationOpts")
1074            .field("scope", &self.scope)
1075            .field("resource", &self.resource)
1076            .field("client_id", &self.client_id)
1077            .finish_non_exhaustive()
1078    }
1079}
1080
1081/// Options for [`Client::exchange_token`].
1082#[derive(Clone, Default)]
1083pub struct TokenExchangeOpts {
1084    /// Defaults to the access token type, the only one the service exchanges.
1085    pub subject_token_type: Option<String>,
1086    /// The acting party's access token (delegation).
1087    pub actor_token: Option<String>,
1088    pub actor_token_type: Option<String>,
1089    pub requested_token_type: Option<String>,
1090    pub scope: Option<String>,
1091    pub resource: Option<Vec<String>>,
1092    pub client_id: Option<String>,
1093    pub client_secret: Option<String>,
1094}
1095
1096impl fmt::Debug for TokenExchangeOpts {
1097    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1098        f.debug_struct("TokenExchangeOpts")
1099            .field("scope", &self.scope)
1100            .field("resource", &self.resource)
1101            .field("client_id", &self.client_id)
1102            .finish_non_exhaustive()
1103    }
1104}
1105
1106/// Options for [`Client::push_authorization_request`].
1107#[derive(Clone, Default)]
1108pub struct PushedAuthorizationOpts {
1109    pub state: Option<String>,
1110    pub scope: Option<String>,
1111    pub nonce: Option<String>,
1112    pub resource: Option<Vec<String>>,
1113    pub redirect_uri: Option<String>,
1114    /// More authorize parameters (`prompt`, `login_hint`, `max_age`, `organization` ...). Nothing that authenticates the
1115    /// client and no parameter the SDK sets itself.
1116    pub extra: Vec<(String, String)>,
1117    pub client_id: Option<String>,
1118    pub client_secret: Option<String>,
1119}
1120
1121impl fmt::Debug for PushedAuthorizationOpts {
1122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1123        f.debug_struct("PushedAuthorizationOpts")
1124            .field("scope", &self.scope)
1125            .field("resource", &self.resource)
1126            .field("client_id", &self.client_id)
1127            .finish_non_exhaustive()
1128    }
1129}