Skip to main content

kanidm_proto/
oauth2.rs

1//! Oauth2 RFC protocol definitions.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    fmt::Display,
6};
7
8use base64::{engine::general_purpose::STANDARD, Engine as _};
9use serde::{Deserialize, Serialize};
10use serde_with::{
11    base64::{Base64, UrlSafe},
12    formats,
13    formats::SpaceSeparator,
14    rust::deserialize_ignore_any,
15    serde_as, skip_serializing_none, StringWithSeparator,
16};
17use url::Url;
18use uuid::Uuid;
19
20/// How many seconds a device code is valid for.
21pub const OAUTH2_DEVICE_CODE_EXPIRY_SECONDS: u64 = 300;
22/// How often a client device can query the status of the token
23pub const OAUTH2_DEVICE_CODE_INTERVAL_SECONDS: u64 = 5;
24/// Token type URI for OAuth2 access tokens as per RFC8693.
25pub const OAUTH2_TOKEN_TYPE_ACCESS_TOKEN: &str = "urn:ietf:params:oauth:token-type:access_token";
26
27#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)]
28pub enum CodeChallengeMethod {
29    // default to plain if not requested as S256. Reject the auth?
30    // plain
31    // BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))
32    S256,
33}
34
35#[serde_as]
36#[derive(Serialize, Deserialize, Debug, Clone)]
37pub struct PkceRequest {
38    #[serde_as(as = "Base64<UrlSafe, formats::Unpadded>")]
39    pub code_challenge: Vec<u8>,
40    pub code_challenge_method: CodeChallengeMethod,
41}
42
43/// An OAuth2 client redirects to the authorisation server with Authorisation Request
44/// parameters.
45#[serde_as]
46#[skip_serializing_none]
47#[derive(Serialize, Deserialize, Debug, Clone)]
48pub struct AuthorisationRequest {
49    // Must be "code". (or token, see 4.2.1)
50    pub response_type: ResponseType,
51    /// Response mode.
52    ///
53    /// Optional; defaults to `query` for `response_type=code` (Auth Code), and
54    /// `fragment` for `response_type=token` (Implicit Grant, which we probably
55    /// won't support).
56    ///
57    /// Reference:
58    /// [OAuth 2.0 Multiple Response Type Encoding Practices: Response Modes](https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes)
59    pub response_mode: Option<ResponseMode>,
60    pub client_id: String,
61    pub state: Option<String>,
62    #[serde(flatten)]
63    pub pkce_request: Option<PkceRequest>,
64    pub redirect_uri: Url,
65    #[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
66    pub scope: BTreeSet<String>,
67    // OIDC adds a nonce parameter that is optional.
68    pub nonce: Option<String>,
69    // OIDC also allows other optional params
70    #[serde(flatten)]
71    pub oidc_ext: AuthorisationRequestOidc,
72    // Needs to be hoisted here due to serde flatten bug #3185
73    pub max_age: Option<i64>,
74    #[serde_as(as = "StringWithSeparator::<SpaceSeparator, Prompt>")]
75    #[serde(default)]
76    pub prompt: Vec<Prompt>,
77
78    #[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
79    #[serde(default)]
80    pub ui_locales: Vec<String>,
81
82    #[serde(flatten)]
83    pub unknown_keys: BTreeMap<String, serde_json::value::Value>,
84}
85
86impl AuthorisationRequest {
87    /// Get the `response_mode` appropriate for this request, taking into
88    /// account defaults from the `response_type` parameter.
89    ///
90    /// Returns `None` if the selection is invalid.
91    ///
92    /// Reference:
93    /// [OAuth 2.0 Multiple Response Type Encoding Practices: Response Modes](https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes)
94    pub const fn get_response_mode(&self) -> Option<ResponseMode> {
95        match (self.response_mode, self.response_type) {
96            // https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#id_token
97            // The default Response Mode for this Response Type is the fragment
98            // encoding and the query encoding MUST NOT be used.
99            (None, ResponseType::IdToken) => Some(ResponseMode::Fragment),
100            (Some(ResponseMode::Query), ResponseType::IdToken) => None,
101
102            // https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2
103            (None, ResponseType::Code) => Some(ResponseMode::Query),
104            // https://datatracker.ietf.org/doc/html/rfc6749#section-4.2.2
105            (None, ResponseType::Token) => Some(ResponseMode::Fragment),
106
107            // https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#Security
108            // In no case should a set of Authorization Response parameters
109            // whose default Response Mode is the fragment encoding be encoded
110            // using the query encoding.
111            (Some(ResponseMode::Query), ResponseType::Token) => None,
112
113            // Allow others.
114            (Some(m), _) => Some(m),
115        }
116    }
117}
118
119/// An OIDC client redirects to the authorisation server with Authorisation Request
120/// parameters.
121#[skip_serializing_none]
122#[derive(Serialize, Deserialize, Debug, Clone, Default)]
123pub struct AuthorisationRequestOidc {
124    pub display: Option<String>,
125    pub prompt: Option<String>,
126    pub ui_locales: Option<()>,
127    pub claims_locales: Option<()>,
128    pub id_token_hint: Option<String>,
129    pub login_hint: Option<String>,
130    pub acr: Option<String>,
131}
132
133/// In response to an Authorisation request, the user may be prompted to consent to the
134/// scopes requested by the OAuth2 client. If they have previously consented, they will
135/// immediately proceed.
136#[derive(Serialize, Deserialize, Debug, Clone)]
137pub enum AuthorisationResponse {
138    ConsentRequested {
139        // A pretty-name of the client
140        client_name: String,
141        // A list of scopes requested / to be issued.
142        scopes: BTreeSet<String>,
143        // Extra PII that may be requested
144        pii_scopes: BTreeSet<String>,
145        // The users displayname (?)
146        // pub display_name: String,
147        // The token we need to be given back to allow this to proceed
148        consent_token: String,
149    },
150    Permitted,
151}
152
153#[serde_as]
154#[skip_serializing_none]
155#[derive(Serialize, Deserialize, Debug)]
156#[serde(tag = "grant_type", rename_all = "snake_case")]
157pub enum GrantTypeReq {
158    AuthorizationCode {
159        // As sent by the authorisationCode
160        code: String,
161        // Must be the same as the original redirect uri.
162        redirect_uri: Url,
163        code_verifier: Option<String>,
164    },
165    ClientCredentials {
166        #[serde_as(as = "Option<StringWithSeparator::<SpaceSeparator, String>>")]
167        scope: Option<BTreeSet<String>>,
168    },
169    RefreshToken {
170        refresh_token: String,
171        #[serde_as(as = "Option<StringWithSeparator::<SpaceSeparator, String>>")]
172        scope: Option<BTreeSet<String>>,
173    },
174    #[serde(rename = "urn:ietf:params:oauth:grant-type:token-exchange")]
175    TokenExchange {
176        subject_token: String,
177        subject_token_type: String,
178        requested_token_type: Option<String>,
179        audience: Option<String>,
180        resource: Option<String>,
181        actor_token: Option<String>,
182        actor_token_type: Option<String>,
183        #[serde_as(as = "Option<StringWithSeparator::<SpaceSeparator, String>>")]
184        scope: Option<BTreeSet<String>>,
185    },
186    /// ref <https://www.rfc-editor.org/rfc/rfc8628#section-3.4>
187    #[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
188    DeviceCode {
189        device_code: String,
190        // #[serde_as(as = "Option<StringWithSeparator::<SpaceSeparator, String>>")]
191        scope: Option<BTreeSet<String>>,
192    },
193}
194
195/// An Access Token request. This requires a set of grant-type parameters to satisfy the request.
196#[skip_serializing_none]
197#[derive(Serialize, Deserialize, Debug)]
198pub struct AccessTokenRequest {
199    #[serde(flatten)]
200    pub grant_type: GrantTypeReq,
201    // REQUIRED, if the client is not authenticating with the
202    //  authorization server as described in Section 3.2.1.
203    #[serde(flatten)]
204    pub client_post_auth: ClientPostAuth,
205}
206
207impl From<GrantTypeReq> for AccessTokenRequest {
208    fn from(req: GrantTypeReq) -> AccessTokenRequest {
209        AccessTokenRequest {
210            grant_type: req,
211            client_post_auth: ClientPostAuth::default(),
212        }
213    }
214}
215
216#[derive(Serialize, Debug, Clone, Deserialize)]
217#[skip_serializing_none]
218pub struct OAuth2RFC9068Token<V>
219where
220    V: Clone,
221{
222    /// The issuer of this token
223    pub iss: String,
224    /// Unique id of the subject
225    pub sub: Uuid,
226    /// client_id of the oauth2 rp
227    pub aud: String,
228    /// Expiry in UTC epoch seconds
229    pub exp: i64,
230    /// Not valid before.
231    pub nbf: i64,
232    /// Issued at time.
233    pub iat: i64,
234    /// JWT ID <https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7> - we set it to the session ID
235    pub jti: Uuid,
236    pub client_id: String,
237    #[serde(flatten)]
238    pub extensions: V,
239}
240
241/// Extensions for RFC 9068 Access Token
242#[serde_as]
243#[skip_serializing_none]
244#[derive(Serialize, Deserialize, Debug, Clone)]
245pub struct OAuth2RFC9068TokenExtensions {
246    pub auth_time: Option<i64>,
247    pub acr: Option<String>,
248    pub amr: Option<Vec<String>>,
249
250    #[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
251    pub scope: BTreeSet<String>,
252
253    pub nonce: Option<String>,
254
255    pub session_id: Uuid,
256    pub parent_session_id: Option<Uuid>,
257}
258
259#[derive(Serialize, Deserialize, Debug, PartialEq)]
260pub enum IssuedTokenType {
261    #[serde(rename = "urn:ietf:params:oauth:token-type:access_token")]
262    AccessToken,
263    #[serde(rename = "urn:ietf:params:oauth:token-type:refresh_token")]
264    RefreshToken,
265    #[serde(rename = "urn:ietf:params:oauth:token-type:id_token")]
266    IdToken,
267    #[serde(rename = "urn:ietf:params:oauth:token-type:saml1")]
268    Saml1,
269    #[serde(rename = "urn:ietf:params:oauth:token-type:saml2")]
270    Saml2,
271}
272
273/// The response for an access token
274#[serde_as]
275#[skip_serializing_none]
276#[derive(Serialize, Deserialize, Debug)]
277pub struct AccessTokenResponse {
278    pub access_token: String,
279    pub token_type: AccessTokenType,
280    /// Optional RFC8693 issued_token_type.
281    pub issued_token_type: Option<IssuedTokenType>,
282    /// Expiration relative to `now` in seconds.
283    pub expires_in: u32,
284    pub refresh_token: Option<String>,
285    /// Space separated list of scopes that were approved, if this differs from the
286    /// original request.
287    #[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
288    pub scope: BTreeSet<String>,
289    /// If the `openid` scope was requested, an `id_token` may be present in the response.
290    pub id_token: Option<String>,
291}
292
293/// Access token types, per [IANA Registry - OAuth Access Token Types](https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#token-types)
294#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
295#[serde(try_from = "&str")]
296pub enum AccessTokenType {
297    Bearer,
298    PoP,
299    #[serde(rename = "N_A")]
300    NA,
301    DPoP,
302}
303
304impl TryFrom<&str> for AccessTokenType {
305    type Error = String;
306
307    fn try_from(s: &str) -> Result<Self, Self::Error> {
308        match s.to_lowercase().as_str() {
309            "bearer" => Ok(AccessTokenType::Bearer),
310            "pop" => Ok(AccessTokenType::PoP),
311            "n_a" => Ok(AccessTokenType::NA),
312            "dpop" => Ok(AccessTokenType::DPoP),
313            _ => Err(format!("Unknown AccessTokenType: {s}")),
314        }
315    }
316}
317
318/// Request revocation of an Access or Refresh token. On success the response is OK 200
319/// with no body.
320#[skip_serializing_none]
321#[derive(Serialize, Deserialize, Debug)]
322pub struct TokenRevokeRequest {
323    pub token: String,
324    /// Not required for Kanidm.
325    /// <https://datatracker.ietf.org/doc/html/rfc7009#section-4.1.2>
326    pub token_type_hint: Option<String>,
327
328    #[serde(flatten)]
329    pub client_post_auth: ClientPostAuth,
330}
331
332#[skip_serializing_none]
333#[derive(Serialize, Deserialize, Debug, Default)]
334/// <https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1>
335pub struct ClientPostAuth {
336    pub client_id: Option<String>,
337    pub client_secret: Option<String>,
338}
339
340impl From<(String, Option<String>)> for ClientPostAuth {
341    fn from((client_id, client_secret): (String, Option<String>)) -> Self {
342        ClientPostAuth {
343            client_id: Some(client_id),
344            client_secret,
345        }
346    }
347}
348
349impl From<(&str, Option<&str>)> for ClientPostAuth {
350    fn from((client_id, client_secret): (&str, Option<&str>)) -> Self {
351        ClientPostAuth {
352            client_id: Some(client_id.to_string()),
353            client_secret: client_secret.map(|s| s.to_string()),
354        }
355    }
356}
357
358#[skip_serializing_none]
359#[derive(Serialize, Deserialize, Debug, Default)]
360/// <https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1>
361pub struct ClientAuth {
362    pub client_id: String,
363    pub client_secret: Option<String>,
364}
365
366impl From<(&str, Option<&str>)> for ClientAuth {
367    fn from((client_id, client_secret): (&str, Option<&str>)) -> Self {
368        ClientAuth {
369            client_id: client_id.to_string(),
370            client_secret: client_secret.map(|s| s.to_string()),
371        }
372    }
373}
374
375/// Request to introspect the identity of the account associated to a token.
376#[skip_serializing_none]
377#[derive(Serialize, Deserialize, Debug)]
378pub struct AccessTokenIntrospectRequest {
379    pub token: String,
380    /// Not required for Kanidm.
381    /// <https://datatracker.ietf.org/doc/html/rfc7009#section-4.1.2>
382    pub token_type_hint: Option<String>,
383
384    // For when they want to use POST auth
385    // https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1
386    #[serde(flatten)]
387    pub client_post_auth: ClientPostAuth,
388}
389
390impl From<String> for AccessTokenIntrospectRequest {
391    fn from(token: String) -> Self {
392        Self {
393            token,
394            token_type_hint: None,
395            client_post_auth: ClientPostAuth::default(),
396        }
397    }
398}
399
400/// Response to an introspection request. If the token is inactive or revoked, only
401/// `active` will be set to the value of `false`.
402#[serde_as]
403#[skip_serializing_none]
404#[derive(Serialize, Deserialize, Debug, Default)]
405pub struct AccessTokenIntrospectResponse {
406    pub active: bool,
407    #[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
408    pub scope: BTreeSet<String>,
409    pub client_id: Option<String>,
410    pub username: Option<String>,
411    pub token_type: Option<AccessTokenType>,
412    pub exp: Option<i64>,
413    pub iat: Option<i64>,
414    pub nbf: Option<i64>,
415    pub sub: Option<String>,
416    pub aud: Option<String>,
417    pub iss: Option<String>,
418    // JWT ID <https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7> set to session ID
419    pub jti: Uuid,
420}
421
422impl AccessTokenIntrospectResponse {
423    pub fn inactive(session_id: Uuid) -> Self {
424        AccessTokenIntrospectResponse {
425            active: false,
426            scope: BTreeSet::default(),
427            client_id: None,
428            username: None,
429            token_type: None,
430            exp: None,
431            iat: None,
432            nbf: None,
433            sub: None,
434            aud: None,
435            iss: None,
436            jti: session_id,
437        }
438    }
439}
440
441#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
442#[serde(rename_all = "snake_case")]
443pub enum ResponseType {
444    // Auth Code flow
445    // https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.1
446    Code,
447    // Implicit Grant flow
448    // https://datatracker.ietf.org/doc/html/rfc6749#section-4.2.1
449    Token,
450    // https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#id_token
451    IdToken,
452}
453
454#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
455#[serde(rename_all = "snake_case")]
456pub enum ResponseMode {
457    Query,
458    Fragment,
459    FormPost,
460    #[serde(other, deserialize_with = "deserialize_ignore_any")]
461    Invalid,
462}
463
464fn response_modes_supported_default() -> Vec<ResponseMode> {
465    vec![ResponseMode::Query, ResponseMode::Fragment]
466}
467
468#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
469#[serde(rename_all = "snake_case")]
470pub enum Prompt {
471    /// None is not the absence of a value but a rather a value itself.
472    /// Prompt::None signifies to kanidm that *if* the authentications server
473    /// cannot automatically proceed thanks to an already logged in user,
474    /// It must return a error response rather than allowing a user to proceed
475    /// through the regular login flow.
476    ///
477    /// This is specified in OIDC Core 1.0 ยง3.1.2.1
478    /// <https://openid.net/specs/openid-connect-core-1_0.html>
479    None,
480    Login,
481    Consent,
482    SelectAccount,
483    #[serde(untagged)]
484    Invalid(String),
485}
486
487impl Display for Prompt {
488    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
489        let s = match self {
490            Prompt::None => "none",
491            Prompt::Login => "login",
492            Prompt::Consent => "consent",
493            Prompt::SelectAccount => "select_account",
494            Prompt::Invalid(str) => &format!("invalid({})", str),
495        };
496        write!(f, "{s}")
497    }
498}
499
500impl std::str::FromStr for Prompt {
501    type Err = std::convert::Infallible;
502
503    fn from_str(s: &str) -> Result<Self, Self::Err> {
504        Ok(match s {
505            "none" => Prompt::None,
506            "login" => Prompt::Login,
507            "consent" => Prompt::Consent,
508            "select_account" => Prompt::SelectAccount,
509            other => Prompt::Invalid(other.to_string()),
510        })
511    }
512}
513
514#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
515#[serde(rename_all = "snake_case")]
516pub enum GrantType {
517    #[serde(rename = "authorization_code")]
518    AuthorisationCode,
519    Implicit,
520    #[serde(rename = "urn:ietf:params:oauth:grant-type:token-exchange")]
521    TokenExchange,
522    ClientCredentials,
523    RefreshToken,
524    #[serde(rename = "urn:ietf:params:oauth:grant-type:jwt-bearer")]
525    JwtBearer,
526}
527
528fn grant_types_supported_default() -> Vec<GrantType> {
529    vec![
530        GrantType::AuthorisationCode,
531        GrantType::Implicit,
532        GrantType::TokenExchange,
533    ]
534}
535
536#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
537#[serde(rename_all = "snake_case")]
538pub enum SubjectType {
539    Pairwise,
540    Public,
541}
542
543#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
544pub enum PkceAlg {
545    S256,
546}
547
548#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
549#[serde(rename_all = "UPPERCASE")]
550/// Algorithms supported for token signatures. Prefers `ES256`
551pub enum IdTokenSignAlg {
552    // WE REFUSE TO SUPPORT NONE. DON'T EVEN ASK. IT WON'T HAPPEN.
553    ES256,
554    RS256,
555}
556
557#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
558#[serde(rename_all = "snake_case")]
559pub enum EndpointAuthMethod {
560    None,
561    ClientSecretPost,
562    ClientSecretBasic,
563    ClientSecretJwt,
564    PrivateKeyJwt,
565}
566
567fn token_endpoint_auth_methods_supported_default() -> Vec<EndpointAuthMethod> {
568    vec![EndpointAuthMethod::ClientSecretBasic]
569}
570
571#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
572#[serde(rename_all = "snake_case")]
573pub enum DisplayValue {
574    Page,
575    Popup,
576    Touch,
577    Wap,
578}
579
580#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
581#[serde(rename_all = "snake_case")]
582// https://openid.net/specs/openid-connect-core-1_0.html#ClaimTypes
583pub enum ClaimType {
584    Normal,
585    Aggregated,
586    Distributed,
587}
588
589fn claim_types_supported_default() -> Vec<ClaimType> {
590    vec![ClaimType::Normal]
591}
592
593fn claims_parameter_supported_default() -> bool {
594    false
595}
596
597fn request_parameter_supported_default() -> bool {
598    false
599}
600
601fn request_uri_parameter_supported_default() -> bool {
602    false
603}
604
605fn require_request_uri_parameter_supported_default() -> bool {
606    false
607}
608
609#[derive(Serialize, Deserialize, Debug)]
610pub struct OidcWebfingerRel {
611    pub rel: String,
612    pub href: String,
613}
614
615/// The response to an Webfinger request. Only a subset of the body is defined here.
616/// <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4>
617#[skip_serializing_none]
618#[derive(Serialize, Deserialize, Debug)]
619pub struct OidcWebfingerResponse {
620    pub subject: String,
621    pub links: Vec<OidcWebfingerRel>,
622}
623
624/// The response to an OpenID connect discovery request
625/// <https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata>
626#[skip_serializing_none]
627#[derive(Serialize, Deserialize, Debug)]
628pub struct OidcDiscoveryResponse {
629    pub issuer: Url,
630    pub authorization_endpoint: Url,
631    pub token_endpoint: Url,
632    pub userinfo_endpoint: Option<Url>,
633    pub jwks_uri: Url,
634    pub registration_endpoint: Option<Url>,
635    pub scopes_supported: Option<Vec<String>>,
636    // https://datatracker.ietf.org/doc/html/rfc6749#section-3.1.1
637    pub response_types_supported: Vec<ResponseType>,
638    // https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes
639    #[serde(default = "response_modes_supported_default")]
640    pub response_modes_supported: Vec<ResponseMode>,
641    // Need to fill in as authorization_code only else a default is assumed.
642    #[serde(default = "grant_types_supported_default")]
643    pub grant_types_supported: Vec<GrantType>,
644    pub acr_values_supported: Option<Vec<String>>,
645    // https://openid.net/specs/openid-connect-core-1_0.html#PairwiseAlg
646    pub subject_types_supported: Vec<SubjectType>,
647    pub id_token_signing_alg_values_supported: Vec<IdTokenSignAlg>,
648    pub id_token_encryption_alg_values_supported: Option<Vec<String>>,
649    pub id_token_encryption_enc_values_supported: Option<Vec<String>>,
650    pub userinfo_signing_alg_values_supported: Option<Vec<String>>,
651    pub userinfo_encryption_alg_values_supported: Option<Vec<String>>,
652    pub userinfo_encryption_enc_values_supported: Option<Vec<String>>,
653    pub request_object_signing_alg_values_supported: Option<Vec<String>>,
654    pub request_object_encryption_alg_values_supported: Option<Vec<String>>,
655    pub request_object_encryption_enc_values_supported: Option<Vec<String>>,
656    // Defaults to client_secret_basic
657    #[serde(default = "token_endpoint_auth_methods_supported_default")]
658    pub token_endpoint_auth_methods_supported: Vec<EndpointAuthMethod>,
659    pub token_endpoint_auth_signing_alg_values_supported: Option<Vec<String>>,
660    // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
661    pub display_values_supported: Option<Vec<DisplayValue>>,
662    // Default to normal.
663    #[serde(default = "claim_types_supported_default")]
664    pub claim_types_supported: Vec<ClaimType>,
665    pub claims_supported: Option<Vec<String>>,
666    pub service_documentation: Option<Url>,
667    pub claims_locales_supported: Option<Vec<String>>,
668    pub ui_locales_supported: Option<Vec<String>>,
669    // Default false.
670    #[serde(default = "claims_parameter_supported_default")]
671    pub claims_parameter_supported: bool,
672
673    pub op_policy_uri: Option<Url>,
674    pub op_tos_uri: Option<Url>,
675
676    // these are related to RFC9101 JWT-Secured Authorization Request support
677    #[serde(default = "request_parameter_supported_default")]
678    pub request_parameter_supported: bool,
679    #[serde(default = "request_uri_parameter_supported_default")]
680    pub request_uri_parameter_supported: bool,
681    #[serde(default = "require_request_uri_parameter_supported_default")]
682    pub require_request_uri_registration: bool,
683
684    pub code_challenge_methods_supported: Vec<PkceAlg>,
685
686    // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse
687    // "content type that contains a set of Claims as its members that are a subset of the Metadata
688    //  values defined in Section 3. Other Claims MAY also be returned. "
689    //
690    // In addition, we also return the following claims in kanidm
691
692    // rfc7009
693    pub revocation_endpoint: Option<Url>,
694    pub revocation_endpoint_auth_methods_supported: Vec<EndpointAuthMethod>,
695
696    // rfc7662
697    pub introspection_endpoint: Option<Url>,
698    pub introspection_endpoint_auth_methods_supported: Vec<EndpointAuthMethod>,
699    pub introspection_endpoint_auth_signing_alg_values_supported: Option<Vec<IdTokenSignAlg>>,
700
701    /// Ref <https://www.rfc-editor.org/rfc/rfc8628#section-4>
702    pub device_authorization_endpoint: Option<Url>,
703}
704
705/// The response to an OAuth2 rfc8414 metadata request
706#[skip_serializing_none]
707#[derive(Serialize, Deserialize, Debug)]
708pub struct Oauth2Rfc8414MetadataResponse {
709    pub issuer: Url,
710    pub authorization_endpoint: Url,
711    pub token_endpoint: Url,
712
713    pub jwks_uri: Option<Url>,
714
715    // rfc7591 reg endpoint.
716    pub registration_endpoint: Option<Url>,
717
718    pub scopes_supported: Option<Vec<String>>,
719
720    // For Oauth2 should be Code, Token.
721    pub response_types_supported: Vec<ResponseType>,
722    #[serde(default = "response_modes_supported_default")]
723    pub response_modes_supported: Vec<ResponseMode>,
724    #[serde(default = "grant_types_supported_default")]
725    pub grant_types_supported: Vec<GrantType>,
726
727    #[serde(default = "token_endpoint_auth_methods_supported_default")]
728    pub token_endpoint_auth_methods_supported: Vec<EndpointAuthMethod>,
729
730    pub token_endpoint_auth_signing_alg_values_supported: Option<Vec<IdTokenSignAlg>>,
731
732    pub service_documentation: Option<Url>,
733    pub ui_locales_supported: Option<Vec<String>>,
734
735    pub op_policy_uri: Option<Url>,
736    pub op_tos_uri: Option<Url>,
737
738    // rfc7009
739    pub revocation_endpoint: Option<Url>,
740    pub revocation_endpoint_auth_methods_supported: Vec<EndpointAuthMethod>,
741
742    // rfc7662
743    pub introspection_endpoint: Option<Url>,
744    pub introspection_endpoint_auth_methods_supported: Vec<EndpointAuthMethod>,
745    pub introspection_endpoint_auth_signing_alg_values_supported: Option<Vec<IdTokenSignAlg>>,
746
747    // RFC7636
748    pub code_challenge_methods_supported: Vec<PkceAlg>,
749}
750
751#[skip_serializing_none]
752#[derive(Serialize, Deserialize, Debug, Default)]
753pub struct ErrorResponse {
754    pub error: String,
755    pub error_description: Option<String>,
756    pub error_uri: Option<Url>,
757}
758
759#[derive(Debug, Serialize, Deserialize)]
760/// Ref <https://www.rfc-editor.org/rfc/rfc8628#section-3.2>
761pub struct DeviceAuthorizationResponse {
762    /// Base64-encoded bundle of 16 bytes
763    device_code: String,
764    /// xxx-yyy-zzz where x/y/z are digits. Stored internally as a u32 because we'll drop the dashes and parse as a number.
765    user_code: String,
766    verification_uri: Url,
767    verification_uri_complete: Url,
768    expires_in: u64,
769    interval: u64,
770}
771
772impl DeviceAuthorizationResponse {
773    pub fn new(verification_uri: Url, device_code: [u8; 16], user_code: String) -> Self {
774        let mut verification_uri_complete = verification_uri.clone();
775        verification_uri_complete
776            .query_pairs_mut()
777            .append_pair("user_code", &user_code);
778
779        let device_code = STANDARD.encode(device_code);
780
781        Self {
782            verification_uri_complete,
783            device_code,
784            user_code,
785            verification_uri,
786            expires_in: OAUTH2_DEVICE_CODE_EXPIRY_SECONDS,
787            interval: OAUTH2_DEVICE_CODE_INTERVAL_SECONDS,
788        }
789    }
790}
791
792#[cfg(test)]
793mod tests {
794    use super::{AccessTokenRequest, GrantTypeReq, OAUTH2_TOKEN_TYPE_ACCESS_TOKEN};
795    use std::collections::BTreeSet;
796    use url::Url;
797
798    #[test]
799    fn test_oauth2_access_token_req() {
800        let atr: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
801            code: "demo code".to_string(),
802            redirect_uri: Url::parse("http://[::1]").unwrap(),
803            code_verifier: None,
804        }
805        .into();
806
807        println!("{:?}", serde_json::to_string(&atr).expect("JSON failure"));
808    }
809
810    #[test]
811    fn test_oauth2_access_token_type_serde() {
812        for testcase in ["bearer", "Bearer", "BeArEr"] {
813            let at: super::AccessTokenType =
814                serde_json::from_str(&format!("\"{testcase}\"")).expect("Failed to parse");
815            assert_eq!(at, super::AccessTokenType::Bearer);
816        }
817
818        for testcase in ["dpop", "dPoP", "DPOP", "DPoP"] {
819            let at: super::AccessTokenType =
820                serde_json::from_str(&format!("\"{testcase}\"")).expect("Failed to parse");
821            assert_eq!(at, super::AccessTokenType::DPoP);
822        }
823
824        {
825            let testcase = "cheese";
826            let at = serde_json::from_str::<super::AccessTokenType>(&format!("\"{testcase}\""));
827            assert!(at.is_err())
828        }
829    }
830
831    #[test]
832    fn test_token_exchange_grant_serialization() {
833        let scopes: BTreeSet<String> = ["groups", "openid"]
834            .into_iter()
835            .map(str::to_string)
836            .collect();
837
838        let atr = AccessTokenRequest {
839            grant_type: GrantTypeReq::TokenExchange {
840                subject_token: "subject".to_string(),
841                subject_token_type: OAUTH2_TOKEN_TYPE_ACCESS_TOKEN.to_string(),
842                requested_token_type: None,
843                audience: Some("test_resource_server".to_string()),
844                resource: None,
845                actor_token: None,
846                actor_token_type: None,
847                scope: Some(scopes.clone()),
848            },
849            client_post_auth: Default::default(),
850        };
851
852        let json = serde_json::to_string(&atr).expect("JSON failure");
853        let de: AccessTokenRequest = serde_json::from_str(&json).expect("Roundtrip failure");
854
855        match de.grant_type {
856            GrantTypeReq::TokenExchange {
857                subject_token,
858                subject_token_type,
859                requested_token_type,
860                audience,
861                actor_token,
862                actor_token_type,
863                scope: descope,
864                ..
865            } => {
866                assert_eq!(subject_token, "subject");
867                assert_eq!(subject_token_type, OAUTH2_TOKEN_TYPE_ACCESS_TOKEN);
868                assert_eq!(requested_token_type, None);
869                assert_eq!(audience.as_deref(), Some("test_resource_server"));
870                assert_eq!(actor_token, None);
871                assert_eq!(actor_token_type, None);
872                assert_eq!(descope, Some(scopes));
873            }
874            _ => panic!("Wrong grant type"),
875        }
876    }
877
878    #[test]
879    fn test_authorisation_request_prompt_single_value() {
880        let qs = "response_type=code\
881            &client_id=test_client\
882            &redirect_uri=http%3A%2F%2Flocalhost\
883            &scope=openid\
884            &prompt=login";
885
886        let req: super::AuthorisationRequest =
887            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
888
889        assert_eq!(req.prompt.len(), 1);
890        assert!(req.prompt.contains(&super::Prompt::Login));
891    }
892
893    #[test]
894    fn test_authorisation_request_prompt_multiple_values() {
895        let qs = "response_type=code\
896            &client_id=test_client\
897            &redirect_uri=http%3A%2F%2Flocalhost\
898            &scope=openid\
899            &prompt=login%20consent";
900
901        let req: super::AuthorisationRequest =
902            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
903
904        assert_eq!(req.prompt.len(), 2);
905        assert!(req.prompt.contains(&super::Prompt::Login));
906        assert!(req.prompt.contains(&super::Prompt::Consent));
907    }
908
909    #[test]
910    fn test_authorisation_request_prompt_none() {
911        let qs = "response_type=code\
912            &client_id=test_client\
913            &redirect_uri=http%3A%2F%2Flocalhost\
914            &scope=openid\
915            &prompt=none";
916
917        let req: super::AuthorisationRequest =
918            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
919
920        assert_eq!(req.prompt.len(), 1);
921        assert!(req.prompt.contains(&super::Prompt::None));
922    }
923
924    #[test]
925    fn test_authorisation_request_prompt_absent() {
926        let qs = "response_type=code\
927            &client_id=test_client\
928            &redirect_uri=http%3A%2F%2Flocalhost\
929            &scope=openid";
930
931        let req: super::AuthorisationRequest =
932            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
933
934        assert!(req.prompt.is_empty());
935    }
936
937    #[test]
938    fn test_authorisation_request_prompt_invalid_value() {
939        let qs = "response_type=code\
940            &client_id=test_client\
941            &redirect_uri=http%3A%2F%2Flocalhost\
942            &scope=openid\
943            &prompt=bogus";
944
945        let req: super::AuthorisationRequest =
946            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
947
948        assert_eq!(req.prompt.len(), 1);
949        assert!(req
950            .prompt
951            .contains(&super::Prompt::Invalid("bogus".to_string())));
952    }
953
954    #[test]
955    fn test_authorisation_request_prompt_select_account() {
956        let qs = "response_type=code\
957            &client_id=test_client\
958            &redirect_uri=http%3A%2F%2Flocalhost\
959            &scope=openid\
960            &prompt=select_account";
961
962        let req: super::AuthorisationRequest =
963            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
964
965        assert_eq!(req.prompt.len(), 1);
966        assert!(req.prompt.contains(&super::Prompt::SelectAccount));
967    }
968
969    #[test]
970    fn test_authorisation_request_ui_locales() {
971        let qs = "response_type=code\
972            &client_id=test_client\
973            &redirect_uri=http%3A%2F%2Flocalhost\
974            &scope=openid\
975            &ui_locales=en-US";
976
977        let req: super::AuthorisationRequest =
978            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
979
980        assert_eq!(req.ui_locales.len(), 1);
981        assert!(req.ui_locales.contains(&"en-US".to_string()));
982
983        let qs = "response_type=code\
984            &client_id=test_client\
985            &redirect_uri=http%3A%2F%2Flocalhost\
986            &scope=openid\
987            &ui_locales=en-US%20fr-FR";
988
989        let req: super::AuthorisationRequest =
990            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
991        assert_eq!(req.ui_locales.len(), 2);
992        assert!(req.ui_locales.contains(&"fr-FR".to_string()));
993
994        let qs = "response_type=code\
995            &client_id=test_client\
996            &redirect_uri=http%3A%2F%2Flocalhost\
997            &scope=openid";
998
999        let req: super::AuthorisationRequest =
1000            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
1001        assert_eq!(req.ui_locales.len(), 0);
1002        assert!(req.ui_locales.is_empty());
1003    }
1004
1005    #[test]
1006    fn test_authorisation_request_prompt_all_valid_values() {
1007        let qs = "response_type=code\
1008            &client_id=test_client\
1009            &redirect_uri=http%3A%2F%2Flocalhost\
1010            &scope=openid\
1011            &prompt=login+consent+select_account";
1012
1013        let req: super::AuthorisationRequest =
1014            serde_urlencoded::from_str(qs).expect("Failed to deserialize");
1015
1016        assert_eq!(req.prompt.len(), 3);
1017        assert!(req.prompt.contains(&super::Prompt::Login));
1018        assert!(req.prompt.contains(&super::Prompt::Consent));
1019        assert!(req.prompt.contains(&super::Prompt::SelectAccount));
1020    }
1021}