Skip to main content

kanidmd_lib/idm/
oauth2.rs

1//! Oauth2 resource server configurations
2//!
3//! This contains the in memory and loaded set of active OAuth2 resource server
4//! integrations, which are then able to be used an accessed from the IDM layer
5//! for operations involving OAuth2 authentication processing.
6
7use crate::{
8    idm::{
9        account::Account,
10        server::{
11            IdmServerProxyReadTransaction, IdmServerProxyWriteTransaction, IdmServerTransaction,
12            Token,
13        },
14    },
15    prelude::*,
16    server::keys::{KeyId, KeyObject, KeyProvidersTransaction, KeyProvidersWriteTransaction},
17    utils,
18    value::{Oauth2Session, OauthClaimMapJoin, SessionState, OAUTHSCOPE_RE},
19};
20use base64::{engine::general_purpose, Engine as _};
21pub use compact_jwt::{compact::JwkKeySet, OidcToken};
22use compact_jwt::{
23    crypto::{JweA256GCMEncipher, JweA256KWEncipher},
24    jwe::JweBuilder,
25    jws::JwsBuilder,
26    JweCompact, JwsCompact, OidcClaims, OidcSubject,
27};
28use concread::cowcell::*;
29use crypto_glue::{
30    s256::{Sha256, Sha256Output},
31    traits::Digest,
32};
33use hashbrown::{HashMap, HashSet};
34pub use kanidm_proto::oauth2::{
35    AccessTokenIntrospectRequest, AccessTokenIntrospectResponse, AccessTokenRequest,
36    AccessTokenResponse, AccessTokenType, AuthorisationRequest, ClaimType, ClientAuth,
37    ClientPostAuth, CodeChallengeMethod, DeviceAuthorizationResponse, DisplayValue,
38    EndpointAuthMethod, ErrorResponse, GrantType, GrantTypeReq, IdTokenSignAlg, OAuth2RFC9068Token,
39    OAuth2RFC9068TokenExtensions, Oauth2Rfc8414MetadataResponse, OidcDiscoveryResponse,
40    OidcWebfingerRel, OidcWebfingerResponse, PkceAlg, PkceRequest, ResponseMode, ResponseType,
41    SubjectType, TokenRevokeRequest, OAUTH2_TOKEN_TYPE_ACCESS_TOKEN,
42};
43use kanidm_proto::{
44    constants::*,
45    oauth2::{IssuedTokenType, Prompt},
46};
47use serde::{Deserialize, Serialize};
48use serde_with::{formats, serde_as};
49use std::{
50    collections::{btree_map::Entry as BTreeEntry, BTreeMap, BTreeSet},
51    fmt,
52    str::FromStr,
53    sync::Arc,
54    time::Duration,
55};
56use subtle::ConstantTimeEq;
57use time::OffsetDateTime;
58use tracing::trace;
59use uri::{OAUTH2_TOKEN_INTROSPECT_ENDPOINT, OAUTH2_TOKEN_REVOKE_ENDPOINT};
60use url::{Host, Origin, Url};
61use utoipa::ToSchema;
62
63const TOKEN_EXCHANGE_SUBJECT_TOKEN_TYPE_ACCESS: &str = OAUTH2_TOKEN_TYPE_ACCESS_TOKEN;
64
65#[derive(Serialize, Deserialize, Debug, PartialEq, ToSchema)]
66#[serde(rename_all = "snake_case")]
67pub enum Oauth2Error {
68    // Non-standard - these are used to guide some control flow.
69    AuthenticationRequired,
70    InvalidClientId,
71    InvalidOrigin,
72    // Standard
73    InvalidRequest,
74    InvalidGrant,
75    UnauthorizedClient,
76    LoginRequired,
77    InteractionRequired,
78    AccessDenied,
79    UnsupportedResponseType,
80    InvalidScope,
81    InvalidTarget,
82    ServerError(OperationError),
83    TemporarilyUnavailable,
84    // from https://datatracker.ietf.org/doc/html/rfc6750
85    InvalidToken,
86    InsufficientScope,
87    // from https://datatracker.ietf.org/doc/html/rfc7009#section-2.2.1
88    UnsupportedTokenType,
89    /// <https://datatracker.ietf.org/doc/html/rfc8628#section-3.5>  A variant of "authorization_pending", the authorization request is
90    ///   still pending and polling should continue, but the interval MUST
91    ///   be increased by 5 seconds for this and all subsequent requests.
92    SlowDown,
93    /// The authorization request is still pending as the end user hasn't
94    ///   yet completed the user-interaction steps (Section 3.3).  The
95    ///   client SHOULD repeat the access token request to the token
96    ///   endpoint (a process known as polling).  Before each new request,
97    ///   the client MUST wait at least the number of seconds specified by
98    ///   the "interval" parameter of the device authorization response (see
99    ///   Section 3.2), or 5 seconds if none was provided, and respect any
100    ///   increase in the polling interval required by the "slow_down"
101    ///   error.
102    AuthorizationPending,
103    /// The "device_code" has expired, and the device authorization
104    ///   session has concluded.  The client MAY commence a new device
105    ///   authorization request but SHOULD wait for user interaction before
106    ///   restarting to avoid unnecessary polling.
107    ExpiredToken,
108}
109
110impl AsRef<str> for Oauth2Error {
111    fn as_ref(&self) -> &'static str {
112        match self {
113            Oauth2Error::AuthenticationRequired => "authentication_required",
114            Oauth2Error::InvalidClientId => "invalid_client_id",
115            Oauth2Error::InvalidOrigin => "invalid_origin",
116            Oauth2Error::InvalidGrant => "invalid_grant",
117            Oauth2Error::InvalidRequest => "invalid_request",
118            Oauth2Error::UnauthorizedClient => "unauthorized_client",
119            Oauth2Error::LoginRequired => "login_required",
120            Oauth2Error::InteractionRequired => "interaction_required",
121            Oauth2Error::AccessDenied => "access_denied",
122            Oauth2Error::UnsupportedResponseType => "unsupported_response_type",
123            Oauth2Error::InvalidScope => "invalid_scope",
124            Oauth2Error::InvalidTarget => "invalid_target",
125            Oauth2Error::ServerError(_) => "server_error",
126            Oauth2Error::TemporarilyUnavailable => "temporarily_unavailable",
127            Oauth2Error::InvalidToken => "invalid_token",
128            Oauth2Error::InsufficientScope => "insufficient_scope",
129            Oauth2Error::UnsupportedTokenType => "unsupported_token_type",
130            Oauth2Error::SlowDown => "slow_down",
131            Oauth2Error::AuthorizationPending => "authorization_pending",
132            Oauth2Error::ExpiredToken => "expired_token",
133        }
134    }
135}
136
137impl std::fmt::Display for Oauth2Error {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        f.write_str(self.as_ref())
140    }
141}
142
143#[derive(Clone)]
144pub struct PkceS256Secret {
145    secret: String,
146}
147
148impl Default for PkceS256Secret {
149    fn default() -> Self {
150        Self {
151            secret: utils::password_from_random(),
152        }
153    }
154}
155
156impl From<String> for PkceS256Secret {
157    fn from(secret: String) -> Self {
158        Self { secret }
159    }
160}
161
162impl PkceS256Secret {
163    pub fn to_challenge(&self) -> Sha256Output {
164        let mut hasher = Sha256::new();
165        hasher.update(self.secret.as_bytes());
166        hasher.finalize()
167    }
168
169    pub fn to_request(&self) -> PkceRequest {
170        let code_challenge = self.to_challenge();
171
172        PkceRequest {
173            code_challenge: code_challenge.to_vec(),
174            code_challenge_method: CodeChallengeMethod::S256,
175        }
176    }
177
178    pub(crate) fn verifier(&self) -> &str {
179        &self.secret
180    }
181
182    pub fn to_verifier(self) -> String {
183        self.secret
184    }
185
186    pub fn verify<V: AsRef<[u8]>>(&self, challenge: V) -> bool {
187        let code_challenge = self.to_challenge();
188        challenge.as_ref() == code_challenge.as_slice()
189    }
190}
191
192#[derive(Debug, Default)]
193pub struct AuthorisationRequestContext {
194    resumed: bool,
195}
196
197impl AuthorisationRequestContext {
198    pub fn resumed_session() -> Self {
199        Self { resumed: true }
200    }
201}
202
203struct OAuth2SessionContext {
204    pub(crate) auth_time: Option<OffsetDateTime>,
205    pub(crate) nonce: Option<String>,
206    pub(crate) account_uuid: Uuid,
207}
208
209// == internal state formats that we encrypt and send.
210#[derive(Serialize, Deserialize, Debug, PartialEq)]
211enum SupportedResponseMode {
212    Query,
213    Fragment,
214}
215
216#[serde_as]
217#[derive(Serialize, Deserialize, Debug, PartialEq)]
218struct ConsentToken {
219    pub client_id: String,
220    // Must match the session id of the Uat,
221    pub session_id: Uuid,
222    pub expiry: u64,
223
224    // So we can ensure that we really match the same uat to prevent confusions.
225    pub ident_id: IdentityId,
226    // CSRF
227    pub state: Option<String>,
228    // The S256 code challenge.
229    #[serde_as(
230        as = "Option<serde_with::base64::Base64<serde_with::base64::UrlSafe, formats::Unpadded>>"
231    )]
232    pub code_challenge: Option<Vec<u8>>,
233    // Where the client wants us to go back to.
234    pub redirect_uri: Url,
235    // The scopes being granted
236    pub scopes: BTreeSet<String>,
237    // We stash some details here for oidc.
238    pub nonce: Option<String>,
239    /// The format the response should be returned to the application in.
240    pub response_mode: SupportedResponseMode,
241}
242
243#[serde_as]
244#[derive(Serialize, Deserialize, Debug)]
245struct TokenExchangeCode {
246    // We don't need the client_id here, because it's signed with an RS specific
247    // key which gives us the assurance that it's the correct combination.
248    pub account_uuid: Uuid,
249    pub session_id: Uuid,
250
251    pub expiry: u64,
252
253    // The S256 code challenge.
254    #[serde_as(
255        as = "Option<serde_with::base64::Base64<serde_with::base64::UrlSafe, formats::Unpadded>>"
256    )]
257    pub code_challenge: Option<Vec<u8>>,
258    // The original redirect uri
259    pub redirect_uri: Url,
260    // The scopes being granted
261    pub scopes: BTreeSet<String>,
262    // We stash some details here for oidc.
263    pub nonce: Option<String>,
264    pub auth_time: Option<OffsetDateTime>,
265}
266
267#[derive(Serialize, Deserialize, Debug)]
268pub(crate) enum Oauth2TokenType {
269    Refresh {
270        scopes: BTreeSet<String>,
271        parent_session_id: Option<Uuid>,
272        session_id: Uuid,
273        exp: i64,
274        uuid: Uuid,
275        //
276        iat: i64,
277        nbf: i64,
278        // We stash some details here for oidc.
279        nonce: Option<String>,
280        auth_time: Option<OffsetDateTime>,
281    },
282    ClientAccess {
283        scopes: BTreeSet<String>,
284        session_id: Uuid,
285        uuid: Uuid,
286        exp: i64,
287        iat: i64,
288        nbf: i64,
289    },
290}
291
292impl fmt::Display for Oauth2TokenType {
293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294        match self {
295            Oauth2TokenType::Refresh { session_id, .. } => {
296                write!(f, "refresh_token ({session_id}) ")
297            }
298            Oauth2TokenType::ClientAccess { session_id, .. } => {
299                write!(f, "client_access_token ({session_id})")
300            }
301        }
302    }
303}
304
305#[derive(Debug)]
306pub enum AuthoriseResponse {
307    AuthenticationRequired {
308        // A pretty-name of the client
309        client_name: String,
310        // A username hint, if any
311        login_hint: Option<String>,
312    },
313    ReauthenticationRequired {
314        // A pretty-name of the client
315        client_name: String,
316    },
317    ConsentRequested {
318        // A pretty-name of the client
319        client_name: String,
320        // A list of scopes requested / to be issued.
321        scopes: BTreeSet<String>,
322        // Extra PII that may be requested
323        pii_scopes: BTreeSet<String>,
324        // The users displayname (?)
325        // pub display_name: String,
326        // The token we need to be given back to allow this to proceed
327        consent_token: String,
328    },
329    Permitted(AuthorisePermitSuccess),
330
331    Reject(AuthoriseReject),
332}
333
334#[derive(Debug)]
335pub struct AuthorisePermitSuccess {
336    // Where the client wants us to go back to.
337    pub redirect_uri: Url,
338    // The CSRF as a string
339    pub state: Option<String>,
340    // The exchange code as a String
341    pub code: String,
342    /// The format the response should be returned to the application in.
343    response_mode: SupportedResponseMode,
344}
345
346impl AuthorisePermitSuccess {
347    /// Builds a redirect URI to go back to the application when permission was
348    /// granted.
349    pub fn build_redirect_uri(&self) -> Url {
350        let mut redirect_uri = self.redirect_uri.clone();
351
352        // Always clear the fragment per RFC
353        redirect_uri.set_fragment(None);
354
355        match self.response_mode {
356            SupportedResponseMode::Query => {
357                redirect_uri
358                    .query_pairs_mut()
359                    .append_pair("code", &self.code);
360
361                if let Some(state) = self.state.as_ref() {
362                    redirect_uri.query_pairs_mut().append_pair("state", state);
363                };
364            }
365            SupportedResponseMode::Fragment => {
366                redirect_uri.set_query(None);
367
368                // Per [the RFC](https://www.rfc-editor.org/rfc/rfc6749#section-3.1.2), we can't set query pairs on fragment-containing redirects, only query ones.
369                let mut uri_builder = url::form_urlencoded::Serializer::new(String::new());
370                uri_builder.append_pair("code", &self.code);
371                if let Some(state) = self.state.as_ref() {
372                    uri_builder.append_pair("state", state);
373                };
374                let encoded = uri_builder.finish();
375
376                redirect_uri.set_fragment(Some(&encoded))
377            }
378        }
379
380        redirect_uri
381    }
382}
383
384#[derive(Debug)]
385pub struct AuthoriseReject {
386    // Where the client wants us to go back to.
387    pub redirect_uri: Url,
388    // The CSRF as a string
389    pub state: Option<String>,
390    /// The error we are returning.
391    pub error: Oauth2Error,
392    /// The format the response should be returned to the application in.
393    response_mode: SupportedResponseMode,
394}
395
396impl AuthoriseReject {
397    /// Builds a redirect URI to go back to the application when permission was
398    /// rejected.
399    pub fn build_redirect_uri(&self) -> Url {
400        let mut redirect_uri = self.redirect_uri.clone();
401
402        // Always clear query and fragment, regardless of the response mode
403        redirect_uri.set_query(None);
404        redirect_uri.set_fragment(None);
405
406        // We can't set query pairs on fragments, only query.
407        let encoded = url::form_urlencoded::Serializer::new(String::new())
408            .append_pair("error", self.error.as_ref())
409            .finish();
410
411        match self.response_mode {
412            SupportedResponseMode::Query => redirect_uri.set_query(Some(&encoded)),
413            SupportedResponseMode::Fragment => redirect_uri.set_fragment(Some(&encoded)),
414        }
415
416        redirect_uri
417    }
418}
419
420#[derive(Clone)]
421struct CtSecret {
422    inner: String,
423}
424
425impl CtSecret {
426    fn ct_eq(&self, rhs: &str) -> bool {
427        self.inner.as_bytes().ct_eq(rhs.as_bytes()).unwrap_u8() == 1
428    }
429}
430
431impl From<String> for CtSecret {
432    fn from(inner: String) -> Self {
433        CtSecret { inner }
434    }
435}
436
437#[derive(Clone)]
438enum OauthRSType {
439    Basic {
440        authz_secret: CtSecret,
441        enable_pkce: bool,
442        enable_consent_prompt: bool,
443    },
444    // Public clients must have pkce and consent prompt
445    Public {
446        allow_localhost_redirect: bool,
447    },
448}
449
450impl OauthRSType {
451    /// We only allow localhost redirects if PKCE is enabled/required
452    fn allow_localhost_redirect(&self) -> bool {
453        match self {
454            OauthRSType::Basic { .. } => false,
455            OauthRSType::Public {
456                allow_localhost_redirect,
457            } => *allow_localhost_redirect,
458        }
459    }
460
461    /// This type COULD have localhost redirection enabled, but does not reflect
462    /// the current configuration state.
463    fn allow_localhost_redirect_could_be_possible(&self) -> bool {
464        match self {
465            OauthRSType::Basic { .. } => false,
466            OauthRSType::Public { .. } => true,
467        }
468    }
469}
470
471impl std::fmt::Debug for OauthRSType {
472    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
473        let mut ds = f.debug_struct("OauthRSType");
474        match self {
475            OauthRSType::Basic {
476                enable_pkce,
477                enable_consent_prompt,
478                ..
479            } => ds
480                .field("type", &"basic")
481                .field("pkce", enable_pkce)
482                .field("consent_prompt", enable_consent_prompt),
483            OauthRSType::Public {
484                allow_localhost_redirect,
485            } => ds
486                .field("type", &"public")
487                .field("allow_localhost_redirect", allow_localhost_redirect),
488        };
489        ds.finish()
490    }
491}
492
493#[derive(Clone, Debug)]
494struct ClaimValue {
495    join: OauthClaimMapJoin,
496    values: BTreeSet<String>,
497}
498
499impl ClaimValue {
500    fn merge(&mut self, other: &Self) {
501        self.values.extend(other.values.iter().cloned())
502    }
503
504    fn to_json_value(&self) -> serde_json::Value {
505        let join_str = match self.join {
506            OauthClaimMapJoin::JsonArray => {
507                let arr: Vec<_> = self
508                    .values
509                    .iter()
510                    .cloned()
511                    .map(serde_json::Value::String)
512                    .collect();
513
514                // This shortcuts out.
515                return serde_json::Value::Array(arr);
516            }
517            joiner => joiner.to_str(),
518        };
519
520        let joined = str_concat!(&self.values, join_str);
521
522        serde_json::Value::String(joined)
523    }
524}
525
526#[derive(Clone, Copy, Debug)]
527enum SignatureAlgo {
528    Es256,
529    Rs256,
530}
531
532#[derive(Clone)]
533pub struct Oauth2RS {
534    name: String,
535    displayname: String,
536    uuid: Uuid,
537
538    origins: HashSet<Origin>,
539    opaque_origins: HashSet<Url>,
540    redirect_uris: HashSet<Url>,
541    origin_secure_required: bool,
542
543    claim_map: BTreeMap<Uuid, Vec<(String, ClaimValue)>>,
544    scope_maps: BTreeMap<Uuid, BTreeSet<String>>,
545    sup_scope_maps: BTreeMap<Uuid, BTreeSet<String>>,
546    client_scopes: BTreeSet<String>,
547    client_sup_scopes: BTreeSet<String>,
548    // Our internal exchange encryption material for this rs.
549    sign_alg: SignatureAlgo,
550    key_object: Arc<KeyObject>,
551
552    refresh_token_expiry: u32,
553
554    // For oidc we also need our issuer url.
555    iss: Url,
556    // For discovery we need to build and keep a number of values.
557    authorization_endpoint: Url,
558    token_endpoint: Url,
559    revocation_endpoint: Url,
560    introspection_endpoint: Url,
561    userinfo_endpoint: Url,
562    jwks_uri: Url,
563    scopes_supported: BTreeSet<String>,
564    prefer_short_username: bool,
565    type_: OauthRSType,
566    /// Does the RS have a custom image set? If not, we use the default.
567    has_custom_image: bool,
568
569    device_authorization_endpoint: Option<Url>,
570}
571
572impl Oauth2RS {
573    pub fn is_basic(&self) -> bool {
574        match self.type_ {
575            OauthRSType::Basic { .. } => true,
576            OauthRSType::Public { .. } => false,
577        }
578    }
579
580    pub fn is_pkce(&self) -> bool {
581        match self.type_ {
582            OauthRSType::Basic { .. } => false,
583            OauthRSType::Public { .. } => true,
584        }
585    }
586
587    /// Does this client require PKCE?
588    pub fn require_pkce(&self) -> bool {
589        match &self.type_ {
590            OauthRSType::Basic { enable_pkce, .. } => *enable_pkce,
591            OauthRSType::Public { .. } => true,
592        }
593    }
594
595    /// Does this RS have device flow enabled?
596    pub fn device_flow_enabled(&self) -> bool {
597        self.device_authorization_endpoint.is_some()
598    }
599
600    /// Does this client have the consent prompt enabled?
601    /// As per RFC-6819 5.2.3.2 it can't be disabled on Public clients
602    pub fn enable_consent_prompt(&self) -> bool {
603        match &self.type_ {
604            OauthRSType::Basic {
605                enable_consent_prompt,
606                ..
607            } => *enable_consent_prompt,
608            OauthRSType::Public { .. } => true,
609        }
610    }
611}
612
613impl std::fmt::Debug for Oauth2RS {
614    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
615        f.debug_struct("Oauth2RS")
616            .field("name", &self.name)
617            .field("displayname", &self.displayname)
618            .field("uuid", &self.uuid)
619            .field("type", &self.type_)
620            .field("origins", &self.origins)
621            .field("opaque_origins", &self.opaque_origins)
622            .field("scope_maps", &self.scope_maps)
623            .field("sup_scope_maps", &self.sup_scope_maps)
624            .field("claim_map", &self.claim_map)
625            .field("has_custom_image", &self.has_custom_image)
626            .finish()
627    }
628}
629
630#[derive(Clone)]
631struct Oauth2RSInner {
632    origin: Url,
633    consent_key: JweA256KWEncipher,
634    private_rs_set: HashMap<String, Oauth2RS>,
635    private_key_map: HashMap<KeyId, String>,
636}
637
638impl Oauth2RSInner {
639    fn rs_set_get(&self, client_id: &str) -> Option<&Oauth2RS> {
640        self.private_rs_set.get(client_id.to_lowercase().as_str())
641    }
642
643    fn rs_from_kid(&self, kid: &str) -> Option<&Oauth2RS> {
644        self.private_key_map
645            .get(kid)
646            .and_then(|client_id| self.private_rs_set.get(client_id))
647    }
648}
649
650pub struct Oauth2ResourceServers {
651    inner: CowCell<Oauth2RSInner>,
652}
653
654pub struct Oauth2ResourceServersReadTransaction {
655    inner: CowCellReadTxn<Oauth2RSInner>,
656}
657
658pub struct Oauth2ResourceServersWriteTransaction<'a> {
659    inner: CowCellWriteTxn<'a, Oauth2RSInner>,
660}
661
662impl Oauth2ResourceServers {
663    pub fn new(origin: Url) -> Result<Self, OperationError> {
664        let consent_key = JweA256KWEncipher::generate_ephemeral()
665            .map_err(|_| OperationError::CryptographyError)?;
666
667        Ok(Oauth2ResourceServers {
668            inner: CowCell::new(Oauth2RSInner {
669                origin,
670                consent_key,
671                private_rs_set: HashMap::new(),
672                private_key_map: HashMap::new(),
673            }),
674        })
675    }
676
677    pub fn read(&self) -> Oauth2ResourceServersReadTransaction {
678        Oauth2ResourceServersReadTransaction {
679            inner: self.inner.read(),
680        }
681    }
682
683    pub fn write(&self) -> Oauth2ResourceServersWriteTransaction<'_> {
684        Oauth2ResourceServersWriteTransaction {
685            inner: self.inner.write(),
686        }
687    }
688}
689
690/// For when you've got the bearer auth and the post auth and you just want the resulting auth attempt
691fn get_client_auth(
692    client_auth_info: &ClientAuthInfo,
693    client_post_auth: &ClientPostAuth,
694) -> Result<ClientAuth, Oauth2Error> {
695    if let Some(client_authz) = client_auth_info.basic_authz.as_ref() {
696        parse_basic_authz(client_authz.as_str())
697    } else if let Some(client_id) = &client_post_auth.client_id {
698        Ok(ClientAuth {
699            client_id: client_id.clone(),
700            client_secret: client_post_auth.client_secret.clone(),
701        })
702    } else {
703        Err(Oauth2Error::AuthenticationRequired)
704    }
705}
706
707impl Oauth2ResourceServersWriteTransaction<'_> {
708    #[instrument(level = "debug", name = "oauth2::reload", skip_all)]
709    pub fn reload(
710        &mut self,
711        value: Vec<Arc<EntrySealedCommitted>>,
712        key_providers: &KeyProvidersWriteTransaction,
713        domain_level: DomainVersion,
714    ) -> Result<(), OperationError> {
715        let mut kid_map: HashMap<KeyId, String> = Default::default();
716
717        let rs_set: Result<HashMap<_, _>, _> = value
718            .into_iter()
719            .map(|ent| {
720                let uuid = ent.get_uuid();
721
722                trace!(?uuid, "Checking OAuth2 configuration");
723
724                // From each entry, attempt to make an OAuth2 configuration.
725                if !ent
726                    .attribute_equality(Attribute::Class, &EntryClass::OAuth2ResourceServer.into())
727                {
728                    error!("Missing class oauth2_resource_server");
729                    // Check we have oauth2_resource_server class
730                    return Err(OperationError::InvalidEntryState);
731                }
732
733                let Some(key_object) = key_providers.get_key_object_handle(uuid) else {
734                    error!("OAuth2 RS is missing its key object!");
735                    return Err(OperationError::InvalidEntryState);
736                };
737
738                let type_ = if ent.attribute_equality(
739                    Attribute::Class,
740                    &EntryClass::OAuth2ResourceServerBasic.into(),
741                ) {
742                    let authz_secret = ent
743                        .get_ava_single_secret(Attribute::OAuth2RsBasicSecret)
744                        .map(str::to_string)
745                        .map(CtSecret::from)
746                        .ok_or(OperationError::InvalidValueState)?;
747
748                    let enable_pkce = ent
749                        .get_ava_single_bool(Attribute::OAuth2AllowInsecureClientDisablePkce)
750                        .map(|e| !e)
751                        .unwrap_or(true);
752
753                    let enable_consent_prompt = ent
754                        .get_ava_single_bool(Attribute::OAuth2ConsentPromptEnable)
755                        .unwrap_or(true);
756
757                    OauthRSType::Basic {
758                        authz_secret,
759                        enable_pkce,
760                        enable_consent_prompt,
761                    }
762                } else if ent.attribute_equality(
763                    Attribute::Class,
764                    &EntryClass::OAuth2ResourceServerPublic.into(),
765                ) {
766                    let allow_localhost_redirect = ent
767                        .get_ava_single_bool(Attribute::OAuth2AllowLocalhostRedirect)
768                        .unwrap_or(false);
769
770                    OauthRSType::Public {
771                        allow_localhost_redirect,
772                    }
773                } else {
774                    error!("Missing class determining OAuth2 rs type");
775                    return Err(OperationError::InvalidEntryState);
776                };
777
778                // Now we know we can load the shared attrs.
779                let client_id = ent
780                    .get_ava_single_iname(Attribute::Name)
781                    .map(str::to_string)
782                    .ok_or(OperationError::InvalidValueState)?;
783
784                let displayname = ent
785                    .get_ava_single_utf8(Attribute::DisplayName)
786                    .map(str::to_string)
787                    .ok_or(OperationError::InvalidValueState)?;
788
789                // Setup the landing uri and its implied origin, as well as
790                // the supplemental origins.
791                let landing_url = ent
792                    .get_ava_single_url(Attribute::OAuth2RsOriginLanding)
793                    .cloned()
794                    .ok_or(OperationError::InvalidValueState)?;
795
796                let maybe_extra_urls = ent
797                    .get_ava_set(Attribute::OAuth2RsOrigin)
798                    .and_then(|s| s.as_url_set());
799
800                let len_uris = maybe_extra_urls.map(|s| s.len() + 1).unwrap_or(1);
801
802                // The reason we have to allocate this is that we need to do some processing on these
803                // urls to determine if they are opaque or not.
804                let mut redirect_uris_v = Vec::with_capacity(len_uris);
805
806                redirect_uris_v.push(landing_url);
807                if let Some(extra_origins) = maybe_extra_urls {
808                    for x_origin in extra_origins {
809                        redirect_uris_v.push(x_origin.clone());
810                    }
811                }
812
813                // Now redirect_uris has the full set of the landing uri and the other uris
814                // that may or may not be an opaque origin. We need to split these up now.
815
816                let mut origins = HashSet::with_capacity(len_uris);
817                let mut redirect_uris = HashSet::with_capacity(len_uris);
818                let mut opaque_origins = HashSet::with_capacity(len_uris);
819                let mut origin_secure_required = false;
820
821                for mut uri in redirect_uris_v.into_iter() {
822                    // https://www.rfc-editor.org/rfc/rfc6749#section-3.1.2
823                    // Must not include a fragment.
824                    uri.set_fragment(None);
825                    // Given the presence of a single https url, then all other urls must be https.
826                    if uri.scheme() == "https" {
827                        origin_secure_required = true;
828                        origins.insert(uri.origin());
829                        redirect_uris.insert(uri);
830                    } else if uri.scheme() == "http" {
831                        origins.insert(uri.origin());
832                        redirect_uris.insert(uri);
833                    } else {
834                        opaque_origins.insert(uri);
835                    }
836                }
837
838                let scope_maps = ent
839                    .get_ava_as_oauthscopemaps(Attribute::OAuth2RsScopeMap)
840                    .cloned()
841                    .unwrap_or_default();
842
843                let sup_scope_maps = ent
844                    .get_ava_as_oauthscopemaps(Attribute::OAuth2RsSupScopeMap)
845                    .cloned()
846                    .unwrap_or_default();
847
848                // From our scope maps we can now determine what scopes would be granted to our
849                // client during a client credentials authentication.
850                let (client_scopes, client_sup_scopes) =
851                    if let Some(client_member_of) = ent.get_ava_refer(Attribute::MemberOf) {
852                        let client_scopes = scope_maps
853                            .iter()
854                            .filter_map(|(u, m)| {
855                                if client_member_of.contains(u) {
856                                    Some(m.iter())
857                                } else {
858                                    None
859                                }
860                            })
861                            .flatten()
862                            .cloned()
863                            .collect::<BTreeSet<_>>();
864
865                        let client_sup_scopes = sup_scope_maps
866                            .iter()
867                            .filter_map(|(u, m)| {
868                                if client_member_of.contains(u) {
869                                    Some(m.iter())
870                                } else {
871                                    None
872                                }
873                            })
874                            .flatten()
875                            .cloned()
876                            .collect::<BTreeSet<_>>();
877
878                        (client_scopes, client_sup_scopes)
879                    } else {
880                        (BTreeSet::default(), BTreeSet::default())
881                    };
882
883                let e_claim_maps = ent
884                    .get_ava_set(Attribute::OAuth2RsClaimMap)
885                    .and_then(|vs| vs.as_oauthclaim_map());
886
887                // ⚠️  Claim Maps as they are stored in the DB are optimised
888                // for referential integrity and user interaction. However we
889                // need to "invert" these for fast lookups during actual
890                // operation of the oauth2 client.
891                let claim_map = if let Some(e_claim_maps) = e_claim_maps {
892                    let mut claim_map = BTreeMap::default();
893
894                    for (claim_name, claim_mapping) in e_claim_maps.iter() {
895                        for (group_uuid, claim_values) in claim_mapping.values().iter() {
896                            // We always insert/append here because the outer claim_name has
897                            // to be unique.
898                            match claim_map.entry(*group_uuid) {
899                                BTreeEntry::Vacant(e) => {
900                                    e.insert(vec![(
901                                        claim_name.clone(),
902                                        ClaimValue {
903                                            join: claim_mapping.join(),
904                                            values: claim_values.clone(),
905                                        },
906                                    )]);
907                                }
908                                BTreeEntry::Occupied(mut e) => {
909                                    e.get_mut().push((
910                                        claim_name.clone(),
911                                        ClaimValue {
912                                            join: claim_mapping.join(),
913                                            values: claim_values.clone(),
914                                        },
915                                    ));
916                                }
917                            }
918                        }
919                    }
920
921                    claim_map
922                } else {
923                    BTreeMap::default()
924                };
925
926                let sign_alg = if ent
927                    .get_ava_single_bool(Attribute::OAuth2JwtLegacyCryptoEnable)
928                    .unwrap_or(false)
929                {
930                    // Add the relevant KID's to the lookup map.
931                    kid_map.extend(
932                        key_object
933                            .jws_rs256_kid()
934                            .into_iter()
935                            .map(|kid| (kid.clone(), client_id.clone())),
936                    );
937
938                    SignatureAlgo::Rs256
939                } else {
940                    // Add the relevant KID's to the lookup map.
941                    kid_map.extend(
942                        key_object
943                            .jws_es256_kid()
944                            .into_iter()
945                            .map(|kid| (kid.clone(), client_id.clone())),
946                    );
947
948                    SignatureAlgo::Es256
949                };
950
951                // We also need the encryption keyids
952                if domain_level >= DOMAIN_LEVEL_1_12 {
953                    kid_map.extend(
954                        key_object
955                            .jwe_a256gcm_kid()
956                            .into_iter()
957                            .map(|kid| (kid.clone(), client_id.clone())),
958                    );
959                } else {
960                    kid_map.extend(
961                        key_object
962                            .jwe_a128gcm_kid()
963                            .into_iter()
964                            .map(|kid| (kid.clone(), client_id.clone())),
965                    );
966                }
967
968                let prefer_short_username = ent
969                    .get_ava_single_bool(Attribute::OAuth2PreferShortUsername)
970                    .unwrap_or(false);
971
972                let has_custom_image = ent.get_ava_single_image(Attribute::Image).is_some();
973
974                let refresh_token_expiry = ent
975                    .get_ava_single_uint32(Attribute::OAuth2RefreshTokenExpiry)
976                    .unwrap_or(OAUTH_REFRESH_TOKEN_EXPIRY);
977
978                let mut authorization_endpoint = self.inner.origin.clone();
979                authorization_endpoint.set_path("/ui/oauth2");
980
981                let mut token_endpoint = self.inner.origin.clone();
982                token_endpoint.set_path(uri::OAUTH2_TOKEN_ENDPOINT);
983
984                let mut revocation_endpoint = self.inner.origin.clone();
985                revocation_endpoint.set_path(OAUTH2_TOKEN_REVOKE_ENDPOINT);
986
987                let mut introspection_endpoint = self.inner.origin.clone();
988                introspection_endpoint.set_path(OAUTH2_TOKEN_INTROSPECT_ENDPOINT);
989
990                let mut userinfo_endpoint = self.inner.origin.clone();
991                userinfo_endpoint.set_path(&format!("/oauth2/openid/{client_id}/userinfo"));
992
993                let mut jwks_uri = self.inner.origin.clone();
994                jwks_uri.set_path(&format!("/oauth2/openid/{client_id}/public_key.jwk"));
995
996                let mut iss = self.inner.origin.clone();
997                iss.set_path(&format!("/oauth2/openid/{client_id}"));
998
999                let scopes_supported: BTreeSet<String> = scope_maps
1000                    .values()
1001                    .flat_map(|bts| bts.iter())
1002                    .chain(sup_scope_maps.values().flat_map(|bts| bts.iter()))
1003                    .cloned()
1004                    .collect();
1005
1006                let device_authorization_endpoint: Option<Url> =
1007                    match cfg!(feature = "dev-oauth2-device-flow") {
1008                        true => {
1009                            match ent
1010                                .get_ava_single_bool(Attribute::OAuth2DeviceFlowEnable)
1011                                .unwrap_or(false)
1012                            {
1013                                true => {
1014                                    let mut device_authorization_endpoint =
1015                                        self.inner.origin.clone();
1016                                    device_authorization_endpoint
1017                                        .set_path(uri::OAUTH2_AUTHORISE_DEVICE);
1018                                    Some(device_authorization_endpoint)
1019                                }
1020                                false => None,
1021                            }
1022                        }
1023                        false => None,
1024                    };
1025
1026                let rscfg = Oauth2RS {
1027                    name: client_id.clone(),
1028                    displayname,
1029                    uuid,
1030                    origins,
1031                    opaque_origins,
1032                    redirect_uris,
1033                    origin_secure_required,
1034                    scope_maps,
1035                    sup_scope_maps,
1036                    client_scopes,
1037                    client_sup_scopes,
1038                    claim_map,
1039                    sign_alg,
1040                    key_object,
1041                    refresh_token_expiry,
1042                    iss,
1043                    authorization_endpoint,
1044                    token_endpoint,
1045                    revocation_endpoint,
1046                    introspection_endpoint,
1047                    userinfo_endpoint,
1048                    jwks_uri,
1049                    scopes_supported,
1050                    prefer_short_username,
1051                    type_,
1052                    has_custom_image,
1053                    device_authorization_endpoint,
1054                };
1055
1056                Ok((client_id, rscfg))
1057            })
1058            .collect();
1059
1060        rs_set.map(|mut rs_set| {
1061            // Delay getting the inner mut (which may clone) until we know we are ok.
1062            let inner_ref = self.inner.get_mut();
1063            // Swap them if we are ok
1064            std::mem::swap(&mut inner_ref.private_rs_set, &mut rs_set);
1065            std::mem::swap(&mut inner_ref.private_key_map, &mut kid_map);
1066        })
1067    }
1068
1069    pub fn commit(self) {
1070        self.inner.commit();
1071    }
1072}
1073
1074impl IdmServerProxyWriteTransaction<'_> {
1075    #[instrument(level = "debug", skip_all)]
1076    pub fn oauth2_token_revoke(
1077        &mut self,
1078        revoke_req: &TokenRevokeRequest,
1079        ct: Duration,
1080    ) -> Result<(), Oauth2Error> {
1081        // We don't need to authenticate, since possession of the access token is already enough
1082        // to prove identity, and we enforce it is cryptographically valid so it can't be bruteforced
1083        // by a scanning attack.
1084
1085        // Because this is the only path that deals with the tokens that
1086        // are either signed *or* encrypted, we need to check both options.
1087
1088        let (session_id, expiry, uuid) = if let Ok(jwsc) = JwsCompact::from_str(&revoke_req.token) {
1089            let unverified_kid = jwsc.header().kid.as_ref().ok_or_else(|| {
1090                error!("Token does not contain signature key id");
1091                Oauth2Error::AuthenticationRequired
1092            })?;
1093
1094            // Get the o2rs for the handle.
1095            let o2rs = self
1096                .oauth2rs
1097                .inner
1098                .rs_from_kid(unverified_kid)
1099                .ok_or_else(|| {
1100                    warn!("Invalid OAuth2 key id");
1101                    Oauth2Error::AuthenticationRequired
1102                })?;
1103
1104            let access_token = o2rs
1105                .key_object
1106                .jws_verify(&jwsc)
1107                .map_err(|err| {
1108                    admin_error!(?err, "Unable to verify access token");
1109                    Oauth2Error::AuthenticationRequired
1110                })
1111                .and_then(|jws| {
1112                    jws.from_json().map_err(|err| {
1113                        admin_error!(?err, "Unable to deserialise access token");
1114                        Oauth2Error::InvalidRequest
1115                    })
1116                })?;
1117
1118            let OAuth2RFC9068Token::<_> {
1119                sub: uuid,
1120                exp,
1121                extensions: OAuth2RFC9068TokenExtensions { session_id, .. },
1122                ..
1123            } = access_token;
1124
1125            (session_id, exp, uuid)
1126        } else if let Ok(jwec) = JweCompact::from_str(&revoke_req.token) {
1127            // Assume it's encrypted.
1128            let unverified_kid = jwec.header().kid.as_ref().ok_or_else(|| {
1129                error!("Token does not contain encryption key id");
1130                Oauth2Error::AuthenticationRequired
1131            })?;
1132
1133            // Get the o2rs for the handle.
1134            let o2rs = self
1135                .oauth2rs
1136                .inner
1137                .rs_from_kid(unverified_kid)
1138                .ok_or_else(|| {
1139                    warn!("Invalid OAuth2 key id");
1140                    Oauth2Error::AuthenticationRequired
1141                })?;
1142
1143            let token: Oauth2TokenType = o2rs
1144                .key_object
1145                .jwe_decrypt(&jwec)
1146                .map_err(|_| {
1147                    error!("Failed to decrypt token revoke request");
1148                    Oauth2Error::AuthenticationRequired
1149                })
1150                .and_then(|jwe| {
1151                    jwe.from_json().map_err(|err| {
1152                        error!(?err, "Failed to deserialise token");
1153                        Oauth2Error::InvalidRequest
1154                    })
1155                })?;
1156
1157            match token {
1158                Oauth2TokenType::ClientAccess {
1159                    session_id,
1160                    exp,
1161                    uuid,
1162                    ..
1163                }
1164                | Oauth2TokenType::Refresh {
1165                    session_id,
1166                    exp,
1167                    uuid,
1168                    ..
1169                } => (session_id, exp, uuid),
1170            }
1171        } else {
1172            error!("Failed to deserialise a valid JWE or JWS");
1173            return Err(Oauth2Error::AuthenticationRequired);
1174        };
1175
1176        // Only submit a revocation if the token is not yet expired.
1177        if expiry <= ct.as_secs() as i64 {
1178            security_info!(?uuid, "token has expired, returning inactive");
1179            return Ok(());
1180        }
1181
1182        // Consider replication. We have servers A and B. A issues our oauth2
1183        // token to the client. The resource server then issues the revoke request
1184        // to B. In this case A has not yet replicated the session to B, but we
1185        // still need to ensure the revoke is respected. As a result, we don't
1186        // actually consult if the session is present on the account, we simply
1187        // submit the Modify::Remove. This way it's inserted into the entry changelog
1188        // and when replication converges the session is actually removed.
1189
1190        let modlist: ModifyList<ModifyInvalid> = ModifyList::new_list(vec![Modify::Removed(
1191            Attribute::OAuth2Session,
1192            PartialValue::Refer(session_id),
1193        )]);
1194
1195        self.qs_write
1196            .internal_modify(
1197                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid))),
1198                &modlist,
1199            )
1200            .map_err(|e| {
1201                admin_error!("Failed to modify - revoke OAuth2 session {:?}", e);
1202                Oauth2Error::ServerError(e)
1203            })
1204    }
1205
1206    #[instrument(level = "debug", skip_all)]
1207    pub fn check_oauth2_token_exchange(
1208        &mut self,
1209        client_auth_info: &ClientAuthInfo,
1210        token_req: &AccessTokenRequest,
1211        ct: Duration,
1212    ) -> Result<AccessTokenResponse, Oauth2Error> {
1213        // Public clients will send the client_id via the ATR, so we need to handle this case.
1214        let client_auth = get_client_auth(client_auth_info, &token_req.client_post_auth)
1215            .inspect_err(|_| {
1216                warn!("OAuth2 Client Authentcation Required");
1217            })?;
1218
1219        let o2rs = self
1220            .oauth2rs
1221            .inner
1222            .rs_set_get(&client_auth.client_id)
1223            .ok_or_else(|| {
1224                debug!("Invalid OAuth2 client_id {}", &client_auth.client_id);
1225                Oauth2Error::AuthenticationRequired
1226            })?
1227            .clone();
1228
1229        let is_token_exchange = matches!(token_req.grant_type, GrantTypeReq::TokenExchange { .. });
1230
1231        // check the secret.
1232        let client_authentication_valid = match (&o2rs.type_, is_token_exchange) {
1233            (OauthRSType::Basic { .. }, true) => {
1234                if client_auth.client_secret.is_some() {
1235                    security_info!(
1236                        "Client secret is not accepted when exchanging a service account token"
1237                    );
1238                    return Err(Oauth2Error::InvalidRequest);
1239                }
1240                true
1241            }
1242            (OauthRSType::Basic { authz_secret, .. }, false) => {
1243                match client_auth.client_secret {
1244                    Some(secret) => {
1245                        if authz_secret.ct_eq(&secret) {
1246                            true
1247                        } else {
1248                            info!("Invalid OAuth2 client_id secret");
1249                            return Err(Oauth2Error::AuthenticationRequired);
1250                        }
1251                    }
1252                    None => {
1253                        // We can only get here if we relied on the atr for the client_id and secret
1254                        info!(
1255                            "Invalid OAuth2 authentication - no secret in access token request - this can happen if you're expecting a public client and configured a basic one."
1256                        );
1257                        return Err(Oauth2Error::AuthenticationRequired);
1258                    }
1259                }
1260            }
1261            // Relies on the token to be valid - no further action needed.
1262            (OauthRSType::Public { .. }, _) => false,
1263        };
1264
1265        // We are authenticated! Yay! Now we can actually check things ...
1266        match &token_req.grant_type {
1267            GrantTypeReq::AuthorizationCode {
1268                code,
1269                redirect_uri,
1270                code_verifier,
1271            } => self.check_oauth2_token_exchange_authorization_code(
1272                &o2rs,
1273                code,
1274                redirect_uri,
1275                code_verifier.as_deref(),
1276                ct,
1277            ),
1278            GrantTypeReq::ClientCredentials { scope } => {
1279                if client_authentication_valid {
1280                    self.check_oauth2_token_client_credentials(&o2rs, scope.as_ref(), ct)
1281                } else {
1282                    security_info!(
1283                        "Unable to proceed with client credentials grant unless client authentication is provided and valid"
1284                    );
1285                    Err(Oauth2Error::AuthenticationRequired)
1286                }
1287            }
1288            GrantTypeReq::RefreshToken {
1289                refresh_token,
1290                scope,
1291            } => self.check_oauth2_token_refresh(&o2rs, refresh_token, scope.as_ref(), ct),
1292            GrantTypeReq::TokenExchange {
1293                subject_token,
1294                subject_token_type,
1295                requested_token_type,
1296                audience,
1297                resource,
1298                actor_token,
1299                actor_token_type,
1300                scope,
1301            } => {
1302                if actor_token.is_some() || actor_token_type.is_some() {
1303                    warn!("actor_token is not supported for token exchange");
1304                    return Err(Oauth2Error::InvalidRequest);
1305                }
1306
1307                self.check_oauth2_token_exchange_service_account(
1308                    &o2rs,
1309                    subject_token,
1310                    subject_token_type,
1311                    requested_token_type.as_deref(),
1312                    audience.as_deref(),
1313                    resource.as_deref(),
1314                    scope.as_ref(),
1315                    ct,
1316                )
1317            }
1318            GrantTypeReq::DeviceCode { device_code, scope } => {
1319                self.check_oauth2_device_code_status(device_code, scope)
1320            }
1321        }
1322    }
1323
1324    #[instrument(level = "info", skip(self))]
1325    pub fn handle_oauth2_start_device_flow(
1326        &mut self,
1327        _client_auth_info: ClientAuthInfo,
1328        _client_id: &str,
1329        _scope: &Option<BTreeSet<String>>,
1330        _eventid: Uuid,
1331    ) -> Result<DeviceAuthorizationResponse, Oauth2Error> {
1332        // let o2rs = self.get_client(client_id)?;
1333
1334        // info!("Got Client: {:?}", o2rs);
1335
1336        // // TODO: change this to checking if it's got device flow enabled
1337        // if !o2rs.require_pkce() {
1338        //     security_info!("Device flow is only available for PKCE-enabled clients");
1339        //     return Err(Oauth2Error::InvalidRequest);
1340        // }
1341
1342        // info!(
1343        //     "Starting device flow for client_id={} scopes={} source={:?}",
1344        //     client_id,
1345        //     scope
1346        //         .as_ref()
1347        //         .map(|s| s.iter().cloned().collect::<Vec<_>>().into_iter().join(","))
1348        //         .unwrap_or("[]".to_string()),
1349        //     client_auth_info.source
1350        // );
1351
1352        // let mut verification_uri = self.oauth2rs.inner.origin.clone();
1353        // verification_uri.set_path(uri::OAUTH2_DEVICE_LOGIN);
1354
1355        // let (user_code_string, _user_code) = gen_user_code();
1356        // let expiry =
1357        //     Duration::from_secs(OAUTH2_DEVICE_CODE_EXPIRY_SECONDS) + duration_from_epoch_now();
1358        // let device_code = gen_device_code()
1359        //     .inspect_err(|err| error!("Failed to generate a device code! {:?}", err))?;
1360
1361        Err(Oauth2Error::InvalidGrant)
1362
1363        // TODO: store user_code / expiry / client_id / device_code in the backend, needs to be checked on the token exchange.
1364        // Ok(DeviceAuthorizationResponse::new(
1365        //     verification_uri,
1366        //     device_code,
1367        //     user_code_string,
1368        // ))
1369    }
1370
1371    #[instrument(level = "info", skip(self))]
1372    fn check_oauth2_device_code_status(
1373        &mut self,
1374        device_code: &str,
1375        scope: &Option<BTreeSet<String>>,
1376    ) -> Result<AccessTokenResponse, Oauth2Error> {
1377        // TODO: check the device code is valid, do the needful
1378
1379        error!(
1380            "haven't done the device grant yet! Got device_code={} scope={:?}",
1381            device_code, scope
1382        );
1383        Err(Oauth2Error::AuthorizationPending)
1384
1385        // if it's an expired code, then just delete it from the db and return an error.
1386        // Err(Oauth2Error::ExpiredToken)
1387    }
1388
1389    #[instrument(level = "debug", skip_all)]
1390    pub fn check_oauth2_authorise_permit(
1391        &mut self,
1392        ident: &Identity,
1393        consent_token: &str,
1394        ct: Duration,
1395    ) -> Result<AuthorisePermitSuccess, OperationError> {
1396        let account_uuid = ident.get_uuid();
1397
1398        let consent_token_jwe = JweCompact::from_str(consent_token).map_err(|err| {
1399            error!(?err, "Consent token is not a valid jwe compact");
1400            OperationError::InvalidSessionState
1401        })?;
1402
1403        let consent_req: ConsentToken = self
1404            .oauth2rs
1405            .inner
1406            .consent_key
1407            .decipher(&consent_token_jwe)
1408            .map_err(|err| {
1409                error!(?err, "Failed to decrypt consent request");
1410                OperationError::CryptographyError
1411            })
1412            .and_then(|jwe| {
1413                jwe.from_json().map_err(|err| {
1414                    error!(?err, "Failed to deserialise consent request");
1415                    OperationError::SerdeJsonError
1416                })
1417            })?;
1418
1419        // Validate that the ident_id matches our current ident.
1420        if consent_req.ident_id != ident.get_event_origin_id() {
1421            security_info!("consent request ident id does not match the identity of our UAT.");
1422            return Err(OperationError::InvalidSessionState);
1423        }
1424
1425        // Validate that the session id matches our uat.
1426        if consent_req.session_id != ident.get_session_id() {
1427            security_info!("consent request session id does not match the session id of our UAT.");
1428            return Err(OperationError::InvalidSessionState);
1429        }
1430
1431        if consent_req.expiry <= ct.as_secs() {
1432            // Token is expired
1433            error!("Failed to decrypt consent request");
1434            return Err(OperationError::CryptographyError);
1435        }
1436
1437        // The exchange must be performed in the next 60 seconds.
1438        let expiry = ct.as_secs() + 60;
1439
1440        // Get the resource server config based on this client_id.
1441        let o2rs = self
1442            .oauth2rs
1443            .inner
1444            .rs_set_get(&consent_req.client_id)
1445            .ok_or_else(|| {
1446                admin_error!("Invalid consent request OAuth2 client_id");
1447                OperationError::InvalidRequestState
1448            })?;
1449
1450        // Extract the state, code challenge, redirect_uri
1451        let xchg_code = TokenExchangeCode {
1452            account_uuid,
1453            session_id: ident.get_session_id(),
1454            expiry,
1455            code_challenge: consent_req.code_challenge,
1456            redirect_uri: consent_req.redirect_uri.clone(),
1457            scopes: consent_req.scopes.clone(),
1458            nonce: consent_req.nonce,
1459            auth_time: ident.last_verified_at(),
1460        };
1461
1462        // Encrypt the exchange token
1463        let code_data_jwe = JweBuilder::into_json(&xchg_code)
1464            .map(|builder| builder.build())
1465            .map_err(|err| {
1466                error!(?err, "Unable to encode xchg_code data");
1467                OperationError::SerdeJsonError
1468            })?;
1469
1470        let domain_level = self.qs_write.get_domain_version();
1471
1472        let code = if domain_level >= DOMAIN_LEVEL_1_12 {
1473            o2rs.key_object
1474                .jwe_a256gcm_encrypt(&code_data_jwe, ct)
1475                .map(|code| code.to_string())
1476                .map_err(|err| {
1477                    error!(?err, "Unable to encrypt xchg_code");
1478                    OperationError::CryptographyError
1479                })?
1480        } else {
1481            o2rs.key_object
1482                .jwe_a128gcm_encrypt(&code_data_jwe, ct)
1483                .map(|code| code.to_string())
1484                .map_err(|err| {
1485                    error!(?err, "Unable to encrypt xchg_code");
1486                    OperationError::CryptographyError
1487                })?
1488        };
1489
1490        // Everything is DONE! Now submit that it's all happy and the user consented correctly.
1491        // this will let them bypass consent steps in the future.
1492        // Submit that we consented to the delayed action queue
1493
1494        let modlist = ModifyList::new_list(vec![
1495            Modify::Removed(
1496                Attribute::OAuth2ConsentScopeMap,
1497                PartialValue::Refer(o2rs.uuid),
1498            ),
1499            Modify::Present(
1500                Attribute::OAuth2ConsentScopeMap,
1501                Value::OauthScopeMap(o2rs.uuid, consent_req.scopes.iter().cloned().collect()),
1502            ),
1503        ]);
1504
1505        self.qs_write.internal_modify(
1506            &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(account_uuid))),
1507            &modlist,
1508        )?;
1509
1510        Ok(AuthorisePermitSuccess {
1511            redirect_uri: consent_req.redirect_uri,
1512            state: consent_req.state,
1513            code,
1514            response_mode: consent_req.response_mode,
1515        })
1516    }
1517
1518    #[instrument(level = "debug", skip_all)]
1519    fn check_oauth2_token_exchange_authorization_code(
1520        &mut self,
1521        o2rs: &Oauth2RS,
1522        token_req_code: &str,
1523        token_req_redirect_uri: &Url,
1524        token_req_code_verifier: Option<&str>,
1525        ct: Duration,
1526    ) -> Result<AccessTokenResponse, Oauth2Error> {
1527        // Check the token_req is within the valid time, and correctly signed for
1528        // this client.
1529        let jwe_compact = JweCompact::from_str(token_req_code).map_err(|_| {
1530            error!("Failed to deserialise a valid JWE");
1531            Oauth2Error::InvalidRequest
1532        })?;
1533
1534        let code_xchg: TokenExchangeCode = o2rs
1535            .key_object
1536            .jwe_decrypt(&jwe_compact)
1537            .map_err(|_| {
1538                admin_error!("Failed to decrypt token exchange request");
1539                Oauth2Error::InvalidRequest
1540            })
1541            .and_then(|jwe| {
1542                debug!(?jwe);
1543                jwe.from_json::<TokenExchangeCode>().map_err(|err| {
1544                    error!(?err, "Failed to deserialise token exchange code");
1545                    Oauth2Error::InvalidRequest
1546                })
1547            })?;
1548
1549        if code_xchg.expiry <= ct.as_secs() {
1550            error!("Expired token exchange request");
1551            return Err(Oauth2Error::InvalidRequest);
1552        }
1553
1554        // If we have a verifier present, we MUST assert that a code challenge is present!
1555        // It is worth noting here that code_xchg is *server issued* and encrypted, with
1556        // a short validity period. The client controlled value is in token_req.code_verifier
1557        if let Some(code_challenge) = code_xchg.code_challenge {
1558            // Validate the code_verifier
1559            let code_verifier = token_req_code_verifier
1560                    .ok_or_else(|| {
1561                        security_info!("PKCE code verification failed - code challenge is present, but no verifier was provided");
1562                        Oauth2Error::InvalidRequest
1563                    })?;
1564
1565            let verifier_secret = PkceS256Secret::from(code_verifier.to_string());
1566
1567            if !verifier_secret.verify(code_challenge) {
1568                security_info!(
1569                    "PKCE code verification failed - this may indicate malicious activity"
1570                );
1571                return Err(Oauth2Error::InvalidRequest);
1572            }
1573        } else if o2rs.require_pkce() {
1574            security_info!(
1575                "PKCE code verification failed - no code challenge present in PKCE enforced mode"
1576            );
1577            return Err(Oauth2Error::InvalidRequest);
1578        } else if token_req_code_verifier.is_some() {
1579            security_info!(
1580                "PKCE code verification failed - a code verifier is present, but no code challenge in exchange"
1581            );
1582            return Err(Oauth2Error::InvalidRequest);
1583        }
1584
1585        // Validate the redirect_uri is the same as the original.
1586        if token_req_redirect_uri != &code_xchg.redirect_uri {
1587            security_info!("Invalid OAuth2 redirect_uri (differs from original request uri)");
1588            return Err(Oauth2Error::InvalidOrigin);
1589        }
1590
1591        /*
1592        // Check that the UAT we are issuing for still is valid.
1593        //
1594        // Not sure this is actually needed. To create the token exchange code you need to have
1595        // a valid, non-expired session, so why do we double check this here?
1596        let odt_ct = OffsetDateTime::UNIX_EPOCH + ct;
1597        if let Some(expiry) = code_xchg.uat.expiry {
1598            if expiry <= odt_ct {
1599                security_info!(
1600                    "User Auth Token has expired before we could publish the OAuth2 response"
1601                );
1602                return Err(Oauth2Error::AccessDenied);
1603            }
1604        }
1605        */
1606
1607        // ==== We are now GOOD TO GO! ====
1608        // Grant the access token response.
1609        let parent_session_id = Some(code_xchg.session_id);
1610        let session_id = Uuid::new_v4();
1611
1612        let scopes = code_xchg.scopes;
1613        let session_ctx = OAuth2SessionContext {
1614            auth_time: code_xchg.auth_time,
1615            nonce: code_xchg.nonce,
1616            account_uuid: code_xchg.account_uuid,
1617        };
1618
1619        self.generate_access_token_response(
1620            o2rs,
1621            ct,
1622            scopes,
1623            parent_session_id,
1624            session_id,
1625            session_ctx,
1626        )
1627    }
1628
1629    #[instrument(level = "debug", skip_all)]
1630    fn check_oauth2_token_refresh(
1631        &mut self,
1632        o2rs: &Oauth2RS,
1633        refresh_token: &str,
1634        req_scopes: Option<&BTreeSet<String>>,
1635        ct: Duration,
1636    ) -> Result<AccessTokenResponse, Oauth2Error> {
1637        let jwe_compact = JweCompact::from_str(refresh_token).map_err(|_| {
1638            error!("Failed to deserialise a valid JWE");
1639            Oauth2Error::InvalidRequest
1640        })?;
1641
1642        // Validate the refresh token decrypts and it's expiry is within the valid window.
1643        let token: Oauth2TokenType = o2rs
1644            .key_object
1645            .jwe_decrypt(&jwe_compact)
1646            .map_err(|_| {
1647                admin_error!("Failed to decrypt refresh token request");
1648                Oauth2Error::InvalidRequest
1649            })
1650            .and_then(|jwe| {
1651                jwe.from_json().map_err(|err| {
1652                    error!(?err, "Failed to deserialise token");
1653                    Oauth2Error::InvalidRequest
1654                })
1655            })?;
1656
1657        match token {
1658            // Oauth2TokenType::Access { .. } |
1659            Oauth2TokenType::ClientAccess { .. } => {
1660                admin_error!("attempt to refresh with an access token");
1661                Err(Oauth2Error::InvalidRequest)
1662            }
1663            Oauth2TokenType::Refresh {
1664                scopes,
1665                parent_session_id,
1666                session_id,
1667                exp,
1668                uuid,
1669                iat,
1670                nbf: _,
1671                nonce,
1672                auth_time,
1673            } => {
1674                if exp <= ct.as_secs() as i64 {
1675                    security_info!(?uuid, "refresh token has expired, ");
1676                    return Err(Oauth2Error::InvalidGrant);
1677                }
1678
1679                // Check the session is still valid. This call checks the parent session
1680                // and the OAuth2 session.
1681                let valid = self
1682                    .check_oauth2_account_uuid_valid(uuid, session_id, parent_session_id, iat, ct)
1683                    .map_err(|_| admin_error!("Account is not valid"));
1684
1685                let Ok(Some(entry)) = valid else {
1686                    security_info!(
1687                        ?uuid,
1688                        "access token has no account not valid, returning inactive"
1689                    );
1690                    return Err(Oauth2Error::InvalidGrant);
1691                };
1692
1693                // Check the not issued before of the session relative to this refresh iat
1694                let oauth2_session = entry
1695                    .get_ava_as_oauth2session_map(Attribute::OAuth2Session)
1696                    .and_then(|map| map.get(&session_id))
1697                    .ok_or_else(|| {
1698                        security_info!(
1699                            ?session_id,
1700                            "No OAuth2 session found, unable to proceed with refresh"
1701                        );
1702                        Oauth2Error::InvalidGrant
1703                    })?;
1704
1705                // If the refresh token was issued previous to the time listed in our oauth2_session
1706                // this indicates session desync / replay. We must nuke the session at this point.
1707                //
1708                // Need to think about how to handle this nicely give transactions.
1709                if iat < oauth2_session.issued_at.unix_timestamp() {
1710                    security_info!(
1711                        ?session_id,
1712                        "Attempt to reuse a refresh token detected, destroying session"
1713                    );
1714
1715                    // Revoke it
1716                    let modlist = ModifyList::new_list(vec![Modify::Removed(
1717                        Attribute::OAuth2Session,
1718                        PartialValue::Refer(session_id),
1719                    )]);
1720
1721                    self.qs_write
1722                        .internal_modify(
1723                            &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid))),
1724                            &modlist,
1725                        )
1726                        .map_err(|e| {
1727                            admin_error!("Failed to modify - revoke OAuth2 session {:?}", e);
1728                            Oauth2Error::ServerError(e)
1729                        })?;
1730
1731                    return Err(Oauth2Error::InvalidGrant);
1732                }
1733
1734                // Check the scopes are equal or subset, OR none.
1735                let update_scopes = if let Some(req_scopes) = req_scopes {
1736                    if req_scopes.is_subset(&scopes) {
1737                        debug!("oauth2 scopes requested, checked as valid.");
1738                        // We have to return the requested set since it
1739                        // may be constrained.
1740                        req_scopes.clone()
1741                    } else {
1742                        warn!("oauth2 scopes requested, invalid.");
1743                        return Err(Oauth2Error::InvalidScope);
1744                    }
1745                } else {
1746                    debug!("No OAuth2 scopes requested, this is valid.");
1747                    // Return the initial set of scopes.
1748                    scopes
1749                };
1750
1751                // ----------
1752                // good to go
1753                let account_uuid = uuid;
1754                let session_ctx = OAuth2SessionContext {
1755                    auth_time,
1756                    nonce,
1757                    account_uuid,
1758                };
1759
1760                self.generate_access_token_response(
1761                    o2rs,
1762                    ct,
1763                    update_scopes,
1764                    parent_session_id,
1765                    session_id,
1766                    session_ctx,
1767                )
1768            }
1769        }
1770    }
1771
1772    #[allow(clippy::too_many_arguments)]
1773    #[instrument(level = "debug", skip_all)]
1774    fn check_oauth2_token_exchange_service_account(
1775        &mut self,
1776        o2rs: &Oauth2RS,
1777        subject_token: &str,
1778        subject_token_type: &str,
1779        requested_token_type: Option<&str>,
1780        audience: Option<&str>,
1781        resource: Option<&str>,
1782        req_scopes: Option<&BTreeSet<String>>,
1783        ct: Duration,
1784    ) -> Result<AccessTokenResponse, Oauth2Error> {
1785        if let Some(rtt) = requested_token_type {
1786            if rtt != OAUTH2_TOKEN_TYPE_ACCESS_TOKEN {
1787                warn!(
1788                    requested_token_type = rtt,
1789                    "Unsupported requested_token_type in token exchange"
1790                );
1791                return Err(Oauth2Error::InvalidRequest);
1792            }
1793        }
1794
1795        if let Some(aud) = audience {
1796            if aud != o2rs.name {
1797                warn!(expected = %o2rs.name, requested = aud, "Token exchange audience mismatch");
1798                return Err(Oauth2Error::InvalidTarget);
1799            }
1800        }
1801
1802        if let Some(res) = resource {
1803            let parsed_resource = Url::parse(res).map_err(|_| {
1804                warn!(
1805                    requested = res,
1806                    "Invalid resource parameter in token exchange"
1807                );
1808                Oauth2Error::InvalidRequest
1809            })?;
1810
1811            if parsed_resource.fragment().is_some() {
1812                warn!(
1813                    requested = res,
1814                    "Resource parameter must not contain a fragment"
1815                );
1816                return Err(Oauth2Error::InvalidRequest);
1817            }
1818
1819            let origin = parsed_resource.origin();
1820            let target_allowed =
1821                o2rs.origins.contains(&origin) || o2rs.opaque_origins.contains(&parsed_resource);
1822            if !target_allowed {
1823                admin_warn!(requested = res, "Token exchange resource target mismatch");
1824                return Err(Oauth2Error::InvalidTarget);
1825            }
1826        }
1827
1828        if subject_token_type != TOKEN_EXCHANGE_SUBJECT_TOKEN_TYPE_ACCESS {
1829            security_info!(
1830                ?subject_token_type,
1831                "Unsupported subject_token_type in token exchange"
1832            );
1833            return Err(Oauth2Error::InvalidRequest);
1834        }
1835
1836        let jwsc = JwsCompact::from_str(subject_token).map_err(|_| {
1837            error!("Failed to deserialise subject token for token exchange");
1838            Oauth2Error::InvalidRequest
1839        })?;
1840
1841        let token = self
1842            .validate_and_parse_token_to_identity_token(&jwsc, ct)
1843            .map_err(|err| {
1844                security_info!(?err, "Unable to validate subject token for token exchange");
1845                Oauth2Error::InvalidRequest
1846            })?;
1847
1848        let (apit, entry) = match token {
1849            Token::ApiToken(apit, entry) => (apit, entry),
1850            Token::UserAuthToken(_) => {
1851                security_info!("Token exchange subject_token must be a service account api token");
1852                return Err(Oauth2Error::InvalidRequest);
1853            }
1854        };
1855
1856        let ident = self
1857            .process_apit_to_identity(&apit, Source::Internal, entry, ct)
1858            .map_err(|err| match err {
1859                OperationError::SessionExpired | OperationError::NotAuthenticated => {
1860                    security_info!(
1861                        ?err,
1862                        "Service account api token rejected during token exchange"
1863                    );
1864                    Oauth2Error::InvalidRequest
1865                }
1866                err => Oauth2Error::ServerError(err),
1867            })?;
1868
1869        let (_req_scopes, granted_scopes) =
1870            process_requested_scopes_for_identity(o2rs, &ident, req_scopes)?;
1871
1872        let session_id = Uuid::new_v4();
1873        let parent_session_id = None;
1874        let session_ctx = OAuth2SessionContext {
1875            // Service accounts don't have an auth time
1876            auth_time: None,
1877            account_uuid: apit.account_id,
1878            nonce: None,
1879        };
1880
1881        self.generate_access_token_response(
1882            o2rs,
1883            ct,
1884            granted_scopes,
1885            parent_session_id,
1886            session_id,
1887            session_ctx,
1888        )
1889    }
1890
1891    fn check_oauth2_token_client_credentials(
1892        &mut self,
1893        o2rs: &Oauth2RS,
1894        req_scopes: Option<&BTreeSet<String>>,
1895        ct: Duration,
1896    ) -> Result<AccessTokenResponse, Oauth2Error> {
1897        let req_scopes = req_scopes.cloned().unwrap_or_default();
1898
1899        // Validate all request scopes have valid syntax.
1900        validate_scopes(&req_scopes)?;
1901
1902        // Of these scopes, which do we have available?
1903        let avail_scopes: Vec<String> = req_scopes
1904            .intersection(&o2rs.client_scopes)
1905            .map(|s| s.to_string())
1906            .collect();
1907
1908        if avail_scopes.len() != req_scopes.len() {
1909            admin_warn!(
1910                ident = %o2rs.name,
1911                requested_scopes = ?req_scopes,
1912                available_scopes = ?o2rs.client_scopes,
1913                "Client does not have access to the requested scopes"
1914            );
1915            return Err(Oauth2Error::AccessDenied);
1916        }
1917
1918        // == ready to build the access token ==
1919
1920        let granted_scopes = avail_scopes
1921            .into_iter()
1922            .chain(o2rs.client_sup_scopes.iter().cloned())
1923            .collect::<BTreeSet<_>>();
1924
1925        let odt_ct = OffsetDateTime::UNIX_EPOCH + ct;
1926        let iat = ct.as_secs() as i64;
1927        let exp = iat + OAUTH2_ACCESS_TOKEN_EXPIRY as i64;
1928        let odt_exp = odt_ct + Duration::from_secs(OAUTH2_ACCESS_TOKEN_EXPIRY as u64);
1929        let expires_in = OAUTH2_ACCESS_TOKEN_EXPIRY;
1930
1931        let session_id = Uuid::new_v4();
1932
1933        let scope = granted_scopes.clone();
1934
1935        let uuid = o2rs.uuid;
1936
1937        let access_token_raw = Oauth2TokenType::ClientAccess {
1938            scopes: granted_scopes,
1939            session_id,
1940            uuid,
1941            exp,
1942            iat,
1943            nbf: iat,
1944        };
1945
1946        let access_token_data = JweBuilder::into_json(&access_token_raw)
1947            .map(|builder| builder.build())
1948            .map_err(|err| {
1949                error!(?err, "Unable to encode token data");
1950                Oauth2Error::ServerError(OperationError::SerdeJsonError)
1951            })?;
1952
1953        let domain_level = self.qs_write.get_domain_version();
1954
1955        let access_token = if domain_level >= DOMAIN_LEVEL_1_12 {
1956            o2rs.key_object
1957                .jwe_a256gcm_encrypt(&access_token_data, ct)
1958                .map(|jwe| jwe.to_string())
1959                .map_err(|err| {
1960                    error!(?err, "Unable to encode token data");
1961                    Oauth2Error::ServerError(OperationError::CryptographyError)
1962                })?
1963        } else {
1964            o2rs.key_object
1965                .jwe_a128gcm_encrypt(&access_token_data, ct)
1966                .map(|jwe| jwe.to_string())
1967                .map_err(|err| {
1968                    error!(?err, "Unable to encode token data");
1969                    Oauth2Error::ServerError(OperationError::CryptographyError)
1970                })?
1971        };
1972
1973        // Write the session to the db
1974        let session = Value::Oauth2Session(
1975            session_id,
1976            Oauth2Session {
1977                parent: None,
1978                state: SessionState::ExpiresAt(odt_exp),
1979                issued_at: odt_ct,
1980                rs_uuid: o2rs.uuid,
1981            },
1982        );
1983
1984        // We need to create this session on the o2rs
1985        let modlist =
1986            ModifyList::new_list(vec![Modify::Present(Attribute::OAuth2Session, session)]);
1987
1988        self.qs_write
1989            .internal_modify(
1990                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(uuid))),
1991                &modlist,
1992            )
1993            .map_err(|e| {
1994                admin_error!("Failed to persist OAuth2 session record {:?}", e);
1995                Oauth2Error::ServerError(e)
1996            })?;
1997
1998        Ok(AccessTokenResponse {
1999            access_token,
2000            token_type: AccessTokenType::Bearer,
2001            issued_token_type: Some(IssuedTokenType::AccessToken),
2002            expires_in,
2003            refresh_token: None,
2004            scope,
2005            id_token: None,
2006        })
2007    }
2008
2009    fn generate_access_token_response(
2010        &mut self,
2011        o2rs: &Oauth2RS,
2012        ct: Duration,
2013        scopes: BTreeSet<String>,
2014        parent_session_id: Option<Uuid>,
2015        session_id: Uuid,
2016        session_ctx: OAuth2SessionContext,
2017    ) -> Result<AccessTokenResponse, Oauth2Error> {
2018        let odt_ct = OffsetDateTime::UNIX_EPOCH + ct;
2019        let iat = ct.as_secs() as i64;
2020
2021        // Disclaimer: It may seem odd here that we are ignoring our session when it comes to expiry
2022        // times. However, this actually is valid because when we take the initial code exchange
2023        // path we have already validate the expiry of the account/session in that process. For the
2024        // refresh path, we validate the session expiry and validity before we call this. So these
2025        // expiries are *purely* for the tokens we issue and are *not related* to the expiries of the
2026        // the session - these are enforced as above!
2027
2028        // Refresh tokens can be configured, but access token expiry can not. This is because
2029        // OAuth2 has no *revocation* mechanism, so we need to be validating and re-issuing
2030        // access tokens frequently.
2031        let expiry = odt_ct + Duration::from_secs(OAUTH2_ACCESS_TOKEN_EXPIRY as u64);
2032        let expires_in = OAUTH2_ACCESS_TOKEN_EXPIRY;
2033        let refresh_expiry = iat + o2rs.refresh_token_expiry as i64;
2034        let odt_refresh_expiry = odt_ct + Duration::from_secs(o2rs.refresh_token_expiry as u64);
2035
2036        let scope = scopes.clone();
2037
2038        let iss = o2rs.iss.clone();
2039
2040        // Just reflect the access token expiry.
2041        let exp = expiry.unix_timestamp();
2042
2043        let aud = o2rs.name.clone();
2044
2045        let client_id = o2rs.name.clone();
2046
2047        let entry = match self.qs_write.internal_search_uuid(session_ctx.account_uuid) {
2048            Ok(entry) => entry,
2049            Err(err) => return Err(Oauth2Error::ServerError(err)),
2050        };
2051
2052        let auth_time = session_ctx.auth_time;
2053
2054        let id_token = if scopes.contains(OAUTH2_SCOPE_OPENID) {
2055            // TODO: Scopes map to claims:
2056            //
2057            // * profile - (name, family\_name, given\_name, middle\_name, nickname, preferred\_username, profile, picture, website, gender, birthdate, zoneinfo, locale, and updated\_at)
2058            // * email - (email, email\_verified)
2059            // * address - (address)
2060            // * phone - (phone\_number, phone\_number\_verified)
2061            //
2062            // https://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims
2063
2064            // TODO: Can the user consent to which claims are released? Today as we don't support most
2065            // of them anyway, no, but in the future, we can stash these to the consent req.
2066
2067            // amr == auth method
2068            // We removed this from uat, and I think that it's okay here. AMR is a bit useless anyway
2069            // since there is no standard for what it should look like wrt to cred strength.
2070            let amr = None;
2071
2072            let account = match Account::try_from_entry_rw(&entry, &mut self.qs_write) {
2073                Ok(account) => account,
2074                Err(err) => return Err(Oauth2Error::ServerError(err)),
2075            };
2076
2077            let s_claims = s_claims_for_account(o2rs, &account, &scopes);
2078            let extra_claims = extra_claims_for_account(&account, &o2rs.claim_map, &scopes);
2079
2080            let oidc = OidcToken {
2081                iss: iss.clone(),
2082                sub: OidcSubject::U(session_ctx.account_uuid),
2083                aud: aud.clone(),
2084                iat,
2085                nbf: Some(iat),
2086                exp,
2087                auth_time: auth_time.map(|at| at.unix_timestamp()),
2088                nonce: session_ctx.nonce.clone(),
2089                at_hash: None,
2090                acr: None,
2091                amr,
2092                azp: Some(o2rs.name.clone()),
2093                jti: Some(session_id.to_string()),
2094                s_claims,
2095                claims: extra_claims,
2096            };
2097
2098            trace!(?oidc);
2099            let oidc = JwsBuilder::into_json(&oidc)
2100                .map(|builder| builder.build())
2101                .map_err(|err| {
2102                    admin_error!(?err, "Unable to encode access token data");
2103                    Oauth2Error::ServerError(OperationError::InvalidState)
2104                })?;
2105
2106            let jwt_signed = match o2rs.sign_alg {
2107                SignatureAlgo::Es256 => o2rs.key_object.jws_es256_sign(&oidc, ct),
2108                SignatureAlgo::Rs256 => o2rs.key_object.jws_rs256_sign(&oidc, ct),
2109            }
2110            .map_err(|err| {
2111                error!(?err, "Unable to encode oidc token data");
2112                Oauth2Error::ServerError(OperationError::InvalidState)
2113            })?;
2114
2115            Some(jwt_signed.to_string())
2116        } else {
2117            // id_token is not required in non-openid flows.
2118            None
2119        };
2120
2121        // We need to record this into the record? Delayed action?
2122        let access_token_data = OAuth2RFC9068Token {
2123            iss: iss.to_string(),
2124            sub: session_ctx.account_uuid,
2125            aud,
2126            exp,
2127            nbf: iat,
2128            iat,
2129            jti: session_id,
2130            client_id,
2131            extensions: OAuth2RFC9068TokenExtensions {
2132                auth_time: auth_time.map(|at| at.unix_timestamp()),
2133                acr: None,
2134                amr: None,
2135                scope: scopes.clone(),
2136                nonce: session_ctx.nonce.clone(),
2137                session_id,
2138                parent_session_id,
2139            },
2140        };
2141
2142        let access_token_data = JwsBuilder::into_json(&access_token_data)
2143            .map(|builder| builder.set_typ(Some("at+jwt")).build())
2144            .map_err(|err| {
2145                error!(?err, "Unable to encode access token data");
2146                Oauth2Error::ServerError(OperationError::InvalidState)
2147            })?;
2148
2149        let access_token = match o2rs.sign_alg {
2150            SignatureAlgo::Es256 => o2rs.key_object.jws_es256_sign(&access_token_data, ct),
2151            SignatureAlgo::Rs256 => o2rs.key_object.jws_rs256_sign(&access_token_data, ct),
2152        }
2153        .map_err(|e| {
2154            admin_error!(err = ?e, "Unable to sign access token data");
2155            Oauth2Error::ServerError(OperationError::InvalidState)
2156        })?;
2157
2158        let refresh_token_raw = Oauth2TokenType::Refresh {
2159            scopes,
2160            parent_session_id,
2161            session_id,
2162            exp: refresh_expiry,
2163            uuid: session_ctx.account_uuid,
2164            iat,
2165            nbf: iat,
2166            nonce: session_ctx.nonce,
2167            auth_time,
2168        };
2169
2170        let refresh_token_data = JweBuilder::into_json(&refresh_token_raw)
2171            .map(|builder| builder.build())
2172            .map_err(|err| {
2173                error!(?err, "Unable to encode token data");
2174                Oauth2Error::ServerError(OperationError::SerdeJsonError)
2175            })?;
2176
2177        let domain_level = self.qs_write.get_domain_version();
2178
2179        let refresh_token = if domain_level >= DOMAIN_LEVEL_1_12 {
2180            o2rs.key_object
2181                .jwe_a256gcm_encrypt(&refresh_token_data, ct)
2182                .map(|jwe| jwe.to_string())
2183                .map_err(|err| {
2184                    error!(?err, "Unable to encrypt token data");
2185                    Oauth2Error::ServerError(OperationError::CryptographyError)
2186                })?
2187        } else {
2188            o2rs.key_object
2189                .jwe_a128gcm_encrypt(&refresh_token_data, ct)
2190                .map(|jwe| jwe.to_string())
2191                .map_err(|err| {
2192                    error!(?err, "Unable to encrypt token data");
2193                    Oauth2Error::ServerError(OperationError::CryptographyError)
2194                })?
2195        };
2196
2197        // Write the session to the db even with the refresh path, we need to do
2198        // this to update the "not issued before" time.
2199        let session = Value::Oauth2Session(
2200            session_id,
2201            Oauth2Session {
2202                parent: parent_session_id,
2203                state: SessionState::ExpiresAt(odt_refresh_expiry),
2204                issued_at: odt_ct,
2205                rs_uuid: o2rs.uuid,
2206            },
2207        );
2208
2209        // We need to update (replace) this session id if present.
2210        let modlist = ModifyList::new_list(vec![
2211            // NOTE: Oauth2_session has special handling that allows update in place without
2212            // the remove step needing to be carried out.
2213            // Modify::Removed("oauth2_session".into(), PartialValue::Refer(session_id)),
2214            Modify::Present(Attribute::OAuth2Session, session),
2215        ]);
2216
2217        self.qs_write
2218            .internal_modify(
2219                &filter!(f_eq(
2220                    Attribute::Uuid,
2221                    PartialValue::Uuid(session_ctx.account_uuid)
2222                )),
2223                &modlist,
2224            )
2225            .map_err(|e| {
2226                admin_error!("Failed to persist OAuth2 session record {:?}", e);
2227                Oauth2Error::ServerError(e)
2228            })?;
2229
2230        Ok(AccessTokenResponse {
2231            access_token: access_token.to_string(),
2232            token_type: AccessTokenType::Bearer,
2233            issued_token_type: Some(IssuedTokenType::AccessToken),
2234            expires_in,
2235            refresh_token: Some(refresh_token),
2236            scope,
2237            id_token,
2238        })
2239    }
2240
2241    #[cfg(test)]
2242    fn reflect_oauth2_token(&mut self, token: &str) -> Result<Oauth2TokenType, OperationError> {
2243        let jwec = JweCompact::from_str(token).map_err(|err| {
2244            error!(?err, "Failed to deserialise a valid JWE");
2245            OperationError::InvalidSessionState
2246        })?;
2247
2248        let unverified_kid = jwec.header().kid.as_ref().ok_or_else(|| {
2249            error!("Token does not contain encryption key id");
2250            OperationError::InvalidSessionState
2251        })?;
2252
2253        let o2rs = self
2254            .oauth2rs
2255            .inner
2256            .rs_from_kid(unverified_kid)
2257            .ok_or_else(|| {
2258                debug!("Invalid OAuth2 key id");
2259                OperationError::InvalidSessionState
2260            })?;
2261
2262        o2rs.key_object
2263            .jwe_decrypt(&jwec)
2264            .map_err(|_| {
2265                admin_error!("Failed to decrypt token introspection request");
2266                OperationError::CryptographyError
2267            })
2268            .and_then(|jwe| {
2269                jwe.from_json().map_err(|err| {
2270                    error!(?err, "Failed to deserialise token");
2271                    OperationError::InvalidSessionState
2272                })
2273            })
2274    }
2275}
2276
2277impl IdmServerProxyReadTransaction<'_> {
2278    #[instrument(level = "debug", skip_all)]
2279    pub fn check_oauth2_authorisation(
2280        &self,
2281        maybe_ident: Option<&Identity>,
2282        auth_req: &AuthorisationRequest,
2283        auth_req_ctx: &AuthorisationRequestContext,
2284        ct: Duration,
2285    ) -> Result<AuthoriseResponse, Oauth2Error> {
2286        // due to identity processing we already know that:
2287        // * the session must be authenticated, and valid
2288        // * is within it's valid time window.
2289        trace!(?auth_req, ?auth_req_ctx);
2290
2291        if auth_req.response_type != ResponseType::Code {
2292            admin_warn!("Unsupported OAuth2 response_type (should be 'code')");
2293            return Err(Oauth2Error::UnsupportedResponseType);
2294        }
2295
2296        let Some(response_mode) = auth_req.get_response_mode() else {
2297            warn!(
2298                "Invalid response_mode {:?} for response_type {:?}",
2299                auth_req.response_mode, auth_req.response_type
2300            );
2301            return Err(Oauth2Error::InvalidRequest);
2302        };
2303
2304        let response_mode = match response_mode {
2305            ResponseMode::Query => SupportedResponseMode::Query,
2306            ResponseMode::Fragment => SupportedResponseMode::Fragment,
2307            ResponseMode::FormPost => {
2308                warn!(
2309                    "Invalid response mode form_post requested - many clients request this incorrectly but proceed with response_mode=query. Remapping to query."
2310                );
2311                warn!("This behaviour WILL BE REMOVED in a future release.");
2312                SupportedResponseMode::Query
2313            }
2314            ResponseMode::Invalid => {
2315                warn!("Invalid response mode requested, unable to proceed");
2316                return Err(Oauth2Error::InvalidRequest);
2317            }
2318        };
2319
2320        if auth_req.prompt.len() > 4 {
2321            warn!(
2322                "Request contained too many prompt values. Max: 4, Provided: {}",
2323                auth_req.prompt.len()
2324            );
2325            return Err(Oauth2Error::InvalidRequest);
2326        }
2327
2328        let invalid_prompts: Vec<&str> = auth_req
2329            .prompt
2330            .iter()
2331            .filter_map(|v| match v {
2332                Prompt::Invalid(s) => Some(s.as_str()),
2333                _ => None,
2334            })
2335            .collect();
2336
2337        if !invalid_prompts.is_empty() {
2338            warn!("Invalid prompt value(s): {:?}", invalid_prompts);
2339            return Err(Oauth2Error::InvalidRequest);
2340        }
2341
2342        if auth_req.prompt.contains(&Prompt::None) && auth_req.prompt.len() > 1 {
2343            warn!("Prompt cannot be none and contain other values at the same time");
2344            return Err(Oauth2Error::InvalidRequest);
2345        }
2346
2347        /*
2348         * 4.1.2.1.  Error Response
2349         *
2350         * If the request fails due to a missing, invalid, or mismatching
2351         * redirection URI, or if the client identifier is missing or invalid,
2352         * the authorization server SHOULD inform the resource owner of the
2353         * error and MUST NOT automatically redirect the user-agent to the
2354         * invalid redirection URI.
2355         */
2356
2357        //
2358        let o2rs = self
2359            .oauth2rs
2360            .inner
2361            .rs_set_get(&auth_req.client_id)
2362            .ok_or_else(|| {
2363                warn!(
2364                    "Invalid OAuth2 client_id ({}) Have you configured the OAuth2 resource server?",
2365                    &auth_req.client_id
2366                );
2367                Oauth2Error::InvalidClientId
2368            })?;
2369
2370        // redirect_uri must be part of the client_id origins, unless the client is public and then it MAY
2371        // be a loopback address exempting it from this check and enforcement and we can carry on safely.
2372
2373        // == start validate oauth2 redirect conditions.
2374
2375        let auth_req_uri_is_loopback = check_is_loopback(&auth_req.redirect_uri);
2376        let type_allows_localhost_redirect = o2rs.type_.allow_localhost_redirect();
2377
2378        // This allows loopback uri's that are *not* part of the origin/redirect_uri configurations.
2379        let loopback_uri_matched = auth_req_uri_is_loopback && type_allows_localhost_redirect;
2380
2381        // Strict uri validation is in use, must be an exact match.
2382        let strict_redirect_uri_matched = o2rs.redirect_uris.contains(&auth_req.redirect_uri);
2383
2384        // Allow opaque origins such as app uris.
2385        let opaque_origin_matched = o2rs.opaque_origins.contains(&auth_req.redirect_uri);
2386
2387        // Was the redirect origin secure?
2388        let redirect_origin_is_secure = opaque_origin_matched
2389            || auth_req_uri_is_loopback
2390            || auth_req.redirect_uri.scheme() == "https";
2391
2392        // We must assert that *AT LEAST* one of the above match conditions holds true to proceed.
2393        let valid_match_condition_asserted =
2394            loopback_uri_matched || strict_redirect_uri_matched || opaque_origin_matched;
2395
2396        if valid_match_condition_asserted {
2397            debug!(
2398                ?loopback_uri_matched,
2399                ?strict_redirect_uri_matched,
2400                ?opaque_origin_matched,
2401                "valid redirect uri match condition met."
2402            );
2403        } else {
2404            // Display why it failed.
2405
2406            // This is to catch the specific case that a public client gets a localhost redirect, but
2407            // the admin hasn't enabled the flag for it. This way we direct them to the correct cause
2408            // of the issue, rather than telling them to configure localhost as a redirect location.
2409            let could_allow_localhost_redirect =
2410                o2rs.type_.allow_localhost_redirect_could_be_possible();
2411
2412            if auth_req_uri_is_loopback
2413                && could_allow_localhost_redirect
2414                && !type_allows_localhost_redirect
2415            {
2416                warn!(redirect_uri = %auth_req.redirect_uri, "OAuth2 redirect_uri returns to localhost, but localhost redirection is not allowed. See 'kanidm system oauth2 enable-localhost-redirects'");
2417            } else {
2418                // Not localhost - must be missing the redirect uri then, which is why strict/origin/opaque all failed to assert
2419                warn!(
2420                    "Invalid OAuth2 redirect_uri (must be an exact match to a redirect-url) - got {} from client but configured uris do not match (check oauth2_rs_origin entries)",
2421                    auth_req.redirect_uri.as_str()
2422                );
2423            }
2424
2425            // All roads lead to error.
2426            return Err(Oauth2Error::InvalidOrigin);
2427        }
2428
2429        // Assert that if secure origins were required, that we are enforcing that.
2430        if o2rs.origin_secure_required && !redirect_origin_is_secure {
2431            warn!(
2432                "Invalid OAuth2 redirect_uri scheme (must be a secure origin) - got {} instead. Secure origins are required when *at least* one redirect_uri is https, then all uri's must also be secure origins.",
2433                auth_req.redirect_uri
2434            );
2435            return Err(Oauth2Error::InvalidOrigin);
2436        }
2437
2438        // == end validation of oauth2 redirect conditions.
2439
2440        let code_challenge = if let Some(pkce_request) = &auth_req.pkce_request {
2441            if !o2rs.require_pkce() {
2442                security_info!(?o2rs.name, "Insecure OAuth2 client configuration - PKCE is not enforced, but client is requesting it!");
2443            }
2444            // CodeChallengeMethod must be S256
2445            if pkce_request.code_challenge_method != CodeChallengeMethod::S256 {
2446                admin_warn!("Invalid OAuth2 code_challenge_method (must be 'S256')");
2447                return Err(Oauth2Error::InvalidRequest);
2448            }
2449            Some(pkce_request.code_challenge.clone())
2450        } else if o2rs.require_pkce() {
2451            security_error!(?o2rs.name, "No PKCE code challenge was provided with client in enforced PKCE mode");
2452            return Err(Oauth2Error::InvalidRequest);
2453        } else {
2454            security_info!(?o2rs.name, "Insecure client configuration - PKCE is not enforced");
2455            None
2456        };
2457
2458        // =============================================================================
2459        // By this point, we have validated the majority of the security related
2460        // parameters of the request. We can now inspect the identity and decide
2461        // if we should ask the user to re-authenticate and proceed.
2462
2463        // TODO: https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters
2464        // Are we going to provide the functions for these? Most of these can be "later".
2465        // IF CHANGED: Update OidcDiscoveryResponse!!!
2466
2467        // TODO: https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters
2468        // prompt - if set to login, we need to force a re-auth. But we don't want to
2469        // if the user "only just" logged in, that's annoying. So we need a time window for
2470        // this, to detect when we should force it to the consent req.
2471
2472        // TODO: display = popup vs touch vs wap etc.
2473
2474        // TODO: ui_locales / claims_locales for the ui. Only if we don't have a Uat that
2475        // would provide this.
2476
2477        // TODO: id_token_hint - a past token which can be used as a hint.
2478
2479        let Some(ident) = maybe_ident else {
2480            // OIDC Core 1.0 §3.1.2.1
2481            // prompt=none - The Authorization Server MUST NOT display any authentication or consent user interface pages
2482            if auth_req.prompt.contains(&Prompt::None) {
2483                warn!("prompt=none was requested by the client, but no authenticated identity is available, returning authorise reject.");
2484
2485                return Ok(AuthoriseResponse::Reject(AuthoriseReject {
2486                    redirect_uri: auth_req.redirect_uri.clone(),
2487                    error: Oauth2Error::LoginRequired,
2488                    state: auth_req.state.clone(),
2489                    response_mode,
2490                }));
2491            } else {
2492                debug!("No identity available, assume authentication required");
2493
2494                return Ok(AuthoriseResponse::AuthenticationRequired {
2495                    client_name: o2rs.displayname.clone(),
2496                    login_hint: auth_req.oidc_ext.login_hint.clone(),
2497                });
2498            }
2499        };
2500
2501        // OIDC Core 1.0 §3.1.2.1
2502        // prompt=login - The Authorization Server MUST prompt the End-User to re-authenticate.
2503        // This is equivalent to max_age=0;
2504        let max_age = if auth_req.prompt.contains(&Prompt::Login) {
2505            Some(0)
2506        } else {
2507            auth_req
2508                .max_age
2509                .map(|m| m.clamp(0, OAUTH2_OIDC_MAX_AGE_CLAMP))
2510        };
2511
2512        let auth_time = ident.last_verified_at();
2513
2514        if let Some(max_age) = max_age {
2515            let session_recently_validated = if max_age <= 0 {
2516                // Reauth will be forced.
2517                false
2518            } else {
2519                let odt_prompt_deadline =
2520                    (OffsetDateTime::UNIX_EPOCH + ct) - Duration::from_secs(max_age as u64);
2521
2522                // Was the session recently validated?
2523                auth_time
2524                    .map(|at| {
2525                        // We need to limit this to whole seconds.
2526                        let at = at.truncate_to_second();
2527                        let odt_prompt_deadline = odt_prompt_deadline.truncate_to_second();
2528                        at > odt_prompt_deadline
2529                    })
2530                    .unwrap_or_default()
2531            };
2532
2533            if auth_req_ctx.resumed {
2534                // We must have just arrived here after an authentication or reauthentication - as
2535                // a result the session is fresh, and we can continue.
2536                debug!("auth_request_context indicates that the session was just authenticated - proceeding.");
2537            } else if session_recently_validated {
2538                debug!("prompt=login was requested, session is fresh enough to proceed");
2539            } else {
2540                debug!("prompt=login was requested, forcing re-authentication");
2541                return Ok(AuthoriseResponse::ReauthenticationRequired {
2542                    client_name: o2rs.displayname.clone(),
2543                });
2544            }
2545        }
2546
2547        let account_uuid = ident.get_uuid();
2548
2549        // Deny anonymous access to oauth2
2550        if account_uuid == UUID_ANONYMOUS {
2551            admin_error!(
2552                "Invalid OAuth2 request - refusing to allow user that authenticated with anonymous"
2553            );
2554            return Err(Oauth2Error::AccessDenied);
2555        }
2556
2557        // scopes - you need to have every requested scope or this auth_req is denied.
2558        let (req_scopes, granted_scopes) =
2559            process_requested_scopes_for_identity(o2rs, ident, Some(&auth_req.scope))?;
2560
2561        // MICRO OPTIMISATION = flag if we have openid first, so we can into_iter here rather than
2562        // cloning.
2563        let openid_requested = req_scopes.contains(OAUTH2_SCOPE_OPENID);
2564
2565        let consent_previously_granted =
2566            if let Some(consent_scopes) = ident.get_oauth2_consent_scopes(o2rs.uuid) {
2567                trace!(?granted_scopes);
2568                trace!(?consent_scopes);
2569                granted_scopes.eq(consent_scopes)
2570            } else {
2571                false
2572            };
2573
2574        let session_id = ident.get_session_id();
2575
2576        let consent_required = (
2577                // consent was NOT previously granted, we SHOULD request it.
2578                !consent_previously_granted
2579                // OR
2580                ||
2581                // client is NOT basic AND is localhost
2582                // - This prevents a malicious localhost client hijacking an existing localhost
2583                // - consent that was granted.
2584                (!o2rs.is_basic() && loopback_uri_matched)
2585                // Future - if we add DCR then we will always force TRUE here.
2586            )
2587            // AND
2588            &&
2589            // consent prompt is enabled. This can only be false on confidential clients.
2590            o2rs.enable_consent_prompt();
2591
2592        if !consent_required {
2593            if event_enabled!(tracing::Level::DEBUG) {
2594                let pretty_scopes: Vec<String> =
2595                    granted_scopes.iter().map(|s| s.to_owned()).collect();
2596                debug!(
2597                    pretty_scopes = pretty_scopes.join(","),
2598                    prompt_enabled = o2rs.enable_consent_prompt(),
2599                    previously_granted = consent_previously_granted,
2600                    "Consent flow passed"
2601                );
2602            }
2603
2604            // Xchg token expires in
2605            let expiry = ct.as_secs() + 60;
2606
2607            // Setup for the permit success
2608            let xchg_code = TokenExchangeCode {
2609                account_uuid,
2610                session_id,
2611                expiry,
2612                code_challenge,
2613                redirect_uri: auth_req.redirect_uri.clone(),
2614                scopes: granted_scopes.into_iter().collect(),
2615                nonce: auth_req.nonce.clone(),
2616                auth_time,
2617            };
2618
2619            // Encrypt the exchange token with the key of the client
2620            let code_data_jwe = JweBuilder::into_json(&xchg_code)
2621                .map(|builder| builder.build())
2622                .map_err(|err| {
2623                    error!(?err, "Unable to encode xchg_code data");
2624                    Oauth2Error::ServerError(OperationError::SerdeJsonError)
2625                })?;
2626
2627            let domain_level = self.qs_read.get_domain_version();
2628
2629            let code = if domain_level >= DOMAIN_LEVEL_1_12 {
2630                o2rs.key_object
2631                    .jwe_a256gcm_encrypt(&code_data_jwe, ct)
2632                    .map(|jwe| jwe.to_string())
2633                    .map_err(|err| {
2634                        error!(?err, "Unable to encrypt xchg_code data");
2635                        Oauth2Error::ServerError(OperationError::CryptographyError)
2636                    })?
2637            } else {
2638                o2rs.key_object
2639                    .jwe_a128gcm_encrypt(&code_data_jwe, ct)
2640                    .map(|jwe| jwe.to_string())
2641                    .map_err(|err| {
2642                        error!(?err, "Unable to encrypt xchg_code data");
2643                        Oauth2Error::ServerError(OperationError::CryptographyError)
2644                    })?
2645            };
2646
2647            Ok(AuthoriseResponse::Permitted(AuthorisePermitSuccess {
2648                redirect_uri: auth_req.redirect_uri.clone(),
2649                state: auth_req.state.clone(),
2650                code,
2651                response_mode,
2652            }))
2653        } else {
2654            // OIDC Core 1.0 §3.1.2.1:
2655            // prompt=none - The Authorization Server MUST NOT display any authentication or
2656            // consent user interface pages.
2657            if auth_req.prompt.contains(&Prompt::None) {
2658                debug!("prompt=none was requested, but consent is required, returning error");
2659                return Ok(AuthoriseResponse::Reject(AuthoriseReject {
2660                    redirect_uri: auth_req.redirect_uri.clone(),
2661                    error: Oauth2Error::InteractionRequired,
2662                    state: auth_req.state.clone(),
2663                    response_mode,
2664                }));
2665            }
2666
2667            //  Check that the scopes are the same as a previous consent (if any)
2668            // If oidc, what PII is visible?
2669            // TODO: Scopes map to claims:
2670            //
2671            // * profile - (name, family\_name, given\_name, middle\_name, nickname, preferred\_username, profile, picture, website, gender, birthdate, zoneinfo, locale, and updated\_at)
2672            // * email - (email, email\_verified)
2673            // * address - (address)
2674            // * phone - (phone\_number, phone\_number\_verified)
2675            //
2676            // https://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims
2677
2678            // IMPORTANT DISTINCTION - Here req scopes must contain openid, but the PII can be supplemented
2679            // be the servers scopes!
2680            let mut pii_scopes = BTreeSet::default();
2681            if openid_requested {
2682                // Only mutate if things were requested under openid
2683                if granted_scopes.contains(OAUTH2_SCOPE_EMAIL) {
2684                    pii_scopes.insert(OAUTH2_SCOPE_EMAIL.to_string());
2685                    pii_scopes.insert("email_verified".to_string());
2686                }
2687            };
2688
2689            if granted_scopes.contains(OAUTH2_SCOPE_SSH_PUBLICKEYS) {
2690                pii_scopes.insert(OAUTH2_SCOPE_SSH_PUBLICKEYS.to_string());
2691            }
2692
2693            // Consent token expires in
2694            let expiry = ct.as_secs() + 300;
2695
2696            // Subsequent we then return an encrypted session handle which allows
2697            // the user to indicate their consent to this authorisation.
2698            //
2699            // This session handle is what we use in "permit" to generate the redirect.
2700
2701            let consent_req = ConsentToken {
2702                client_id: auth_req.client_id.clone(),
2703                ident_id: ident.get_event_origin_id(),
2704                expiry,
2705                session_id,
2706                state: auth_req.state.clone(),
2707                code_challenge,
2708                redirect_uri: auth_req.redirect_uri.clone(),
2709                scopes: granted_scopes.iter().cloned().collect(),
2710                nonce: auth_req.nonce.clone(),
2711                response_mode,
2712            };
2713
2714            let consent_jwe = JweBuilder::into_json(&consent_req)
2715                .map(|builder| builder.build())
2716                .map_err(|err| {
2717                    error!(?err, "Unable to encode consent data");
2718                    Oauth2Error::ServerError(OperationError::SerdeJsonError)
2719                })?;
2720
2721            let consent_token = self
2722                .oauth2rs
2723                .inner
2724                .consent_key
2725                .encipher::<JweA256GCMEncipher>(&consent_jwe)
2726                .map(|jwe_compact| jwe_compact.to_string())
2727                .map_err(|err| {
2728                    error!(?err, "Unable to encrypt jwe");
2729                    Oauth2Error::ServerError(OperationError::CryptographyError)
2730                })?;
2731
2732            Ok(AuthoriseResponse::ConsentRequested {
2733                client_name: o2rs.displayname.clone(),
2734                scopes: granted_scopes.into_iter().collect(),
2735                pii_scopes,
2736                consent_token,
2737            })
2738        }
2739    }
2740
2741    #[instrument(level = "debug", skip_all)]
2742    pub fn check_oauth2_authorise_reject(
2743        &self,
2744        ident: &Identity,
2745        consent_token: &str,
2746        ct: Duration,
2747    ) -> Result<AuthoriseReject, OperationError> {
2748        let jwe_compact = JweCompact::from_str(consent_token).map_err(|_| {
2749            error!("Failed to deserialise a valid JWE");
2750            OperationError::CryptographyError
2751        })?;
2752
2753        // Decode the consent req with our system fernet key. Use a ttl of 5 minutes.
2754        let consent_req: ConsentToken = self
2755            .oauth2rs
2756            .inner
2757            .consent_key
2758            .decipher(&jwe_compact)
2759            .map_err(|_| {
2760                admin_error!("Failed to decrypt consent request");
2761                OperationError::CryptographyError
2762            })
2763            .and_then(|jwe| {
2764                jwe.from_json().map_err(|err| {
2765                    error!(?err, "Failed to deserialise consent request");
2766                    OperationError::SerdeJsonError
2767                })
2768            })?;
2769
2770        // Validate that the ident_id matches our current ident.
2771        if consent_req.ident_id != ident.get_event_origin_id() {
2772            security_info!("consent request ident id does not match the identity of our UAT.");
2773            return Err(OperationError::InvalidSessionState);
2774        }
2775
2776        // Validate that the session id matches our session
2777        if consent_req.session_id != ident.get_session_id() {
2778            security_info!("consent request sessien id does not match the session id of our UAT.");
2779            return Err(OperationError::InvalidSessionState);
2780        }
2781
2782        if consent_req.expiry <= ct.as_secs() {
2783            // Token is expired
2784            error!("Failed to decrypt consent request");
2785            return Err(OperationError::CryptographyError);
2786        }
2787
2788        // Get the resource server config based on this client_id.
2789        let _o2rs = self
2790            .oauth2rs
2791            .inner
2792            .rs_set_get(&consent_req.client_id)
2793            .ok_or_else(|| {
2794                admin_error!("Invalid consent request OAuth2 client_id");
2795                OperationError::InvalidRequestState
2796            })?;
2797
2798        // All good, now confirm the rejection to the client application.
2799        Ok(AuthoriseReject {
2800            redirect_uri: consent_req.redirect_uri,
2801            error: Oauth2Error::AccessDenied,
2802            state: consent_req.state,
2803            response_mode: consent_req.response_mode,
2804        })
2805    }
2806
2807    #[instrument(level = "debug", skip_all)]
2808    pub fn check_oauth2_token_introspect(
2809        &mut self,
2810        intr_req: &AccessTokenIntrospectRequest,
2811        ct: Duration,
2812    ) -> Result<AccessTokenIntrospectResponse, Oauth2Error> {
2813        // We don't need to authenticate, since possession of the access token is already enough
2814        // to prove identity, and we enforce it is cryptographically valid so it can't be bruteforced
2815        // by a scanning attack.
2816
2817        if let Ok(jwsc) = JwsCompact::from_str(&intr_req.token) {
2818            self.oauth2_token_introspect_jwt(&jwsc, ct)
2819        } else if let Ok(jwec) = JweCompact::from_str(&intr_req.token) {
2820            self.oauth2_token_introspect_jwe(&jwec, ct)
2821        } else {
2822            error!("Failed to deserialise a valid JWE");
2823            Err(Oauth2Error::AuthenticationRequired)
2824        }
2825    }
2826
2827    #[instrument(level = "trace", skip_all)]
2828    pub fn oauth2_token_introspect_jwt(
2829        &mut self,
2830        jwsc: &JwsCompact,
2831        ct: Duration,
2832    ) -> Result<AccessTokenIntrospectResponse, Oauth2Error> {
2833        let unverified_kid = jwsc.header().kid.as_ref().ok_or_else(|| {
2834            error!("Token does not contain signature key id");
2835            Oauth2Error::AuthenticationRequired
2836        })?;
2837
2838        let o2rs = self
2839            .oauth2rs
2840            .inner
2841            .rs_from_kid(unverified_kid)
2842            .ok_or_else(|| {
2843                warn!("Invalid OAuth2 key id");
2844                Oauth2Error::AuthenticationRequired
2845            })?;
2846
2847        let access_token = o2rs
2848            .key_object
2849            .jws_verify(jwsc)
2850            .map_err(|err| {
2851                error!(?err, "Unable to verify access token");
2852                Oauth2Error::AuthenticationRequired
2853            })
2854            .and_then(|jws| {
2855                jws.from_json().map_err(|err| {
2856                    error!(?err, "Unable to deserialise access token");
2857                    Oauth2Error::InvalidRequest
2858                })
2859            })?;
2860
2861        let OAuth2RFC9068Token::<_> {
2862            iss: _,
2863            sub,
2864            aud: _,
2865            exp,
2866            nbf,
2867            iat,
2868            jti,
2869            client_id: _,
2870            extensions:
2871                OAuth2RFC9068TokenExtensions {
2872                    auth_time: _,
2873                    acr: _,
2874                    amr: _,
2875                    scope: scopes,
2876                    nonce: _,
2877                    session_id,
2878                    parent_session_id,
2879                },
2880        } = access_token;
2881
2882        // Has this token expired?
2883        if exp <= ct.as_secs() as i64 {
2884            security_info!(?sub, "access token has expired, returning inactive");
2885            return Ok(AccessTokenIntrospectResponse::inactive(jti));
2886        }
2887
2888        let prefer_short_username = o2rs.prefer_short_username;
2889        let client_id = o2rs.name.clone();
2890        let iss = o2rs.iss.to_string();
2891
2892        // Is the user expired, or the OAuth2 session invalid?
2893        let valid = self
2894            .check_oauth2_account_uuid_valid(sub, session_id, parent_session_id, iat, ct)
2895            .map_err(|_| admin_error!("Account is not valid"));
2896
2897        let Ok(Some(entry)) = valid else {
2898            security_info!(
2899                ?sub,
2900                "access token account is not valid, returning inactive"
2901            );
2902            return Ok(AccessTokenIntrospectResponse::inactive(jti));
2903        };
2904
2905        let account = match Account::try_from_entry_ro(&entry, &mut self.qs_read) {
2906            Ok(account) => account,
2907            Err(err) => return Err(Oauth2Error::ServerError(err)),
2908        };
2909
2910        // ==== good to generate response ====
2911
2912        let scope = scopes.clone();
2913
2914        let preferred_username = if prefer_short_username {
2915            Some(account.name().into())
2916        } else {
2917            Some(account.spn().into())
2918        };
2919
2920        let token_type = Some(AccessTokenType::Bearer);
2921        Ok(AccessTokenIntrospectResponse {
2922            active: true,
2923            scope,
2924            client_id: Some(client_id.clone()),
2925            username: preferred_username,
2926            token_type,
2927            iat: Some(iat),
2928            exp: Some(exp),
2929            nbf: Some(nbf),
2930            sub: Some(sub.to_string()),
2931            aud: Some(client_id),
2932            iss: Some(iss),
2933            jti,
2934        })
2935    }
2936
2937    #[instrument(level = "trace", skip_all)]
2938    pub fn oauth2_token_introspect_jwe(
2939        &mut self,
2940        jwec: &JweCompact,
2941        ct: Duration,
2942    ) -> Result<AccessTokenIntrospectResponse, Oauth2Error> {
2943        let unverified_kid = jwec.header().kid.as_ref().ok_or_else(|| {
2944            error!("Token does not contain signature key id");
2945            Oauth2Error::AuthenticationRequired
2946        })?;
2947
2948        let o2rs = self
2949            .oauth2rs
2950            .inner
2951            .rs_from_kid(unverified_kid)
2952            .ok_or_else(|| {
2953                warn!("Invalid OAuth2 key id");
2954                Oauth2Error::AuthenticationRequired
2955            })?;
2956
2957        let token: Oauth2TokenType = o2rs
2958            .key_object
2959            .jwe_decrypt(jwec)
2960            .map_err(|_| {
2961                admin_error!("Failed to decrypt token introspection request");
2962                Oauth2Error::AuthenticationRequired
2963            })
2964            .and_then(|jwe| {
2965                jwe.from_json().map_err(|err| {
2966                    error!(?err, "Failed to deserialise token");
2967                    Oauth2Error::InvalidRequest
2968                })
2969            })?;
2970
2971        match token {
2972            Oauth2TokenType::ClientAccess {
2973                scopes,
2974                session_id,
2975                uuid,
2976                exp,
2977                iat,
2978                nbf,
2979            } => {
2980                // Has this token expired?
2981                if exp <= ct.as_secs() as i64 {
2982                    security_info!(?uuid, "access token has expired, returning inactive");
2983                    return Ok(AccessTokenIntrospectResponse::inactive(session_id));
2984                }
2985
2986                let prefer_short_username = o2rs.prefer_short_username;
2987                let client_id = o2rs.name.clone();
2988                let iss = o2rs.iss.to_string();
2989
2990                // We can't do the same validity check for the client as we do with an account
2991                let valid = self
2992                    .check_oauth2_account_uuid_valid(uuid, session_id, None, iat, ct)
2993                    .map_err(|_| admin_error!("Account is not valid"));
2994
2995                let Ok(Some(entry)) = valid else {
2996                    security_info!(
2997                        ?uuid,
2998                        "access token account is not valid, returning inactive"
2999                    );
3000                    return Ok(AccessTokenIntrospectResponse::inactive(session_id));
3001                };
3002
3003                let scope = scopes.clone();
3004
3005                let token_type = Some(AccessTokenType::Bearer);
3006
3007                let username = if prefer_short_username {
3008                    entry
3009                        .get_ava_single_iname(Attribute::Name)
3010                        .map(|s| s.to_string())
3011                } else {
3012                    entry.get_ava_single_proto_string(Attribute::Spn)
3013                };
3014
3015                Ok(AccessTokenIntrospectResponse {
3016                    active: true,
3017                    scope,
3018                    client_id: Some(client_id.clone()),
3019                    username,
3020                    token_type,
3021                    iat: Some(iat),
3022                    exp: Some(exp),
3023                    nbf: Some(nbf),
3024                    sub: Some(uuid.to_string()),
3025                    aud: Some(client_id),
3026                    iss: Some(iss),
3027                    jti: session_id,
3028                })
3029            }
3030            Oauth2TokenType::Refresh { session_id, .. } => {
3031                Ok(AccessTokenIntrospectResponse::inactive(session_id))
3032            }
3033        }
3034    }
3035
3036    #[instrument(level = "debug", skip_all)]
3037    pub fn oauth2_openid_userinfo(
3038        &mut self,
3039        client_id: &str,
3040        token: &JwsCompact,
3041        ct: Duration,
3042    ) -> Result<OidcToken, Oauth2Error> {
3043        // DANGER: Why do we have to do this? During the use of qs for internal search
3044        // and other operations we need qs to be mut. But when we borrow oauth2rs here we
3045        // cause multiple borrows to occur on struct members that freaks rust out. This *IS*
3046        // safe however because no element of the search or write process calls the oauth2rs
3047        // excepting for this idm layer within a single thread, meaning that stripping the
3048        // lifetime here is safe since we are the sole accessor.
3049        let o2rs: &Oauth2RS = unsafe {
3050            let s = self.oauth2rs.inner.rs_set_get(client_id).ok_or_else(|| {
3051                warn!("Invalid OAuth2 client_id (have you configured the OAuth2 resource server?)");
3052                Oauth2Error::InvalidClientId
3053            })?;
3054            &*(s as *const _)
3055        };
3056
3057        let access_token = o2rs
3058            .key_object
3059            .jws_verify(token)
3060            .map_err(|err| {
3061                error!(?err, "Unable to verify access token");
3062                Oauth2Error::InvalidRequest
3063            })
3064            .and_then(|jws| {
3065                jws.from_json().map_err(|err| {
3066                    error!(?err, "Unable to deserialise access token");
3067                    Oauth2Error::InvalidRequest
3068                })
3069            })?;
3070
3071        let OAuth2RFC9068Token::<_> {
3072            iss: _,
3073            sub,
3074            aud: _,
3075            exp,
3076            nbf,
3077            iat,
3078            jti: _,
3079            client_id: _,
3080            extensions:
3081                OAuth2RFC9068TokenExtensions {
3082                    auth_time,
3083                    acr: _,
3084                    amr: _,
3085                    scope: scopes,
3086                    nonce,
3087                    session_id,
3088                    parent_session_id,
3089                },
3090        } = access_token;
3091        // Has this token expired?
3092        if exp <= ct.as_secs() as i64 {
3093            security_info!(?sub, "access token has expired, returning inactive");
3094            return Err(Oauth2Error::InvalidToken);
3095        }
3096
3097        // Is the user expired, or the OAuth2 session invalid?
3098        let valid = self
3099            .check_oauth2_account_uuid_valid(sub, session_id, parent_session_id, iat, ct)
3100            .map_err(|_| admin_error!("Account is not valid"));
3101
3102        let Ok(Some(entry)) = valid else {
3103            security_info!(
3104                ?sub,
3105                "access token has account not valid, returning inactive"
3106            );
3107            return Err(Oauth2Error::InvalidToken);
3108        };
3109
3110        let account = match Account::try_from_entry_ro(&entry, &mut self.qs_read) {
3111            Ok(account) => account,
3112            Err(err) => return Err(Oauth2Error::ServerError(err)),
3113        };
3114
3115        let amr = None;
3116
3117        let iss = o2rs.iss.clone();
3118
3119        let s_claims = s_claims_for_account(o2rs, &account, &scopes);
3120        let extra_claims = extra_claims_for_account(&account, &o2rs.claim_map, &scopes);
3121
3122        // ==== good to generate response ====
3123
3124        Ok(OidcToken {
3125            iss,
3126            sub: OidcSubject::U(sub),
3127            aud: client_id.to_string(),
3128            iat,
3129            nbf: Some(nbf),
3130            exp,
3131            auth_time,
3132            nonce,
3133            at_hash: None,
3134            acr: None,
3135            amr,
3136            azp: Some(client_id.to_string()),
3137            jti: Some(session_id.to_string()),
3138            s_claims,
3139            claims: extra_claims,
3140        })
3141    }
3142
3143    #[instrument(level = "debug", skip_all)]
3144    pub fn oauth2_rfc8414_metadata(
3145        &self,
3146        client_id: &str,
3147    ) -> Result<Oauth2Rfc8414MetadataResponse, OperationError> {
3148        let o2rs = self.oauth2rs.inner.rs_set_get(client_id).ok_or_else(|| {
3149            warn!("Invalid OAuth2 client_id (have you configured the OAuth2 resource server?)");
3150            OperationError::NoMatchingEntries
3151        })?;
3152
3153        let issuer = o2rs.iss.clone();
3154        let authorization_endpoint = o2rs.authorization_endpoint.clone();
3155        let token_endpoint = o2rs.token_endpoint.clone();
3156        let revocation_endpoint = Some(o2rs.revocation_endpoint.clone());
3157        let introspection_endpoint = Some(o2rs.introspection_endpoint.clone());
3158        let jwks_uri = Some(o2rs.jwks_uri.clone());
3159        let scopes_supported = Some(o2rs.scopes_supported.iter().cloned().collect());
3160        let response_types_supported = vec![ResponseType::Code];
3161        let response_modes_supported = vec![ResponseMode::Query, ResponseMode::Fragment];
3162        let grant_types_supported = vec![
3163            GrantType::AuthorisationCode,
3164            GrantType::TokenExchange,
3165            GrantType::RefreshToken,
3166        ];
3167
3168        let token_endpoint_auth_methods_supported = if o2rs.is_basic() {
3169            vec![
3170                EndpointAuthMethod::ClientSecretBasic,
3171                EndpointAuthMethod::ClientSecretPost,
3172            ]
3173        } else {
3174            vec![EndpointAuthMethod::None]
3175        };
3176
3177        let revocation_endpoint_auth_methods_supported = vec![EndpointAuthMethod::None];
3178
3179        let introspection_endpoint_auth_methods_supported = vec![EndpointAuthMethod::None];
3180
3181        let service_documentation = Some(URL_SERVICE_DOCUMENTATION.clone());
3182
3183        let code_challenge_methods_supported = if o2rs.require_pkce() {
3184            vec![PkceAlg::S256]
3185        } else {
3186            Vec::with_capacity(0)
3187        };
3188
3189        Ok(Oauth2Rfc8414MetadataResponse {
3190            issuer,
3191            authorization_endpoint,
3192            token_endpoint,
3193            jwks_uri,
3194            registration_endpoint: None,
3195            scopes_supported,
3196            response_types_supported,
3197            response_modes_supported,
3198            grant_types_supported,
3199            token_endpoint_auth_methods_supported,
3200            token_endpoint_auth_signing_alg_values_supported: None,
3201            service_documentation,
3202            ui_locales_supported: None,
3203            op_policy_uri: None,
3204            op_tos_uri: None,
3205            revocation_endpoint,
3206            revocation_endpoint_auth_methods_supported,
3207            introspection_endpoint,
3208            introspection_endpoint_auth_methods_supported,
3209            introspection_endpoint_auth_signing_alg_values_supported: None,
3210            code_challenge_methods_supported,
3211        })
3212    }
3213
3214    #[instrument(level = "debug", skip_all)]
3215    pub fn oauth2_openid_discovery(
3216        &self,
3217        client_id: &str,
3218    ) -> Result<OidcDiscoveryResponse, OperationError> {
3219        let o2rs = self.oauth2rs.inner.rs_set_get(client_id).ok_or_else(|| {
3220            warn!("Invalid OAuth2 client_id (have you configured the OAuth2 resource server?)");
3221            OperationError::NoMatchingEntries
3222        })?;
3223
3224        let issuer = o2rs.iss.clone();
3225
3226        let authorization_endpoint = o2rs.authorization_endpoint.clone();
3227        let token_endpoint = o2rs.token_endpoint.clone();
3228        let userinfo_endpoint = Some(o2rs.userinfo_endpoint.clone());
3229        let jwks_uri = o2rs.jwks_uri.clone();
3230        let scopes_supported = Some(o2rs.scopes_supported.iter().cloned().collect());
3231        let response_types_supported = vec![ResponseType::Code];
3232        let response_modes_supported = vec![ResponseMode::Query, ResponseMode::Fragment];
3233
3234        // TODO: add device code if the rs supports it per <https://www.rfc-editor.org/rfc/rfc8628#section-4>
3235        // `urn:ietf:params:oauth:grant-type:device_code`
3236        let grant_types_supported = vec![
3237            GrantType::AuthorisationCode,
3238            GrantType::TokenExchange,
3239            GrantType::RefreshToken,
3240        ];
3241
3242        let subject_types_supported = vec![SubjectType::Public];
3243
3244        let id_token_signing_alg_values_supported = match &o2rs.sign_alg {
3245            SignatureAlgo::Es256 => vec![IdTokenSignAlg::ES256],
3246            SignatureAlgo::Rs256 => vec![IdTokenSignAlg::RS256],
3247        };
3248
3249        let userinfo_signing_alg_values_supported = None;
3250
3251        let token_endpoint_auth_methods_supported = if o2rs.is_basic() {
3252            vec![
3253                EndpointAuthMethod::ClientSecretBasic,
3254                EndpointAuthMethod::ClientSecretPost,
3255            ]
3256        } else {
3257            vec![EndpointAuthMethod::None]
3258        };
3259
3260        let display_values_supported = Some(vec![DisplayValue::Page]);
3261        let claim_types_supported = vec![ClaimType::Normal];
3262        // What claims can we offer?
3263        let claims_supported = None;
3264        let service_documentation = Some(URL_SERVICE_DOCUMENTATION.clone());
3265
3266        let code_challenge_methods_supported = if o2rs.require_pkce() {
3267            vec![PkceAlg::S256]
3268        } else {
3269            Vec::with_capacity(0)
3270        };
3271
3272        // The following are extensions allowed by the oidc specification.
3273
3274        let revocation_endpoint = Some(o2rs.revocation_endpoint.clone());
3275        let revocation_endpoint_auth_methods_supported = vec![EndpointAuthMethod::None];
3276
3277        let introspection_endpoint = Some(o2rs.introspection_endpoint.clone());
3278        let introspection_endpoint_auth_methods_supported = vec![EndpointAuthMethod::None];
3279
3280        Ok(OidcDiscoveryResponse {
3281            issuer,
3282            authorization_endpoint,
3283            token_endpoint,
3284            userinfo_endpoint,
3285            jwks_uri,
3286            registration_endpoint: None,
3287            scopes_supported,
3288            response_types_supported,
3289            response_modes_supported,
3290            grant_types_supported,
3291            acr_values_supported: None,
3292            subject_types_supported,
3293            id_token_signing_alg_values_supported,
3294            id_token_encryption_alg_values_supported: None,
3295            id_token_encryption_enc_values_supported: None,
3296            userinfo_signing_alg_values_supported,
3297            userinfo_encryption_alg_values_supported: None,
3298            userinfo_encryption_enc_values_supported: None,
3299            request_object_signing_alg_values_supported: None,
3300            request_object_encryption_alg_values_supported: None,
3301            request_object_encryption_enc_values_supported: None,
3302            token_endpoint_auth_methods_supported,
3303            token_endpoint_auth_signing_alg_values_supported: None,
3304            display_values_supported,
3305            claim_types_supported,
3306            claims_supported,
3307            service_documentation,
3308            claims_locales_supported: None,
3309            ui_locales_supported: None,
3310            claims_parameter_supported: false,
3311            // TODO: once we support RFC9101 this can be true again
3312            request_parameter_supported: false,
3313            // TODO: if we support RFC9101 request_uri methods this can be true
3314            request_uri_parameter_supported: false,
3315            // TODO: if we support RFC9101 request_uri methods this should be true
3316            require_request_uri_registration: false,
3317            op_policy_uri: None,
3318            op_tos_uri: None,
3319            code_challenge_methods_supported,
3320            // Extensions
3321            revocation_endpoint,
3322            revocation_endpoint_auth_methods_supported,
3323            introspection_endpoint,
3324            introspection_endpoint_auth_methods_supported,
3325            introspection_endpoint_auth_signing_alg_values_supported: None,
3326            device_authorization_endpoint: o2rs.device_authorization_endpoint.clone(),
3327        })
3328    }
3329
3330    #[instrument(level = "debug", skip_all)]
3331    pub fn oauth2_openid_webfinger(
3332        &mut self,
3333        client_id: &str,
3334        resource_id: &str,
3335    ) -> Result<OidcWebfingerResponse, OperationError> {
3336        let o2rs = self.oauth2rs.inner.rs_set_get(client_id).ok_or_else(|| {
3337            warn!("Invalid OAuth2 client_id (have you configured the OAuth2 resource server?)");
3338            OperationError::NoMatchingEntries
3339        })?;
3340
3341        let Some(spn) = PartialValue::new_spn_s(resource_id) else {
3342            return Err(OperationError::NoMatchingEntries);
3343        };
3344
3345        // Ensure that the account exists.
3346        if !self
3347            .qs_read
3348            .internal_exists(&Filter::new(f_eq(Attribute::Spn, spn)))?
3349        {
3350            return Err(OperationError::NoMatchingEntries);
3351        }
3352
3353        let issuer = o2rs.iss.clone();
3354
3355        Ok(OidcWebfingerResponse {
3356            // we set the subject to the resource_id to ensure we always send something valid back
3357            // but realistically this will be overwritten on at the API layer
3358            subject: resource_id.to_string(),
3359            links: vec![OidcWebfingerRel {
3360                rel: "http://openid.net/specs/connect/1.0/issuer".into(),
3361                href: issuer.into(),
3362            }],
3363        })
3364    }
3365
3366    #[instrument(level = "debug", skip_all)]
3367    pub fn oauth2_openid_publickey(&self, client_id: &str) -> Result<JwkKeySet, OperationError> {
3368        let o2rs = self.oauth2rs.inner.rs_set_get(client_id).ok_or_else(|| {
3369            warn!("Invalid OAuth2 client_id (have you configured the OAuth2 resource server?)");
3370            OperationError::NoMatchingEntries
3371        })?;
3372
3373        trace!(sign_alg = ?o2rs.sign_alg);
3374
3375        match o2rs.sign_alg {
3376            SignatureAlgo::Es256 => o2rs.key_object.jws_es256_jwks(),
3377            SignatureAlgo::Rs256 => o2rs.key_object.jws_rs256_jwks(),
3378        }
3379        .ok_or_else(|| {
3380            error!(o2_client = ?o2rs.name, "Unable to retrieve public keys");
3381            OperationError::InvalidState
3382        })
3383    }
3384}
3385
3386fn parse_basic_authz(client_authz: &str) -> Result<ClientAuth, Oauth2Error> {
3387    // Check the client_authz
3388    let authz = general_purpose::STANDARD
3389        .decode(client_authz)
3390        .map_err(|_| {
3391            admin_error!("Basic authz invalid base64");
3392            Oauth2Error::AuthenticationRequired
3393        })
3394        .and_then(|data| {
3395            String::from_utf8(data).map_err(|_| {
3396                admin_error!("Basic authz invalid utf8");
3397                Oauth2Error::AuthenticationRequired
3398            })
3399        })?;
3400
3401    // Get the first :, it should be our delim.
3402    //
3403    let mut split_iter = authz.split(':');
3404
3405    let client_id = split_iter.next().ok_or_else(|| {
3406        admin_error!("Basic authz invalid format (corrupt input?)");
3407        Oauth2Error::AuthenticationRequired
3408    })?;
3409    let secret = split_iter.next().ok_or_else(|| {
3410        admin_error!("Basic authz invalid format (missing ':' separator?)");
3411        Oauth2Error::AuthenticationRequired
3412    })?;
3413
3414    // OAuth2 is bad and should feel bad:
3415    // https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1
3416    // The client_id MIGHT be url encoded. The secret won't be, because we
3417    // always generate it in a "safe" manner.
3418    //
3419    // If we *fail* to decode, then we just drop the raw client_id back out,
3420    // as this could be a client that didn't urlencoded their client_id.
3421    //
3422    // Both serde_urlencode and form_urlencoded can't handle this, as they assume
3423    // you have a map, so you can't deseralise to a string.
3424    //
3425    // Thankfully in our case we only allow - and _ so we can just replace these
3426    // directly.
3427    let client_id = client_id.replace("%2D", "-").replace("%5F", "_");
3428
3429    Ok((client_id.as_str(), Some(secret)).into())
3430}
3431
3432fn s_claims_for_account(
3433    o2rs: &Oauth2RS,
3434    account: &Account,
3435    scopes: &BTreeSet<String>,
3436) -> OidcClaims {
3437    let preferred_username = if o2rs.prefer_short_username {
3438        Some(account.name().into())
3439    } else {
3440        Some(account.spn().into())
3441    };
3442
3443    let (email, email_verified) = if scopes.contains(OAUTH2_SCOPE_EMAIL) {
3444        if let Some(mp) = &account.mail_primary {
3445            (Some(mp.clone()), Some(true))
3446        } else {
3447            (None, None)
3448        }
3449    } else {
3450        (None, None)
3451    };
3452
3453    let updated_at: Option<OffsetDateTime> = if scopes.contains(OAUTH2_SCOPE_PROFILE) {
3454        account
3455            .updated_at
3456            .as_ref()
3457            .map(OffsetDateTime::from)
3458            .and_then(|odt| odt.replace_nanosecond(0).ok())
3459    } else {
3460        None
3461    };
3462    OidcClaims {
3463        // Map from displayname
3464        name: Some(account.displayname.clone()),
3465        scopes: scopes.iter().cloned().collect(),
3466        preferred_username,
3467        email,
3468        email_verified,
3469        updated_at,
3470        ..Default::default()
3471    }
3472}
3473
3474fn extra_claims_for_account(
3475    account: &Account,
3476
3477    claim_map: &BTreeMap<Uuid, Vec<(String, ClaimValue)>>,
3478
3479    scopes: &BTreeSet<String>,
3480) -> BTreeMap<String, serde_json::Value> {
3481    let mut extra_claims = BTreeMap::new();
3482
3483    let mut account_claims: BTreeMap<&str, ClaimValue> = BTreeMap::new();
3484
3485    // for each group
3486    for group_uuid in account.groups.iter().map(|g| g.uuid()) {
3487        // Does this group have any custom claims?
3488        if let Some(claim) = claim_map.get(group_uuid) {
3489            // If so, iterate over the set of claims and values.
3490            for (claim_name, claim_value) in claim.iter() {
3491                // Does this claim name already exist in our in-progress map?
3492                match account_claims.entry(claim_name.as_str()) {
3493                    BTreeEntry::Vacant(e) => {
3494                        e.insert(claim_value.clone());
3495                    }
3496                    BTreeEntry::Occupied(mut e) => {
3497                        let mut_claim_value = e.get_mut();
3498                        // Merge the extra details into this.
3499                        mut_claim_value.merge(claim_value);
3500                    }
3501                }
3502            }
3503        }
3504    }
3505
3506    // Now, flatten all these into the final structure.
3507    for (claim_name, claim_value) in account_claims {
3508        extra_claims.insert(claim_name.to_string(), claim_value.to_json_value());
3509    }
3510
3511    // Now perform our custom claim's from scopes. We do these second so that
3512    // a user can't stomp our claim names.
3513
3514    if scopes.contains(OAUTH2_SCOPE_SSH_PUBLICKEYS) {
3515        extra_claims.insert(
3516            OAUTH2_SCOPE_SSH_PUBLICKEYS.to_string(),
3517            account
3518                .sshkeys()
3519                .values()
3520                .map(|pub_key| serde_json::Value::String(pub_key.to_string()))
3521                .collect(),
3522        );
3523    }
3524
3525    let wants_groups = scopes.contains(OAUTH2_SCOPE_GROUPS);
3526    // groups implies uuid + spn to match current behaviour.
3527    let wants_groups_uuid = wants_groups || scopes.contains(OAUTH2_SCOPE_GROUPS_UUID);
3528    let wants_groups_spn = wants_groups || scopes.contains(OAUTH2_SCOPE_GROUPS_SPN);
3529    let wants_groups_name = scopes.contains(OAUTH2_SCOPE_GROUPS_NAME);
3530
3531    if wants_groups_uuid || wants_groups_name || wants_groups_spn {
3532        extra_claims.insert(
3533            OAUTH2_SCOPE_GROUPS.to_string(),
3534            account
3535                .groups
3536                .iter()
3537                .flat_map(|group| {
3538                    let mut attrs = Vec::with_capacity(3);
3539
3540                    if wants_groups_uuid {
3541                        attrs.push(group.uuid().as_hyphenated().to_string())
3542                    }
3543
3544                    if wants_groups_spn {
3545                        attrs.push(group.spn().clone())
3546                    }
3547
3548                    if wants_groups_name {
3549                        if let Some(name) = group.name() {
3550                            attrs.push(name.into())
3551                        }
3552                    }
3553
3554                    attrs
3555                })
3556                .collect(),
3557        );
3558    }
3559
3560    trace!(?extra_claims);
3561
3562    extra_claims
3563}
3564
3565fn process_requested_scopes_for_identity(
3566    o2rs: &Oauth2RS,
3567    ident: &Identity,
3568    req_scopes: Option<&BTreeSet<String>>,
3569) -> Result<(BTreeSet<String>, BTreeSet<String>), Oauth2Error> {
3570    let req_scopes = req_scopes.cloned().unwrap_or_default();
3571
3572    if req_scopes.is_empty() {
3573        admin_error!("Invalid OAuth2 request - must contain at least one requested scope");
3574        return Err(Oauth2Error::InvalidRequest);
3575    }
3576
3577    validate_scopes(&req_scopes)?;
3578
3579    let available_scopes: BTreeSet<String> = o2rs
3580        .scope_maps
3581        .iter()
3582        .filter_map(|(u, m)| ident.is_memberof(*u).then_some(m.iter()))
3583        .flatten()
3584        .cloned()
3585        .collect();
3586
3587    if !req_scopes.is_subset(&available_scopes) {
3588        admin_warn!(
3589            %ident,
3590            requested_scopes = ?req_scopes,
3591            available_scopes = ?available_scopes,
3592            "Identity does not have access to the requested scopes"
3593        );
3594        return Err(Oauth2Error::AccessDenied);
3595    }
3596
3597    let granted_scopes: BTreeSet<String> = o2rs
3598        .sup_scope_maps
3599        .iter()
3600        .filter_map(|(u, m)| ident.is_memberof(*u).then_some(m.iter()))
3601        .flatten()
3602        .cloned()
3603        .chain(req_scopes.iter().cloned())
3604        .collect();
3605
3606    Ok((req_scopes, granted_scopes))
3607}
3608
3609fn validate_scopes(req_scopes: &BTreeSet<String>) -> Result<(), Oauth2Error> {
3610    let failed_scopes = req_scopes
3611        .iter()
3612        .filter(|&s| !OAUTHSCOPE_RE.is_match(s))
3613        .cloned()
3614        .collect::<Vec<String>>();
3615
3616    if !failed_scopes.is_empty() {
3617        let requested_scopes_string = req_scopes
3618            .iter()
3619            .cloned()
3620            .collect::<Vec<String>>()
3621            .join(",");
3622        admin_error!(
3623                "Invalid OAuth2 request - requested scopes ({}) but ({}) failed to pass validation rules - all must match the regex {}",
3624                    requested_scopes_string,
3625                    failed_scopes.join(","),
3626                    OAUTHSCOPE_RE.as_str()
3627            );
3628        return Err(Oauth2Error::InvalidScope);
3629    }
3630    Ok(())
3631}
3632
3633/// device code is a random bucket of bytes used in the device flow
3634#[inline]
3635#[cfg(any(feature = "dev-oauth2-device-flow", test))]
3636#[allow(dead_code)]
3637fn gen_device_code() -> Result<[u8; 16], Oauth2Error> {
3638    use rand::TryRng;
3639
3640    let mut rng = rand::rng();
3641    let mut result = [0u8; 16];
3642    // doing it here because of feature-shenanigans.
3643    if let Err(err) = rng.try_fill_bytes(&mut result) {
3644        error!("Failed to generate device code! {:?}", err);
3645        return Err(Oauth2Error::ServerError(OperationError::Backend));
3646    }
3647    Ok(result)
3648}
3649
3650#[inline]
3651#[cfg(any(feature = "dev-oauth2-device-flow", test))]
3652#[allow(dead_code)]
3653/// Returns (xxx-yyy-zzz, digits) where one's the human-facing code, the other is what we store in the DB.
3654fn gen_user_code() -> (String, u32) {
3655    use rand::RngExt;
3656    let mut rng = rand::rng();
3657    let num: u32 = rng.random_range(0..=999999999);
3658    let result = format!("{num:09}");
3659    (
3660        format!("{}-{}-{}", &result[0..3], &result[3..6], &result[6..9]),
3661        num,
3662    )
3663}
3664
3665/// Take the supplied user code and check it's a valid u32
3666#[allow(dead_code)]
3667fn parse_user_code(val: &str) -> Result<u32, Oauth2Error> {
3668    let mut val = val.to_string();
3669    val.retain(|c| c.is_ascii_digit());
3670    val.parse().map_err(|err| {
3671        debug!("Failed to parse value={} as u32: {:?}", val, err);
3672        Oauth2Error::InvalidRequest
3673    })
3674}
3675
3676/// Check if a host is local (loopback or localhost)
3677fn host_is_local(host: &Host<&str>) -> bool {
3678    match host {
3679        Host::Ipv4(ip) => ip.is_loopback(),
3680        Host::Ipv6(ip) => ip.is_loopback(),
3681        Host::Domain(domain) => *domain == "localhost",
3682    }
3683}
3684
3685/// Ensure that the redirect URI is a loopback/localhost address
3686fn check_is_loopback(redirect_uri: &Url) -> bool {
3687    redirect_uri.host().is_some_and(|host| {
3688        // Check if the host is a loopback/localhost address.
3689        host_is_local(&host)
3690    })
3691}
3692
3693#[cfg(test)]
3694mod tests {
3695    use super::{
3696        AuthorisationRequestContext, CtSecret, Oauth2TokenType, PkceS256Secret,
3697        TOKEN_EXCHANGE_SUBJECT_TOKEN_TYPE_ACCESS,
3698    };
3699    use crate::{
3700        credential::Credential,
3701        idm::{
3702            accountpolicy::ResolvedAccountPolicy,
3703            oauth2::{
3704                host_is_local, parse_basic_authz, AuthoriseResponse, Oauth2Error, OauthRSType,
3705            },
3706            server::{IdmServer, IdmServerTransaction},
3707            serviceaccount::GenerateApiTokenEvent,
3708        },
3709        prelude::*,
3710        value::{AuthType, OauthClaimMapJoin, SessionState},
3711        valueset::{ValueSetOauthScopeMap, ValueSetSshKey, ValueSetUint32},
3712    };
3713    use base64::{engine::general_purpose, Engine as _};
3714    use compact_jwt::{
3715        compact::JwkUse, crypto::JwsRs256Verifier, dangernoverify::JwsDangerReleaseWithoutVerify,
3716        JwaAlg, Jwk, JwsCompact, JwsEs256Verifier, JwsVerifier, OidcSubject, OidcToken,
3717        OidcUnverified,
3718    };
3719    use kanidm_lib_crypto::CryptoPolicy;
3720    use kanidm_proto::{
3721        constants::*,
3722        internal::{SshPublicKey, UserAuthToken},
3723        oauth2::*,
3724    };
3725    use std::{
3726        collections::{BTreeMap, BTreeSet},
3727        convert::TryFrom,
3728        str::FromStr,
3729        time::Duration,
3730    };
3731    use time::OffsetDateTime;
3732    use uri::{OAUTH2_TOKEN_INTROSPECT_ENDPOINT, OAUTH2_TOKEN_REVOKE_ENDPOINT};
3733
3734    const TEST_CURRENT_TIME: u64 = 6000;
3735    const UAT_EXPIRE: u64 = 5;
3736    const TOKEN_EXPIRE: u64 = 900;
3737
3738    const UUID_TESTGROUP: Uuid = uuid!("a3028223-bf20-47d5-8b65-967b5d2bb3eb");
3739
3740    macro_rules! good_authorisation_request {
3741        (
3742            $idms_prox_read:expr,
3743            $ident:expr,
3744            $ct:expr,
3745            $pkce_request:expr,
3746            $scope:expr
3747        ) => {{
3748            #[allow(clippy::unnecessary_to_owned)]
3749            let scope: BTreeSet<String> = $scope.split(" ").map(|s| s.to_string()).collect();
3750
3751            let auth_req = AuthorisationRequest {
3752                response_type: ResponseType::Code,
3753                response_mode: None,
3754                client_id: "test_resource_server".to_string(),
3755                state: Some("123".to_string()),
3756                pkce_request: Some($pkce_request),
3757                redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
3758                scope,
3759                nonce: Some("abcdef".to_string()),
3760                oidc_ext: Default::default(),
3761                max_age: None,
3762                prompt: Default::default(),
3763                ui_locales: Default::default(),
3764                unknown_keys: Default::default(),
3765            };
3766
3767            let auth_req_ctx = AuthorisationRequestContext { resumed: false };
3768
3769            $idms_prox_read
3770                .check_oauth2_authorisation(Some($ident), &auth_req, &auth_req_ctx, $ct)
3771                .expect("OAuth2 authorisation failed")
3772        }};
3773    }
3774
3775    // setup an OAuth2 instance.
3776    async fn setup_oauth2_resource_server_basic(
3777        idms: &IdmServer,
3778        ct: Duration,
3779        enable_pkce: bool,
3780        enable_legacy_crypto: bool,
3781        prefer_short_username: bool,
3782    ) -> (String, UserAuthToken, Identity, Uuid) {
3783        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3784
3785        let rs_uuid = Uuid::new_v4();
3786
3787        let entry_group: Entry<EntryInit, EntryNew> = entry_init!(
3788            (Attribute::Class, EntryClass::Group.to_value()),
3789            (Attribute::Name, Value::new_iname("testgroup")),
3790            (Attribute::Description, Value::new_utf8s("testgroup")),
3791            (Attribute::Uuid, Value::Uuid(UUID_TESTGROUP)),
3792            (Attribute::Member, Value::ReferN(UUID_TESTPERSON_1),)
3793        );
3794
3795        let entry_rs: Entry<EntryInit, EntryNew> = entry_init!(
3796            (Attribute::Class, EntryClass::Object.to_value()),
3797            (Attribute::Class, EntryClass::Account.to_value()),
3798            (
3799                Attribute::Class,
3800                EntryClass::OAuth2ResourceServer.to_value()
3801            ),
3802            (
3803                Attribute::Class,
3804                EntryClass::OAuth2ResourceServerBasic.to_value()
3805            ),
3806            (Attribute::Uuid, Value::Uuid(rs_uuid)),
3807            (Attribute::Name, Value::new_iname("test_resource_server")),
3808            (
3809                Attribute::DisplayName,
3810                Value::new_utf8s("test_resource_server")
3811            ),
3812            (
3813                Attribute::OAuth2RsOriginLanding,
3814                Value::new_url_s("https://demo.example.com").unwrap()
3815            ),
3816            // Supplemental origins
3817            (
3818                Attribute::OAuth2RsOrigin,
3819                Value::new_urln_s("https://demo.example.com/oauth2/result").unwrap()
3820            ),
3821            (
3822                Attribute::OAuth2RsOrigin,
3823                Value::new_urln_s("https://portal.example.com/?custom=foo").unwrap()
3824            ),
3825            (
3826                Attribute::OAuth2RsOrigin,
3827                Value::new_urln_s("app://cheese").unwrap()
3828            ),
3829            // System admins
3830            (
3831                Attribute::OAuth2RsScopeMap,
3832                Value::new_oauthscopemap(
3833                    UUID_TESTGROUP,
3834                    btreeset![OAUTH2_SCOPE_GROUPS.to_string()]
3835                )
3836                .expect("invalid oauthscope")
3837            ),
3838            (
3839                Attribute::OAuth2RsScopeMap,
3840                Value::new_oauthscopemap(
3841                    UUID_IDM_ALL_ACCOUNTS,
3842                    btreeset![
3843                        OAUTH2_SCOPE_OPENID.to_string(),
3844                        OAUTH2_SCOPE_PROFILE.to_string()
3845                    ]
3846                )
3847                .expect("invalid oauthscope")
3848            ),
3849            (
3850                Attribute::OAuth2RsSupScopeMap,
3851                Value::new_oauthscopemap(
3852                    UUID_IDM_ALL_ACCOUNTS,
3853                    btreeset!["supplement".to_string()]
3854                )
3855                .expect("invalid oauthscope")
3856            ),
3857            (
3858                Attribute::OAuth2AllowInsecureClientDisablePkce,
3859                Value::new_bool(!enable_pkce)
3860            ),
3861            (
3862                Attribute::OAuth2JwtLegacyCryptoEnable,
3863                Value::new_bool(enable_legacy_crypto)
3864            ),
3865            (
3866                Attribute::OAuth2PreferShortUsername,
3867                Value::new_bool(prefer_short_username)
3868            )
3869        );
3870
3871        let ce = CreateEvent::new_internal(vec![entry_rs, entry_group, E_TESTPERSON_1.clone()]);
3872        assert!(idms_prox_write.qs_write.create(&ce).is_ok());
3873
3874        let entry = idms_prox_write
3875            .qs_write
3876            .internal_search_uuid(rs_uuid)
3877            .expect("Failed to retrieve OAuth2 resource entry ");
3878        let secret = entry
3879            .get_ava_single_secret(Attribute::OAuth2RsBasicSecret)
3880            .map(str::to_string)
3881            .expect("No oauth2_rs_basic_secret found");
3882
3883        // Setup the uat we'll be using - note for these tests they *require*
3884        // the parent session to be valid and present!
3885        let session_id = uuid::Uuid::new_v4();
3886
3887        let account = idms_prox_write
3888            .target_to_account(UUID_TESTPERSON_1)
3889            .expect("account must exist");
3890
3891        let uat = account
3892            .to_userauthtoken(
3893                session_id,
3894                SessionScope::ReadWrite,
3895                ct,
3896                &ResolvedAccountPolicy::test_policy(),
3897            )
3898            .expect("Unable to create uat");
3899
3900        // Need the uat first for expiry.
3901        let state = uat
3902            .expiry
3903            .map(SessionState::ExpiresAt)
3904            .unwrap_or(SessionState::NeverExpires);
3905
3906        let p = CryptoPolicy::minimum();
3907        let cred =
3908            Credential::new_password_only(&p, "test_password", OffsetDateTime::UNIX_EPOCH).unwrap();
3909        let cred_id = cred.uuid;
3910
3911        let session = Value::Session(
3912            session_id,
3913            crate::value::Session {
3914                label: "label".to_string(),
3915                state,
3916                issued_at: time::OffsetDateTime::UNIX_EPOCH + ct,
3917                issued_by: IdentityId::Internal(UUID_SYSTEM),
3918                cred_id,
3919                scope: SessionScope::ReadWrite,
3920                type_: AuthType::Passkey,
3921                ext_metadata: Default::default(),
3922            },
3923        );
3924
3925        // Mod the user
3926        let modlist = ModifyList::new_list(vec![
3927            Modify::Present(Attribute::UserAuthTokenSession, session),
3928            Modify::Present(
3929                Attribute::PrimaryCredential,
3930                Value::Cred("primary".to_string(), cred),
3931            ),
3932        ]);
3933
3934        idms_prox_write
3935            .qs_write
3936            .internal_modify(
3937                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_TESTPERSON_1))),
3938                &modlist,
3939            )
3940            .expect("Failed to modify user");
3941
3942        let ident = idms_prox_write
3943            .process_uat_to_identity(&uat, ct, Source::Internal)
3944            .expect("Unable to process uat");
3945
3946        idms_prox_write.commit().expect("failed to commit");
3947
3948        (secret, uat, ident, rs_uuid)
3949    }
3950
3951    async fn setup_oauth2_resource_server_public(
3952        idms: &IdmServer,
3953        ct: Duration,
3954    ) -> (UserAuthToken, Identity, Uuid) {
3955        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3956
3957        let rs_uuid = Uuid::new_v4();
3958
3959        let entry_group: Entry<EntryInit, EntryNew> = entry_init!(
3960            (Attribute::Class, EntryClass::Group.to_value()),
3961            (Attribute::Name, Value::new_iname("testgroup")),
3962            (Attribute::Description, Value::new_utf8s("testgroup")),
3963            (Attribute::Uuid, Value::Uuid(UUID_TESTGROUP)),
3964            (Attribute::Member, Value::ReferN(UUID_TESTPERSON_1),)
3965        );
3966
3967        let entry_rs: Entry<EntryInit, EntryNew> = entry_init!(
3968            (Attribute::Class, EntryClass::Object.to_value()),
3969            (Attribute::Class, EntryClass::Account.to_value()),
3970            (
3971                Attribute::Class,
3972                EntryClass::OAuth2ResourceServer.to_value()
3973            ),
3974            (
3975                Attribute::Class,
3976                EntryClass::OAuth2ResourceServerPublic.to_value()
3977            ),
3978            (Attribute::Uuid, Value::Uuid(rs_uuid)),
3979            (Attribute::Name, Value::new_iname("test_resource_server")),
3980            (
3981                Attribute::DisplayName,
3982                Value::new_utf8s("test_resource_server")
3983            ),
3984            (
3985                Attribute::OAuth2RsOriginLanding,
3986                Value::new_url_s("https://demo.example.com").unwrap()
3987            ),
3988            (
3989                Attribute::OAuth2RsOrigin,
3990                Value::new_urln_s("https://demo.example.com/oauth2/result").unwrap()
3991            ),
3992            // System admins
3993            (
3994                Attribute::OAuth2RsScopeMap,
3995                Value::new_oauthscopemap(
3996                    UUID_TESTGROUP,
3997                    btreeset![OAUTH2_SCOPE_GROUPS.to_string()]
3998                )
3999                .expect("invalid oauthscope")
4000            ),
4001            (
4002                Attribute::OAuth2RsScopeMap,
4003                Value::new_oauthscopemap(
4004                    UUID_IDM_ALL_ACCOUNTS,
4005                    btreeset![OAUTH2_SCOPE_OPENID.to_string()]
4006                )
4007                .expect("invalid oauthscope")
4008            ),
4009            (
4010                Attribute::OAuth2RsSupScopeMap,
4011                Value::new_oauthscopemap(
4012                    UUID_IDM_ALL_ACCOUNTS,
4013                    btreeset!["supplement".to_string()]
4014                )
4015                .expect("invalid oauthscope")
4016            )
4017        );
4018        let ce = CreateEvent::new_internal(vec![entry_rs, entry_group, E_TESTPERSON_1.clone()]);
4019        assert!(idms_prox_write.qs_write.create(&ce).is_ok());
4020
4021        // Setup the uat we'll be using - note for these tests they *require*
4022        // the parent session to be valid and present!
4023
4024        let session_id = uuid::Uuid::new_v4();
4025
4026        let account = idms_prox_write
4027            .target_to_account(UUID_TESTPERSON_1)
4028            .expect("account must exist");
4029        let uat = account
4030            .to_userauthtoken(
4031                session_id,
4032                SessionScope::ReadWrite,
4033                ct,
4034                &ResolvedAccountPolicy::test_policy(),
4035            )
4036            .expect("Unable to create uat");
4037
4038        // Need the uat first for expiry.
4039        let state = uat
4040            .expiry
4041            .map(SessionState::ExpiresAt)
4042            .unwrap_or(SessionState::NeverExpires);
4043
4044        let p = CryptoPolicy::minimum();
4045        let cred =
4046            Credential::new_password_only(&p, "test_password", OffsetDateTime::UNIX_EPOCH).unwrap();
4047        let cred_id = cred.uuid;
4048
4049        let session = Value::Session(
4050            session_id,
4051            crate::value::Session {
4052                label: "label".to_string(),
4053                state,
4054                issued_at: time::OffsetDateTime::UNIX_EPOCH + ct,
4055                issued_by: IdentityId::Internal(UUID_SYSTEM),
4056                cred_id,
4057                scope: SessionScope::ReadWrite,
4058                type_: AuthType::Passkey,
4059                ext_metadata: Default::default(),
4060            },
4061        );
4062
4063        // Mod the user
4064        let modlist = ModifyList::new_list(vec![
4065            Modify::Present(Attribute::UserAuthTokenSession, session),
4066            Modify::Present(
4067                Attribute::PrimaryCredential,
4068                Value::Cred("primary".to_string(), cred),
4069            ),
4070        ]);
4071
4072        idms_prox_write
4073            .qs_write
4074            .internal_modify(
4075                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_TESTPERSON_1))),
4076                &modlist,
4077            )
4078            .expect("Failed to modify user");
4079
4080        let ident = idms_prox_write
4081            .process_uat_to_identity(&uat, ct, Source::Internal)
4082            .expect("Unable to process uat");
4083
4084        idms_prox_write.commit().expect("failed to commit");
4085
4086        (uat, ident, rs_uuid)
4087    }
4088
4089    /// Perform an oauth2 exchange, assuming that it will succeed.
4090    async fn perform_oauth2_exchange(
4091        idms: &IdmServer,
4092        ident: &Identity,
4093        ct: Duration,
4094        client_authz: ClientAuthInfo,
4095        scopes: String,
4096    ) -> AccessTokenResponse {
4097        let idms_prox_read = idms.proxy_read().await.unwrap();
4098
4099        let pkce_secret = PkceS256Secret::default();
4100
4101        let consent_request = good_authorisation_request!(
4102            idms_prox_read,
4103            ident,
4104            ct,
4105            pkce_secret.to_request(),
4106            scopes
4107        );
4108
4109        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
4110            unreachable!();
4111        };
4112
4113        // == Manually submit the consent token to the permit for the permit_success
4114        drop(idms_prox_read);
4115        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4116
4117        let permit_success = idms_prox_write
4118            .check_oauth2_authorise_permit(ident, &consent_token, ct)
4119            .expect("Failed to perform OAuth2 permit");
4120
4121        // == Submit the token exchange code.
4122        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
4123            code: permit_success.code,
4124            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4125            code_verifier: Some(pkce_secret.to_verifier()),
4126        }
4127        .into();
4128
4129        let token_response = idms_prox_write
4130            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
4131            .expect("Failed to perform OAuth2 token exchange");
4132
4133        assert!(idms_prox_write.commit().is_ok());
4134
4135        token_response
4136    }
4137
4138    async fn validate_id_token(idms: &IdmServer, ct: Duration, id_token: &str) -> OidcToken {
4139        let idms_prox_read = idms.proxy_read().await.unwrap();
4140
4141        let mut jwkset = idms_prox_read
4142            .oauth2_openid_publickey("test_resource_server")
4143            .expect("Failed to get public key");
4144        let public_jwk = jwkset.keys.pop().expect("no such jwk");
4145
4146        let jws_validator =
4147            JwsEs256Verifier::try_from(&public_jwk).expect("failed to build validator");
4148
4149        let oidc_unverified = OidcUnverified::from_str(id_token).expect("Failed to parse id_token");
4150
4151        let iat = ct.as_secs() as i64;
4152
4153        jws_validator
4154            .verify(&oidc_unverified)
4155            .unwrap()
4156            .verify_exp(iat)
4157            .expect("Failed to verify oidc")
4158    }
4159
4160    async fn setup_idm_admin(idms: &IdmServer, ct: Duration) -> (UserAuthToken, Identity) {
4161        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4162        let account = idms_prox_write
4163            .target_to_account(UUID_IDM_ADMIN)
4164            .expect("account must exist");
4165        let session_id = uuid::Uuid::new_v4();
4166        let uat = account
4167            .to_userauthtoken(
4168                session_id,
4169                SessionScope::ReadWrite,
4170                ct,
4171                &ResolvedAccountPolicy::test_policy(),
4172            )
4173            .expect("Unable to create uat");
4174        let ident = idms_prox_write
4175            .process_uat_to_identity(&uat, ct, Source::Internal)
4176            .expect("Unable to process uat");
4177
4178        idms_prox_write.commit().expect("failed to commit");
4179
4180        (uat, ident)
4181    }
4182
4183    #[test]
4184    fn oauth2_parse_basic_authz() {
4185        let r1 = parse_basic_authz("czZCaGRSa3F0Mzo3RmpmcDBaQnIxS3REUmJuZlZkbUl3").unwrap();
4186        assert_eq!(r1.client_id, "s6BhdRkqt3");
4187        assert_eq!(r1.client_secret.as_deref(), Some("7Fjfp0ZBr1KtDRbnfVdmIw"));
4188
4189        // This contains: "my%2Did:Dei7thai1ahne4a" which has a url-encoded client-id
4190        let r2 = parse_basic_authz("bXklMkRpZDpEZWk3dGhhaTFhaG5lNGE=").unwrap();
4191        assert_eq!(r2.client_id, "my-id");
4192        assert_eq!(r2.client_secret.as_deref(), Some("Dei7thai1ahne4a"));
4193    }
4194
4195    #[idm_test]
4196    async fn test_idm_oauth2_basic_function(
4197        idms: &IdmServer,
4198        _idms_delayed: &mut IdmServerDelayed,
4199    ) {
4200        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4201        let (secret, _uat, ident, _) =
4202            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
4203
4204        let idms_prox_read = idms.proxy_read().await.unwrap();
4205
4206        // == Setup the authorisation request
4207        let pkce_secret = PkceS256Secret::default();
4208
4209        let consent_request = good_authorisation_request!(
4210            idms_prox_read,
4211            &ident,
4212            ct,
4213            pkce_secret.to_request(),
4214            OAUTH2_SCOPE_OPENID.to_string()
4215        );
4216
4217        // Should be in the consent phase;
4218        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
4219            unreachable!();
4220        };
4221
4222        // == Manually submit the consent token to the permit for the permit_success
4223        drop(idms_prox_read);
4224        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4225
4226        let permit_success = idms_prox_write
4227            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
4228            .expect("Failed to perform OAuth2 permit");
4229
4230        // Check we are reflecting the CSRF properly.
4231        assert_eq!(permit_success.state.as_deref(), Some("123"));
4232
4233        // == Submit the token exchange code.
4234
4235        let token_req = AccessTokenRequest {
4236            grant_type: GrantTypeReq::AuthorizationCode {
4237                code: permit_success.code,
4238                redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4239                code_verifier: Some(pkce_secret.to_verifier()),
4240            },
4241            client_post_auth: ClientPostAuth {
4242                client_id: Some("test_resource_server".to_string()),
4243                client_secret: Some(secret),
4244            },
4245        };
4246
4247        let token_response = idms_prox_write
4248            .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
4249            .expect("Failed to perform OAuth2 token exchange");
4250
4251        // 🎉 We got a token! In the future we can then check introspection from this point.
4252        assert_eq!(token_response.token_type, AccessTokenType::Bearer);
4253
4254        assert!(idms_prox_write.commit().is_ok());
4255    }
4256
4257    #[idm_test]
4258    async fn test_idm_oauth2_public_function(
4259        idms: &IdmServer,
4260        _idms_delayed: &mut IdmServerDelayed,
4261    ) {
4262        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4263        let (_uat, ident, _) = setup_oauth2_resource_server_public(idms, ct).await;
4264
4265        let idms_prox_read = idms.proxy_read().await.unwrap();
4266
4267        // Get an ident/uat for now.
4268
4269        // == Setup the authorisation request
4270        let pkce_secret = PkceS256Secret::default();
4271
4272        let consent_request = good_authorisation_request!(
4273            idms_prox_read,
4274            &ident,
4275            ct,
4276            pkce_secret.to_request(),
4277            OAUTH2_SCOPE_OPENID.to_string()
4278        );
4279
4280        // Should be in the consent phase;
4281        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
4282            unreachable!();
4283        };
4284
4285        // == Manually submit the consent token to the permit for the permit_success
4286        drop(idms_prox_read);
4287        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4288
4289        let permit_success = idms_prox_write
4290            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
4291            .expect("Failed to perform OAuth2 permit");
4292
4293        // Check we are reflecting the CSRF properly.
4294        assert_eq!(permit_success.state.as_deref(), Some("123"));
4295
4296        // == Submit the token exchange code.
4297
4298        let token_req = AccessTokenRequest {
4299            grant_type: GrantTypeReq::AuthorizationCode {
4300                code: permit_success.code,
4301                redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4302                // From the first step.
4303                code_verifier: Some(pkce_secret.to_verifier()),
4304            },
4305
4306            client_post_auth: ClientPostAuth {
4307                client_id: Some("Test_Resource_Server".to_string()),
4308                client_secret: None,
4309            },
4310        };
4311
4312        let token_response = idms_prox_write
4313            .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
4314            .expect("Failed to perform OAuth2 token exchange");
4315
4316        // 🎉 We got a token! In the future we can then check introspection from this point.
4317        assert_eq!(token_response.token_type, AccessTokenType::Bearer);
4318
4319        assert!(idms_prox_write.commit().is_ok());
4320    }
4321
4322    #[idm_test]
4323    async fn test_idm_oauth2_invalid_authorisation_requests(
4324        idms: &IdmServer,
4325        _idms_delayed: &mut IdmServerDelayed,
4326    ) {
4327        // Test invalid OAuth2 authorisation states/requests.
4328        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4329        let (_secret, _uat, ident, _) =
4330            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
4331
4332        let (_anon_uat, anon_ident) = setup_idm_admin(idms, ct).await;
4333        let (_idm_admin_uat, idm_admin_ident) = setup_idm_admin(idms, ct).await;
4334
4335        // Need a uat from a user not in the group. Probs anonymous.
4336        let idms_prox_read = idms.proxy_read().await.unwrap();
4337
4338        let pkce_secret = PkceS256Secret::default();
4339
4340        let pkce_request = pkce_secret.to_request();
4341
4342        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
4343
4344        //  * response type != code.
4345        let auth_req = AuthorisationRequest {
4346            // We're unlikely to support Implicit Grant
4347            response_type: ResponseType::Token,
4348            response_mode: None,
4349            client_id: "test_resource_server".to_string(),
4350            state: Some("123".to_string()),
4351            pkce_request: Some(pkce_request.clone()),
4352            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4353            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
4354            nonce: None,
4355            oidc_ext: Default::default(),
4356            max_age: None,
4357            ui_locales: Default::default(),
4358            prompt: Default::default(),
4359            unknown_keys: Default::default(),
4360        };
4361
4362        assert!(
4363            idms_prox_read
4364                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4365                .unwrap_err()
4366                == Oauth2Error::UnsupportedResponseType
4367        );
4368
4369        // * No pkce in pkce enforced mode.
4370        let auth_req = AuthorisationRequest {
4371            response_type: ResponseType::Code,
4372            response_mode: None,
4373            client_id: "test_resource_server".to_string(),
4374            state: Some("123".to_string()),
4375            pkce_request: None,
4376            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4377            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
4378            nonce: None,
4379            oidc_ext: Default::default(),
4380            max_age: None,
4381            ui_locales: Default::default(),
4382            prompt: Default::default(),
4383            unknown_keys: Default::default(),
4384        };
4385
4386        assert!(
4387            idms_prox_read
4388                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4389                .unwrap_err()
4390                == Oauth2Error::InvalidRequest
4391        );
4392
4393        //  * invalid rs name
4394        let auth_req = AuthorisationRequest {
4395            response_type: ResponseType::Code,
4396            response_mode: None,
4397            client_id: "NOT A REAL RESOURCE SERVER".to_string(),
4398            state: Some("123".to_string()),
4399            pkce_request: Some(pkce_request.clone()),
4400            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4401            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
4402            nonce: None,
4403            oidc_ext: Default::default(),
4404            max_age: None,
4405            ui_locales: Default::default(),
4406            prompt: Default::default(),
4407            unknown_keys: Default::default(),
4408        };
4409
4410        assert!(
4411            idms_prox_read
4412                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4413                .unwrap_err()
4414                == Oauth2Error::InvalidClientId
4415        );
4416
4417        //  * mismatched origin in the redirect.
4418        let auth_req = AuthorisationRequest {
4419            response_type: ResponseType::Code,
4420            response_mode: None,
4421            client_id: "test_resource_server".to_string(),
4422            state: Some("123".to_string()),
4423            pkce_request: Some(pkce_request.clone()),
4424            redirect_uri: Url::parse("https://totes.not.sus.org/oauth2/result").unwrap(),
4425            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
4426            nonce: None,
4427            oidc_ext: Default::default(),
4428            max_age: None,
4429            prompt: Default::default(),
4430            ui_locales: Default::default(),
4431            unknown_keys: Default::default(),
4432        };
4433
4434        assert!(
4435            idms_prox_read
4436                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4437                .unwrap_err()
4438                == Oauth2Error::InvalidOrigin
4439        );
4440
4441        // * invalid uri in the redirect
4442        let auth_req = AuthorisationRequest {
4443            response_type: ResponseType::Code,
4444            response_mode: None,
4445            client_id: "test_resource_server".to_string(),
4446            state: Some("123".to_string()),
4447            pkce_request: Some(pkce_request.clone()),
4448            redirect_uri: Url::parse("https://demo.example.com/oauth2/wrong_place").unwrap(),
4449            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
4450            nonce: None,
4451            oidc_ext: Default::default(),
4452            max_age: None,
4453            ui_locales: Default::default(),
4454            prompt: Default::default(),
4455            unknown_keys: Default::default(),
4456        };
4457
4458        assert!(
4459            idms_prox_read
4460                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4461                .unwrap_err()
4462                == Oauth2Error::InvalidOrigin
4463        );
4464
4465        // * invalid uri (doesn't match query params)
4466        let auth_req = AuthorisationRequest {
4467            response_type: ResponseType::Code,
4468            response_mode: None,
4469            client_id: "test_resource_server".to_string(),
4470            state: Some("123".to_string()),
4471            pkce_request: Some(pkce_request.clone()),
4472            redirect_uri: Url::parse("https://portal.example.com/?custom=foo&too=many").unwrap(),
4473            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
4474            nonce: None,
4475            oidc_ext: Default::default(),
4476            max_age: None,
4477            ui_locales: Default::default(),
4478            prompt: Default::default(),
4479            unknown_keys: Default::default(),
4480        };
4481
4482        assert!(
4483            idms_prox_read
4484                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4485                .unwrap_err()
4486                == Oauth2Error::InvalidOrigin
4487        );
4488
4489        let auth_req = AuthorisationRequest {
4490            response_type: ResponseType::Code,
4491            response_mode: None,
4492            client_id: "test_resource_server".to_string(),
4493            state: Some("123".to_string()),
4494            pkce_request: Some(pkce_request.clone()),
4495            redirect_uri: Url::parse("https://portal.example.com").unwrap(),
4496            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
4497            nonce: None,
4498            oidc_ext: Default::default(),
4499            max_age: None,
4500            ui_locales: Default::default(),
4501            prompt: Default::default(),
4502            unknown_keys: Default::default(),
4503        };
4504
4505        assert!(
4506            idms_prox_read
4507                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4508                .unwrap_err()
4509                == Oauth2Error::InvalidOrigin
4510        );
4511
4512        let auth_req = AuthorisationRequest {
4513            response_type: ResponseType::Code,
4514            response_mode: None,
4515            client_id: "test_resource_server".to_string(),
4516            state: Some("123".to_string()),
4517            pkce_request: Some(pkce_request.clone()),
4518            redirect_uri: Url::parse("https://portal.example.com/?wrong=queryparam").unwrap(),
4519            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
4520            nonce: None,
4521            oidc_ext: Default::default(),
4522            max_age: None,
4523            ui_locales: Default::default(),
4524            prompt: Default::default(),
4525            unknown_keys: Default::default(),
4526        };
4527
4528        assert!(
4529            idms_prox_read
4530                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4531                .unwrap_err()
4532                == Oauth2Error::InvalidOrigin
4533        );
4534
4535        // Not Authenticated
4536        let auth_req = AuthorisationRequest {
4537            response_type: ResponseType::Code,
4538            response_mode: None,
4539            client_id: "test_resource_server".to_string(),
4540            state: Some("123".to_string()),
4541            pkce_request: Some(pkce_request.clone()),
4542            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4543            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
4544            nonce: None,
4545            oidc_ext: Default::default(),
4546            max_age: None,
4547            ui_locales: Default::default(),
4548            prompt: Default::default(),
4549            unknown_keys: Default::default(),
4550        };
4551
4552        let req = idms_prox_read
4553            .check_oauth2_authorisation(None, &auth_req, &auth_req_ctx, ct)
4554            .unwrap();
4555
4556        assert!(matches!(
4557            req,
4558            AuthoriseResponse::AuthenticationRequired { .. }
4559        ));
4560
4561        // Requested scope is not available
4562        let auth_req = AuthorisationRequest {
4563            response_type: ResponseType::Code,
4564            response_mode: None,
4565            client_id: "test_resource_server".to_string(),
4566            state: Some("123".to_string()),
4567            pkce_request: Some(pkce_request.clone()),
4568            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4569            scope: btreeset!["invalid_scope".to_string(), "read".to_string()],
4570            nonce: None,
4571            oidc_ext: Default::default(),
4572            max_age: None,
4573            ui_locales: Default::default(),
4574            prompt: Default::default(),
4575            unknown_keys: Default::default(),
4576        };
4577
4578        assert!(
4579            idms_prox_read
4580                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4581                .unwrap_err()
4582                == Oauth2Error::AccessDenied
4583        );
4584
4585        // Not a member of the group.
4586        let auth_req = AuthorisationRequest {
4587            response_type: ResponseType::Code,
4588            response_mode: None,
4589            client_id: "test_resource_server".to_string(),
4590            state: Some("123".to_string()),
4591            pkce_request: Some(pkce_request.clone()),
4592            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4593            scope: btreeset!["openid".to_string(), "read".to_string()],
4594            nonce: None,
4595            oidc_ext: Default::default(),
4596            max_age: None,
4597            ui_locales: Default::default(),
4598            prompt: Default::default(),
4599            unknown_keys: Default::default(),
4600        };
4601
4602        assert!(
4603            idms_prox_read
4604                .check_oauth2_authorisation(Some(&idm_admin_ident), &auth_req, &auth_req_ctx, ct)
4605                .unwrap_err()
4606                == Oauth2Error::AccessDenied
4607        );
4608
4609        // Deny Anonymous auth methods
4610        let auth_req = AuthorisationRequest {
4611            response_type: ResponseType::Code,
4612            response_mode: None,
4613            client_id: "test_resource_server".to_string(),
4614            state: Some("123".to_string()),
4615            pkce_request: Some(pkce_request),
4616            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4617            scope: btreeset!["openid".to_string(), "read".to_string()],
4618            nonce: None,
4619            oidc_ext: Default::default(),
4620            max_age: None,
4621            ui_locales: Default::default(),
4622            prompt: Default::default(),
4623            unknown_keys: Default::default(),
4624        };
4625
4626        assert!(
4627            idms_prox_read
4628                .check_oauth2_authorisation(Some(&anon_ident), &auth_req, &auth_req_ctx, ct)
4629                .unwrap_err()
4630                == Oauth2Error::AccessDenied
4631        );
4632    }
4633
4634    #[idm_test]
4635    async fn test_idm_oauth2_invalid_authorisation_permit_requests(
4636        idms: &IdmServer,
4637        _idms_delayed: &mut IdmServerDelayed,
4638    ) {
4639        // Test invalid OAuth2 authorisation states/requests.
4640        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4641        let (_secret, uat, ident, _) =
4642            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
4643
4644        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4645
4646        let mut uat_wrong_session_id = uat.clone();
4647        uat_wrong_session_id.session_id = uuid::Uuid::new_v4();
4648        let ident_wrong_session_id = idms_prox_write
4649            .process_uat_to_identity(&uat_wrong_session_id, ct, Source::Internal)
4650            .expect("Unable to process uat");
4651
4652        let account = idms_prox_write
4653            .target_to_account(UUID_IDM_ADMIN)
4654            .expect("account must exist");
4655        let session_id = uuid::Uuid::new_v4();
4656        let uat2 = account
4657            .to_userauthtoken(
4658                session_id,
4659                SessionScope::ReadWrite,
4660                ct,
4661                &ResolvedAccountPolicy::test_policy(),
4662            )
4663            .expect("Unable to create uat");
4664        let ident2 = idms_prox_write
4665            .process_uat_to_identity(&uat2, ct, Source::Internal)
4666            .expect("Unable to process uat");
4667
4668        assert!(idms_prox_write.commit().is_ok());
4669
4670        // Now start the test
4671
4672        let idms_prox_read = idms.proxy_read().await.unwrap();
4673
4674        let pkce_secret = PkceS256Secret::default();
4675
4676        let consent_request = good_authorisation_request!(
4677            idms_prox_read,
4678            &ident,
4679            ct,
4680            pkce_secret.to_request(),
4681            OAUTH2_SCOPE_OPENID.to_string()
4682        );
4683
4684        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
4685            unreachable!();
4686        };
4687
4688        drop(idms_prox_read);
4689        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4690
4691        // Invalid permits
4692        //  * expired token, aka past ttl.
4693        assert!(
4694            idms_prox_write
4695                .check_oauth2_authorise_permit(
4696                    &ident,
4697                    &consent_token,
4698                    ct + Duration::from_secs(TOKEN_EXPIRE),
4699                )
4700                .unwrap_err()
4701                == OperationError::CryptographyError
4702        );
4703
4704        //  * incorrect ident
4705        // We get another uat, but for a different user, and we'll introduce these
4706        // inconsistently to cause confusion.
4707
4708        assert!(
4709            idms_prox_write
4710                .check_oauth2_authorise_permit(&ident2, &consent_token, ct,)
4711                .unwrap_err()
4712                == OperationError::InvalidSessionState
4713        );
4714
4715        //  * incorrect session id
4716        assert!(
4717            idms_prox_write
4718                .check_oauth2_authorise_permit(&ident_wrong_session_id, &consent_token, ct,)
4719                .unwrap_err()
4720                == OperationError::InvalidSessionState
4721        );
4722
4723        assert!(idms_prox_write.commit().is_ok());
4724    }
4725
4726    #[idm_test]
4727    async fn test_idm_oauth2_invalid_token_exchange_requests(
4728        idms: &IdmServer,
4729        _idms_delayed: &mut IdmServerDelayed,
4730    ) {
4731        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4732        let (secret, mut uat, ident, _) =
4733            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
4734
4735        // ⚠️  We set the uat expiry time to 5 seconds from TEST_CURRENT_TIME. This
4736        // allows all our other tests to pass, but it means when we specifically put the
4737        // clock forward a fraction, the fernet tokens are still valid, but the uat
4738        // is not.
4739        // IE
4740        //   |---------------------|------------------|
4741        //   TEST_CURRENT_TIME     UAT_EXPIRE         TOKEN_EXPIRE
4742        //
4743        // This lets us check a variety of time based cases.
4744        uat.expiry = Some(
4745            time::OffsetDateTime::UNIX_EPOCH
4746                + Duration::from_secs(TEST_CURRENT_TIME + UAT_EXPIRE - 1),
4747        );
4748
4749        let idms_prox_read = idms.proxy_read().await.unwrap();
4750
4751        // == Setup the authorisation request
4752        let pkce_secret = PkceS256Secret::default();
4753
4754        let consent_request = good_authorisation_request!(
4755            idms_prox_read,
4756            &ident,
4757            ct,
4758            pkce_secret.to_request(),
4759            OAUTH2_SCOPE_OPENID.to_string()
4760        );
4761
4762        let code_verifier = Some(pkce_secret.to_verifier());
4763
4764        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
4765            unreachable!();
4766        };
4767
4768        drop(idms_prox_read);
4769        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4770
4771        // == Manually submit the consent token to the permit for the permit_success
4772        let permit_success = idms_prox_write
4773            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
4774            .expect("Failed to perform OAuth2 permit");
4775
4776        // == Submit the token exchange code.
4777
4778        // Invalid token exchange
4779        //  * invalid client_authz (not base64)
4780        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
4781            code: permit_success.code.clone(),
4782            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4783            code_verifier: code_verifier.clone(),
4784        }
4785        .into();
4786
4787        let client_authz = ClientAuthInfo::from("not base64");
4788
4789        assert!(
4790            idms_prox_write
4791                .check_oauth2_token_exchange(&client_authz, &token_req, ct)
4792                .unwrap_err()
4793                == Oauth2Error::AuthenticationRequired
4794        );
4795
4796        //  * doesn't have ':'
4797        let client_authz =
4798            general_purpose::STANDARD.encode(format!("test_resource_server {secret}"));
4799        let client_authz = ClientAuthInfo::from(client_authz.as_str());
4800
4801        assert!(
4802            idms_prox_write
4803                .check_oauth2_token_exchange(&client_authz, &token_req, ct)
4804                .unwrap_err()
4805                == Oauth2Error::AuthenticationRequired
4806        );
4807
4808        //  * invalid client_id
4809        let client_authz = ClientAuthInfo::encode_basic("NOT A REAL SERVER", secret.as_str());
4810
4811        assert!(
4812            idms_prox_write
4813                .check_oauth2_token_exchange(&client_authz, &token_req, ct)
4814                .unwrap_err()
4815                == Oauth2Error::AuthenticationRequired
4816        );
4817
4818        //  * valid client_id, but invalid secret
4819        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", "12345");
4820
4821        assert!(
4822            idms_prox_write
4823                .check_oauth2_token_exchange(&client_authz, &token_req, ct)
4824                .unwrap_err()
4825                == Oauth2Error::AuthenticationRequired
4826        );
4827
4828        // ✅ Now the valid client_authz is in place.
4829        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
4830
4831        //  * expired exchange code (took too long)
4832        assert!(
4833            idms_prox_write
4834                .check_oauth2_token_exchange(
4835                    &client_authz,
4836                    &token_req,
4837                    ct + Duration::from_secs(TOKEN_EXPIRE)
4838                )
4839                .unwrap_err()
4840                == Oauth2Error::InvalidRequest
4841        );
4842
4843        /*
4844        //  * incorrect grant_type
4845        // No longer possible due to changes in json api
4846        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
4847            grant_type: "INCORRECT GRANT TYPE".to_string(),
4848            code: permit_success.code.clone(),
4849            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4850            client_id: None,
4851            client_secret: None,
4852            code_verifier: code_verifier.clone(),
4853        };
4854        assert!(
4855            idms_prox_read
4856                .check_oauth2_token_exchange(client_authz.as_deref(), &token_req, ct)
4857                .unwrap_err()
4858                == Oauth2Error::InvalidRequest
4859        );
4860        */
4861
4862        //  * Incorrect redirect uri
4863        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
4864            code: permit_success.code.clone(),
4865            redirect_uri: Url::parse("https://totes.not.sus.org/oauth2/result").unwrap(),
4866            code_verifier: code_verifier.clone(),
4867        }
4868        .into();
4869        assert!(
4870            idms_prox_write
4871                .check_oauth2_token_exchange(&client_authz, &token_req, ct)
4872                .unwrap_err()
4873                == Oauth2Error::InvalidOrigin
4874        );
4875
4876        //  * code verifier incorrect
4877        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
4878            code: permit_success.code,
4879            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
4880            code_verifier: Some("12345".to_string()),
4881        }
4882        .into();
4883        assert!(
4884            idms_prox_write
4885                .check_oauth2_token_exchange(&client_authz, &token_req, ct)
4886                .unwrap_err()
4887                == Oauth2Error::InvalidRequest
4888        );
4889
4890        assert!(idms_prox_write.commit().is_ok());
4891    }
4892
4893    #[idm_test]
4894    async fn test_idm_oauth2_supplemental_origin_redirect(
4895        idms: &IdmServer,
4896        _idms_delayed: &mut IdmServerDelayed,
4897    ) {
4898        let ct = Duration::from_secs(TEST_CURRENT_TIME);
4899        let (secret, uat, ident, _) =
4900            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
4901
4902        let idms_prox_read = idms.proxy_read().await.unwrap();
4903
4904        // == Setup the authorisation request
4905        let pkce_secret = PkceS256Secret::default();
4906
4907        let redirect_uri = Url::parse("https://portal.example.com/?custom=foo").unwrap();
4908
4909        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
4910
4911        let auth_req = AuthorisationRequest {
4912            response_type: ResponseType::Code,
4913            response_mode: None,
4914            client_id: "test_resource_server".to_string(),
4915            state: None,
4916            pkce_request: Some(pkce_secret.to_request()),
4917            redirect_uri: redirect_uri.clone(),
4918            scope: btreeset![OAUTH2_SCOPE_GROUPS.to_string()],
4919            nonce: Some("abcdef".to_string()),
4920            oidc_ext: Default::default(),
4921            max_age: None,
4922            ui_locales: Default::default(),
4923            prompt: Default::default(),
4924            unknown_keys: Default::default(),
4925        };
4926
4927        let consent_request = idms_prox_read
4928            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
4929            .expect("OAuth2 authorisation failed");
4930
4931        trace!(?consent_request);
4932
4933        // Should be in the consent phase;
4934        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
4935            unreachable!();
4936        };
4937
4938        // == Manually submit the consent token to the permit for the permit_success
4939        drop(idms_prox_read);
4940        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
4941
4942        let permit_success = idms_prox_write
4943            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
4944            .expect("Failed to perform OAuth2 permit");
4945
4946        // Check we are reflecting the CSRF properly.
4947        assert_eq!(permit_success.state.as_deref(), None);
4948
4949        // Assert we followed the redirect uri including the query elements
4950        // we have in the url.
4951        let permit_redirect_uri = permit_success.build_redirect_uri();
4952
4953        assert_eq!(permit_redirect_uri.origin(), redirect_uri.origin());
4954        assert_eq!(permit_redirect_uri.path(), redirect_uri.path());
4955        let query = BTreeMap::from_iter(permit_redirect_uri.query_pairs().into_owned());
4956        // Assert the query pair wasn't changed
4957        assert_eq!(query.get("custom").map(|s| s.as_str()), Some("foo"));
4958
4959        // == Submit the token exchange code.
4960        // ⚠️  This is where we submit a different origin!
4961        let token_req = AccessTokenRequest {
4962            grant_type: GrantTypeReq::AuthorizationCode {
4963                code: permit_success.code,
4964                redirect_uri,
4965                code_verifier: Some(pkce_secret.to_verifier()),
4966            },
4967
4968            client_post_auth: ClientPostAuth {
4969                client_id: Some("test_resource_server".to_string()),
4970                client_secret: Some(secret.clone()),
4971            },
4972        };
4973
4974        let token_response = idms_prox_write
4975            .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
4976            .expect("Failed to perform OAuth2 token exchange");
4977
4978        // 🎉 We got a token! In the future we can then check introspection from this point.
4979        assert_eq!(token_response.token_type, AccessTokenType::Bearer);
4980
4981        assert!(idms_prox_write.commit().is_ok());
4982
4983        // ============================================================================
4984        // Now repeat the test with the app url.
4985
4986        let mut idms_prox_read = idms.proxy_read().await.unwrap();
4987
4988        // Reload the ident since it pins an entry in memory.
4989        let ident = idms_prox_read
4990            .process_uat_to_identity(&uat, ct, Source::Internal)
4991            .expect("Unable to process uat");
4992
4993        let pkce_secret = PkceS256Secret::default();
4994
4995        let auth_req = AuthorisationRequest {
4996            response_type: ResponseType::Code,
4997            response_mode: None,
4998            client_id: "test_resource_server".to_string(),
4999            state: Some("123".to_string()),
5000            pkce_request: Some(pkce_secret.to_request()),
5001            redirect_uri: Url::parse("app://cheese").unwrap(),
5002            scope: btreeset![OAUTH2_SCOPE_GROUPS.to_string()],
5003            nonce: Some("abcdef".to_string()),
5004            oidc_ext: Default::default(),
5005            max_age: None,
5006            ui_locales: Default::default(),
5007            prompt: Default::default(),
5008            unknown_keys: Default::default(),
5009        };
5010
5011        let consent_request = idms_prox_read
5012            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
5013            .expect("OAuth2 authorisation failed");
5014
5015        trace!(?consent_request);
5016
5017        let AuthoriseResponse::Permitted(permit_success) = consent_request else {
5018            unreachable!();
5019        };
5020
5021        // == Manually submit the consent token to the permit for the permit_success
5022        // Check we are reflecting the CSRF properly.
5023        assert_eq!(permit_success.state.as_deref(), Some("123"));
5024
5025        // == Submit the token exchange code.
5026        // ⚠️  This is where we submit a different origin!
5027        let token_req = AccessTokenRequest {
5028            grant_type: GrantTypeReq::AuthorizationCode {
5029                code: permit_success.code,
5030                redirect_uri: Url::parse("app://cheese").unwrap(),
5031                code_verifier: Some(pkce_secret.to_verifier()),
5032            },
5033
5034            client_post_auth: ClientPostAuth {
5035                client_id: Some("test_resource_server".to_string()),
5036                client_secret: Some(secret),
5037            },
5038        };
5039
5040        drop(idms_prox_read);
5041        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5042
5043        let token_response = idms_prox_write
5044            .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
5045            .expect("Failed to perform OAuth2 token exchange");
5046
5047        // 🎉 We got a token! In the future we can then check introspection from this point.
5048        assert_eq!(token_response.token_type, AccessTokenType::Bearer);
5049    }
5050
5051    #[idm_test]
5052    async fn test_idm_oauth2_token_introspect(
5053        idms: &IdmServer,
5054        _idms_delayed: &mut IdmServerDelayed,
5055    ) {
5056        let ct = Duration::from_secs(TEST_CURRENT_TIME);
5057        let (secret, _uat, ident, _) =
5058            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
5059        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
5060
5061        let idms_prox_read = idms.proxy_read().await.unwrap();
5062
5063        // == Setup the authorisation request
5064        let pkce_secret = PkceS256Secret::default();
5065        let consent_request = good_authorisation_request!(
5066            idms_prox_read,
5067            &ident,
5068            ct,
5069            pkce_secret.to_request(),
5070            OAUTH2_SCOPE_OPENID.to_string()
5071        );
5072
5073        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
5074            unreachable!();
5075        };
5076
5077        // == Manually submit the consent token to the permit for the permit_success
5078        drop(idms_prox_read);
5079        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5080
5081        let permit_success = idms_prox_write
5082            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
5083            .expect("Failed to perform OAuth2 permit");
5084
5085        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
5086            code: permit_success.code,
5087            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
5088            code_verifier: Some(pkce_secret.to_verifier()),
5089        }
5090        .into();
5091        let oauth2_token = idms_prox_write
5092            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
5093            .expect("Unable to exchange for OAuth2 token");
5094
5095        assert!(idms_prox_write.commit().is_ok());
5096
5097        // Okay, now we have the token, we can check it works with introspect.
5098        let mut idms_prox_read = idms.proxy_read().await.unwrap();
5099
5100        let intr_request = AccessTokenIntrospectRequest {
5101            token: oauth2_token.access_token,
5102            token_type_hint: None,
5103            client_post_auth: ClientPostAuth::default(),
5104        };
5105        let intr_response = idms_prox_read
5106            .check_oauth2_token_introspect(&intr_request, ct)
5107            .expect("Failed to inspect token");
5108
5109        eprintln!("👉  {intr_response:?}");
5110        assert!(intr_response.active);
5111        assert_eq!(
5112            intr_response.scope,
5113            btreeset!["openid".to_string(), "supplement".to_string()]
5114        );
5115        assert_eq!(
5116            intr_response.client_id.as_deref(),
5117            Some("test_resource_server")
5118        );
5119        assert_eq!(
5120            intr_response.username.as_deref(),
5121            Some("testperson1@example.com")
5122        );
5123        assert_eq!(intr_response.token_type, Some(AccessTokenType::Bearer));
5124        assert_eq!(intr_response.iat, Some(ct.as_secs() as i64));
5125        assert_eq!(intr_response.nbf, Some(ct.as_secs() as i64));
5126
5127        drop(idms_prox_read);
5128        // start a write,
5129
5130        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5131        // Expire the account, should cause introspect to return inactive.
5132        let v_expire = Value::new_datetime_epoch(Duration::from_secs(TEST_CURRENT_TIME - 1));
5133        let me_inv_m = ModifyEvent::new_internal_invalid(
5134            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_TESTPERSON_1))),
5135            ModifyList::new_list(vec![Modify::Present(Attribute::AccountExpire, v_expire)]),
5136        );
5137        // go!
5138        assert!(idms_prox_write.qs_write.modify(&me_inv_m).is_ok());
5139        assert!(idms_prox_write.commit().is_ok());
5140
5141        // start a new read
5142        // check again.
5143        let mut idms_prox_read = idms.proxy_read().await.unwrap();
5144        let intr_response = idms_prox_read
5145            .check_oauth2_token_introspect(&intr_request, ct)
5146            .expect("Failed to inspect token");
5147
5148        assert!(!intr_response.active);
5149    }
5150
5151    #[idm_test]
5152    async fn test_idm_oauth2_token_revoke(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
5153        // First, setup to get a token.
5154        let ct = Duration::from_secs(TEST_CURRENT_TIME);
5155        let (secret, _uat, ident, _) =
5156            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
5157        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
5158
5159        let idms_prox_read = idms.proxy_read().await.unwrap();
5160
5161        // == Setup the authorisation request
5162        let pkce_secret = PkceS256Secret::default();
5163
5164        let consent_request = good_authorisation_request!(
5165            idms_prox_read,
5166            &ident,
5167            ct,
5168            pkce_secret.to_request(),
5169            OAUTH2_SCOPE_OPENID.to_string()
5170        );
5171
5172        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
5173            unreachable!();
5174        };
5175
5176        // == Manually submit the consent token to the permit for the permit_success
5177        drop(idms_prox_read);
5178        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5179
5180        let permit_success = idms_prox_write
5181            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
5182            .expect("Failed to perform OAuth2 permit");
5183
5184        // Assert that the consent was submitted
5185        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
5186            code: permit_success.code,
5187            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
5188            code_verifier: Some(pkce_secret.to_verifier()),
5189        }
5190        .into();
5191        let oauth2_token = idms_prox_write
5192            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
5193            .expect("Unable to exchange for OAuth2 token");
5194
5195        assert!(idms_prox_write.commit().is_ok());
5196
5197        // Okay, now we have the token, we can check behaviours with the revoke interface.
5198
5199        // First, assert it is valid, similar to the introspect api.
5200        let mut idms_prox_read = idms.proxy_read().await.unwrap();
5201        let intr_request = AccessTokenIntrospectRequest {
5202            token: oauth2_token.access_token.clone(),
5203            token_type_hint: None,
5204            client_post_auth: ClientPostAuth::default(),
5205        };
5206        let intr_response = idms_prox_read
5207            .check_oauth2_token_introspect(&intr_request, ct)
5208            .expect("Failed to inspect token");
5209        eprintln!("👉  {intr_response:?}");
5210        assert!(intr_response.active);
5211        drop(idms_prox_read);
5212
5213        // Now submit a non-existent/invalid token. Considered a failure to authenticate
5214        // as the token wasn't valid.
5215        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5216        let revoke_request = TokenRevokeRequest {
5217            token: "this is an invalid token, nothing will happen!".to_string(),
5218            token_type_hint: None,
5219            client_post_auth: ClientPostAuth::default(),
5220        };
5221        let e = idms_prox_write
5222            .oauth2_token_revoke(&revoke_request, ct)
5223            .unwrap_err();
5224        assert!(matches!(e, Oauth2Error::AuthenticationRequired));
5225        assert!(idms_prox_write.commit().is_ok());
5226
5227        // Check our token is still valid.
5228        let mut idms_prox_read = idms.proxy_read().await.unwrap();
5229        let intr_response = idms_prox_read
5230            .check_oauth2_token_introspect(&intr_request, ct)
5231            .expect("Failed to inspect token");
5232        assert!(intr_response.active);
5233        drop(idms_prox_read);
5234
5235        // Finally revoke it.
5236        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5237        let revoke_request = TokenRevokeRequest {
5238            token: oauth2_token.access_token.clone(),
5239            token_type_hint: None,
5240            client_post_auth: ClientPostAuth::default(),
5241        };
5242        assert!(idms_prox_write
5243            .oauth2_token_revoke(&revoke_request, ct,)
5244            .is_ok());
5245        assert!(idms_prox_write.commit().is_ok());
5246
5247        // Assert it is now invalid.
5248        let mut idms_prox_read = idms.proxy_read().await.unwrap();
5249        let intr_response = idms_prox_read
5250            .check_oauth2_token_introspect(&intr_request, ct)
5251            .expect("Failed to inspect token");
5252
5253        assert!(!intr_response.active);
5254        drop(idms_prox_read);
5255
5256        // Force trim the session and wait for the grace window to pass. The token will be invalidated
5257        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5258        let filt = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(ident.get_uuid())));
5259        let mut work_set = idms_prox_write
5260            .qs_write
5261            .internal_search_writeable(&filt)
5262            .expect("Failed to perform internal search writeable");
5263        for (_, entry) in work_set.iter_mut() {
5264            let _ = entry.force_trim_ava(Attribute::OAuth2Session);
5265        }
5266        assert!(idms_prox_write
5267            .qs_write
5268            .internal_apply_writable(work_set)
5269            .is_ok());
5270
5271        assert!(idms_prox_write.commit().is_ok());
5272
5273        let mut idms_prox_read = idms.proxy_read().await.unwrap();
5274        // Grace window in effect.
5275        let intr_response = idms_prox_read
5276            .check_oauth2_token_introspect(&intr_request, ct)
5277            .expect("Failed to inspect token");
5278        assert!(intr_response.active);
5279
5280        // Grace window passed, it will now be invalid.
5281        let ct = ct + AUTH_TOKEN_GRACE_WINDOW;
5282        let intr_response = idms_prox_read
5283            .check_oauth2_token_introspect(&intr_request, ct)
5284            .expect("Failed to inspect token");
5285        assert!(!intr_response.active);
5286
5287        drop(idms_prox_read);
5288
5289        // A second invalidation of the token "does nothing".
5290        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5291        let revoke_request = TokenRevokeRequest {
5292            token: oauth2_token.access_token,
5293            token_type_hint: None,
5294            client_post_auth: ClientPostAuth::default(),
5295        };
5296        assert!(idms_prox_write
5297            .oauth2_token_revoke(&revoke_request, ct,)
5298            .is_ok());
5299        assert!(idms_prox_write.commit().is_ok());
5300    }
5301
5302    #[idm_test]
5303    async fn test_idm_oauth2_session_cleanup_post_rs_delete(
5304        idms: &IdmServer,
5305        _idms_delayed: &mut IdmServerDelayed,
5306    ) {
5307        // First, setup to get a token.
5308        let ct = Duration::from_secs(TEST_CURRENT_TIME);
5309        let (secret, _uat, ident, _) =
5310            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
5311        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
5312
5313        let idms_prox_read = idms.proxy_read().await.unwrap();
5314
5315        // == Setup the authorisation request
5316        let pkce_secret = PkceS256Secret::default();
5317
5318        let consent_request = good_authorisation_request!(
5319            idms_prox_read,
5320            &ident,
5321            ct,
5322            pkce_secret.to_request(),
5323            OAUTH2_SCOPE_OPENID.to_string()
5324        );
5325
5326        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
5327            unreachable!();
5328        };
5329
5330        // == Manually submit the consent token to the permit for the permit_success
5331        drop(idms_prox_read);
5332        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5333
5334        let permit_success = idms_prox_write
5335            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
5336            .expect("Failed to perform OAuth2 permit");
5337
5338        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
5339            code: permit_success.code,
5340            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
5341            code_verifier: Some(pkce_secret.to_verifier()),
5342        }
5343        .into();
5344
5345        let oauth2_token = idms_prox_write
5346            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
5347            .expect("Unable to exchange for OAuth2 token");
5348
5349        let access_token =
5350            JwsCompact::from_str(&oauth2_token.access_token).expect("Invalid Access Token");
5351
5352        let jws_verifier = JwsDangerReleaseWithoutVerify::default();
5353
5354        let reflected_token = jws_verifier
5355            .verify(&access_token)
5356            .unwrap()
5357            .from_json::<OAuth2RFC9068Token<OAuth2RFC9068TokenExtensions>>()
5358            .expect("Failed to access internals of the refresh token");
5359
5360        let session_id = reflected_token.extensions.session_id;
5361
5362        assert!(idms_prox_write.commit().is_ok());
5363
5364        // Process it to ensure the record exists.
5365        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5366
5367        // Check it is now there
5368        let entry = idms_prox_write
5369            .qs_write
5370            .internal_search_uuid(UUID_TESTPERSON_1)
5371            .expect("failed");
5372        let valid = entry
5373            .get_ava_as_oauth2session_map(Attribute::OAuth2Session)
5374            .map(|map| map.get(&session_id).is_some())
5375            .unwrap_or(false);
5376        assert!(valid);
5377
5378        // Delete the resource server.
5379
5380        let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
5381            Attribute::Name,
5382            PartialValue::new_iname("test_resource_server")
5383        )));
5384
5385        assert!(idms_prox_write.qs_write.delete(&de).is_ok());
5386
5387        // Assert the session is revoked. This is cleaned up as an artifact of the referential
5388        // integrity plugin. Remember, refint doesn't consider revoked sessions once they are
5389        // revoked.
5390        let entry = idms_prox_write
5391            .qs_write
5392            .internal_search_uuid(UUID_TESTPERSON_1)
5393            .expect("failed");
5394        let revoked = entry
5395            .get_ava_as_oauth2session_map(Attribute::OAuth2Session)
5396            .and_then(|sessions| sessions.get(&session_id))
5397            .map(|session| matches!(session.state, SessionState::RevokedAt(_)))
5398            .unwrap_or(false);
5399        assert!(revoked);
5400
5401        assert!(idms_prox_write.commit().is_ok());
5402    }
5403
5404    #[idm_test]
5405    async fn test_idm_oauth2_authorisation_reject(
5406        idms: &IdmServer,
5407        _idms_delayed: &mut IdmServerDelayed,
5408    ) {
5409        let ct = Duration::from_secs(TEST_CURRENT_TIME);
5410        let (_secret, _uat, ident, _) =
5411            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
5412
5413        let ident2 = {
5414            let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5415            let account = idms_prox_write
5416                .target_to_account(UUID_IDM_ADMIN)
5417                .expect("account must exist");
5418            let session_id = uuid::Uuid::new_v4();
5419            let uat2 = account
5420                .to_userauthtoken(
5421                    session_id,
5422                    SessionScope::ReadWrite,
5423                    ct,
5424                    &ResolvedAccountPolicy::test_policy(),
5425                )
5426                .expect("Unable to create uat");
5427
5428            idms_prox_write
5429                .process_uat_to_identity(&uat2, ct, Source::Internal)
5430                .expect("Unable to process uat")
5431        };
5432
5433        let idms_prox_read = idms.proxy_read().await.unwrap();
5434        let redirect_uri = Url::parse("https://demo.example.com/oauth2/result").unwrap();
5435
5436        let pkce_secret = PkceS256Secret::default();
5437
5438        // Check reject behaviour
5439        let consent_request = good_authorisation_request!(
5440            idms_prox_read,
5441            &ident,
5442            ct,
5443            pkce_secret.to_request(),
5444            OAUTH2_SCOPE_OPENID.to_string()
5445        );
5446
5447        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
5448            unreachable!();
5449        };
5450
5451        let reject_success = idms_prox_read
5452            .check_oauth2_authorise_reject(&ident, &consent_token, ct)
5453            .expect("Failed to perform OAuth2 reject");
5454
5455        assert_eq!(reject_success.redirect_uri, redirect_uri);
5456
5457        // Too much time past to reject
5458        let past_ct = Duration::from_secs(TEST_CURRENT_TIME + 301);
5459        assert!(
5460            idms_prox_read
5461                .check_oauth2_authorise_reject(&ident, &consent_token, past_ct)
5462                .unwrap_err()
5463                == OperationError::CryptographyError
5464        );
5465
5466        // Invalid consent token
5467        assert_eq!(
5468            idms_prox_read
5469                .check_oauth2_authorise_reject(&ident, "not a token", ct)
5470                .unwrap_err(),
5471            OperationError::CryptographyError
5472        );
5473
5474        // Wrong ident
5475        assert!(
5476            idms_prox_read
5477                .check_oauth2_authorise_reject(&ident2, &consent_token, ct)
5478                .unwrap_err()
5479                == OperationError::InvalidSessionState
5480        );
5481    }
5482
5483    #[idm_test]
5484    async fn test_idm_oauth2_rfc8414_metadata(
5485        idms: &IdmServer,
5486        _idms_delayed: &mut IdmServerDelayed,
5487    ) {
5488        let ct = Duration::from_secs(TEST_CURRENT_TIME);
5489        let (_secret, _uat, _ident, _) =
5490            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
5491
5492        let idms_prox_read = idms.proxy_read().await.unwrap();
5493
5494        // check the discovery end point works as we expect
5495        assert!(
5496            idms_prox_read
5497                .oauth2_rfc8414_metadata("nosuchclient")
5498                .unwrap_err()
5499                == OperationError::NoMatchingEntries
5500        );
5501
5502        let discovery = idms_prox_read
5503            .oauth2_rfc8414_metadata("test_resource_server")
5504            .expect("Failed to get discovery");
5505
5506        assert!(
5507            discovery.issuer
5508                == Url::parse("https://idm.example.com/oauth2/openid/test_resource_server")
5509                    .unwrap()
5510        );
5511
5512        assert!(
5513            discovery.authorization_endpoint
5514                == Url::parse("https://idm.example.com/ui/oauth2").unwrap()
5515        );
5516
5517        assert!(
5518            discovery.token_endpoint
5519                == Url::parse(&format!(
5520                    "https://idm.example.com{}",
5521                    uri::OAUTH2_TOKEN_ENDPOINT
5522                ))
5523                .unwrap()
5524        );
5525
5526        assert!(
5527            discovery.jwks_uri
5528                == Some(
5529                    Url::parse(
5530                        "https://idm.example.com/oauth2/openid/test_resource_server/public_key.jwk"
5531                    )
5532                    .unwrap()
5533                )
5534        );
5535
5536        assert!(discovery.registration_endpoint.is_none());
5537
5538        assert!(
5539            discovery.scopes_supported
5540                == Some(vec![
5541                    OAUTH2_SCOPE_GROUPS.to_string(),
5542                    OAUTH2_SCOPE_OPENID.to_string(),
5543                    OAUTH2_SCOPE_PROFILE.to_string(),
5544                    "supplement".to_string(),
5545                ])
5546        );
5547
5548        assert_eq!(discovery.response_types_supported, vec![ResponseType::Code]);
5549        assert_eq!(
5550            discovery.response_modes_supported,
5551            vec![ResponseMode::Query, ResponseMode::Fragment]
5552        );
5553        assert_eq!(
5554            discovery.grant_types_supported,
5555            vec![
5556                GrantType::AuthorisationCode,
5557                GrantType::TokenExchange,
5558                GrantType::RefreshToken
5559            ]
5560        );
5561        assert!(
5562            discovery.token_endpoint_auth_methods_supported
5563                == vec![
5564                    EndpointAuthMethod::ClientSecretBasic,
5565                    EndpointAuthMethod::ClientSecretPost
5566                ]
5567        );
5568        assert!(discovery.service_documentation.is_some());
5569
5570        assert!(discovery.ui_locales_supported.is_none());
5571        assert!(discovery.op_policy_uri.is_none());
5572        assert!(discovery.op_tos_uri.is_none());
5573
5574        assert!(
5575            discovery.revocation_endpoint
5576                == Some(
5577                    Url::parse(&format!(
5578                        "https://idm.example.com{OAUTH2_TOKEN_REVOKE_ENDPOINT}"
5579                    ))
5580                    .unwrap()
5581                )
5582        );
5583        assert!(
5584            discovery.revocation_endpoint_auth_methods_supported == vec![EndpointAuthMethod::None,]
5585        );
5586
5587        assert!(
5588            discovery.introspection_endpoint
5589                == Some(
5590                    Url::parse(&format!(
5591                        "https://idm.example.com{}",
5592                        kanidm_proto::constants::uri::OAUTH2_TOKEN_INTROSPECT_ENDPOINT
5593                    ))
5594                    .unwrap()
5595                )
5596        );
5597        assert!(
5598            discovery.introspection_endpoint_auth_methods_supported
5599                == vec![EndpointAuthMethod::None,]
5600        );
5601        assert!(discovery
5602            .introspection_endpoint_auth_signing_alg_values_supported
5603            .is_none());
5604
5605        assert_eq!(
5606            discovery.code_challenge_methods_supported,
5607            vec![PkceAlg::S256]
5608        )
5609    }
5610
5611    #[idm_test]
5612    async fn test_idm_oauth2_openid_discovery(
5613        idms: &IdmServer,
5614        _idms_delayed: &mut IdmServerDelayed,
5615    ) {
5616        let ct = Duration::from_secs(TEST_CURRENT_TIME);
5617        let (_secret, _uat, _ident, _) =
5618            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
5619
5620        let idms_prox_read = idms.proxy_read().await.unwrap();
5621
5622        // check the discovery end point works as we expect
5623        assert!(
5624            idms_prox_read
5625                .oauth2_openid_discovery("nosuchclient")
5626                .unwrap_err()
5627                == OperationError::NoMatchingEntries
5628        );
5629
5630        assert!(
5631            idms_prox_read
5632                .oauth2_openid_publickey("nosuchclient")
5633                .unwrap_err()
5634                == OperationError::NoMatchingEntries
5635        );
5636
5637        let discovery = idms_prox_read
5638            .oauth2_openid_discovery("test_resource_server")
5639            .expect("Failed to get discovery");
5640
5641        let mut jwkset = idms_prox_read
5642            .oauth2_openid_publickey("test_resource_server")
5643            .expect("Failed to get public key");
5644
5645        let jwk = jwkset.keys.pop().expect("no such jwk");
5646
5647        match jwk {
5648            Jwk::EC { alg, use_, kid, .. } => {
5649                match (
5650                    alg.unwrap(),
5651                    &discovery.id_token_signing_alg_values_supported[0],
5652                ) {
5653                    (JwaAlg::ES256, IdTokenSignAlg::ES256) => {}
5654                    _ => panic!(),
5655                };
5656                assert_eq!(use_.unwrap(), JwkUse::Sig);
5657                assert!(kid.is_some())
5658            }
5659            _ => panic!(),
5660        };
5661
5662        assert!(
5663            discovery.issuer
5664                == Url::parse("https://idm.example.com/oauth2/openid/test_resource_server")
5665                    .unwrap()
5666        );
5667
5668        assert!(
5669            discovery.authorization_endpoint
5670                == Url::parse("https://idm.example.com/ui/oauth2").unwrap()
5671        );
5672
5673        assert!(
5674            discovery.token_endpoint == Url::parse("https://idm.example.com/oauth2/token").unwrap()
5675        );
5676
5677        assert!(
5678            discovery.userinfo_endpoint
5679                == Some(
5680                    Url::parse(
5681                        "https://idm.example.com/oauth2/openid/test_resource_server/userinfo"
5682                    )
5683                    .unwrap()
5684                )
5685        );
5686
5687        assert!(
5688            discovery.jwks_uri
5689                == Url::parse(
5690                    "https://idm.example.com/oauth2/openid/test_resource_server/public_key.jwk"
5691                )
5692                .unwrap()
5693        );
5694
5695        assert!(
5696            discovery.scopes_supported
5697                == Some(vec![
5698                    OAUTH2_SCOPE_GROUPS.to_string(),
5699                    OAUTH2_SCOPE_OPENID.to_string(),
5700                    OAUTH2_SCOPE_PROFILE.to_string(),
5701                    "supplement".to_string(),
5702                ])
5703        );
5704
5705        assert_eq!(discovery.response_types_supported, vec![ResponseType::Code]);
5706        assert_eq!(
5707            discovery.response_modes_supported,
5708            vec![ResponseMode::Query, ResponseMode::Fragment]
5709        );
5710        assert_eq!(
5711            discovery.grant_types_supported,
5712            vec![
5713                GrantType::AuthorisationCode,
5714                GrantType::TokenExchange,
5715                GrantType::RefreshToken
5716            ]
5717        );
5718        assert_eq!(discovery.subject_types_supported, vec![SubjectType::Public]);
5719        assert_eq!(
5720            discovery.id_token_signing_alg_values_supported,
5721            vec![IdTokenSignAlg::ES256]
5722        );
5723        assert!(discovery.userinfo_signing_alg_values_supported.is_none());
5724        assert!(
5725            discovery.token_endpoint_auth_methods_supported
5726                == vec![
5727                    EndpointAuthMethod::ClientSecretBasic,
5728                    EndpointAuthMethod::ClientSecretPost
5729                ]
5730        );
5731        assert_eq!(
5732            discovery.display_values_supported,
5733            Some(vec![DisplayValue::Page])
5734        );
5735        assert_eq!(discovery.claim_types_supported, vec![ClaimType::Normal]);
5736        assert!(discovery.claims_supported.is_none());
5737        assert!(discovery.service_documentation.is_some());
5738
5739        assert!(discovery.registration_endpoint.is_none());
5740        assert!(discovery.acr_values_supported.is_none());
5741        assert!(discovery.id_token_encryption_alg_values_supported.is_none());
5742        assert!(discovery.id_token_encryption_enc_values_supported.is_none());
5743        assert!(discovery.userinfo_encryption_alg_values_supported.is_none());
5744        assert!(discovery.userinfo_encryption_enc_values_supported.is_none());
5745        assert!(discovery
5746            .request_object_signing_alg_values_supported
5747            .is_none());
5748        assert!(discovery
5749            .request_object_encryption_alg_values_supported
5750            .is_none());
5751        assert!(discovery
5752            .request_object_encryption_enc_values_supported
5753            .is_none());
5754        assert!(discovery
5755            .token_endpoint_auth_signing_alg_values_supported
5756            .is_none());
5757        assert!(discovery.claims_locales_supported.is_none());
5758        assert!(discovery.ui_locales_supported.is_none());
5759        assert!(discovery.op_policy_uri.is_none());
5760        assert!(discovery.op_tos_uri.is_none());
5761        assert!(!discovery.claims_parameter_supported);
5762        assert!(!discovery.request_uri_parameter_supported);
5763        assert!(!discovery.require_request_uri_registration);
5764        assert!(!discovery.request_parameter_supported);
5765        assert_eq!(
5766            discovery.code_challenge_methods_supported,
5767            vec![PkceAlg::S256]
5768        );
5769
5770        // Extensions
5771        assert!(
5772            discovery.revocation_endpoint
5773                == Some(
5774                    Url::parse(&format!(
5775                        "https://idm.example.com{OAUTH2_TOKEN_REVOKE_ENDPOINT}"
5776                    ))
5777                    .unwrap()
5778                )
5779        );
5780        assert!(
5781            discovery.revocation_endpoint_auth_methods_supported == vec![EndpointAuthMethod::None,]
5782        );
5783
5784        assert!(
5785            discovery.introspection_endpoint
5786                == Some(
5787                    Url::parse(&format!(
5788                        "https://idm.example.com{OAUTH2_TOKEN_INTROSPECT_ENDPOINT}"
5789                    ))
5790                    .unwrap()
5791                )
5792        );
5793        assert!(
5794            discovery.introspection_endpoint_auth_methods_supported
5795                == vec![EndpointAuthMethod::None,]
5796        );
5797        assert!(discovery
5798            .introspection_endpoint_auth_signing_alg_values_supported
5799            .is_none());
5800    }
5801
5802    #[idm_test]
5803    async fn test_idm_oauth2_openid_extensions(
5804        idms: &IdmServer,
5805        _idms_delayed: &mut IdmServerDelayed,
5806    ) {
5807        let ct = Duration::from_secs(TEST_CURRENT_TIME);
5808        let (secret, _uat, ident, _) =
5809            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
5810        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
5811
5812        let idms_prox_read = idms.proxy_read().await.unwrap();
5813
5814        let pkce_secret = PkceS256Secret::default();
5815
5816        let consent_request = good_authorisation_request!(
5817            idms_prox_read,
5818            &ident,
5819            ct,
5820            pkce_secret.to_request(),
5821            format!("{OAUTH2_SCOPE_OPENID} {OAUTH2_SCOPE_PROFILE}")
5822        );
5823
5824        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
5825            unreachable!();
5826        };
5827
5828        // == Manually submit the consent token to the permit for the permit_success
5829        drop(idms_prox_read);
5830        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5831
5832        let permit_success = idms_prox_write
5833            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
5834            .expect("Failed to perform OAuth2 permit");
5835
5836        // == Submit the token exchange code.
5837        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
5838            code: permit_success.code,
5839            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
5840            code_verifier: Some(pkce_secret.to_verifier()),
5841        }
5842        .into();
5843
5844        let token_response = idms_prox_write
5845            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
5846            .expect("Failed to perform OAuth2 token exchange");
5847
5848        // 🎉 We got a token!
5849        assert_eq!(token_response.token_type, AccessTokenType::Bearer);
5850
5851        let id_token = token_response.id_token.expect("No id_token in response!");
5852
5853        let access_token =
5854            JwsCompact::from_str(&token_response.access_token).expect("Invalid Access Token");
5855
5856        let refresh_token = token_response
5857            .refresh_token
5858            .as_ref()
5859            .expect("no refresh token was issued")
5860            .clone();
5861
5862        // Get the read txn for inspecting the tokens
5863        assert!(idms_prox_write.commit().is_ok());
5864
5865        let mut idms_prox_read = idms.proxy_read().await.unwrap();
5866
5867        let mut jwkset = idms_prox_read
5868            .oauth2_openid_publickey("test_resource_server")
5869            .expect("Failed to get public key");
5870
5871        let public_jwk = jwkset.keys.pop().expect("no such jwk");
5872
5873        let jws_validator =
5874            JwsEs256Verifier::try_from(&public_jwk).expect("failed to build validator");
5875
5876        let oidc_unverified =
5877            OidcUnverified::from_str(&id_token).expect("Failed to parse id_token");
5878
5879        let iat = ct.as_secs() as i64;
5880
5881        let oidc = jws_validator
5882            .verify(&oidc_unverified)
5883            .unwrap()
5884            .verify_exp(iat)
5885            .expect("Failed to verify oidc");
5886
5887        // Are the id_token values what we expect?
5888        assert!(
5889            oidc.iss
5890                == Url::parse("https://idm.example.com/oauth2/openid/test_resource_server")
5891                    .unwrap()
5892        );
5893        assert_eq!(oidc.sub, OidcSubject::U(UUID_TESTPERSON_1));
5894        assert_eq!(oidc.aud, "test_resource_server");
5895        assert_eq!(oidc.iat, iat);
5896        assert_eq!(oidc.nbf, Some(iat));
5897        // Previously this was the auth session but it's now inline with the access token expiry.
5898        assert_eq!(oidc.exp, iat + (OAUTH2_ACCESS_TOKEN_EXPIRY as i64));
5899        assert!(oidc.auth_time.is_some());
5900        // Is nonce correctly passed through?
5901        assert_eq!(oidc.nonce, Some("abcdef".to_string()));
5902        assert!(oidc.at_hash.is_none());
5903        assert!(oidc.acr.is_none());
5904        assert!(oidc.amr.is_none());
5905        assert_eq!(oidc.azp, Some("test_resource_server".to_string()));
5906        assert!(oidc.jti.is_some());
5907        if let Some(jti) = &oidc.jti {
5908            assert!(Uuid::from_str(jti).is_ok());
5909        }
5910        assert_eq!(oidc.s_claims.name, Some("Test Person 1".to_string()));
5911        assert_eq!(
5912            oidc.s_claims.preferred_username,
5913            Some("testperson1@example.com".to_string())
5914        );
5915        assert!(
5916            oidc.s_claims.scopes
5917                == vec![
5918                    OAUTH2_SCOPE_OPENID.to_string(),
5919                    OAUTH2_SCOPE_PROFILE.to_string(),
5920                    "supplement".to_string()
5921                ]
5922        );
5923        assert!(oidc.claims.is_empty());
5924        // Does our access token work with the userinfo endpoint?
5925        // Do the id_token details line up to the userinfo?
5926        let userinfo = idms_prox_read
5927            .oauth2_openid_userinfo("test_resource_server", &access_token, ct)
5928            .expect("failed to get userinfo");
5929
5930        assert_eq!(oidc.iss, userinfo.iss);
5931        assert_eq!(oidc.sub, userinfo.sub);
5932        assert_eq!(oidc.aud, userinfo.aud);
5933        assert_eq!(oidc.iat, userinfo.iat);
5934        assert_eq!(oidc.nbf, userinfo.nbf);
5935        assert_eq!(oidc.exp, userinfo.exp);
5936        assert_eq!(oidc.auth_time, userinfo.auth_time);
5937        assert_eq!(userinfo.nonce, Some("abcdef".to_string()));
5938        assert!(userinfo.at_hash.is_none());
5939        assert!(userinfo.acr.is_none());
5940        assert_eq!(oidc.amr, userinfo.amr);
5941        assert_eq!(oidc.azp, userinfo.azp);
5942        assert!(userinfo.jti.is_some());
5943        if let Some(jti) = &userinfo.jti {
5944            assert!(Uuid::from_str(jti).is_ok());
5945        }
5946        assert_eq!(oidc.s_claims, userinfo.s_claims);
5947        assert!(userinfo.claims.is_empty());
5948
5949        drop(idms_prox_read);
5950
5951        // Importantly, we need to persist the nonce through access/refresh token operations
5952        // because some clients like the rust openidconnect library require it always for claim
5953        // verification.
5954        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
5955
5956        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
5957            refresh_token,
5958            scope: None,
5959        }
5960        .into();
5961
5962        let token_response = idms_prox_write
5963            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
5964            .expect("Unable to exchange for OAuth2 token");
5965
5966        let access_token =
5967            JwsCompact::from_str(&token_response.access_token).expect("Invalid Access Token");
5968
5969        assert!(idms_prox_write.commit().is_ok());
5970
5971        // Okay, refresh done, lets check it.
5972        let mut idms_prox_read = idms.proxy_read().await.unwrap();
5973
5974        let userinfo = idms_prox_read
5975            .oauth2_openid_userinfo("test_resource_server", &access_token, ct)
5976            .expect("failed to get userinfo");
5977
5978        assert_eq!(oidc.iss, userinfo.iss);
5979        assert_eq!(oidc.sub, userinfo.sub);
5980        assert_eq!(oidc.aud, userinfo.aud);
5981        assert_eq!(oidc.iat, userinfo.iat);
5982        assert_eq!(oidc.nbf, userinfo.nbf);
5983        assert_eq!(oidc.exp, userinfo.exp);
5984        assert_eq!(oidc.auth_time, userinfo.auth_time);
5985        assert_eq!(userinfo.nonce, Some("abcdef".to_string()));
5986        assert!(userinfo.at_hash.is_none());
5987        assert!(userinfo.acr.is_none());
5988        assert_eq!(oidc.amr, userinfo.amr);
5989        assert_eq!(oidc.azp, userinfo.azp);
5990        assert!(userinfo.jti.is_some());
5991        if let Some(jti) = &userinfo.jti {
5992            assert!(Uuid::from_str(jti).is_ok());
5993        }
5994        assert_eq!(oidc.s_claims, userinfo.s_claims);
5995        assert!(userinfo.claims.is_empty());
5996    }
5997
5998    #[idm_test]
5999    async fn test_idm_oauth2_openid_short_username(
6000        idms: &IdmServer,
6001        _idms_delayed: &mut IdmServerDelayed,
6002    ) {
6003        // we run the same test as test_idm_oauth2_openid_extensions()
6004        // but change the preferred_username setting on the RS
6005        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6006        let (secret, _uat, ident, _) =
6007            setup_oauth2_resource_server_basic(idms, ct, true, false, true).await;
6008        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
6009
6010        let idms_prox_read = idms.proxy_read().await.unwrap();
6011
6012        let pkce_secret = PkceS256Secret::default();
6013
6014        let consent_request = good_authorisation_request!(
6015            idms_prox_read,
6016            &ident,
6017            ct,
6018            pkce_secret.to_request(),
6019            OAUTH2_SCOPE_OPENID.to_string()
6020        );
6021
6022        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
6023            unreachable!();
6024        };
6025
6026        // == Manually submit the consent token to the permit for the permit_success
6027        drop(idms_prox_read);
6028        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6029
6030        let permit_success = idms_prox_write
6031            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
6032            .expect("Failed to perform OAuth2 permit");
6033
6034        // == Submit the token exchange code.
6035        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
6036            code: permit_success.code,
6037            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
6038            code_verifier: Some(pkce_secret.to_verifier()),
6039        }
6040        .into();
6041
6042        let token_response = idms_prox_write
6043            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
6044            .expect("Failed to perform OAuth2 token exchange");
6045
6046        let id_token = token_response.id_token.expect("No id_token in response!");
6047        let access_token =
6048            JwsCompact::from_str(&token_response.access_token).expect("Invalid Access Token");
6049
6050        assert!(idms_prox_write.commit().is_ok());
6051        let mut idms_prox_read = idms.proxy_read().await.unwrap();
6052
6053        let mut jwkset = idms_prox_read
6054            .oauth2_openid_publickey("test_resource_server")
6055            .expect("Failed to get public key");
6056        let public_jwk = jwkset.keys.pop().expect("no such jwk");
6057
6058        let jws_validator =
6059            JwsEs256Verifier::try_from(&public_jwk).expect("failed to build validator");
6060
6061        let oidc_unverified =
6062            OidcUnverified::from_str(&id_token).expect("Failed to parse id_token");
6063
6064        let iat = ct.as_secs() as i64;
6065
6066        let oidc = jws_validator
6067            .verify(&oidc_unverified)
6068            .unwrap()
6069            .verify_exp(iat)
6070            .expect("Failed to verify oidc");
6071
6072        // Do we have the short username in the token claims?
6073        assert_eq!(
6074            oidc.s_claims.preferred_username,
6075            Some("testperson1".to_string())
6076        );
6077        // Do the id_token details line up to the userinfo?
6078        let userinfo = idms_prox_read
6079            .oauth2_openid_userinfo("test_resource_server", &access_token, ct)
6080            .expect("failed to get userinfo");
6081
6082        assert_eq!(oidc.s_claims, userinfo.s_claims);
6083    }
6084
6085    #[idm_test]
6086    async fn test_idm_oauth2_openid_group_claims(
6087        idms: &IdmServer,
6088        _idms_delayed: &mut IdmServerDelayed,
6089    ) {
6090        // we run the same test as test_idm_oauth2_openid_extensions()
6091        // but change the preferred_username setting on the RS
6092        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6093        let (secret, _uat, ident, _) =
6094            setup_oauth2_resource_server_basic(idms, ct, true, false, true).await;
6095
6096        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
6097
6098        let token_response = perform_oauth2_exchange(
6099            idms,
6100            &ident,
6101            ct,
6102            client_authz,
6103            format!("{OAUTH2_SCOPE_OPENID} {OAUTH2_SCOPE_GROUPS}"),
6104        )
6105        .await;
6106
6107        let id_token = token_response.id_token.expect("No id_token in response!");
6108        let access_token =
6109            JwsCompact::from_str(&token_response.access_token).expect("Invalid Access Token");
6110
6111        let oidc = validate_id_token(idms, ct, &id_token).await;
6112
6113        // does our id_token contain the expected groups?
6114        assert!(oidc.claims.contains_key("groups"));
6115
6116        assert!(oidc
6117            .claims
6118            .get("groups")
6119            .expect("unable to find key")
6120            .as_array()
6121            .unwrap()
6122            .contains(&serde_json::json!(STR_UUID_IDM_ALL_ACCOUNTS)));
6123
6124        let mut idms_prox_read = idms.proxy_read().await.unwrap();
6125
6126        // Do the id_token details line up to the userinfo?
6127        let userinfo = idms_prox_read
6128            .oauth2_openid_userinfo("test_resource_server", &access_token, ct)
6129            .expect("failed to get userinfo");
6130
6131        // does the userinfo endpoint provide the same groups?
6132        assert_eq!(oidc.claims.get("groups"), userinfo.claims.get("groups"));
6133    }
6134
6135    #[idm_test]
6136    async fn test_idm_oauth2_openid_group_extended_claims(
6137        idms: &IdmServer,
6138        _idms_delayed: &mut IdmServerDelayed,
6139    ) {
6140        // we run the same test as test_idm_oauth2_openid_extensions()
6141        // but change the preferred_username setting on the RS
6142        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6143        let (secret, _uat, ident, oauth2_client_uuid) =
6144            setup_oauth2_resource_server_basic(idms, ct, true, false, true).await;
6145
6146        // Modify the oauth2 client to have different scope maps.
6147        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6148
6149        let modlist = ModifyList::new_list(vec![
6150            Modify::Removed(
6151                Attribute::OAuth2RsScopeMap,
6152                PartialValue::Refer(UUID_TESTGROUP),
6153            ),
6154            Modify::Present(
6155                Attribute::OAuth2RsScopeMap,
6156                Value::new_oauthscopemap(
6157                    UUID_TESTGROUP,
6158                    btreeset![OAUTH2_SCOPE_GROUPS_NAME.to_string()],
6159                )
6160                .expect("invalid oauthscope"),
6161            ),
6162        ]);
6163
6164        idms_prox_write
6165            .qs_write
6166            .internal_modify_uuid(oauth2_client_uuid, &modlist)
6167            .expect("Failed to modify scopes");
6168
6169        idms_prox_write.commit().expect("failed to commit");
6170
6171        // Now actually do the test.
6172        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
6173
6174        let token_response = perform_oauth2_exchange(
6175            idms,
6176            &ident,
6177            ct,
6178            client_authz,
6179            format!("{OAUTH2_SCOPE_OPENID} {OAUTH2_SCOPE_GROUPS_NAME}"),
6180        )
6181        .await;
6182
6183        let id_token = token_response.id_token.expect("No id_token in response!");
6184        let access_token =
6185            JwsCompact::from_str(&token_response.access_token).expect("Invalid Access Token");
6186
6187        let oidc = validate_id_token(idms, ct, &id_token).await;
6188
6189        // does our id_token contain the expected groups?
6190        assert!(oidc.claims.contains_key("groups"));
6191
6192        assert!(oidc
6193            .claims
6194            .get("groups")
6195            .expect("unable to find key")
6196            .as_array()
6197            .unwrap()
6198            .contains(&serde_json::json!("testgroup")));
6199
6200        let mut idms_prox_read = idms.proxy_read().await.unwrap();
6201
6202        // Do the id_token details line up to the userinfo?
6203        let userinfo = idms_prox_read
6204            .oauth2_openid_userinfo("test_resource_server", &access_token, ct)
6205            .expect("failed to get userinfo");
6206
6207        // does the userinfo endpoint provide the same groups?
6208        assert_eq!(oidc.claims.get("groups"), userinfo.claims.get("groups"));
6209    }
6210
6211    #[idm_test]
6212    async fn test_idm_oauth2_openid_ssh_publickey_claim(
6213        idms: &IdmServer,
6214        _idms_delayed: &mut IdmServerDelayed,
6215    ) {
6216        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6217        let (secret, _uat, ident, client_uuid) =
6218            setup_oauth2_resource_server_basic(idms, ct, true, false, true).await;
6219
6220        // Extra setup for our test - add the correct claim and give an ssh publickey
6221        // to our testperson
6222        const ECDSA_SSH_PUBLIC_KEY: &str = "ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAGyIY7o3BtOzRiJ9vvjj96bRImwmyy5GvFSIUPlK00HitiAWGhiO1jGZKmK7220Oe4rqU3uAwA00a0758UODs+0OQHLMDRtl81lzPrVSdrYEDldxH9+a86dBZhdm0e15+ODDts2LHUknsJCRRldO4o9R9VrohlF7cbyBlnhJQrR4S+Oag== william@amethyst";
6223        let ssh_pubkey = SshPublicKey::from_string(ECDSA_SSH_PUBLIC_KEY).unwrap();
6224
6225        let scope_set = BTreeSet::from([OAUTH2_SCOPE_SSH_PUBLICKEYS.to_string()]);
6226
6227        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6228
6229        idms_prox_write
6230            .qs_write
6231            .internal_batch_modify(
6232                [
6233                    (
6234                        UUID_TESTPERSON_1,
6235                        ModifyList::new_set(
6236                            Attribute::SshPublicKey,
6237                            ValueSetSshKey::new("label".to_string(), ssh_pubkey),
6238                        ),
6239                    ),
6240                    (
6241                        client_uuid,
6242                        ModifyList::new_set(
6243                            Attribute::OAuth2RsSupScopeMap,
6244                            ValueSetOauthScopeMap::new(UUID_IDM_ALL_ACCOUNTS, scope_set),
6245                        ),
6246                    ),
6247                ]
6248                .into_iter(),
6249            )
6250            .expect("Failed to modify test entries");
6251
6252        assert!(idms_prox_write.commit().is_ok());
6253
6254        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
6255
6256        let idms_prox_read = idms.proxy_read().await.unwrap();
6257
6258        let pkce_secret = PkceS256Secret::default();
6259
6260        let consent_request = good_authorisation_request!(
6261            idms_prox_read,
6262            &ident,
6263            ct,
6264            pkce_secret.to_request(),
6265            "openid groups".to_string()
6266        );
6267
6268        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
6269            unreachable!();
6270        };
6271
6272        // == Manually submit the consent token to the permit for the permit_success
6273        drop(idms_prox_read);
6274        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6275
6276        let permit_success = idms_prox_write
6277            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
6278            .expect("Failed to perform OAuth2 permit");
6279
6280        // == Submit the token exchange code.
6281        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
6282            code: permit_success.code,
6283            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
6284            code_verifier: Some(pkce_secret.to_verifier()),
6285        }
6286        .into();
6287
6288        let token_response = idms_prox_write
6289            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
6290            .expect("Failed to perform OAuth2 token exchange");
6291
6292        let id_token = token_response.id_token.expect("No id_token in response!");
6293        let access_token =
6294            JwsCompact::from_str(&token_response.access_token).expect("Invalid Access Token");
6295
6296        assert!(idms_prox_write.commit().is_ok());
6297        let mut idms_prox_read = idms.proxy_read().await.unwrap();
6298
6299        let mut jwkset = idms_prox_read
6300            .oauth2_openid_publickey("test_resource_server")
6301            .expect("Failed to get public key");
6302        let public_jwk = jwkset.keys.pop().expect("no such jwk");
6303
6304        let jws_validator =
6305            JwsEs256Verifier::try_from(&public_jwk).expect("failed to build validator");
6306
6307        let oidc_unverified =
6308            OidcUnverified::from_str(&id_token).expect("Failed to parse id_token");
6309
6310        let iat = ct.as_secs() as i64;
6311
6312        let oidc = jws_validator
6313            .verify(&oidc_unverified)
6314            .unwrap()
6315            .verify_exp(iat)
6316            .expect("Failed to verify oidc");
6317
6318        // does our id_token contain the expected groups?
6319        assert!(oidc.claims.contains_key(OAUTH2_SCOPE_SSH_PUBLICKEYS));
6320
6321        assert!(oidc
6322            .claims
6323            .get(OAUTH2_SCOPE_SSH_PUBLICKEYS)
6324            .expect("unable to find key")
6325            .as_array()
6326            .unwrap()
6327            .contains(&serde_json::json!(ECDSA_SSH_PUBLIC_KEY)));
6328
6329        // Do the id_token details line up to the userinfo?
6330        let userinfo = idms_prox_read
6331            .oauth2_openid_userinfo("test_resource_server", &access_token, ct)
6332            .expect("failed to get userinfo");
6333
6334        // does the userinfo endpoint provide the same groups?
6335        assert_eq!(
6336            oidc.claims.get(OAUTH2_SCOPE_SSH_PUBLICKEYS),
6337            userinfo.claims.get(OAUTH2_SCOPE_SSH_PUBLICKEYS)
6338        );
6339    }
6340
6341    //  Check insecure pkce behaviour.
6342    #[idm_test]
6343    async fn test_idm_oauth2_insecure_pkce(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
6344        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6345        let (_secret, _uat, ident, _) =
6346            setup_oauth2_resource_server_basic(idms, ct, false, false, false).await;
6347
6348        let idms_prox_read = idms.proxy_read().await.unwrap();
6349
6350        // == Setup the authorisation request
6351        let pkce_secret = PkceS256Secret::default();
6352
6353        // Even in disable pkce mode, we will allow pkce
6354        let _consent_request = good_authorisation_request!(
6355            idms_prox_read,
6356            &ident,
6357            ct,
6358            pkce_secret.to_request(),
6359            OAUTH2_SCOPE_OPENID.to_string()
6360        );
6361
6362        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
6363
6364        // Check we allow none.
6365        let auth_req = AuthorisationRequest {
6366            response_type: ResponseType::Code,
6367            response_mode: None,
6368            client_id: "test_resource_server".to_string(),
6369            state: Some("123".to_string()),
6370            pkce_request: None,
6371            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
6372            scope: btreeset![OAUTH2_SCOPE_GROUPS.to_string()],
6373            nonce: Some("abcdef".to_string()),
6374            oidc_ext: Default::default(),
6375            max_age: None,
6376            ui_locales: Default::default(),
6377            prompt: Default::default(),
6378            unknown_keys: Default::default(),
6379        };
6380
6381        idms_prox_read
6382            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
6383            .expect("Oauth2 authorisation failed");
6384    }
6385
6386    #[idm_test]
6387    async fn test_idm_oauth2_webfinger(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
6388        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6389        let (_secret, _uat, _ident, _) =
6390            setup_oauth2_resource_server_basic(idms, ct, true, false, true).await;
6391        let mut idms_prox_read = idms.proxy_read().await.unwrap();
6392
6393        let user = "testperson1@example.com";
6394
6395        let webfinger = idms_prox_read
6396            .oauth2_openid_webfinger("test_resource_server", user)
6397            .expect("Failed to get webfinger");
6398
6399        assert_eq!(webfinger.subject, user);
6400        assert_eq!(webfinger.links.len(), 1);
6401
6402        let link = &webfinger.links[0];
6403        assert_eq!(link.rel, "http://openid.net/specs/connect/1.0/issuer");
6404        assert_eq!(
6405            link.href,
6406            "https://idm.example.com/oauth2/openid/test_resource_server"
6407        );
6408
6409        let failed_webfinger = idms_prox_read
6410            .oauth2_openid_webfinger("test_resource_server", "someone@another.domain");
6411        assert!(failed_webfinger.is_err());
6412    }
6413
6414    #[idm_test]
6415    async fn test_idm_oauth2_openid_legacy_crypto(
6416        idms: &IdmServer,
6417        _idms_delayed: &mut IdmServerDelayed,
6418    ) {
6419        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6420        let (secret, _uat, ident, _) =
6421            setup_oauth2_resource_server_basic(idms, ct, false, true, false).await;
6422        let idms_prox_read = idms.proxy_read().await.unwrap();
6423        // The public key url should offer an rs key
6424        // discovery should offer RS256
6425        let discovery = idms_prox_read
6426            .oauth2_openid_discovery("test_resource_server")
6427            .expect("Failed to get discovery");
6428
6429        let mut jwkset = idms_prox_read
6430            .oauth2_openid_publickey("test_resource_server")
6431            .expect("Failed to get public key");
6432
6433        let jwk = jwkset.keys.pop().expect("no such jwk");
6434        let public_jwk = jwk.clone();
6435
6436        match jwk {
6437            Jwk::RSA { alg, use_, kid, .. } => {
6438                match (
6439                    alg.unwrap(),
6440                    &discovery.id_token_signing_alg_values_supported[0],
6441                ) {
6442                    (JwaAlg::RS256, IdTokenSignAlg::RS256) => {}
6443                    _ => panic!(),
6444                };
6445                assert_eq!(use_.unwrap(), JwkUse::Sig);
6446                assert!(kid.is_some());
6447            }
6448            _ => panic!(),
6449        };
6450
6451        // Check that the id_token is signed with the correct key.
6452        let pkce_secret = PkceS256Secret::default();
6453
6454        let consent_request = good_authorisation_request!(
6455            idms_prox_read,
6456            &ident,
6457            ct,
6458            pkce_secret.to_request(),
6459            OAUTH2_SCOPE_OPENID.to_string()
6460        );
6461
6462        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
6463            unreachable!();
6464        };
6465
6466        // == Manually submit the consent token to the permit for the permit_success
6467        drop(idms_prox_read);
6468        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6469
6470        let permit_success = idms_prox_write
6471            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
6472            .expect("Failed to perform OAuth2 permit");
6473
6474        // == Submit the token exchange code.
6475        let token_req = AccessTokenRequest {
6476            grant_type: GrantTypeReq::AuthorizationCode {
6477                code: permit_success.code,
6478                redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
6479                code_verifier: Some(pkce_secret.to_verifier()),
6480            },
6481
6482            client_post_auth: ClientPostAuth {
6483                client_id: Some("test_resource_server".to_string()),
6484                client_secret: Some(secret),
6485            },
6486        };
6487
6488        let token_response = idms_prox_write
6489            .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
6490            .expect("Failed to perform OAuth2 token exchange");
6491
6492        // 🎉 We got a token!
6493        assert_eq!(token_response.token_type, AccessTokenType::Bearer);
6494        let id_token = token_response.id_token.expect("No id_token in response!");
6495
6496        let jws_validator =
6497            JwsRs256Verifier::try_from(&public_jwk).expect("failed to build validator");
6498
6499        let oidc_unverified =
6500            OidcUnverified::from_str(&id_token).expect("Failed to parse id_token");
6501
6502        let iat = ct.as_secs() as i64;
6503
6504        let oidc = jws_validator
6505            .verify(&oidc_unverified)
6506            .unwrap()
6507            .verify_exp(iat)
6508            .expect("Failed to verify oidc");
6509
6510        assert_eq!(oidc.sub, OidcSubject::U(UUID_TESTPERSON_1));
6511
6512        assert!(idms_prox_write.commit().is_ok());
6513    }
6514
6515    #[idm_test]
6516    async fn test_idm_oauth2_consent_granted_and_changed_workflow(
6517        idms: &IdmServer,
6518        _idms_delayed: &mut IdmServerDelayed,
6519    ) {
6520        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6521        let (_secret, uat, ident, _) =
6522            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
6523
6524        let idms_prox_read = idms.proxy_read().await.unwrap();
6525
6526        let pkce_secret = PkceS256Secret::default();
6527
6528        let consent_request = good_authorisation_request!(
6529            idms_prox_read,
6530            &ident,
6531            ct,
6532            pkce_secret.to_request(),
6533            OAUTH2_SCOPE_OPENID.to_string()
6534        );
6535
6536        // Should be in the consent phase;
6537        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
6538            unreachable!();
6539        };
6540
6541        // == Manually submit the consent token to the permit for the permit_success
6542        drop(idms_prox_read);
6543        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6544
6545        let _permit_success = idms_prox_write
6546            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
6547            .expect("Failed to perform OAuth2 permit");
6548
6549        assert!(idms_prox_write.commit().is_ok());
6550
6551        // == Now try the authorise again, should be in the permitted state.
6552        let mut idms_prox_read = idms.proxy_read().await.unwrap();
6553
6554        // We need to reload our identity
6555        let ident = idms_prox_read
6556            .process_uat_to_identity(&uat, ct, Source::Internal)
6557            .expect("Unable to process uat");
6558
6559        let pkce_secret = PkceS256Secret::default();
6560
6561        let consent_request = good_authorisation_request!(
6562            idms_prox_read,
6563            &ident,
6564            ct,
6565            pkce_secret.to_request(),
6566            OAUTH2_SCOPE_OPENID.to_string()
6567        );
6568
6569        // Should be in the consent phase;
6570        let AuthoriseResponse::Permitted(_permit_success) = consent_request else {
6571            unreachable!();
6572        };
6573
6574        drop(idms_prox_read);
6575
6576        // Great! Now change the scopes on the OAuth2 instance, this revokes the permit.
6577        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6578
6579        let me_extend_scopes = ModifyEvent::new_internal_invalid(
6580            filter!(f_eq(
6581                Attribute::Name,
6582                PartialValue::new_iname("test_resource_server")
6583            )),
6584            ModifyList::new_list(vec![Modify::Present(
6585                Attribute::OAuth2RsScopeMap,
6586                Value::new_oauthscopemap(
6587                    UUID_IDM_ALL_ACCOUNTS,
6588                    btreeset![
6589                        OAUTH2_SCOPE_EMAIL.to_string(),
6590                        OAUTH2_SCOPE_PROFILE.to_string(),
6591                        OAUTH2_SCOPE_OPENID.to_string()
6592                    ],
6593                )
6594                .expect("invalid oauthscope"),
6595            )]),
6596        );
6597
6598        assert!(idms_prox_write.qs_write.modify(&me_extend_scopes).is_ok());
6599        assert!(idms_prox_write.commit().is_ok());
6600
6601        // And do the workflow once more to see if we need to consent again.
6602
6603        let mut idms_prox_read = idms.proxy_read().await.unwrap();
6604
6605        // We need to reload our identity
6606        let ident = idms_prox_read
6607            .process_uat_to_identity(&uat, ct, Source::Internal)
6608            .expect("Unable to process uat");
6609
6610        let pkce_secret = PkceS256Secret::default();
6611
6612        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
6613
6614        let auth_req = AuthorisationRequest {
6615            response_type: ResponseType::Code,
6616            response_mode: None,
6617            client_id: "test_resource_server".to_string(),
6618            state: Some("123".to_string()),
6619            pkce_request: Some(pkce_secret.to_request()),
6620            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
6621            scope: btreeset![
6622                "openid".to_string(),
6623                "email".to_string(),
6624                "profile".to_string()
6625            ],
6626            nonce: Some("abcdef".to_string()),
6627            oidc_ext: Default::default(),
6628            max_age: None,
6629            ui_locales: Default::default(),
6630            prompt: Default::default(),
6631            unknown_keys: Default::default(),
6632        };
6633
6634        let consent_request = idms_prox_read
6635            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
6636            .expect("Oauth2 authorisation failed");
6637
6638        // Should be in the consent phase;
6639        let AuthoriseResponse::ConsentRequested { .. } = consent_request else {
6640            unreachable!();
6641        };
6642
6643        drop(idms_prox_read);
6644
6645        // Success! We had to consent again due to the change :)
6646
6647        // Now change the supplemental scopes on the OAuth2 instance, this revokes the permit.
6648        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6649
6650        let me_extend_scopes = ModifyEvent::new_internal_invalid(
6651            filter!(f_eq(
6652                Attribute::Name,
6653                PartialValue::new_iname("test_resource_server")
6654            )),
6655            ModifyList::new_list(vec![Modify::Present(
6656                Attribute::OAuth2RsSupScopeMap,
6657                Value::new_oauthscopemap(UUID_IDM_ALL_ACCOUNTS, btreeset!["newscope".to_string()])
6658                    .expect("invalid oauthscope"),
6659            )]),
6660        );
6661
6662        assert!(idms_prox_write.qs_write.modify(&me_extend_scopes).is_ok());
6663        assert!(idms_prox_write.commit().is_ok());
6664
6665        // And do the workflow once more to see if we need to consent again.
6666
6667        let mut idms_prox_read = idms.proxy_read().await.unwrap();
6668
6669        // We need to reload our identity
6670        let ident = idms_prox_read
6671            .process_uat_to_identity(&uat, ct, Source::Internal)
6672            .expect("Unable to process uat");
6673
6674        let pkce_secret = PkceS256Secret::default();
6675
6676        let auth_req = AuthorisationRequest {
6677            response_type: ResponseType::Code,
6678            response_mode: None,
6679            client_id: "test_resource_server".to_string(),
6680            state: Some("123".to_string()),
6681            pkce_request: Some(pkce_secret.to_request()),
6682            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
6683            // Note the scope isn't requested here!
6684            scope: btreeset![
6685                "openid".to_string(),
6686                "email".to_string(),
6687                "profile".to_string()
6688            ],
6689            nonce: Some("abcdef".to_string()),
6690            oidc_ext: Default::default(),
6691            max_age: None,
6692            ui_locales: Default::default(),
6693            prompt: Default::default(),
6694            unknown_keys: Default::default(),
6695        };
6696
6697        let consent_request = idms_prox_read
6698            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
6699            .expect("Oauth2 authorisation failed");
6700
6701        // Should be present in the consent phase however!
6702        let _consent_token = if let AuthoriseResponse::ConsentRequested {
6703            consent_token,
6704            scopes,
6705            ..
6706        } = consent_request
6707        {
6708            assert!(scopes.contains("newscope"));
6709            consent_token
6710        } else {
6711            unreachable!();
6712        };
6713    }
6714
6715    #[idm_test]
6716    async fn test_idm_oauth2_consent_granted_refint_cleanup_on_delete(
6717        idms: &IdmServer,
6718        _idms_delayed: &mut IdmServerDelayed,
6719    ) {
6720        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6721        let (_secret, uat, ident, o2rs_uuid) =
6722            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
6723
6724        // Assert there are no consent maps yet.
6725        assert!(ident.get_oauth2_consent_scopes(o2rs_uuid).is_none());
6726
6727        let idms_prox_read = idms.proxy_read().await.unwrap();
6728
6729        let pkce_secret = PkceS256Secret::default();
6730        let consent_request = good_authorisation_request!(
6731            idms_prox_read,
6732            &ident,
6733            ct,
6734            pkce_secret.to_request(),
6735            OAUTH2_SCOPE_OPENID.to_string()
6736        );
6737
6738        // Should be in the consent phase;
6739        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
6740            unreachable!();
6741        };
6742
6743        // == Manually submit the consent token to the permit for the permit_success
6744        drop(idms_prox_read);
6745        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6746
6747        let _permit_success = idms_prox_write
6748            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
6749            .expect("Failed to perform OAuth2 permit");
6750
6751        let ident = idms_prox_write
6752            .process_uat_to_identity(&uat, ct, Source::Internal)
6753            .expect("Unable to process uat");
6754
6755        // Assert that the ident now has the consents.
6756        assert!(
6757            ident.get_oauth2_consent_scopes(o2rs_uuid)
6758                == Some(&btreeset![
6759                    OAUTH2_SCOPE_OPENID.to_string(),
6760                    "supplement".to_string()
6761                ])
6762        );
6763
6764        // Now trigger the delete of the RS
6765        let de = DeleteEvent::new_internal_invalid(filter!(f_eq(
6766            Attribute::Name,
6767            PartialValue::new_iname("test_resource_server")
6768        )));
6769
6770        assert!(idms_prox_write.qs_write.delete(&de).is_ok());
6771        // Assert the consent maps are gone.
6772        let ident = idms_prox_write
6773            .process_uat_to_identity(&uat, ct, Source::Internal)
6774            .expect("Unable to process uat");
6775        dbg!(&o2rs_uuid);
6776        dbg!(&ident);
6777        let consent_scopes = ident.get_oauth2_consent_scopes(o2rs_uuid);
6778        dbg!(consent_scopes);
6779        assert!(consent_scopes.is_none());
6780
6781        assert!(idms_prox_write.commit().is_ok());
6782    }
6783
6784    // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#section-4.8
6785    //
6786    // It was reported we were vulnerable to this attack, but that isn't the case. First
6787    // this attack relies on stripping the *code_challenge* from the internals of the returned
6788    // code exchange token. This isn't possible due to our use of encryption of the code exchange
6789    // token. If that code challenge *could* be removed, then the attacker could use the code exchange
6790    // with no verifier or an incorrect verifier.
6791    //
6792    // Due to the logic in our server, if a code exchange contains a code challenge we always enforce
6793    // it is correctly used!
6794    //
6795    // This left a single odd case where if a client did an authorisation request without a pkce
6796    // verifier, but then a verifier was submitted during the code exchange, that the server would
6797    // *ignore* the verifier parameter. In this case, no stripping of the code challenge was done,
6798    // and the client could have simply also submitted *no* verifier anyway. It could be that
6799    // an attacker could gain a code exchange with no code challenge and then force a victim to
6800    // exchange that code exchange with out the verifier, but I'm not sure what damage that would
6801    // lead to? Regardless, we test for and close off that possible hole in this test.
6802    //
6803    #[idm_test]
6804    async fn test_idm_oauth2_1076_pkce_downgrade(
6805        idms: &IdmServer,
6806        _idms_delayed: &mut IdmServerDelayed,
6807    ) {
6808        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6809        // Enable pkce is set to FALSE
6810        let (secret, _uat, ident, _) =
6811            setup_oauth2_resource_server_basic(idms, ct, false, false, false).await;
6812
6813        let idms_prox_read = idms.proxy_read().await.unwrap();
6814
6815        // Get an ident/uat for now.
6816
6817        // == Setup the authorisation request
6818        // We attempt pkce even though the rs is set to not support pkce.
6819        let pkce_secret = PkceS256Secret::default();
6820
6821        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
6822
6823        // First, the user does not request pkce in their exchange.
6824        let auth_req = AuthorisationRequest {
6825            response_type: ResponseType::Code,
6826            response_mode: None,
6827            client_id: "test_resource_server".to_string(),
6828            state: Some("123".to_string()),
6829            pkce_request: None,
6830            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
6831            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
6832            nonce: None,
6833            oidc_ext: Default::default(),
6834            max_age: None,
6835            ui_locales: Default::default(),
6836            prompt: Default::default(),
6837            unknown_keys: Default::default(),
6838        };
6839
6840        let consent_request = idms_prox_read
6841            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
6842            .expect("Failed to perform OAuth2 authorisation request.");
6843
6844        // Should be in the consent phase;
6845        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
6846            unreachable!();
6847        };
6848
6849        // == Manually submit the consent token to the permit for the permit_success
6850        drop(idms_prox_read);
6851        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6852
6853        let permit_success = idms_prox_write
6854            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
6855            .expect("Failed to perform OAuth2 permit");
6856
6857        // == Submit the token exchange code.
6858        // This exchange failed because we submitted a verifier when the code exchange
6859        // has NO code challenge present.
6860        let token_req = AccessTokenRequest {
6861            grant_type: GrantTypeReq::AuthorizationCode {
6862                code: permit_success.code,
6863                redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
6864                code_verifier: Some(pkce_secret.to_verifier()),
6865            },
6866            client_post_auth: ClientPostAuth {
6867                client_id: Some("test_resource_server".to_string()),
6868                client_secret: Some(secret),
6869            },
6870        };
6871
6872        // Assert the exchange fails.
6873        assert!(matches!(
6874            idms_prox_write.check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct),
6875            Err(Oauth2Error::InvalidRequest)
6876        ));
6877
6878        assert!(idms_prox_write.commit().is_ok());
6879    }
6880
6881    #[idm_test]
6882    // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#section-2.1
6883    //
6884    // If the origin configured is https, do not allow downgrading to http on redirect
6885    async fn test_idm_oauth2_redir_http_downgrade(
6886        idms: &IdmServer,
6887        _idms_delayed: &mut IdmServerDelayed,
6888    ) {
6889        let ct = Duration::from_secs(TEST_CURRENT_TIME);
6890        // Enable pkce is set to FALSE
6891        let (secret, _uat, ident, _) =
6892            setup_oauth2_resource_server_basic(idms, ct, false, false, false).await;
6893
6894        let idms_prox_read = idms.proxy_read().await.unwrap();
6895
6896        // Get an ident/uat for now.
6897
6898        // == Setup the authorisation request
6899        // We attempt pkce even though the rs is set to not support pkce.
6900        let pkce_secret = PkceS256Secret::default();
6901
6902        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
6903
6904        // First, NOTE the lack of https on the redir uri.
6905        let auth_req = AuthorisationRequest {
6906            response_type: ResponseType::Code,
6907            response_mode: None,
6908            client_id: "test_resource_server".to_string(),
6909            state: Some("123".to_string()),
6910            pkce_request: Some(pkce_secret.to_request()),
6911            redirect_uri: Url::parse("http://demo.example.com/oauth2/result").unwrap(),
6912            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
6913            nonce: None,
6914            oidc_ext: Default::default(),
6915            max_age: None,
6916            ui_locales: Default::default(),
6917            prompt: Default::default(),
6918            unknown_keys: Default::default(),
6919        };
6920
6921        assert!(
6922            idms_prox_read
6923                .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
6924                .unwrap_err()
6925                == Oauth2Error::InvalidOrigin
6926        );
6927
6928        // This does have https
6929        let consent_request = good_authorisation_request!(
6930            idms_prox_read,
6931            &ident,
6932            ct,
6933            pkce_secret.to_request(),
6934            OAUTH2_SCOPE_OPENID.to_string()
6935        );
6936
6937        // Should be in the consent phase;
6938        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
6939            unreachable!();
6940        };
6941
6942        // == Manually submit the consent token to the permit for the permit_success
6943        drop(idms_prox_read);
6944        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
6945
6946        let permit_success = idms_prox_write
6947            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
6948            .expect("Failed to perform OAuth2 permit");
6949
6950        // == Submit the token exchange code.
6951        // NOTE the url is http again
6952        let token_req = AccessTokenRequest {
6953            grant_type: GrantTypeReq::AuthorizationCode {
6954                code: permit_success.code,
6955                redirect_uri: Url::parse("http://demo.example.com/oauth2/result").unwrap(),
6956                code_verifier: Some(pkce_secret.to_verifier()),
6957            },
6958
6959            client_post_auth: ClientPostAuth {
6960                client_id: Some("test_resource_server".to_string()),
6961                client_secret: Some(secret),
6962            },
6963        };
6964
6965        // Assert the exchange fails.
6966        assert!(matches!(
6967            idms_prox_write.check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct),
6968            Err(Oauth2Error::InvalidOrigin)
6969        ));
6970
6971        assert!(idms_prox_write.commit().is_ok());
6972    }
6973
6974    async fn setup_refresh_token(
6975        idms: &IdmServer,
6976        _idms_delayed: &mut IdmServerDelayed,
6977        ct: Duration,
6978    ) -> (AccessTokenResponse, ClientAuthInfo, Uuid) {
6979        // First, setup to get a token.
6980        let (secret, _uat, ident, oauth2_rs_uuid) =
6981            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
6982        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
6983
6984        let idms_prox_read = idms.proxy_read().await.unwrap();
6985
6986        // == Setup the authorisation request
6987        let pkce_secret = PkceS256Secret::default();
6988
6989        let consent_request = good_authorisation_request!(
6990            idms_prox_read,
6991            &ident,
6992            ct,
6993            pkce_secret.to_request(),
6994            OAUTH2_SCOPE_OPENID.to_string()
6995        );
6996
6997        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
6998            unreachable!();
6999        };
7000
7001        // == Manually submit the consent token to the permit for the permit_success
7002        drop(idms_prox_read);
7003        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7004
7005        let permit_success = idms_prox_write
7006            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
7007            .expect("Failed to perform OAuth2 permit");
7008
7009        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
7010            code: permit_success.code,
7011            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
7012            code_verifier: Some(pkce_secret.to_verifier()),
7013        }
7014        .into();
7015        let access_token_response_1 = idms_prox_write
7016            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7017            .expect("Unable to exchange for OAuth2 token");
7018
7019        assert!(idms_prox_write.commit().is_ok());
7020
7021        trace!(?access_token_response_1);
7022
7023        (access_token_response_1, client_authz, oauth2_rs_uuid)
7024    }
7025
7026    #[idm_test]
7027    async fn test_idm_oauth2_refresh_token_basic(
7028        idms: &IdmServer,
7029        idms_delayed: &mut IdmServerDelayed,
7030    ) {
7031        // First, setup to get a token.
7032        let ct = Duration::from_secs(TEST_CURRENT_TIME);
7033
7034        let (access_token_response_1, client_authz, oauth2_rs_uuid) =
7035            setup_refresh_token(idms, idms_delayed, ct).await;
7036
7037        // ============================================
7038        // test basic refresh while access still valid.
7039
7040        let ct = Duration::from_secs(TEST_CURRENT_TIME + 10);
7041        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7042
7043        let refresh_token = access_token_response_1
7044            .refresh_token
7045            .as_ref()
7046            .expect("no refresh token was issued")
7047            .clone();
7048
7049        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7050            refresh_token,
7051            scope: None,
7052        }
7053        .into();
7054
7055        let access_token_response_2 = idms_prox_write
7056            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7057            .expect("Unable to exchange for OAuth2 token");
7058
7059        assert!(idms_prox_write.commit().is_ok());
7060
7061        trace!(?access_token_response_2);
7062
7063        assert!(access_token_response_1.access_token != access_token_response_2.access_token);
7064        assert!(access_token_response_1.refresh_token != access_token_response_2.refresh_token);
7065        assert!(access_token_response_1.id_token != access_token_response_2.id_token);
7066
7067        // ============================================
7068        // test basic refresh after access exp
7069        let ct =
7070            Duration::from_secs(TEST_CURRENT_TIME + 20 + access_token_response_2.expires_in as u64);
7071
7072        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7073
7074        let refresh_token = access_token_response_2
7075            .refresh_token
7076            .as_ref()
7077            .expect("no refresh token was issued")
7078            .clone();
7079
7080        // get the refresh token expiry now before we use it.
7081        let reflected_token = idms_prox_write
7082            .reflect_oauth2_token(&refresh_token)
7083            .expect("Failed to access internals of the refresh token");
7084
7085        let refresh_exp = match reflected_token {
7086            Oauth2TokenType::Refresh { exp, .. } => exp,
7087            // Oauth2TokenType::Access { .. } |
7088            Oauth2TokenType::ClientAccess { .. } => unreachable!(),
7089        };
7090
7091        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7092            refresh_token,
7093            scope: None,
7094        }
7095        .into();
7096
7097        let access_token_response_3 = idms_prox_write
7098            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7099            .expect("Unable to exchange for OAuth2 token");
7100
7101        // Get the user entry to check the session life was extended.
7102
7103        let entry = idms_prox_write
7104            .qs_write
7105            .internal_search_uuid(UUID_TESTPERSON_1)
7106            .expect("failed");
7107        let session = entry
7108            .get_ava_as_oauth2session_map(Attribute::OAuth2Session)
7109            .and_then(|sessions| sessions.first_key_value())
7110            // If there is no map, then something is wrong.
7111            .unwrap();
7112
7113        trace!(?session);
7114        // The Oauth2 Session must be updated with a newer session time.
7115        assert_eq!(
7116            SessionState::ExpiresAt(
7117                time::OffsetDateTime::UNIX_EPOCH
7118                    + ct
7119                    + Duration::from_secs(OAUTH_REFRESH_TOKEN_EXPIRY as u64)
7120            ),
7121            session.1.state
7122        );
7123
7124        assert!(idms_prox_write.commit().is_ok());
7125
7126        trace!(?access_token_response_3);
7127
7128        assert!(access_token_response_3.access_token != access_token_response_2.access_token);
7129        assert!(access_token_response_3.refresh_token != access_token_response_2.refresh_token);
7130        assert!(access_token_response_3.id_token != access_token_response_2.id_token);
7131
7132        // ========================================
7133        // Check that a custom refresh time applies.
7134
7135        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7136
7137        let custom_exp = OAUTH_REFRESH_TOKEN_EXPIRY + 1;
7138
7139        let modlist = ModifyList::new_list(vec![
7140            // Member of a claim map.
7141            Modify::Set(
7142                Attribute::OAuth2RefreshTokenExpiry,
7143                ValueSetUint32::new(custom_exp),
7144            ),
7145        ]);
7146
7147        assert!(idms_prox_write
7148            .qs_write
7149            .internal_modify(
7150                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(oauth2_rs_uuid))),
7151                &modlist,
7152            )
7153            .is_ok());
7154
7155        assert!(idms_prox_write.commit().is_ok());
7156
7157        // Now check the new token has the updated refresh lifetime.
7158        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7159
7160        let refresh_token = access_token_response_3
7161            .refresh_token
7162            .as_ref()
7163            .expect("no refresh token was issued")
7164            .clone();
7165
7166        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7167            refresh_token,
7168            scope: None,
7169        }
7170        .into();
7171        let access_token_response_4 = idms_prox_write
7172            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7173            .unwrap();
7174
7175        let entry = idms_prox_write
7176            .qs_write
7177            .internal_search_uuid(UUID_TESTPERSON_1)
7178            .expect("failed");
7179        let session = entry
7180            .get_ava_as_oauth2session_map(Attribute::OAuth2Session)
7181            .and_then(|sessions| sessions.first_key_value())
7182            // If there is no map, then something is wrong.
7183            .unwrap();
7184
7185        trace!(?session);
7186        // The Oauth2 Session must be updated with a newer session time, this time it's
7187        // the custom expiration.
7188        assert_eq!(
7189            SessionState::ExpiresAt(
7190                time::OffsetDateTime::UNIX_EPOCH + ct + Duration::from_secs(custom_exp as u64)
7191            ),
7192            session.1.state
7193        );
7194
7195        assert!(idms_prox_write.commit().is_ok());
7196
7197        // refresh after refresh has expired.
7198        // Refresh tokens have a max time limit - the session time limit still bounds it though, but
7199        // so does the refresh token limit. We check both, but the refresh time is checked first so
7200        // we can guarantee this in this test.
7201
7202        let ct = Duration::from_secs(
7203            TEST_CURRENT_TIME + refresh_exp as u64 + access_token_response_4.expires_in as u64,
7204        );
7205
7206        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7207
7208        let refresh_token = access_token_response_4
7209            .refresh_token
7210            .as_ref()
7211            .expect("no refresh token was issued")
7212            .clone();
7213
7214        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7215            refresh_token,
7216            scope: None,
7217        }
7218        .into();
7219        let access_token_response_5 = idms_prox_write
7220            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7221            .unwrap_err();
7222
7223        assert_eq!(access_token_response_5, Oauth2Error::InvalidGrant);
7224
7225        assert!(idms_prox_write.commit().is_ok());
7226    }
7227
7228    // refresh when OAuth2 parent session exp / missing.
7229    #[idm_test]
7230    async fn test_idm_oauth2_refresh_token_oauth2_session_expired(
7231        idms: &IdmServer,
7232        idms_delayed: &mut IdmServerDelayed,
7233    ) {
7234        // First, setup to get a token.
7235        let ct = Duration::from_secs(TEST_CURRENT_TIME);
7236
7237        let (access_token_response_1, client_authz, _oauth2_rs_uuid) =
7238            setup_refresh_token(idms, idms_delayed, ct).await;
7239
7240        // ============================================
7241        // Revoke the OAuth2 session
7242
7243        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7244        let revoke_request = TokenRevokeRequest {
7245            token: access_token_response_1.access_token.clone(),
7246            token_type_hint: None,
7247            client_post_auth: ClientPostAuth::default(),
7248        };
7249        assert!(idms_prox_write
7250            .oauth2_token_revoke(&revoke_request, ct,)
7251            .is_ok());
7252        assert!(idms_prox_write.commit().is_ok());
7253
7254        // ============================================
7255        // then attempt a refresh.
7256        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7257
7258        let refresh_token = access_token_response_1
7259            .refresh_token
7260            .as_ref()
7261            .expect("no refresh token was issued")
7262            .clone();
7263
7264        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7265            refresh_token,
7266            scope: None,
7267        }
7268        .into();
7269        let access_token_response_2 = idms_prox_write
7270            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7271            // Should be unable to exchange.
7272            .unwrap_err();
7273
7274        assert_eq!(access_token_response_2, Oauth2Error::InvalidGrant);
7275
7276        assert!(idms_prox_write.commit().is_ok());
7277    }
7278
7279    // refresh with wrong client id/authz
7280    #[idm_test]
7281    async fn test_idm_oauth2_refresh_token_invalid_client_authz(
7282        idms: &IdmServer,
7283        idms_delayed: &mut IdmServerDelayed,
7284    ) {
7285        // First, setup to get a token.
7286        let ct = Duration::from_secs(TEST_CURRENT_TIME);
7287
7288        let (access_token_response_1, _client_authz, _oauth2_rs_uuid) =
7289            setup_refresh_token(idms, idms_delayed, ct).await;
7290
7291        let bad_client_authz = ClientAuthInfo::encode_basic("test_resource_server", "12345");
7292
7293        // ============================================
7294        // Refresh with invalid client authz
7295
7296        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7297
7298        let refresh_token = access_token_response_1
7299            .refresh_token
7300            .as_ref()
7301            .expect("no refresh token was issued")
7302            .clone();
7303
7304        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7305            refresh_token,
7306            scope: None,
7307        }
7308        .into();
7309        let access_token_response_2 = idms_prox_write
7310            .check_oauth2_token_exchange(&bad_client_authz, &token_req, ct)
7311            .unwrap_err();
7312
7313        assert_eq!(access_token_response_2, Oauth2Error::AuthenticationRequired);
7314
7315        assert!(idms_prox_write.commit().is_ok());
7316    }
7317
7318    // Incorrect scopes re-requested
7319    #[idm_test]
7320    async fn test_idm_oauth2_refresh_token_inconsistent_scopes(
7321        idms: &IdmServer,
7322        idms_delayed: &mut IdmServerDelayed,
7323    ) {
7324        // First, setup to get a token.
7325        let ct = Duration::from_secs(TEST_CURRENT_TIME);
7326
7327        let (access_token_response_1, client_authz, _oauth2_rs_uuid) =
7328            setup_refresh_token(idms, idms_delayed, ct).await;
7329
7330        // ============================================
7331        // Refresh with different scopes
7332
7333        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7334
7335        let refresh_token = access_token_response_1
7336            .refresh_token
7337            .as_ref()
7338            .expect("no refresh token was issued")
7339            .clone();
7340
7341        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7342            refresh_token,
7343            scope: Some(btreeset!["invalid_scope".to_string()]),
7344        }
7345        .into();
7346        let access_token_response_2 = idms_prox_write
7347            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7348            .unwrap_err();
7349
7350        assert_eq!(access_token_response_2, Oauth2Error::InvalidScope);
7351
7352        assert!(idms_prox_write.commit().is_ok());
7353    }
7354
7355    // Test that reuse of a refresh token is denied + terminates the session.
7356    //
7357    // https://www.ietf.org/archive/id/draft-ietf-oauth-security-topics-18.html#refresh_token_protection
7358    #[idm_test]
7359    async fn test_idm_oauth2_refresh_token_reuse_invalidates_session(
7360        idms: &IdmServer,
7361        idms_delayed: &mut IdmServerDelayed,
7362    ) {
7363        // First, setup to get a token.
7364        let ct = Duration::from_secs(TEST_CURRENT_TIME);
7365
7366        let (access_token_response_1, client_authz, _oauth2_rs_uuid) =
7367            setup_refresh_token(idms, idms_delayed, ct).await;
7368
7369        // ============================================
7370        // Use the refresh token once
7371        let ct = Duration::from_secs(TEST_CURRENT_TIME + 1);
7372        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7373
7374        let refresh_token = access_token_response_1
7375            .refresh_token
7376            .as_ref()
7377            .expect("no refresh token was issued")
7378            .clone();
7379
7380        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7381            refresh_token,
7382            scope: None,
7383        }
7384        .into();
7385
7386        let _access_token_response_2 = idms_prox_write
7387            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7388            .expect("Unable to exchange for OAuth2 token");
7389
7390        assert!(idms_prox_write.commit().is_ok());
7391
7392        // Now use it again. - this will cause an error and the session to be terminated.
7393        let ct = Duration::from_secs(TEST_CURRENT_TIME + 2);
7394        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7395
7396        let refresh_token = access_token_response_1
7397            .refresh_token
7398            .as_ref()
7399            .expect("no refresh token was issued")
7400            .clone();
7401
7402        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7403            refresh_token,
7404            scope: None,
7405        }
7406        .into();
7407
7408        let access_token_response_3 = idms_prox_write
7409            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7410            .unwrap_err();
7411
7412        assert_eq!(access_token_response_3, Oauth2Error::InvalidGrant);
7413
7414        let entry = idms_prox_write
7415            .qs_write
7416            .internal_search_uuid(UUID_TESTPERSON_1)
7417            .expect("failed");
7418        let valid = entry
7419            .get_ava_as_oauth2session_map(Attribute::OAuth2Session)
7420            .and_then(|sessions| sessions.first_key_value())
7421            .map(|(_, session)| !matches!(session.state, SessionState::RevokedAt(_)))
7422            // If there is no map, then something is wrong.
7423            .unwrap();
7424        // The session should be invalid at this point.
7425        assert!(!valid);
7426
7427        assert!(idms_prox_write.commit().is_ok());
7428    }
7429
7430    // Test session divergence. This means that we have to:
7431    // access + refresh 1
7432    // use refresh 1 -> access + refresh 2 // don't commit this txn.
7433    // use refresh 2 -> access + refresh 3
7434    //    check the session state.
7435
7436    #[idm_test]
7437    async fn test_idm_oauth2_refresh_token_divergence(
7438        idms: &IdmServer,
7439        idms_delayed: &mut IdmServerDelayed,
7440    ) {
7441        // First, setup to get a token.
7442        let ct = Duration::from_secs(TEST_CURRENT_TIME);
7443
7444        let (access_token_response_1, client_authz, _oauth2_rs_uuid) =
7445            setup_refresh_token(idms, idms_delayed, ct).await;
7446
7447        // ============================================
7448        // Use the refresh token once
7449        let ct = Duration::from_secs(TEST_CURRENT_TIME + 1);
7450        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7451
7452        let refresh_token = access_token_response_1
7453            .refresh_token
7454            .as_ref()
7455            .expect("no refresh token was issued")
7456            .clone();
7457
7458        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7459            refresh_token,
7460            scope: None,
7461        }
7462        .into();
7463
7464        let access_token_response_2 = idms_prox_write
7465            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7466            .expect("Unable to exchange for OAuth2 token");
7467
7468        // DO NOT COMMIT HERE - this is what forces the session issued_at
7469        // time to stay at the original time!
7470        drop(idms_prox_write);
7471
7472        // ============================================
7473        let ct = Duration::from_secs(TEST_CURRENT_TIME + 2);
7474        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7475
7476        let refresh_token = access_token_response_2
7477            .refresh_token
7478            .as_ref()
7479            .expect("no refresh token was issued")
7480            .clone();
7481
7482        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7483            refresh_token,
7484            scope: None,
7485        }
7486        .into();
7487
7488        let _access_token_response_3 = idms_prox_write
7489            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7490            .expect("Unable to exchange for OAuth2 token");
7491
7492        assert!(idms_prox_write.commit().is_ok());
7493
7494        // Success!
7495    }
7496
7497    #[idm_test]
7498    async fn test_idm_oauth2_refresh_token_scope_constraints(
7499        idms: &IdmServer,
7500        idms_delayed: &mut IdmServerDelayed,
7501    ) {
7502        // First, setup to get a token.
7503        let ct = Duration::from_secs(TEST_CURRENT_TIME);
7504
7505        let (access_token_response_1, client_authz, _oauth2_rs_uuid) =
7506            setup_refresh_token(idms, idms_delayed, ct).await;
7507
7508        // https://www.rfc-editor.org/rfc/rfc6749#section-1.5
7509        // Refresh tokens are issued to the client by the authorization
7510        // server and are used to obtain a new access token when the
7511        // current access token becomes invalid or expires, or to obtain
7512        // additional access tokens with identical or narrower scope
7513        // (access tokens may have a shorter lifetime and fewer
7514        // permissions than authorized by the resource owner).
7515
7516        let ct = Duration::from_secs(TEST_CURRENT_TIME + 10);
7517        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7518
7519        let refresh_token = access_token_response_1
7520            .refresh_token
7521            .as_ref()
7522            .expect("no refresh token was issued")
7523            .clone();
7524
7525        // Get the initial scopes.
7526        let jws_verifier = JwsDangerReleaseWithoutVerify::default();
7527
7528        let access_token_unverified = JwsCompact::from_str(&access_token_response_1.access_token)
7529            .expect("Invalid Access Token");
7530
7531        let reflected_token = jws_verifier
7532            .verify(&access_token_unverified)
7533            .unwrap()
7534            .from_json::<OAuth2RFC9068Token<OAuth2RFC9068TokenExtensions>>()
7535            .expect("Failed to access internals of the refresh token");
7536
7537        trace!(?reflected_token);
7538        let initial_scopes = reflected_token.extensions.scope;
7539        trace!(?initial_scopes);
7540
7541        // Should be the same scopes as initial.
7542        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7543            refresh_token,
7544            scope: None,
7545        }
7546        .into();
7547
7548        let access_token_response_2 = idms_prox_write
7549            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7550            .expect("Unable to exchange for OAuth2 token");
7551
7552        let access_token_unverified = JwsCompact::from_str(&access_token_response_2.access_token)
7553            .expect("Invalid Access Token");
7554
7555        let reflected_token = jws_verifier
7556            .verify(&access_token_unverified)
7557            .unwrap()
7558            .from_json::<OAuth2RFC9068Token<OAuth2RFC9068TokenExtensions>>()
7559            .expect("Failed to access internals of the refresh token");
7560
7561        assert_eq!(initial_scopes, reflected_token.extensions.scope);
7562
7563        let refresh_token = access_token_response_2
7564            .refresh_token
7565            .as_ref()
7566            .expect("no refresh token was issued")
7567            .clone();
7568
7569        // Now the scopes can be constrained.
7570        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7571            refresh_token,
7572            scope: Some(["openid".to_string()].into()),
7573        }
7574        .into();
7575
7576        let access_token_response_3 = idms_prox_write
7577            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7578            .expect("Unable to exchange for OAuth2 token");
7579
7580        let access_token_unverified = JwsCompact::from_str(&access_token_response_3.access_token)
7581            .expect("Invalid Access Token");
7582
7583        let reflected_token = jws_verifier
7584            .verify(&access_token_unverified)
7585            .unwrap()
7586            .from_json::<OAuth2RFC9068Token<OAuth2RFC9068TokenExtensions>>()
7587            .expect("Failed to access internals of the refresh token");
7588
7589        assert_ne!(initial_scopes, reflected_token.extensions.scope);
7590
7591        // Keep the constrained scopes.
7592        let constrained_scopes = reflected_token.extensions.scope;
7593
7594        let refresh_token = access_token_response_3
7595            .refresh_token
7596            .as_ref()
7597            .expect("no refresh token was issued")
7598            .clone();
7599
7600        // No scope request still issues the constrained values.
7601        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7602            refresh_token,
7603            scope: None,
7604        }
7605        .into();
7606
7607        let access_token_response_4 = idms_prox_write
7608            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7609            .expect("Unable to exchange for OAuth2 token");
7610
7611        let access_token_unverified = JwsCompact::from_str(&access_token_response_4.access_token)
7612            .expect("Invalid Access Token");
7613
7614        let reflected_token = jws_verifier
7615            .verify(&access_token_unverified)
7616            .unwrap()
7617            .from_json::<OAuth2RFC9068Token<OAuth2RFC9068TokenExtensions>>()
7618            .expect("Failed to access internals of the refresh token");
7619
7620        assert_ne!(initial_scopes, reflected_token.extensions.scope);
7621        assert_eq!(constrained_scopes, reflected_token.extensions.scope);
7622
7623        let refresh_token = access_token_response_4
7624            .refresh_token
7625            .as_ref()
7626            .expect("no refresh token was issued")
7627            .clone();
7628
7629        // We can't now extend back to the initial scopes.
7630        let token_req: AccessTokenRequest = GrantTypeReq::RefreshToken {
7631            refresh_token,
7632            scope: Some(initial_scopes),
7633        }
7634        .into();
7635
7636        let access_token_response_5_err = idms_prox_write
7637            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7638            .unwrap_err();
7639
7640        assert_eq!(access_token_response_5_err, Oauth2Error::InvalidScope);
7641
7642        assert!(idms_prox_write.commit().is_ok());
7643    }
7644
7645    #[test]
7646    // I know this looks kinda dumb but at some point someone pointed out that our scope syntax wasn't compliant with rfc6749
7647    //(https://datatracker.ietf.org/doc/html/rfc6749#section-3.3), so I'm just making sure that we don't break it again.
7648    fn compliant_serialization_test() {
7649        let token_req: Result<AccessTokenRequest, serde_json::Error> = serde_json::from_str(
7650            r#"
7651            {
7652                "grant_type": "refresh_token",
7653                "refresh_token": "some_dumb_refresh_token",
7654                "scope": "invalid_scope vasd asd"
7655            }
7656        "#,
7657        );
7658        assert!(token_req.is_ok());
7659    }
7660
7661    #[idm_test]
7662    async fn test_idm_oauth2_custom_claims(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
7663        let ct = Duration::from_secs(TEST_CURRENT_TIME);
7664        let (secret, _uat, ident, oauth2_rs_uuid) =
7665            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
7666
7667        // Setup custom claim maps here.
7668        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7669
7670        let modlist = ModifyList::new_list(vec![
7671            // Member of a claim map.
7672            Modify::Present(
7673                Attribute::OAuth2RsClaimMap,
7674                Value::OauthClaimMap(
7675                    "custom_a".to_string(),
7676                    OauthClaimMapJoin::CommaSeparatedValue,
7677                ),
7678            ),
7679            Modify::Present(
7680                Attribute::OAuth2RsClaimMap,
7681                Value::OauthClaimValue(
7682                    "custom_a".to_string(),
7683                    UUID_TESTGROUP,
7684                    btreeset!["value_a".to_string()],
7685                ),
7686            ),
7687            // If you are a member of two groups, the claim maps merge.
7688            Modify::Present(
7689                Attribute::OAuth2RsClaimMap,
7690                Value::OauthClaimValue(
7691                    "custom_a".to_string(),
7692                    UUID_IDM_ALL_ACCOUNTS,
7693                    btreeset!["value_b".to_string()],
7694                ),
7695            ),
7696            // Map with a different separator
7697            Modify::Present(
7698                Attribute::OAuth2RsClaimMap,
7699                Value::OauthClaimMap(
7700                    "custom_b".to_string(),
7701                    OauthClaimMapJoin::SpaceSeparatedValue,
7702                ),
7703            ),
7704            Modify::Present(
7705                Attribute::OAuth2RsClaimMap,
7706                Value::OauthClaimValue(
7707                    "custom_b".to_string(),
7708                    UUID_TESTGROUP,
7709                    btreeset!["value_a".to_string()],
7710                ),
7711            ),
7712            Modify::Present(
7713                Attribute::OAuth2RsClaimMap,
7714                Value::OauthClaimValue(
7715                    "custom_b".to_string(),
7716                    UUID_IDM_ALL_ACCOUNTS,
7717                    btreeset!["value_b".to_string()],
7718                ),
7719            ),
7720            // Not a member of the claim map.
7721            Modify::Present(
7722                Attribute::OAuth2RsClaimMap,
7723                Value::OauthClaimValue(
7724                    "custom_b".to_string(),
7725                    UUID_IDM_ADMINS,
7726                    btreeset!["value_c".to_string()],
7727                ),
7728            ),
7729            // Extended claim name syntax, allows characters beyond scope names.
7730            Modify::Present(
7731                Attribute::OAuth2RsClaimMap,
7732                Value::OauthClaimMap(
7733                    "custom:claim-name".to_string(),
7734                    OauthClaimMapJoin::CommaSeparatedValue,
7735                ),
7736            ),
7737            Modify::Present(
7738                Attribute::OAuth2RsClaimMap,
7739                Value::OauthClaimValue(
7740                    "custom:claim-name".to_string(),
7741                    UUID_TESTGROUP,
7742                    btreeset!["value:a-a".to_string()],
7743                ),
7744            ),
7745        ]);
7746
7747        assert!(idms_prox_write
7748            .qs_write
7749            .internal_modify(
7750                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(oauth2_rs_uuid))),
7751                &modlist,
7752            )
7753            .is_ok());
7754
7755        assert!(idms_prox_write.commit().is_ok());
7756
7757        // Claim maps setup, lets go.
7758        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
7759
7760        let idms_prox_read = idms.proxy_read().await.unwrap();
7761
7762        let pkce_secret = PkceS256Secret::default();
7763
7764        let consent_request = good_authorisation_request!(
7765            idms_prox_read,
7766            &ident,
7767            ct,
7768            pkce_secret.to_request(),
7769            OAUTH2_SCOPE_OPENID.to_string()
7770        );
7771
7772        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
7773            unreachable!();
7774        };
7775
7776        // == Manually submit the consent token to the permit for the permit_success
7777        drop(idms_prox_read);
7778        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
7779
7780        let permit_success = idms_prox_write
7781            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
7782            .expect("Failed to perform OAuth2 permit");
7783
7784        // == Submit the token exchange code.
7785        let token_req: AccessTokenRequest = GrantTypeReq::AuthorizationCode {
7786            code: permit_success.code,
7787            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
7788            code_verifier: Some(pkce_secret.to_verifier()),
7789        }
7790        .into();
7791
7792        let token_response = idms_prox_write
7793            .check_oauth2_token_exchange(&client_authz, &token_req, ct)
7794            .expect("Failed to perform OAuth2 token exchange");
7795
7796        // 🎉 We got a token!
7797        assert_eq!(token_response.token_type, AccessTokenType::Bearer);
7798
7799        let id_token = token_response.id_token.expect("No id_token in response!");
7800        let access_token =
7801            JwsCompact::from_str(&token_response.access_token).expect("Invalid Access Token");
7802
7803        // Get the read txn for inspecting the tokens
7804        assert!(idms_prox_write.commit().is_ok());
7805
7806        let mut idms_prox_read = idms.proxy_read().await.unwrap();
7807
7808        let mut jwkset = idms_prox_read
7809            .oauth2_openid_publickey("test_resource_server")
7810            .expect("Failed to get public key");
7811
7812        let public_jwk = jwkset.keys.pop().expect("no such jwk");
7813
7814        let jws_validator =
7815            JwsEs256Verifier::try_from(&public_jwk).expect("failed to build validator");
7816
7817        let oidc_unverified =
7818            OidcUnverified::from_str(&id_token).expect("Failed to parse id_token");
7819
7820        let iat = ct.as_secs() as i64;
7821
7822        let oidc = jws_validator
7823            .verify(&oidc_unverified)
7824            .unwrap()
7825            .verify_exp(iat)
7826            .expect("Failed to verify oidc");
7827
7828        // Are the id_token values what we expect?
7829        assert!(
7830            oidc.iss
7831                == Url::parse("https://idm.example.com/oauth2/openid/test_resource_server")
7832                    .unwrap()
7833        );
7834        assert_eq!(oidc.sub, OidcSubject::U(UUID_TESTPERSON_1));
7835        assert_eq!(oidc.aud, "test_resource_server");
7836        assert_eq!(oidc.iat, iat);
7837        assert_eq!(oidc.nbf, Some(iat));
7838        // Previously this was the auth session but it's now inline with the access token expiry.
7839        assert_eq!(oidc.exp, iat + (OAUTH2_ACCESS_TOKEN_EXPIRY as i64));
7840        assert!(oidc.auth_time.is_some());
7841        // Is nonce correctly passed through?
7842        assert_eq!(oidc.nonce, Some("abcdef".to_string()));
7843        assert!(oidc.at_hash.is_none());
7844        assert!(oidc.acr.is_none());
7845        assert!(oidc.amr.is_none());
7846        assert_eq!(oidc.azp, Some("test_resource_server".to_string()));
7847        assert!(oidc.jti.is_some());
7848        if let Some(jti) = &oidc.jti {
7849            assert!(Uuid::from_str(jti).is_ok());
7850        }
7851        assert_eq!(oidc.s_claims.name, Some("Test Person 1".to_string()));
7852        assert_eq!(
7853            oidc.s_claims.preferred_username,
7854            Some("testperson1@example.com".to_string())
7855        );
7856        assert!(
7857            oidc.s_claims.scopes == vec![OAUTH2_SCOPE_OPENID.to_string(), "supplement".to_string()]
7858        );
7859
7860        assert_eq!(
7861            oidc.claims.get("custom_a").and_then(|v| v.as_str()),
7862            Some("value_a,value_b")
7863        );
7864        assert_eq!(
7865            oidc.claims.get("custom_b").and_then(|v| v.as_str()),
7866            Some("value_a value_b")
7867        );
7868
7869        assert_eq!(
7870            oidc.claims
7871                .get("custom:claim-name")
7872                .and_then(|v| v.as_str()),
7873            Some("value:a-a")
7874        );
7875
7876        // Does our access token work with the userinfo endpoint?
7877        // Do the id_token details line up to the userinfo?
7878        let userinfo = idms_prox_read
7879            .oauth2_openid_userinfo("test_resource_server", &access_token, ct)
7880            .expect("failed to get userinfo");
7881
7882        assert_eq!(oidc.iss, userinfo.iss);
7883        assert_eq!(oidc.sub, userinfo.sub);
7884        assert_eq!(oidc.aud, userinfo.aud);
7885        assert_eq!(oidc.iat, userinfo.iat);
7886        assert_eq!(oidc.nbf, userinfo.nbf);
7887        assert_eq!(oidc.exp, userinfo.exp);
7888        assert_eq!(oidc.auth_time, userinfo.auth_time);
7889        assert_eq!(userinfo.nonce, Some("abcdef".to_string()));
7890        assert!(userinfo.at_hash.is_none());
7891        assert!(userinfo.jti.is_some());
7892        if let Some(jti) = &userinfo.jti {
7893            assert!(Uuid::from_str(jti).is_ok());
7894        }
7895        assert_eq!(oidc.amr, userinfo.amr);
7896        assert_eq!(oidc.azp, userinfo.azp);
7897        assert!(userinfo.jti.is_some());
7898        if let Some(jti) = &userinfo.jti {
7899            assert!(Uuid::from_str(jti).is_ok());
7900        }
7901        assert_eq!(oidc.s_claims, userinfo.s_claims);
7902        assert_eq!(oidc.claims, userinfo.claims);
7903
7904        // Check the oauth2 introspect bits.
7905        let intr_request = AccessTokenIntrospectRequest {
7906            token: token_response.access_token.clone(),
7907            token_type_hint: None,
7908            client_post_auth: ClientPostAuth::default(),
7909        };
7910        let intr_response = idms_prox_read
7911            .check_oauth2_token_introspect(&intr_request, ct)
7912            .expect("Failed to inspect token");
7913
7914        eprintln!("👉  {intr_response:?}");
7915        assert!(intr_response.active);
7916        assert_eq!(
7917            intr_response.scope,
7918            btreeset!["openid".to_string(), "supplement".to_string()]
7919        );
7920        assert_eq!(
7921            intr_response.client_id.as_deref(),
7922            Some("test_resource_server")
7923        );
7924        assert_eq!(
7925            intr_response.username.as_deref(),
7926            Some("testperson1@example.com")
7927        );
7928        assert_eq!(intr_response.token_type, Some(AccessTokenType::Bearer));
7929        assert_eq!(intr_response.iat, Some(ct.as_secs() as i64));
7930        assert_eq!(intr_response.nbf, Some(ct.as_secs() as i64));
7931        // Introspect doesn't have custom claims.
7932
7933        drop(idms_prox_read);
7934    }
7935
7936    #[idm_test]
7937    async fn test_idm_oauth2_public_allow_localhost_redirect(
7938        idms: &IdmServer,
7939        _idms_delayed: &mut IdmServerDelayed,
7940    ) {
7941        let ct = Duration::from_secs(TEST_CURRENT_TIME);
7942        let (_uat, ident, oauth2_rs_uuid) = setup_oauth2_resource_server_public(idms, ct).await;
7943
7944        let mut idms_prox_write: crate::idm::server::IdmServerProxyWriteTransaction<'_> =
7945            idms.proxy_write(ct).await.unwrap();
7946
7947        let redirect_uri = Url::parse("http://localhost:8765/oauth2/result")
7948            .expect("Failed to parse redirect URL");
7949
7950        let modlist = ModifyList::new_list(vec![
7951            Modify::Present(Attribute::OAuth2AllowLocalhostRedirect, Value::Bool(true)),
7952            Modify::Present(Attribute::OAuth2RsOrigin, Value::UrlN(redirect_uri.clone())),
7953        ]);
7954
7955        assert!(idms_prox_write
7956            .qs_write
7957            .internal_modify(
7958                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(oauth2_rs_uuid))),
7959                &modlist,
7960            )
7961            .is_ok());
7962
7963        assert!(idms_prox_write.commit().is_ok());
7964
7965        let idms_prox_read = idms.proxy_read().await.unwrap();
7966
7967        // == Setup the authorisation request
7968        let pkce_secret = PkceS256Secret::default();
7969
7970        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
7971
7972        let auth_req = AuthorisationRequest {
7973            response_type: ResponseType::Code,
7974            response_mode: None,
7975            client_id: "test_resource_server".to_string(),
7976            state: Some("123".to_string()),
7977            pkce_request: Some(pkce_secret.to_request()),
7978            redirect_uri: Url::parse("http://localhost:8765/oauth2/result").unwrap(),
7979            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
7980            nonce: Some("abcdef".to_string()),
7981            oidc_ext: Default::default(),
7982            max_age: None,
7983            ui_locales: Default::default(),
7984            prompt: Default::default(),
7985            unknown_keys: Default::default(),
7986        };
7987
7988        let consent_request = idms_prox_read
7989            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
7990            .expect("OAuth2 authorisation failed");
7991
7992        // Should be in the consent phase;
7993        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
7994            unreachable!();
7995        };
7996
7997        // == Manually submit the consent token to the permit for the permit_success
7998        drop(idms_prox_read);
7999        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
8000
8001        let permit_success = idms_prox_write
8002            .check_oauth2_authorise_permit(&ident, &consent_token, ct)
8003            .expect("Failed to perform OAuth2 permit");
8004
8005        // Check we are reflecting the CSRF properly.
8006        assert_eq!(permit_success.state.as_deref(), Some("123"));
8007
8008        // == Submit the token exchange code.
8009        let token_req = AccessTokenRequest {
8010            grant_type: GrantTypeReq::AuthorizationCode {
8011                code: permit_success.code,
8012                redirect_uri,
8013                code_verifier: Some(pkce_secret.to_verifier()),
8014            },
8015            client_post_auth: ClientPostAuth {
8016                client_id: Some("test_resource_server".to_string()),
8017                client_secret: None,
8018            },
8019        };
8020
8021        let token_response = idms_prox_write
8022            .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
8023            .expect("Failed to perform OAuth2 token exchange");
8024
8025        // 🎉 We got a token! In the future we can then check introspection from this point.
8026        assert_eq!(token_response.token_type, AccessTokenType::Bearer);
8027
8028        assert!(idms_prox_write.commit().is_ok());
8029    }
8030
8031    #[idm_test]
8032    async fn test_idm_oauth2_service_account_token_exchange(
8033        idms: &IdmServer,
8034        _idms_delayed: &mut IdmServerDelayed,
8035    ) {
8036        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8037        let (secret, _uat, _ident, _) =
8038            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8039
8040        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
8041
8042        let service_account_uuid = Uuid::new_v4();
8043        let sa_entry: Entry<EntryInit, EntryNew> = entry_init!(
8044            (Attribute::Class, EntryClass::Object.to_value()),
8045            (Attribute::Class, EntryClass::Account.to_value()),
8046            (Attribute::Class, EntryClass::ServiceAccount.to_value()),
8047            (Attribute::Name, Value::new_iname("test_sa_oauth2")),
8048            (Attribute::Uuid, Value::Uuid(service_account_uuid)),
8049            (Attribute::DisplayName, Value::new_utf8s("test_sa_oauth2")),
8050            (Attribute::Description, Value::new_utf8s("test_sa_oauth2"))
8051        );
8052
8053        idms_prox_write
8054            .qs_write
8055            .internal_create(vec![sa_entry])
8056            .expect("Failed to create service account");
8057
8058        idms_prox_write
8059            .qs_write
8060            .internal_modify(
8061                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(UUID_TESTGROUP))),
8062                &ModifyList::new_list(vec![Modify::Present(
8063                    Attribute::Member,
8064                    Value::ReferN(service_account_uuid),
8065                )]),
8066            )
8067            .expect("Failed to add service account to scope group");
8068
8069        let gte = GenerateApiTokenEvent::new_internal(service_account_uuid, "sa-token", None);
8070
8071        let api_token = idms_prox_write
8072            .service_account_generate_api_token(&gte, ct)
8073            .expect("failed to generate api token");
8074
8075        assert!(idms_prox_write.commit().is_ok());
8076
8077        let client_authz = ClientAuthInfo::encode_basic("test_resource_server", secret.as_str());
8078
8079        let scopes: BTreeSet<String> =
8080            btreeset![OAUTH2_SCOPE_OPENID.into(), OAUTH2_SCOPE_GROUPS.into()];
8081
8082        let build_exchange_request =
8083            |requested_scopes: BTreeSet<String>, client_secret: Option<String>| {
8084                AccessTokenRequest {
8085                    grant_type: GrantTypeReq::TokenExchange {
8086                        subject_token: api_token.to_string(),
8087                        subject_token_type: TOKEN_EXCHANGE_SUBJECT_TOKEN_TYPE_ACCESS.into(),
8088                        requested_token_type: None,
8089                        audience: Some("test_resource_server".into()),
8090                        resource: None,
8091                        actor_token: None,
8092                        actor_token_type: None,
8093                        scope: Some(requested_scopes),
8094                    },
8095                    client_post_auth: ClientPostAuth {
8096                        client_id: Some("test_resource_server".into()),
8097                        client_secret,
8098                    },
8099                }
8100            };
8101
8102        let token_req = build_exchange_request(scopes.clone(), None);
8103        let forbidden_secret_req = build_exchange_request(scopes.clone(), Some(secret.clone()));
8104        let empty_scope_req = build_exchange_request(BTreeSet::new(), None);
8105
8106        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
8107
8108        assert_eq!(
8109            idms_prox_write
8110                .check_oauth2_token_exchange(&client_authz, &forbidden_secret_req, ct)
8111                .unwrap_err(),
8112            Oauth2Error::InvalidRequest
8113        );
8114
8115        assert_eq!(
8116            idms_prox_write
8117                .check_oauth2_token_exchange(&ClientAuthInfo::none(), &empty_scope_req, ct)
8118                .unwrap_err(),
8119            Oauth2Error::InvalidRequest
8120        );
8121
8122        let token_response = idms_prox_write
8123            .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
8124            .expect("Failed to perform OAuth2 token exchange for service account");
8125
8126        assert_eq!(token_response.token_type, AccessTokenType::Bearer);
8127        assert_eq!(
8128            token_response.issued_token_type,
8129            Some(IssuedTokenType::AccessToken)
8130        );
8131        assert!(token_response.refresh_token.is_some());
8132        assert!(token_response.id_token.is_some());
8133        let response_scopes = token_response.scope.clone();
8134        assert!(response_scopes.contains(OAUTH2_SCOPE_OPENID));
8135        assert!(response_scopes.contains(OAUTH2_SCOPE_GROUPS));
8136
8137        assert!(idms_prox_write.commit().is_ok());
8138
8139        let mut idms_prox_read = idms.proxy_read().await.unwrap();
8140        let intr_request = AccessTokenIntrospectRequest {
8141            token: token_response.access_token.clone(),
8142            token_type_hint: None,
8143            client_post_auth: ClientPostAuth::default(),
8144        };
8145        let intr_response = idms_prox_read
8146            .check_oauth2_token_introspect(&intr_request, ct)
8147            .expect("Failed to introspect service account token");
8148
8149        assert!(intr_response.active);
8150        assert_eq!(
8151            intr_response.client_id.as_deref(),
8152            Some("test_resource_server")
8153        );
8154        assert_eq!(
8155            intr_response.sub.as_deref(),
8156            Some(service_account_uuid.to_string().as_str())
8157        );
8158    }
8159
8160    #[idm_test]
8161    async fn test_idm_oauth2_basic_client_credentials_grant_valid(
8162        idms: &IdmServer,
8163        _idms_delayed: &mut IdmServerDelayed,
8164    ) {
8165        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8166        let (secret, _uat, _ident, _) =
8167            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8168
8169        // scope: Some(btreeset!["invalid_scope".to_string()]),
8170        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
8171
8172        let token_req = AccessTokenRequest {
8173            grant_type: GrantTypeReq::ClientCredentials { scope: None },
8174
8175            client_post_auth: ClientPostAuth {
8176                client_id: Some("test_resource_server".to_string()),
8177                client_secret: Some(secret),
8178            },
8179        };
8180
8181        let oauth2_token = idms_prox_write
8182            .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
8183            .expect("Failed to perform OAuth2 token exchange");
8184
8185        assert!(idms_prox_write.commit().is_ok());
8186
8187        // 🎉 We got a token! In the future we can then check introspection from this point.
8188        assert_eq!(oauth2_token.token_type, AccessTokenType::Bearer);
8189
8190        // Check Oauth2 Token Introspection
8191        let mut idms_prox_read = idms.proxy_read().await.unwrap();
8192
8193        let intr_request = AccessTokenIntrospectRequest {
8194            token: oauth2_token.access_token.clone(),
8195            token_type_hint: None,
8196            client_post_auth: ClientPostAuth::default(),
8197        };
8198        let intr_response = idms_prox_read
8199            .check_oauth2_token_introspect(&intr_request, ct)
8200            .expect("Failed to inspect token");
8201
8202        eprintln!("👉  {intr_response:?}");
8203        assert!(intr_response.active);
8204        assert_eq!(intr_response.scope, btreeset!["supplement".to_string()]);
8205        assert_eq!(
8206            intr_response.client_id.as_deref(),
8207            Some("test_resource_server")
8208        );
8209        assert_eq!(
8210            intr_response.username.as_deref(),
8211            Some("test_resource_server@example.com")
8212        );
8213        assert_eq!(intr_response.token_type, Some(AccessTokenType::Bearer));
8214        assert_eq!(intr_response.iat, Some(ct.as_secs() as i64));
8215        assert_eq!(intr_response.nbf, Some(ct.as_secs() as i64));
8216
8217        drop(idms_prox_read);
8218
8219        // Assert we can revoke.
8220        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
8221        let revoke_request = TokenRevokeRequest {
8222            token: oauth2_token.access_token.clone(),
8223            token_type_hint: None,
8224            client_post_auth: ClientPostAuth::default(),
8225        };
8226        assert!(idms_prox_write
8227            .oauth2_token_revoke(&revoke_request, ct,)
8228            .is_ok());
8229        assert!(idms_prox_write.commit().is_ok());
8230
8231        // Now must be invalid.
8232        let ct = ct + AUTH_TOKEN_GRACE_WINDOW;
8233        let mut idms_prox_read = idms.proxy_read().await.unwrap();
8234
8235        let intr_request = AccessTokenIntrospectRequest {
8236            token: oauth2_token.access_token.clone(),
8237            token_type_hint: None,
8238            client_post_auth: ClientPostAuth::default(),
8239        };
8240
8241        let intr_response = idms_prox_read
8242            .check_oauth2_token_introspect(&intr_request, ct)
8243            .expect("Failed to inspect token");
8244        assert!(!intr_response.active);
8245
8246        drop(idms_prox_read);
8247    }
8248
8249    #[idm_test]
8250    async fn test_idm_oauth2_basic_client_credentials_grant_invalid(
8251        idms: &IdmServer,
8252        _idms_delayed: &mut IdmServerDelayed,
8253    ) {
8254        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8255        let (secret, _uat, _ident, _) =
8256            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8257
8258        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
8259
8260        // Public Client
8261        let token_req = AccessTokenRequest {
8262            grant_type: GrantTypeReq::ClientCredentials { scope: None },
8263            client_post_auth: ClientPostAuth {
8264                client_id: Some("test_resource_server".to_string()),
8265                client_secret: None,
8266            },
8267        };
8268
8269        assert_eq!(
8270            idms_prox_write
8271                .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
8272                .unwrap_err(),
8273            Oauth2Error::AuthenticationRequired
8274        );
8275
8276        // Incorrect Password
8277        let token_req = AccessTokenRequest {
8278            grant_type: GrantTypeReq::ClientCredentials { scope: None },
8279
8280            client_post_auth: ClientPostAuth {
8281                client_id: Some("test_resource_server".to_string()),
8282                client_secret: Some("wrong password".to_string()),
8283            },
8284        };
8285
8286        assert_eq!(
8287            idms_prox_write
8288                .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
8289                .unwrap_err(),
8290            Oauth2Error::AuthenticationRequired
8291        );
8292
8293        // Invalid scope
8294        let scope = Some(btreeset!["💅".to_string()]);
8295        let token_req = AccessTokenRequest {
8296            grant_type: GrantTypeReq::ClientCredentials { scope },
8297
8298            client_post_auth: ClientPostAuth {
8299                client_id: Some("test_resource_server".to_string()),
8300                client_secret: Some(secret.clone()),
8301            },
8302        };
8303
8304        assert_eq!(
8305            idms_prox_write
8306                .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
8307                .unwrap_err(),
8308            Oauth2Error::InvalidScope
8309        );
8310
8311        // Scopes we aren't a member-of
8312        let scope = Some(btreeset!["invalid_scope".to_string()]);
8313        let token_req = AccessTokenRequest {
8314            grant_type: GrantTypeReq::ClientCredentials { scope },
8315
8316            client_post_auth: ClientPostAuth {
8317                client_id: Some("test_resource_server".to_string()),
8318                client_secret: Some(secret.clone()),
8319            },
8320        };
8321
8322        assert_eq!(
8323            idms_prox_write
8324                .check_oauth2_token_exchange(&ClientAuthInfo::none(), &token_req, ct)
8325                .unwrap_err(),
8326            Oauth2Error::AccessDenied
8327        );
8328
8329        assert!(idms_prox_write.commit().is_ok());
8330    }
8331
8332    #[test]
8333    fn test_get_code() {
8334        use super::{gen_device_code, gen_user_code, parse_user_code};
8335
8336        assert!(gen_device_code().is_ok());
8337
8338        let (res_string, res_value) = gen_user_code();
8339
8340        assert!(res_string.split('-').count() == 3);
8341
8342        let res_string_clean = res_string.replace("-", "");
8343        let res_string_as_num = res_string_clean
8344            .parse::<u32>()
8345            .expect("Failed to parse as number");
8346        assert_eq!(res_string_as_num, res_value);
8347
8348        assert_eq!(
8349            parse_user_code(&res_string).expect("Failed to parse code"),
8350            res_value
8351        );
8352    }
8353
8354    #[idm_test]
8355    async fn handle_oauth2_start_device_flow(
8356        idms: &IdmServer,
8357        _idms_delayed: &mut IdmServerDelayed,
8358    ) {
8359        let ct = duration_from_epoch_now();
8360
8361        let client_auth_info = ClientAuthInfo::from(Source::Https(
8362            "127.0.0.1"
8363                .parse()
8364                .expect("Failed to parse 127.0.0.1 as an IP!"),
8365        ));
8366        let eventid = Uuid::new_v4();
8367
8368        let res = idms
8369            .proxy_write(ct)
8370            .await
8371            .expect("Failed to get idmspwt")
8372            .handle_oauth2_start_device_flow(client_auth_info, "test_rs_id", &None, eventid);
8373        dbg!(&res);
8374        assert!(res.is_err());
8375    }
8376
8377    #[test]
8378    fn test_url_localhost_domain() {
8379        // ref #2390 - localhost with ports for OAuth2 redirect_uri
8380
8381        // ensure host_is_local isn't true for a non-local host
8382        let example_is_not_local = "https://example.com/sdfsdf";
8383        println!("Ensuring that {example_is_not_local} is not local");
8384        assert!(!host_is_local(
8385            &Url::parse(example_is_not_local)
8386                .expect("Failed to parse example.com as a host?")
8387                .host()
8388                .unwrap_or_else(|| panic!("Couldn't get a host from {example_is_not_local}"))
8389        ));
8390
8391        let test_urls = [
8392            ("http://localhost:8080/oauth2/callback", "/oauth2/callback"),
8393            ("https://localhost/foo/bar", "/foo/bar"),
8394            ("http://127.0.0.1:12345/foo", "/foo"),
8395            ("http://[::1]:12345/foo", "/foo"),
8396        ];
8397
8398        for (url, path) in test_urls.into_iter() {
8399            println!("Testing URL: {url}");
8400            let url = Url::parse(url).expect("One of the test values failed!");
8401            assert!(host_is_local(
8402                &url.host().expect("Didn't parse a host out?")
8403            ));
8404
8405            assert_eq!(url.path(), path);
8406        }
8407    }
8408
8409    #[test]
8410    fn test_oauth2_rs_type_allow_localhost_redirect() {
8411        let test_cases = [
8412            (
8413                OauthRSType::Public {
8414                    allow_localhost_redirect: true,
8415                },
8416                true,
8417            ),
8418            (
8419                OauthRSType::Public {
8420                    allow_localhost_redirect: false,
8421                },
8422                false,
8423            ),
8424            (
8425                OauthRSType::Basic {
8426                    authz_secret: CtSecret::from("supersecret".to_string()),
8427                    enable_pkce: false,
8428                    enable_consent_prompt: true,
8429                },
8430                false,
8431            ),
8432        ];
8433
8434        assert!(test_cases.iter().all(|(rs_type, expected)| {
8435            let actual = rs_type.allow_localhost_redirect();
8436            println!("Testing {rs_type:?} -> {expected}");
8437            actual == *expected
8438        }));
8439    }
8440
8441    #[idm_test]
8442    async fn test_oauth2_auth_with_no_state(
8443        idms: &IdmServer,
8444        _idms_delayed: &mut IdmServerDelayed,
8445    ) {
8446        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8447        let (_secret, _uat, ident, _) =
8448            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8449
8450        let idms_prox_read = idms.proxy_read().await.unwrap();
8451
8452        // == Setup the authorisation request
8453        let pkce_secret = PkceS256Secret::default();
8454
8455        let scope: BTreeSet<String> = OAUTH2_SCOPE_OPENID
8456            .split(" ")
8457            .map(|s| s.to_string())
8458            .collect();
8459
8460        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
8461
8462        let auth_req = AuthorisationRequest {
8463            response_type: ResponseType::Code,
8464            response_mode: None,
8465            client_id: "test_resource_server".to_string(),
8466            state: None,
8467            pkce_request: Some(pkce_secret.to_request()),
8468            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
8469            scope,
8470            nonce: Some("abcdef".to_string()),
8471            oidc_ext: Default::default(),
8472            max_age: None,
8473            ui_locales: Default::default(),
8474            prompt: Default::default(),
8475            unknown_keys: Default::default(),
8476        };
8477        println!("{auth_req:?}");
8478
8479        let consent_request = idms_prox_read
8480            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
8481            .expect("OAuth2 authorisation failed");
8482
8483        // Should be in the consent phase;
8484        let AuthoriseResponse::ConsentRequested { .. } = consent_request else {
8485            unreachable!("Expected a ConsentRequested response, got: {consent_request:?}");
8486        };
8487    }
8488
8489    #[idm_test]
8490    async fn test_idm_oauth2_consent_prompt_disabled(
8491        idms: &IdmServer,
8492        _idms_delayed: &mut IdmServerDelayed,
8493    ) {
8494        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8495        let (_secret, _uat, ident, o2rs_uuid) =
8496            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8497
8498        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
8499        idms_prox_write
8500            .qs_write
8501            .internal_modify_uuid(
8502                o2rs_uuid,
8503                &ModifyList::new_purge_and_set(
8504                    Attribute::OAuth2ConsentPromptEnable,
8505                    Value::new_bool(false),
8506                ),
8507            )
8508            .expect("Unable to disable consent prompt");
8509        assert!(idms_prox_write.commit().is_ok());
8510
8511        // Assert there are no consent maps yet so consent should be required if not disabled
8512        assert!(ident.get_oauth2_consent_scopes(o2rs_uuid).is_none());
8513
8514        let idms_prox_read = idms.proxy_read().await.unwrap();
8515
8516        let pkce_secret = PkceS256Secret::default();
8517        let consent_request = good_authorisation_request!(
8518            idms_prox_read,
8519            &ident,
8520            ct,
8521            pkce_secret.to_request(),
8522            OAUTH2_SCOPE_OPENID.to_string()
8523        );
8524
8525        // Should be permitted
8526        let AuthoriseResponse::Permitted(_permitted) = consent_request else {
8527            unreachable!();
8528        };
8529
8530        // Assert that it still doesn't have any consent maps
8531        assert!(ident.get_oauth2_consent_scopes(o2rs_uuid).is_none());
8532    }
8533
8534    fn auth_req_with_prompt(
8535        pkce_request: PkceRequest,
8536        prompt: Vec<Prompt>,
8537    ) -> AuthorisationRequest {
8538        AuthorisationRequest {
8539            response_type: ResponseType::Code,
8540            response_mode: None,
8541            client_id: "test_resource_server".to_string(),
8542            state: Some("123".to_string()),
8543            pkce_request: Some(pkce_request),
8544            redirect_uri: Url::parse("https://demo.example.com/oauth2/result").unwrap(),
8545            scope: btreeset![OAUTH2_SCOPE_OPENID.to_string()],
8546            nonce: Some("abcdef".to_string()),
8547            oidc_ext: Default::default(),
8548            max_age: None,
8549            ui_locales: Default::default(),
8550            prompt,
8551            unknown_keys: Default::default(),
8552        }
8553    }
8554
8555    async fn grant_consent_for_identity(
8556        idms: &IdmServer,
8557        ident: &Identity,
8558        uat: &UserAuthToken,
8559        ct: Duration,
8560    ) -> Identity {
8561        let idms_prox_read = idms.proxy_read().await.unwrap();
8562
8563        let pkce_secret = PkceS256Secret::default();
8564        let consent_request = good_authorisation_request!(
8565            idms_prox_read,
8566            ident,
8567            ct,
8568            pkce_secret.to_request(),
8569            OAUTH2_SCOPE_OPENID.to_string()
8570        );
8571
8572        let AuthoriseResponse::ConsentRequested { consent_token, .. } = consent_request else {
8573            unreachable!("Expected ConsentRequested, got: {consent_request:?}");
8574        };
8575
8576        drop(idms_prox_read);
8577        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
8578
8579        let _permit_success = idms_prox_write
8580            .check_oauth2_authorise_permit(ident, &consent_token, ct)
8581            .expect("Failed to perform OAuth2 permit");
8582
8583        let new_ident = idms_prox_write
8584            .process_uat_to_identity(uat, ct, Source::Internal)
8585            .expect("Unable to process uat");
8586
8587        assert!(idms_prox_write.commit().is_ok());
8588        new_ident
8589    }
8590
8591    /// When provided with too many arguments for the `prompt` key, we should return a InvalidRequest as we want to
8592    /// protect ourselves from having to linearly search across hundreds or thousands of values
8593    #[idm_test]
8594    async fn test_idm_oauth2_prompt_fails_for_too_many_values(
8595        idms: &IdmServer,
8596        _idms_delayed: &mut IdmServerDelayed,
8597    ) {
8598        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8599        let (_secret, _uat, ident, _) =
8600            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8601
8602        let idms_prox_read = idms.proxy_read().await.unwrap();
8603        let pkce_secret = PkceS256Secret::default();
8604
8605        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
8606
8607        let auth_req = auth_req_with_prompt(
8608            pkce_secret.to_request(),
8609            Vec::from([
8610                Prompt::Login,
8611                Prompt::Consent,
8612                Prompt::SelectAccount,
8613                Prompt::None,
8614                Prompt::Invalid("bagel".into()),
8615                Prompt::Invalid("panko".into()),
8616            ]),
8617        );
8618
8619        // Too many prompt values should cause the request to be rejected with InvalidRequest
8620        let result =
8621            idms_prox_read.check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct);
8622
8623        assert_eq!(
8624            result.unwrap_err(),
8625            Oauth2Error::InvalidRequest,
8626            "An invalid/unrecognised prompt value must return InvalidRequest"
8627        );
8628    }
8629
8630    /// OIDC Core 1.0 §3.1.2.1:
8631    /// > If an OP receives a prompt value outside the set defined above that it does not understand,
8632    /// > it MAY return an error or it MAY ignore it
8633    ///
8634    /// We want to return error in case we do not recognize the prompt provided
8635    #[idm_test]
8636    async fn test_idm_oauth2_prompt_invalid_returns_error(
8637        idms: &IdmServer,
8638        _idms_delayed: &mut IdmServerDelayed,
8639    ) {
8640        let invalid_value = "bor-sirhc".to_string();
8641
8642        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8643        let (_secret, _uat, ident, _) =
8644            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8645
8646        let idms_prox_read = idms.proxy_read().await.unwrap();
8647        let pkce_secret = PkceS256Secret::default();
8648
8649        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
8650
8651        let auth_req = auth_req_with_prompt(
8652            pkce_secret.to_request(),
8653            Vec::from([Prompt::Invalid(invalid_value)]),
8654        );
8655
8656        let result =
8657            idms_prox_read.check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct);
8658
8659        assert_eq!(
8660            result.unwrap_err(),
8661            Oauth2Error::InvalidRequest,
8662            "An invalid/unrecognised prompt value must return InvalidRequest"
8663        );
8664    }
8665
8666    /// OIDC Core 1.0 §3.1.2.1 prompt=none:
8667    ///
8668    /// > The Authorization Server MUST NOT display any authentication or consent
8669    /// > user interface pages. An error is returned if an End-User is not already
8670    /// > authenticated
8671    ///
8672    /// If the user isn't already logged in we return `login_required`
8673    #[idm_test]
8674    async fn test_idm_oauth2_prompt_none_unauthenticated_returns_login_required(
8675        idms: &IdmServer,
8676        _idms_delayed: &mut IdmServerDelayed,
8677    ) {
8678        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8679        let (_secret, _uat, _ident, _) =
8680            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8681
8682        let idms_prox_read = idms.proxy_read().await.unwrap();
8683        let pkce_secret = PkceS256Secret::default();
8684
8685        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
8686
8687        let auth_req = auth_req_with_prompt(pkce_secret.to_request(), Vec::from([Prompt::None]));
8688
8689        // No identity provided (None) - user is not authenticated.
8690        let result = idms_prox_read
8691            .check_oauth2_authorisation(None, &auth_req, &auth_req_ctx, ct)
8692            .unwrap();
8693
8694        let result = matches!(result, AuthoriseResponse::Reject(rejection) if rejection.error == Oauth2Error::LoginRequired);
8695
8696        assert!(
8697            result,
8698            "prompt=none without authentication must return a rejection for login_required"
8699        );
8700    }
8701
8702    /// OIDC Core 1.0 §3.1.2.1 prompt=none:
8703    ///
8704    /// > The Authorization Server MUST NOT display any authentication or consent
8705    /// > user interface pages. An error is returned if an End-User is not already
8706    /// > authenticated
8707    ///
8708    /// If the user is logged in, but hasn't given consent, we return `interaction_required`
8709    #[idm_test]
8710    async fn test_idm_oauth2_prompt_none_no_consent_returns_interaction_required(
8711        idms: &IdmServer,
8712        _idms_delayed: &mut IdmServerDelayed,
8713    ) {
8714        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8715        let (_secret, _uat, ident, _) =
8716            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8717
8718        let idms_prox_read = idms.proxy_read().await.unwrap();
8719        let pkce_secret = PkceS256Secret::default();
8720
8721        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
8722
8723        let auth_req = auth_req_with_prompt(pkce_secret.to_request(), Vec::from([Prompt::None]));
8724
8725        // Ident is authenticated but has never granted consent.
8726        let result = idms_prox_read
8727            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
8728            .unwrap();
8729
8730        let result = matches!(result, AuthoriseResponse::Reject(rejection) if rejection.error == Oauth2Error::InteractionRequired);
8731
8732        assert!(
8733            result,
8734            "prompt=none with authenticated user but no prior consent must return interaction_required"
8735        );
8736    }
8737
8738    /// OIDC Core 1.0 §3.1.2.1 prompt=none:
8739    ///
8740    /// > The Authorization Server MUST NOT display any authentication or consent
8741    /// > user interface pages. An error is returned if an End-User is not already
8742    /// > authenticated
8743    ///
8744    /// If the user is logged in *and* has given consent, we return permitted.
8745    #[idm_test]
8746    async fn test_idm_oauth2_prompt_none_with_prior_consent_succeeds(
8747        idms: &IdmServer,
8748        _idms_delayed: &mut IdmServerDelayed,
8749    ) {
8750        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8751        let (_secret, uat, ident, _) =
8752            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8753
8754        // First, grant consent via the normal flow.
8755        let ident = grant_consent_for_identity(idms, &ident, &uat, ct).await;
8756
8757        // Now issue a prompt=none request - should succeed silently.
8758        let idms_prox_read = idms.proxy_read().await.unwrap();
8759        let pkce_secret = PkceS256Secret::default();
8760
8761        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
8762
8763        let auth_req = auth_req_with_prompt(pkce_secret.to_request(), Vec::from([Prompt::None]));
8764
8765        let result = idms_prox_read
8766            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
8767            .expect("prompt=none with prior consent should succeed");
8768
8769        assert!(
8770            matches!(result, AuthoriseResponse::Permitted(_)),
8771            "prompt=none with authenticated user and prior consent must return Permitted"
8772        );
8773    }
8774
8775    /// OIDC Core 1.0 §3.1.2.1 prompt=login:
8776    ///
8777    /// > The Authorization Server SHOULD prompt the End-User for reauthentication.
8778    ///
8779    /// If the user is already authenticated, we still prompt for re-authentication.
8780    #[idm_test]
8781    async fn test_idm_oauth2_prompt_login_forces_reauthentication(
8782        idms: &IdmServer,
8783        _idms_delayed: &mut IdmServerDelayed,
8784    ) {
8785        const OAUTH2_OIDC_PROMPT_LOGIN_GRACE: i64 = 300;
8786
8787        let ct = Duration::from_secs(TEST_CURRENT_TIME);
8788        let (_secret, _uat, ident, _) =
8789            setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8790
8791        let idms_prox_read = idms.proxy_read().await.unwrap();
8792        let pkce_secret = PkceS256Secret::default();
8793
8794        let auth_req_ctx = AuthorisationRequestContext { resumed: false };
8795
8796        let mut auth_req = auth_req_with_prompt(pkce_secret.to_request(), Vec::from([]));
8797        auth_req.max_age = Some(OAUTH2_OIDC_PROMPT_LOGIN_GRACE);
8798
8799        // We are within the grace time, no prompt forced.
8800        let result = idms_prox_read
8801            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
8802            .expect("prompt=login should not error");
8803
8804        assert!(
8805            matches!(result, AuthoriseResponse::ConsentRequested { .. }),
8806            "prompt=login should not have been forced"
8807        );
8808
8809        // Even though the user is authenticated, max_age now will force re-auth as the session
8810        // is outside of the max_age period.
8811        let ct = ct + Duration::from_secs(OAUTH2_OIDC_PROMPT_LOGIN_GRACE as u64);
8812
8813        let result = idms_prox_read
8814            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
8815            .expect("prompt=login should not error");
8816
8817        assert!(
8818            matches!(result, AuthoriseResponse::ReauthenticationRequired { .. }),
8819            "max_age must force re-authentication even when user is already authenticated"
8820        );
8821
8822        // Prompt login always forces reauth.
8823        let auth_req = auth_req_with_prompt(pkce_secret.to_request(), Vec::from([Prompt::Login]));
8824
8825        let result = idms_prox_read
8826            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
8827            .expect("prompt=login should not error");
8828
8829        assert!(
8830            matches!(result, AuthoriseResponse::ReauthenticationRequired { .. }),
8831            "prompt=login must force re-authentication even when user is already authenticated"
8832        );
8833
8834        // However, if the server indicates that our context is directly after a session resumption
8835        // aka we just logged in - we can proceed.
8836        let auth_req_ctx = AuthorisationRequestContext { resumed: true };
8837
8838        let result = idms_prox_read
8839            .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
8840            .expect("prompt=login should not error");
8841
8842        assert!(
8843            matches!(result, AuthoriseResponse::ConsentRequested { .. }),
8844            "prompt=login should not have been forced"
8845        );
8846    }
8847
8848    //TODO: Implement prompt=consent. Requires supporting prompt=login%20consent which will require extra thinking
8849
8850    // /// OIDC Core 1.0 §3.1.2.1 prompt=consent:
8851    // ///
8852    // /// > The Authorization Server SHOULD prompt the End-User for consent before
8853    // /// > returning information to the Client.
8854    // ///
8855    // /// If the user is logged in and has already given consent, we prompt for consent again
8856    // #[idm_test]
8857    // async fn test_idm_oauth2_prompt_consent_forces_reconsent(
8858    //     idms: &IdmServer,
8859    //     _idms_delayed: &mut IdmServerDelayed,
8860    // ) {
8861    //     let ct = Duration::from_secs(TEST_CURRENT_TIME);
8862    //     let (_secret, uat, ident, _) =
8863    //         setup_oauth2_resource_server_basic(idms, ct, true, false, false).await;
8864
8865    //     // First, grant consent via the normal flow.
8866    //     let ident = grant_consent_for_identity(idms, &ident, &uat, ct).await;
8867
8868    //     // Now issue prompt=consent - should force re-consent even though
8869    //     // the user has previously consented.
8870    //     let idms_prox_read = idms.proxy_read().await.unwrap();
8871    //     let pkce_secret = PkceS256Secret::default();
8872
8873    //     let auth_req = auth_req_with_prompt(pkce_secret.to_request(), Vec::from([Prompt::Consent]));
8874
8875    //     let result = idms_prox_read
8876    //         .check_oauth2_authorisation(Some(&ident), &auth_req, &auth_req_ctx, ct)
8877    //         .expect("prompt=consent should not error");
8878
8879    //     assert!(
8880    //         matches!(result, AuthoriseResponse::ConsentRequested { .. }),
8881    //         "prompt=consent must force the consent screen even when consent was previously granted"
8882    //     );
8883    // }
8884}