oauth2_types/
requests.rs

1// Copyright 2024 New Vector Ltd.
2// Copyright 2021-2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only
5// Please see LICENSE in the repository root for full details.
6
7//! Requests and response types to interact with the [OAuth 2.0] specification.
8//!
9//! [OAuth 2.0]: https://oauth.net/2/
10
11use std::{collections::HashSet, fmt, hash::Hash, num::NonZeroU32};
12
13use chrono::{DateTime, Duration, Utc};
14use language_tags::LanguageTag;
15use mas_iana::oauth::{OAuthAccessTokenType, OAuthTokenTypeHint};
16use serde::{Deserialize, Serialize};
17use serde_with::{
18    DeserializeFromStr, DisplayFromStr, DurationSeconds, SerializeDisplay, StringWithSeparator,
19    TimestampSeconds, formats::SpaceSeparator, serde_as, skip_serializing_none,
20};
21use url::Url;
22
23use crate::{response_type::ResponseType, scope::Scope};
24
25// ref: https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml
26
27/// The mechanism to be used for returning Authorization Response parameters
28/// from the Authorization Endpoint.
29///
30/// Defined in [OAuth 2.0 Multiple Response Type Encoding Practices](https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes).
31#[derive(
32    Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, SerializeDisplay, DeserializeFromStr,
33)]
34#[non_exhaustive]
35pub enum ResponseMode {
36    /// Authorization Response parameters are encoded in the query string added
37    /// to the `redirect_uri`.
38    Query,
39
40    /// Authorization Response parameters are encoded in the fragment added to
41    /// the `redirect_uri`.
42    Fragment,
43
44    /// Authorization Response parameters are encoded as HTML form values that
45    /// are auto-submitted in the User Agent, and thus are transmitted via the
46    /// HTTP `POST` method to the Client, with the result parameters being
47    /// encoded in the body using the `application/x-www-form-urlencoded`
48    /// format.
49    ///
50    /// Defined in [OAuth 2.0 Form Post Response Mode](https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html).
51    FormPost,
52
53    /// An unknown value.
54    Unknown(String),
55}
56
57impl core::fmt::Display for ResponseMode {
58    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
59        match self {
60            ResponseMode::Query => f.write_str("query"),
61            ResponseMode::Fragment => f.write_str("fragment"),
62            ResponseMode::FormPost => f.write_str("form_post"),
63            ResponseMode::Unknown(s) => f.write_str(s),
64        }
65    }
66}
67
68impl core::str::FromStr for ResponseMode {
69    type Err = core::convert::Infallible;
70
71    fn from_str(s: &str) -> Result<Self, Self::Err> {
72        match s {
73            "query" => Ok(ResponseMode::Query),
74            "fragment" => Ok(ResponseMode::Fragment),
75            "form_post" => Ok(ResponseMode::FormPost),
76            s => Ok(ResponseMode::Unknown(s.to_owned())),
77        }
78    }
79}
80
81/// Value that specifies how the Authorization Server displays the
82/// authentication and consent user interface pages to the End-User.
83///
84/// Defined in [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest).
85#[derive(
86    Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, SerializeDisplay, DeserializeFromStr,
87)]
88#[non_exhaustive]
89pub enum Display {
90    /// The Authorization Server should display the authentication and consent
91    /// UI consistent with a full User Agent page view.
92    ///
93    /// This is the default display mode.
94    Page,
95
96    /// The Authorization Server should display the authentication and consent
97    /// UI consistent with a popup User Agent window.
98    Popup,
99
100    /// The Authorization Server should display the authentication and consent
101    /// UI consistent with a device that leverages a touch interface.
102    Touch,
103
104    /// The Authorization Server should display the authentication and consent
105    /// UI consistent with a "feature phone" type display.
106    Wap,
107
108    /// An unknown value.
109    Unknown(String),
110}
111
112impl core::fmt::Display for Display {
113    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
114        match self {
115            Display::Page => f.write_str("page"),
116            Display::Popup => f.write_str("popup"),
117            Display::Touch => f.write_str("touch"),
118            Display::Wap => f.write_str("wap"),
119            Display::Unknown(s) => f.write_str(s),
120        }
121    }
122}
123
124impl core::str::FromStr for Display {
125    type Err = core::convert::Infallible;
126
127    fn from_str(s: &str) -> Result<Self, Self::Err> {
128        match s {
129            "page" => Ok(Display::Page),
130            "popup" => Ok(Display::Popup),
131            "touch" => Ok(Display::Touch),
132            "wap" => Ok(Display::Wap),
133            s => Ok(Display::Unknown(s.to_owned())),
134        }
135    }
136}
137
138impl Default for Display {
139    fn default() -> Self {
140        Self::Page
141    }
142}
143
144/// Value that specifies whether the Authorization Server prompts the End-User
145/// for reauthentication and consent.
146///
147/// Defined in [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest).
148#[derive(
149    Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, SerializeDisplay, DeserializeFromStr,
150)]
151#[non_exhaustive]
152pub enum Prompt {
153    /// The Authorization Server must not display any authentication or consent
154    /// user interface pages.
155    None,
156
157    /// The Authorization Server should prompt the End-User for
158    /// reauthentication.
159    Login,
160
161    /// The Authorization Server should prompt the End-User for consent before
162    /// returning information to the Client.
163    Consent,
164
165    /// The Authorization Server should prompt the End-User to select a user
166    /// account.
167    ///
168    /// This enables an End-User who has multiple accounts at the Authorization
169    /// Server to select amongst the multiple accounts that they might have
170    /// current sessions for.
171    SelectAccount,
172
173    /// The Authorization Server should prompt the End-User to create a user
174    /// account.
175    ///
176    /// Defined in [Initiating User Registration via OpenID Connect](https://openid.net/specs/openid-connect-prompt-create-1_0.html).
177    Create,
178
179    /// An unknown value.
180    Unknown(String),
181}
182
183impl core::fmt::Display for Prompt {
184    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
185        match self {
186            Prompt::None => f.write_str("none"),
187            Prompt::Login => f.write_str("login"),
188            Prompt::Consent => f.write_str("consent"),
189            Prompt::SelectAccount => f.write_str("select_account"),
190            Prompt::Create => f.write_str("create"),
191            Prompt::Unknown(s) => f.write_str(s),
192        }
193    }
194}
195
196impl core::str::FromStr for Prompt {
197    type Err = core::convert::Infallible;
198
199    fn from_str(s: &str) -> Result<Self, Self::Err> {
200        match s {
201            "none" => Ok(Prompt::None),
202            "login" => Ok(Prompt::Login),
203            "consent" => Ok(Prompt::Consent),
204            "select_account" => Ok(Prompt::SelectAccount),
205            "create" => Ok(Prompt::Create),
206            s => Ok(Prompt::Unknown(s.to_owned())),
207        }
208    }
209}
210
211/// The body of a request to the [Authorization Endpoint].
212///
213/// [Authorization Endpoint]: https://www.rfc-editor.org/rfc/rfc6749.html#section-3.1
214#[skip_serializing_none]
215#[serde_as]
216#[derive(Serialize, Deserialize, Clone)]
217pub struct AuthorizationRequest {
218    /// OAuth 2.0 Response Type value that determines the authorization
219    /// processing flow to be used.
220    pub response_type: ResponseType,
221
222    /// OAuth 2.0 Client Identifier valid at the Authorization Server.
223    pub client_id: String,
224
225    /// Redirection URI to which the response will be sent.
226    ///
227    /// This field is required when using a response type returning an
228    /// authorization code.
229    ///
230    /// This URI must have been pre-registered with the OpenID Provider.
231    pub redirect_uri: Option<Url>,
232
233    /// The scope of the access request.
234    ///
235    /// OpenID Connect requests must contain the `openid` scope value.
236    pub scope: Scope,
237
238    /// Opaque value used to maintain state between the request and the
239    /// callback.
240    pub state: Option<String>,
241
242    /// The mechanism to be used for returning parameters from the Authorization
243    /// Endpoint.
244    ///
245    /// This use of this parameter is not recommended when the Response Mode
246    /// that would be requested is the default mode specified for the Response
247    /// Type.
248    pub response_mode: Option<ResponseMode>,
249
250    /// String value used to associate a Client session with an ID Token, and to
251    /// mitigate replay attacks.
252    pub nonce: Option<String>,
253
254    /// How the Authorization Server should display the authentication and
255    /// consent user interface pages to the End-User.
256    pub display: Option<Display>,
257
258    /// Whether the Authorization Server should prompt the End-User for
259    /// reauthentication and consent.
260    ///
261    /// If [`Prompt::None`] is used, it must be the only value.
262    #[serde_as(as = "Option<StringWithSeparator::<SpaceSeparator, Prompt>>")]
263    #[serde(default)]
264    pub prompt: Option<Vec<Prompt>>,
265
266    /// The allowable elapsed time in seconds since the last time the End-User
267    /// was actively authenticated by the OpenID Provider.
268    #[serde(default)]
269    #[serde_as(as = "Option<DisplayFromStr>")]
270    pub max_age: Option<NonZeroU32>,
271
272    /// End-User's preferred languages and scripts for the user interface.
273    #[serde_as(as = "Option<StringWithSeparator::<SpaceSeparator, LanguageTag>>")]
274    #[serde(default)]
275    pub ui_locales: Option<Vec<LanguageTag>>,
276
277    /// ID Token previously issued by the Authorization Server being passed as a
278    /// hint about the End-User's current or past authenticated session with the
279    /// Client.
280    pub id_token_hint: Option<String>,
281
282    /// Hint to the Authorization Server about the login identifier the End-User
283    /// might use to log in.
284    pub login_hint: Option<String>,
285
286    /// Requested Authentication Context Class Reference values.
287    #[serde_as(as = "Option<StringWithSeparator::<SpaceSeparator, String>>")]
288    #[serde(default)]
289    pub acr_values: Option<HashSet<String>>,
290
291    /// A JWT that contains the request's parameter values, called a [Request
292    /// Object].
293    ///
294    /// [Request Object]: https://openid.net/specs/openid-connect-core-1_0.html#RequestObject
295    pub request: Option<String>,
296
297    /// A URI referencing a [Request Object] or a [Pushed Authorization
298    /// Request].
299    ///
300    /// [Request Object]: https://openid.net/specs/openid-connect-core-1_0.html#RequestUriParameter
301    /// [Pushed Authorization Request]: https://datatracker.ietf.org/doc/html/rfc9126
302    pub request_uri: Option<Url>,
303
304    /// A JSON object containing the Client Metadata when interacting with a
305    /// [Self-Issued OpenID Provider].
306    ///
307    /// [Self-Issued OpenID Provider]: https://openid.net/specs/openid-connect-core-1_0.html#SelfIssued
308    pub registration: Option<String>,
309}
310
311impl AuthorizationRequest {
312    /// Creates a basic `AuthorizationRequest`.
313    #[must_use]
314    pub fn new(response_type: ResponseType, client_id: String, scope: Scope) -> Self {
315        Self {
316            response_type,
317            client_id,
318            redirect_uri: None,
319            scope,
320            state: None,
321            response_mode: None,
322            nonce: None,
323            display: None,
324            prompt: None,
325            max_age: None,
326            ui_locales: None,
327            id_token_hint: None,
328            login_hint: None,
329            acr_values: None,
330            request: None,
331            request_uri: None,
332            registration: None,
333        }
334    }
335}
336
337impl fmt::Debug for AuthorizationRequest {
338    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339        f.debug_struct("AuthorizationRequest")
340            .field("response_type", &self.response_type)
341            .field("redirect_uri", &self.redirect_uri)
342            .field("scope", &self.scope)
343            .field("response_mode", &self.response_mode)
344            .field("display", &self.display)
345            .field("prompt", &self.prompt)
346            .field("max_age", &self.max_age)
347            .field("ui_locales", &self.ui_locales)
348            .field("login_hint", &self.login_hint)
349            .field("acr_values", &self.acr_values)
350            .field("request", &self.request)
351            .field("request_uri", &self.request_uri)
352            .field("registration", &self.registration)
353            .finish_non_exhaustive()
354    }
355}
356
357/// A successful response from the [Authorization Endpoint].
358///
359/// [Authorization Endpoint]: https://www.rfc-editor.org/rfc/rfc6749.html#section-3.1
360#[skip_serializing_none]
361#[serde_as]
362#[derive(Serialize, Deserialize, Default, Clone)]
363pub struct AuthorizationResponse {
364    /// The authorization code generated by the authorization server.
365    pub code: Option<String>,
366
367    /// The access token to access the requested scope.
368    pub access_token: Option<String>,
369
370    /// The type of the access token.
371    pub token_type: Option<OAuthAccessTokenType>,
372
373    /// ID Token value associated with the authenticated session.
374    pub id_token: Option<String>,
375
376    /// The duration for which the access token is valid.
377    #[serde_as(as = "Option<DurationSeconds<i64>>")]
378    pub expires_in: Option<Duration>,
379}
380
381impl fmt::Debug for AuthorizationResponse {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        f.debug_struct("AuthorizationResponse")
384            .field("token_type", &self.token_type)
385            .field("id_token", &self.id_token)
386            .field("expires_in", &self.expires_in)
387            .finish_non_exhaustive()
388    }
389}
390
391/// A request to the [Device Authorization Endpoint].
392///
393/// [Device Authorization Endpoint]: https://www.rfc-editor.org/rfc/rfc8628
394#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
395pub struct DeviceAuthorizationRequest {
396    /// The scope of the access request.
397    pub scope: Option<Scope>,
398}
399
400/// The default value of the `interval` between polling requests, if it is not
401/// set.
402pub const DEFAULT_DEVICE_AUTHORIZATION_INTERVAL: Duration = Duration::microseconds(5 * 1000 * 1000);
403
404/// A successful response from the [Device Authorization Endpoint].
405///
406/// [Device Authorization Endpoint]: https://www.rfc-editor.org/rfc/rfc8628
407#[serde_as]
408#[skip_serializing_none]
409#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
410pub struct DeviceAuthorizationResponse {
411    /// The device verification code.
412    pub device_code: String,
413
414    /// The end-user verification code.
415    pub user_code: String,
416
417    /// The end-user verification URI on the authorization server.
418    ///
419    /// The URI should be short and easy to remember as end users will be asked
420    /// to manually type it into their user agent.
421    pub verification_uri: Url,
422
423    /// A verification URI that includes the `user_code` (or other information
424    /// with the same function as the `user_code`), which is designed for
425    /// non-textual transmission.
426    pub verification_uri_complete: Option<Url>,
427
428    /// The lifetime of the `device_code` and `user_code`.
429    #[serde_as(as = "DurationSeconds<i64>")]
430    pub expires_in: Duration,
431
432    /// The minimum amount of time in seconds that the client should wait
433    /// between polling requests to the token endpoint.
434    ///
435    /// Defaults to [`DEFAULT_DEVICE_AUTHORIZATION_INTERVAL`].
436    #[serde_as(as = "Option<DurationSeconds<i64>>")]
437    pub interval: Option<Duration>,
438}
439
440impl DeviceAuthorizationResponse {
441    /// The minimum amount of time in seconds that the client should wait
442    /// between polling requests to the token endpoint.
443    ///
444    /// Defaults to [`DEFAULT_DEVICE_AUTHORIZATION_INTERVAL`].
445    #[must_use]
446    pub fn interval(&self) -> Duration {
447        self.interval
448            .unwrap_or(DEFAULT_DEVICE_AUTHORIZATION_INTERVAL)
449    }
450}
451
452impl fmt::Debug for DeviceAuthorizationResponse {
453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454        f.debug_struct("DeviceAuthorizationResponse")
455            .field("verification_uri", &self.verification_uri)
456            .field("expires_in", &self.expires_in)
457            .field("interval", &self.interval)
458            .finish_non_exhaustive()
459    }
460}
461
462/// A request to the [Token Endpoint] for the [Authorization Code] grant type.
463///
464/// [Token Endpoint]: https://www.rfc-editor.org/rfc/rfc6749#section-3.2
465/// [Authorization Code]: https://www.rfc-editor.org/rfc/rfc6749#section-4.1
466#[skip_serializing_none]
467#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
468pub struct AuthorizationCodeGrant {
469    /// The authorization code that was returned from the authorization
470    /// endpoint.
471    pub code: String,
472
473    /// The `redirect_uri` that was included in the authorization request.
474    ///
475    /// This field must match exactly the value passed to the authorization
476    /// endpoint.
477    pub redirect_uri: Option<Url>,
478
479    /// The code verifier that matches the code challenge that was sent to the
480    /// authorization endpoint.
481    // TODO: move this somehow in the pkce module
482    pub code_verifier: Option<String>,
483}
484
485impl fmt::Debug for AuthorizationCodeGrant {
486    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487        f.debug_struct("AuthorizationCodeGrant")
488            .field("redirect_uri", &self.redirect_uri)
489            .finish_non_exhaustive()
490    }
491}
492
493/// A request to the [Token Endpoint] for [refreshing an access token].
494///
495/// [Token Endpoint]: https://www.rfc-editor.org/rfc/rfc6749#section-3.2
496/// [refreshing an access token]: https://www.rfc-editor.org/rfc/rfc6749#section-6
497#[skip_serializing_none]
498#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
499pub struct RefreshTokenGrant {
500    /// The refresh token issued to the client.
501    pub refresh_token: String,
502
503    /// The scope of the access request.
504    ///
505    /// The requested scope must not include any scope not originally granted by
506    /// the resource owner, and if omitted is treated as equal to the scope
507    /// originally granted by the resource owner.
508    pub scope: Option<Scope>,
509}
510
511impl fmt::Debug for RefreshTokenGrant {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        f.debug_struct("RefreshTokenGrant")
514            .field("scope", &self.scope)
515            .finish_non_exhaustive()
516    }
517}
518
519/// A request to the [Token Endpoint] for the [Client Credentials] grant type.
520///
521/// [Token Endpoint]: https://www.rfc-editor.org/rfc/rfc6749#section-3.2
522/// [Client Credentials]: https://www.rfc-editor.org/rfc/rfc6749#section-4.4
523#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
524pub struct ClientCredentialsGrant {
525    /// The scope of the access request.
526    pub scope: Option<Scope>,
527}
528
529/// A request to the [Token Endpoint] for the [Device Authorization] grant type.
530///
531/// [Token Endpoint]: https://www.rfc-editor.org/rfc/rfc6749#section-3.2
532/// [Device Authorization]: https://www.rfc-editor.org/rfc/rfc8628
533#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
534pub struct DeviceCodeGrant {
535    /// The device verification code, from the device authorization response.
536    pub device_code: String,
537}
538
539impl fmt::Debug for DeviceCodeGrant {
540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541        f.debug_struct("DeviceCodeGrant").finish_non_exhaustive()
542    }
543}
544
545/// All possible values for the `grant_type` parameter.
546#[derive(
547    Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, SerializeDisplay, DeserializeFromStr,
548)]
549pub enum GrantType {
550    /// [`authorization_code`](https://www.rfc-editor.org/rfc/rfc6749#section-4.1)
551    AuthorizationCode,
552
553    /// [`refresh_token`](https://www.rfc-editor.org/rfc/rfc6749#section-6)
554    RefreshToken,
555
556    /// [`implicit`](https://www.rfc-editor.org/rfc/rfc6749#section-4.2)
557    Implicit,
558
559    /// [`client_credentials`](https://www.rfc-editor.org/rfc/rfc6749#section-4.4)
560    ClientCredentials,
561
562    /// [`password`](https://www.rfc-editor.org/rfc/rfc6749#section-4.3)
563    Password,
564
565    /// [`urn:ietf:params:oauth:grant-type:device_code`](https://www.rfc-editor.org/rfc/rfc8628)
566    DeviceCode,
567
568    /// [`https://datatracker.ietf.org/doc/html/rfc7523#section-2.1`](https://www.rfc-editor.org/rfc/rfc7523#section-2.1)
569    JwtBearer,
570
571    /// [`urn:openid:params:grant-type:ciba`](https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html)
572    ClientInitiatedBackchannelAuthentication,
573
574    /// An unknown value.
575    Unknown(String),
576}
577
578impl core::fmt::Display for GrantType {
579    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
580        match self {
581            GrantType::AuthorizationCode => f.write_str("authorization_code"),
582            GrantType::RefreshToken => f.write_str("refresh_token"),
583            GrantType::Implicit => f.write_str("implicit"),
584            GrantType::ClientCredentials => f.write_str("client_credentials"),
585            GrantType::Password => f.write_str("password"),
586            GrantType::DeviceCode => f.write_str("urn:ietf:params:oauth:grant-type:device_code"),
587            GrantType::JwtBearer => f.write_str("urn:ietf:params:oauth:grant-type:jwt-bearer"),
588            GrantType::ClientInitiatedBackchannelAuthentication => {
589                f.write_str("urn:openid:params:grant-type:ciba")
590            }
591            GrantType::Unknown(s) => f.write_str(s),
592        }
593    }
594}
595
596impl core::str::FromStr for GrantType {
597    type Err = core::convert::Infallible;
598
599    fn from_str(s: &str) -> Result<Self, Self::Err> {
600        match s {
601            "authorization_code" => Ok(GrantType::AuthorizationCode),
602            "refresh_token" => Ok(GrantType::RefreshToken),
603            "implicit" => Ok(GrantType::Implicit),
604            "client_credentials" => Ok(GrantType::ClientCredentials),
605            "password" => Ok(GrantType::Password),
606            "urn:ietf:params:oauth:grant-type:device_code" => Ok(GrantType::DeviceCode),
607            "urn:ietf:params:oauth:grant-type:jwt-bearer" => Ok(GrantType::JwtBearer),
608            "urn:openid:params:grant-type:ciba" => {
609                Ok(GrantType::ClientInitiatedBackchannelAuthentication)
610            }
611            s => Ok(GrantType::Unknown(s.to_owned())),
612        }
613    }
614}
615
616/// An enum representing the possible requests to the [Token Endpoint].
617///
618/// [Token Endpoint]: https://www.rfc-editor.org/rfc/rfc6749#section-3.2
619#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
620#[serde(tag = "grant_type", rename_all = "snake_case")]
621#[non_exhaustive]
622pub enum AccessTokenRequest {
623    /// A request in the Authorization Code flow.
624    AuthorizationCode(AuthorizationCodeGrant),
625
626    /// A request to refresh an access token.
627    RefreshToken(RefreshTokenGrant),
628
629    /// A request in the Client Credentials flow.
630    ClientCredentials(ClientCredentialsGrant),
631
632    /// A request in the Device Code flow.
633    #[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
634    DeviceCode(DeviceCodeGrant),
635
636    /// An unsupported request.
637    #[serde(skip_serializing, other)]
638    Unsupported,
639}
640
641/// A successful response from the [Token Endpoint].
642///
643/// [Token Endpoint]: https://www.rfc-editor.org/rfc/rfc6749#section-3.2
644#[serde_as]
645#[skip_serializing_none]
646#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
647pub struct AccessTokenResponse {
648    /// The access token to access the requested scope.
649    pub access_token: String,
650
651    /// The token to refresh the access token when it expires.
652    pub refresh_token: Option<String>,
653
654    /// ID Token value associated with the authenticated session.
655    // TODO: this should be somewhere else
656    pub id_token: Option<String>,
657
658    /// The type of the access token.
659    pub token_type: OAuthAccessTokenType,
660
661    /// The duration for which the access token is valid.
662    #[serde_as(as = "Option<DurationSeconds<i64>>")]
663    pub expires_in: Option<Duration>,
664
665    /// The scope of the access token.
666    pub scope: Option<Scope>,
667}
668
669impl AccessTokenResponse {
670    /// Creates a new `AccessTokenResponse` with the given access token.
671    #[must_use]
672    pub fn new(access_token: String) -> AccessTokenResponse {
673        AccessTokenResponse {
674            access_token,
675            refresh_token: None,
676            id_token: None,
677            token_type: OAuthAccessTokenType::Bearer,
678            expires_in: None,
679            scope: None,
680        }
681    }
682
683    /// Adds a refresh token to an `AccessTokenResponse`.
684    #[must_use]
685    pub fn with_refresh_token(mut self, refresh_token: String) -> Self {
686        self.refresh_token = Some(refresh_token);
687        self
688    }
689
690    /// Adds an ID token to an `AccessTokenResponse`.
691    #[must_use]
692    pub fn with_id_token(mut self, id_token: String) -> Self {
693        self.id_token = Some(id_token);
694        self
695    }
696
697    /// Adds a scope to an `AccessTokenResponse`.
698    #[must_use]
699    pub fn with_scope(mut self, scope: Scope) -> Self {
700        self.scope = Some(scope);
701        self
702    }
703
704    /// Adds an expiration duration to an `AccessTokenResponse`.
705    #[must_use]
706    pub fn with_expires_in(mut self, expires_in: Duration) -> Self {
707        self.expires_in = Some(expires_in);
708        self
709    }
710}
711
712impl fmt::Debug for AccessTokenResponse {
713    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
714        f.debug_struct("AccessTokenResponse")
715            .field("token_type", &self.token_type)
716            .field("expires_in", &self.expires_in)
717            .field("scope", &self.scope)
718            .finish_non_exhaustive()
719    }
720}
721
722/// A request to the [Introspection Endpoint].
723///
724/// [Introspection Endpoint]: https://www.rfc-editor.org/rfc/rfc7662#section-2
725#[skip_serializing_none]
726#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
727pub struct IntrospectionRequest {
728    /// The value of the token.
729    pub token: String,
730
731    /// A hint about the type of the token submitted for introspection.
732    pub token_type_hint: Option<OAuthTokenTypeHint>,
733}
734
735impl fmt::Debug for IntrospectionRequest {
736    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737        f.debug_struct("IntrospectionRequest")
738            .field("token_type_hint", &self.token_type_hint)
739            .finish_non_exhaustive()
740    }
741}
742
743/// A successful response from the [Introspection Endpoint].
744///
745/// [Introspection Endpoint]: https://www.rfc-editor.org/rfc/rfc7662#section-2
746#[serde_as]
747#[skip_serializing_none]
748#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
749pub struct IntrospectionResponse {
750    /// Whether or not the presented token is currently active.
751    pub active: bool,
752
753    /// The scope associated with the token.
754    pub scope: Option<Scope>,
755
756    /// Client identifier for the OAuth 2.0 client that requested this token.
757    pub client_id: Option<String>,
758
759    /// Human-readable identifier for the resource owner who authorized this
760    /// token.
761    pub username: Option<String>,
762
763    /// Type of the token.
764    pub token_type: Option<OAuthTokenTypeHint>,
765
766    /// Timestamp indicating when the token will expire.
767    #[serde_as(as = "Option<TimestampSeconds>")]
768    pub exp: Option<DateTime<Utc>>,
769
770    /// Relative timestamp indicating when the token will expire,
771    /// in seconds from the current instant.
772    #[serde_as(as = "Option<DurationSeconds<i64>>")]
773    pub expires_in: Option<Duration>,
774
775    /// Timestamp indicating when the token was issued.
776    #[serde_as(as = "Option<TimestampSeconds>")]
777    pub iat: Option<DateTime<Utc>>,
778
779    /// Timestamp indicating when the token is not to be used before.
780    #[serde_as(as = "Option<TimestampSeconds>")]
781    pub nbf: Option<DateTime<Utc>>,
782
783    /// Subject of the token.
784    pub sub: Option<String>,
785
786    /// Intended audience of the token.
787    pub aud: Option<String>,
788
789    /// Issuer of the token.
790    pub iss: Option<String>,
791
792    /// String identifier for the token.
793    pub jti: Option<String>,
794
795    /// MAS extension: explicit device ID
796    pub device_id: Option<String>,
797}
798
799/// A request to the [Revocation Endpoint].
800///
801/// [Revocation Endpoint]: https://www.rfc-editor.org/rfc/rfc7009#section-2
802#[skip_serializing_none]
803#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
804pub struct RevocationRequest {
805    /// The value of the token.
806    pub token: String,
807
808    /// A hint about the type of the token submitted for introspection.
809    pub token_type_hint: Option<OAuthTokenTypeHint>,
810}
811
812impl fmt::Debug for RevocationRequest {
813    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
814        f.debug_struct("RevocationRequest")
815            .field("token_type_hint", &self.token_type_hint)
816            .finish_non_exhaustive()
817    }
818}
819
820/// A successful response from the [Pushed Authorization Request Endpoint].
821///
822/// Note that there is no request type because it is by definition the same as
823/// [`AuthorizationRequest`].
824///
825/// [Pushed Authorization Request Endpoint]: https://datatracker.ietf.org/doc/html/rfc9126
826#[serde_as]
827#[skip_serializing_none]
828#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
829pub struct PushedAuthorizationResponse {
830    /// The `request_uri` to use for the request to the authorization endpoint.
831    pub request_uri: String,
832
833    /// The duration for which the request URI is valid.
834    #[serde_as(as = "DurationSeconds<i64>")]
835    pub expires_in: Duration,
836}
837
838#[cfg(test)]
839mod tests {
840    use serde_json::json;
841
842    use super::*;
843    use crate::{scope::OPENID, test_utils::assert_serde_json};
844
845    #[test]
846    fn serde_refresh_token_grant() {
847        let expected = json!({
848            "grant_type": "refresh_token",
849            "refresh_token": "abcd",
850            "scope": "openid",
851        });
852
853        // TODO: insert multiple scopes and test it. It's a bit tricky to test since
854        // HashSet have no guarantees regarding the ordering of items, so right
855        // now the output is unstable.
856        let scope: Option<Scope> = Some(vec![OPENID].into_iter().collect());
857
858        let req = AccessTokenRequest::RefreshToken(RefreshTokenGrant {
859            refresh_token: "abcd".into(),
860            scope,
861        });
862
863        assert_serde_json(&req, expected);
864    }
865
866    #[test]
867    fn serde_authorization_code_grant() {
868        let expected = json!({
869            "grant_type": "authorization_code",
870            "code": "abcd",
871            "redirect_uri": "https://example.com/redirect",
872        });
873
874        let req = AccessTokenRequest::AuthorizationCode(AuthorizationCodeGrant {
875            code: "abcd".into(),
876            redirect_uri: Some("https://example.com/redirect".parse().unwrap()),
877            code_verifier: None,
878        });
879
880        assert_serde_json(&req, expected);
881    }
882
883    #[test]
884    fn serialize_grant_type() {
885        assert_eq!(
886            serde_json::to_string(&GrantType::AuthorizationCode).unwrap(),
887            "\"authorization_code\""
888        );
889        assert_eq!(
890            serde_json::to_string(&GrantType::RefreshToken).unwrap(),
891            "\"refresh_token\""
892        );
893        assert_eq!(
894            serde_json::to_string(&GrantType::Implicit).unwrap(),
895            "\"implicit\""
896        );
897        assert_eq!(
898            serde_json::to_string(&GrantType::ClientCredentials).unwrap(),
899            "\"client_credentials\""
900        );
901        assert_eq!(
902            serde_json::to_string(&GrantType::Password).unwrap(),
903            "\"password\""
904        );
905        assert_eq!(
906            serde_json::to_string(&GrantType::DeviceCode).unwrap(),
907            "\"urn:ietf:params:oauth:grant-type:device_code\""
908        );
909        assert_eq!(
910            serde_json::to_string(&GrantType::ClientInitiatedBackchannelAuthentication).unwrap(),
911            "\"urn:openid:params:grant-type:ciba\""
912        );
913    }
914
915    #[test]
916    fn deserialize_grant_type() {
917        assert_eq!(
918            serde_json::from_str::<GrantType>("\"authorization_code\"").unwrap(),
919            GrantType::AuthorizationCode
920        );
921        assert_eq!(
922            serde_json::from_str::<GrantType>("\"refresh_token\"").unwrap(),
923            GrantType::RefreshToken
924        );
925        assert_eq!(
926            serde_json::from_str::<GrantType>("\"implicit\"").unwrap(),
927            GrantType::Implicit
928        );
929        assert_eq!(
930            serde_json::from_str::<GrantType>("\"client_credentials\"").unwrap(),
931            GrantType::ClientCredentials
932        );
933        assert_eq!(
934            serde_json::from_str::<GrantType>("\"password\"").unwrap(),
935            GrantType::Password
936        );
937        assert_eq!(
938            serde_json::from_str::<GrantType>("\"urn:ietf:params:oauth:grant-type:device_code\"")
939                .unwrap(),
940            GrantType::DeviceCode
941        );
942        assert_eq!(
943            serde_json::from_str::<GrantType>("\"urn:openid:params:grant-type:ciba\"").unwrap(),
944            GrantType::ClientInitiatedBackchannelAuthentication
945        );
946    }
947
948    #[test]
949    fn serialize_response_mode() {
950        assert_eq!(
951            serde_json::to_string(&ResponseMode::Query).unwrap(),
952            "\"query\""
953        );
954        assert_eq!(
955            serde_json::to_string(&ResponseMode::Fragment).unwrap(),
956            "\"fragment\""
957        );
958        assert_eq!(
959            serde_json::to_string(&ResponseMode::FormPost).unwrap(),
960            "\"form_post\""
961        );
962    }
963
964    #[test]
965    fn deserialize_response_mode() {
966        assert_eq!(
967            serde_json::from_str::<ResponseMode>("\"query\"").unwrap(),
968            ResponseMode::Query
969        );
970        assert_eq!(
971            serde_json::from_str::<ResponseMode>("\"fragment\"").unwrap(),
972            ResponseMode::Fragment
973        );
974        assert_eq!(
975            serde_json::from_str::<ResponseMode>("\"form_post\"").unwrap(),
976            ResponseMode::FormPost
977        );
978    }
979
980    #[test]
981    fn serialize_display() {
982        assert_eq!(serde_json::to_string(&Display::Page).unwrap(), "\"page\"");
983        assert_eq!(serde_json::to_string(&Display::Popup).unwrap(), "\"popup\"");
984        assert_eq!(serde_json::to_string(&Display::Touch).unwrap(), "\"touch\"");
985        assert_eq!(serde_json::to_string(&Display::Wap).unwrap(), "\"wap\"");
986    }
987
988    #[test]
989    fn deserialize_display() {
990        assert_eq!(
991            serde_json::from_str::<Display>("\"page\"").unwrap(),
992            Display::Page
993        );
994        assert_eq!(
995            serde_json::from_str::<Display>("\"popup\"").unwrap(),
996            Display::Popup
997        );
998        assert_eq!(
999            serde_json::from_str::<Display>("\"touch\"").unwrap(),
1000            Display::Touch
1001        );
1002        assert_eq!(
1003            serde_json::from_str::<Display>("\"wap\"").unwrap(),
1004            Display::Wap
1005        );
1006    }
1007
1008    #[test]
1009    fn serialize_prompt() {
1010        assert_eq!(serde_json::to_string(&Prompt::None).unwrap(), "\"none\"");
1011        assert_eq!(serde_json::to_string(&Prompt::Login).unwrap(), "\"login\"");
1012        assert_eq!(
1013            serde_json::to_string(&Prompt::Consent).unwrap(),
1014            "\"consent\""
1015        );
1016        assert_eq!(
1017            serde_json::to_string(&Prompt::SelectAccount).unwrap(),
1018            "\"select_account\""
1019        );
1020        assert_eq!(
1021            serde_json::to_string(&Prompt::Create).unwrap(),
1022            "\"create\""
1023        );
1024    }
1025
1026    #[test]
1027    fn deserialize_prompt() {
1028        assert_eq!(
1029            serde_json::from_str::<Prompt>("\"none\"").unwrap(),
1030            Prompt::None
1031        );
1032        assert_eq!(
1033            serde_json::from_str::<Prompt>("\"login\"").unwrap(),
1034            Prompt::Login
1035        );
1036        assert_eq!(
1037            serde_json::from_str::<Prompt>("\"consent\"").unwrap(),
1038            Prompt::Consent
1039        );
1040        assert_eq!(
1041            serde_json::from_str::<Prompt>("\"select_account\"").unwrap(),
1042            Prompt::SelectAccount
1043        );
1044        assert_eq!(
1045            serde_json::from_str::<Prompt>("\"create\"").unwrap(),
1046            Prompt::Create
1047        );
1048    }
1049}