From 12ce2a3d04aa3d4622fb394790b825eb41b5887f Mon Sep 17 00:00:00 2001 From: Quentin Gliech Date: Wed, 7 Dec 2022 15:08:04 +0100 Subject: [PATCH] data-model: simplify the authorization grants and sessions --- crates/axum-utils/src/user_authorization.rs | 11 +-- crates/data-model/src/lib.rs | 2 - .../src/oauth2/authorization_grant.rs | 82 ++++--------------- crates/data-model/src/oauth2/session.rs | 25 ++---- crates/data-model/src/traits.rs | 42 ---------- crates/graphql/src/model/oauth.rs | 6 +- crates/graphql/src/model/users.rs | 2 +- .../src/oauth2/authorization/callback.rs | 6 +- .../src/oauth2/authorization/complete.rs | 3 +- .../handlers/src/oauth2/authorization/mod.rs | 4 +- crates/handlers/src/views/shared.rs | 2 +- crates/policy/src/lib.rs | 6 +- crates/storage/src/lib.rs | 14 ---- crates/storage/src/oauth2/access_token.rs | 12 +-- .../storage/src/oauth2/authorization_grant.rs | 56 ++++++------- crates/storage/src/oauth2/mod.rs | 14 ++-- crates/storage/src/oauth2/refresh_token.rs | 12 +-- crates/templates/src/context.rs | 26 ++---- 18 files changed, 92 insertions(+), 233 deletions(-) delete mode 100644 crates/data-model/src/traits.rs diff --git a/crates/axum-utils/src/user_authorization.rs b/crates/axum-utils/src/user_authorization.rs index 6d4e592e..2c14fc63 100644 --- a/crates/axum-utils/src/user_authorization.rs +++ b/crates/axum-utils/src/user_authorization.rs @@ -29,7 +29,7 @@ use http::{header::WWW_AUTHENTICATE, HeaderMap, HeaderValue, Request, StatusCode use mas_data_model::Session; use mas_storage::{ oauth2::access_token::{lookup_active_access_token, AccessTokenLookupError}, - LookupError, PostgresqlBackend, + LookupError, }; use serde::{de::DeserializeOwned, Deserialize}; use sqlx::PgConnection; @@ -55,10 +55,7 @@ impl AccessToken { pub async fn fetch( &self, conn: &mut PgConnection, - ) -> Result< - (mas_data_model::AccessToken, Session), - AuthorizationVerificationError, - > { + ) -> Result<(mas_data_model::AccessToken, Session), AuthorizationVerificationError> { let token = match self { AccessToken::Form(t) | AccessToken::Header(t) => t, AccessToken::None => return Err(AuthorizationVerificationError::MissingToken), @@ -81,7 +78,7 @@ impl UserAuthorization { pub async fn protected_form( self, conn: &mut PgConnection, - ) -> Result<(Session, F), AuthorizationVerificationError> { + ) -> Result<(Session, F), AuthorizationVerificationError> { let form = match self.form { Some(f) => f, None => return Err(AuthorizationVerificationError::MissingForm), @@ -96,7 +93,7 @@ impl UserAuthorization { pub async fn protected( self, conn: &mut PgConnection, - ) -> Result, AuthorizationVerificationError> { + ) -> Result { let (_token, session) = self.access_token.fetch(conn).await?; Ok(session) diff --git a/crates/data-model/src/lib.rs b/crates/data-model/src/lib.rs index 9143369f..261d20a5 100644 --- a/crates/data-model/src/lib.rs +++ b/crates/data-model/src/lib.rs @@ -26,7 +26,6 @@ pub(crate) mod compat; pub(crate) mod oauth2; pub(crate) mod tokens; -pub(crate) mod traits; pub(crate) mod upstream_oauth2; pub(crate) mod users; @@ -40,7 +39,6 @@ pub use self::{ InvalidRedirectUriError, JwksOrJwksUri, Pkce, Session, }, tokens::{AccessToken, RefreshToken, TokenFormatError, TokenType}, - traits::{StorageBackend, StorageBackendMarker}, upstream_oauth2::{ UpstreamOAuthAuthorizationSession, UpstreamOAuthLink, UpstreamOAuthProvider, }, diff --git a/crates/data-model/src/oauth2/authorization_grant.rs b/crates/data-model/src/oauth2/authorization_grant.rs index 9e3fd485..cb85a265 100644 --- a/crates/data-model/src/oauth2/authorization_grant.rs +++ b/crates/data-model/src/oauth2/authorization_grant.rs @@ -22,10 +22,10 @@ use oauth2_types::{ }; use serde::Serialize; use thiserror::Error; +use ulid::Ulid; use url::Url; use super::{client::Client, session::Session}; -use crate::{traits::StorageBackend, StorageBackendMarker}; #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Pkce { @@ -57,16 +57,17 @@ pub struct AuthorizationCode { #[error("invalid state transition")] pub struct InvalidTransitionError; -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(bound = "T: StorageBackend", tag = "stage", rename_all = "lowercase")] -pub enum AuthorizationGrantStage { +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Default)] +#[serde(tag = "stage", rename_all = "lowercase")] +pub enum AuthorizationGrantStage { + #[default] Pending, Fulfilled { - session: Session, + session: Session, fulfilled_at: DateTime, }, Exchanged { - session: Session, + session: Session, fulfilled_at: DateTime, exchanged_at: DateTime, }, @@ -75,13 +76,7 @@ pub enum AuthorizationGrantStage { }, } -impl Default for AuthorizationGrantStage { - fn default() -> Self { - Self::Pending - } -} - -impl AuthorizationGrantStage { +impl AuthorizationGrantStage { #[must_use] pub fn new() -> Self { Self::Pending @@ -90,7 +85,7 @@ impl AuthorizationGrantStage { pub fn fulfill( self, fulfilled_at: DateTime, - session: Session, + session: Session, ) -> Result { match self { Self::Pending => Ok(Self::Fulfilled { @@ -131,39 +126,11 @@ impl AuthorizationGrantStage { } } -impl From> for AuthorizationGrantStage<()> { - fn from(s: AuthorizationGrantStage) -> Self { - use AuthorizationGrantStage::{Cancelled, Exchanged, Fulfilled, Pending}; - match s { - Pending => Pending, - Fulfilled { - session, - fulfilled_at, - } => Fulfilled { - session: session.into(), - fulfilled_at, - }, - Exchanged { - session, - fulfilled_at, - exchanged_at, - } => Exchanged { - session: session.into(), - fulfilled_at, - exchanged_at, - }, - Cancelled { cancelled_at } => Cancelled { cancelled_at }, - } - } -} - -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(bound = "T: StorageBackend")] -pub struct AuthorizationGrant { - #[serde(skip_serializing)] - pub data: T::AuthorizationGrantData, +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AuthorizationGrant { + pub id: Ulid, #[serde(flatten)] - pub stage: AuthorizationGrantStage, + pub stage: AuthorizationGrantStage, pub code: Option, pub client: Client, pub redirect_uri: Url, @@ -177,27 +144,8 @@ pub struct AuthorizationGrant { pub requires_consent: bool, } -impl From> for AuthorizationGrant<()> { - fn from(g: AuthorizationGrant) -> Self { - AuthorizationGrant { - data: (), - stage: g.stage.into(), - code: g.code, - client: g.client, - redirect_uri: g.redirect_uri, - scope: g.scope, - state: g.state, - nonce: g.nonce, - max_age: g.max_age, - response_mode: g.response_mode, - response_type_id_token: g.response_type_id_token, - created_at: g.created_at, - requires_consent: g.requires_consent, - } - } -} - -impl AuthorizationGrant { +impl AuthorizationGrant { + #[must_use] pub fn max_auth_time(&self) -> DateTime { let max_age: Option = self.max_age.map(|x| x.get().into()); self.created_at - Duration::seconds(max_age.unwrap_or(3600 * 24 * 365)) diff --git a/crates/data-model/src/oauth2/session.rs b/crates/data-model/src/oauth2/session.rs index 7d6b21a4..ff222ca8 100644 --- a/crates/data-model/src/oauth2/session.rs +++ b/crates/data-model/src/oauth2/session.rs @@ -14,30 +14,15 @@ use oauth2_types::scope::Scope; use serde::Serialize; +use ulid::Ulid; use super::client::Client; -use crate::{ - traits::{StorageBackend, StorageBackendMarker}, - users::BrowserSession, -}; +use crate::users::BrowserSession; -#[derive(Debug, Clone, PartialEq, Serialize)] -#[serde(bound = "T: StorageBackend")] -pub struct Session { - #[serde(skip_serializing)] - pub data: T::SessionData, +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Session { + pub id: Ulid, pub browser_session: BrowserSession, pub client: Client, pub scope: Scope, } - -impl From> for Session<()> { - fn from(s: Session) -> Self { - Session { - data: (), - browser_session: s.browser_session, - client: s.client, - scope: s.scope, - } - } -} diff --git a/crates/data-model/src/traits.rs b/crates/data-model/src/traits.rs deleted file mode 100644 index 921894b9..00000000 --- a/crates/data-model/src/traits.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2021 The Matrix.org Foundation C.I.C. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use std::fmt::Debug; - -use serde::{de::DeserializeOwned, Serialize}; - -pub trait StorageBackendMarker: StorageBackend {} - -/// Marker trait of traits that should be implemented by primary keys -pub trait Data: - Clone + Debug + PartialEq + Serialize + DeserializeOwned + Default + Sync + Send -{ -} - -impl Data - for T -{ -} - -pub trait StorageBackend { - type ClientData: Data; - type SessionData: Data; - type AuthorizationGrantData: Data; -} - -impl StorageBackend for () { - type AuthorizationGrantData = (); - type ClientData = (); - type SessionData = (); -} diff --git a/crates/graphql/src/model/oauth.rs b/crates/graphql/src/model/oauth.rs index bc5d50df..fd0c5eab 100644 --- a/crates/graphql/src/model/oauth.rs +++ b/crates/graphql/src/model/oauth.rs @@ -13,7 +13,7 @@ // limitations under the License. use async_graphql::{Context, Description, Object, ID}; -use mas_storage::{oauth2::client::lookup_client, PostgresqlBackend}; +use mas_storage::oauth2::client::lookup_client; use oauth2_types::scope::Scope; use sqlx::PgPool; use ulid::Ulid; @@ -24,13 +24,13 @@ use super::{BrowserSession, NodeType, User}; /// An OAuth 2.0 session represents a client session which used the OAuth APIs /// to login. #[derive(Description)] -pub struct OAuth2Session(pub mas_data_model::Session); +pub struct OAuth2Session(pub mas_data_model::Session); #[Object(use_type_description)] impl OAuth2Session { /// ID of the object. pub async fn id(&self) -> ID { - NodeType::OAuth2Session.id(self.0.data) + NodeType::OAuth2Session.id(self.0.id) } /// OAuth 2.0 client used by this session. diff --git a/crates/graphql/src/model/users.rs b/crates/graphql/src/model/users.rs index 8ec4b003..ad8bfa43 100644 --- a/crates/graphql/src/model/users.rs +++ b/crates/graphql/src/model/users.rs @@ -242,7 +242,7 @@ impl User { let mut connection = Connection::new(has_previous_page, has_next_page); connection.edges.extend(edges.into_iter().map(|s| { Edge::new( - OpaqueCursor(NodeCursor(NodeType::OAuth2Session, s.data)), + OpaqueCursor(NodeCursor(NodeType::OAuth2Session, s.id)), OAuth2Session(s), ) })); diff --git a/crates/handlers/src/oauth2/authorization/callback.rs b/crates/handlers/src/oauth2/authorization/callback.rs index cf51ba81..515e1ff0 100644 --- a/crates/handlers/src/oauth2/authorization/callback.rs +++ b/crates/handlers/src/oauth2/authorization/callback.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use axum::response::{Html, IntoResponse, Redirect, Response}; -use mas_data_model::{AuthorizationGrant, StorageBackend}; +use mas_data_model::AuthorizationGrant; use mas_templates::{FormPostContext, Templates}; use oauth2_types::requests::ResponseMode; use serde::Serialize; @@ -61,10 +61,10 @@ pub enum CallbackDestinationError { ParamsSerialization(#[from] serde_urlencoded::ser::Error), } -impl TryFrom<&AuthorizationGrant> for CallbackDestination { +impl TryFrom<&AuthorizationGrant> for CallbackDestination { type Error = IntoCallbackDestinationError; - fn try_from(value: &AuthorizationGrant) -> Result { + fn try_from(value: &AuthorizationGrant) -> Result { Self::try_new( &value.response_mode, value.redirect_uri.clone(), diff --git a/crates/handlers/src/oauth2/authorization/complete.rs b/crates/handlers/src/oauth2/authorization/complete.rs index b1410c0b..3dbf8dc6 100644 --- a/crates/handlers/src/oauth2/authorization/complete.rs +++ b/crates/handlers/src/oauth2/authorization/complete.rs @@ -32,7 +32,6 @@ use mas_storage::{ consent::fetch_client_consent, }, user::ActiveSessionLookupError, - PostgresqlBackend, }; use mas_templates::Templates; use oauth2_types::requests::{AccessTokenResponse, AuthorizationResponse}; @@ -185,7 +184,7 @@ impl From for GrantCompletionError { } pub(crate) async fn complete( - grant: AuthorizationGrant, + grant: AuthorizationGrant, browser_session: BrowserSession, policy_factory: &PolicyFactory, mut txn: Transaction<'_, Postgres>, diff --git a/crates/handlers/src/oauth2/authorization/mod.rs b/crates/handlers/src/oauth2/authorization/mod.rs index 53930769..bd2906a9 100644 --- a/crates/handlers/src/oauth2/authorization/mod.rs +++ b/crates/handlers/src/oauth2/authorization/mod.rs @@ -315,7 +315,7 @@ pub(crate) async fn get( requires_consent, ) .await?; - let continue_grant = PostAuthAction::continue_grant(grant.data); + let continue_grant = PostAuthAction::continue_grant(grant.id); let res = match maybe_session { // Cases where there is no active session, redirect to the relevant page @@ -391,7 +391,7 @@ pub(crate) async fn get( } } Some(user_session) => { - let grant_id = grant.data; + let grant_id = grant.id; // Else, we show the relevant reauth/consent page if necessary match self::complete::complete(grant, user_session, &policy_factory, txn).await { diff --git a/crates/handlers/src/views/shared.rs b/crates/handlers/src/views/shared.rs index e2cd1815..7165e377 100644 --- a/crates/handlers/src/views/shared.rs +++ b/crates/handlers/src/views/shared.rs @@ -45,7 +45,7 @@ impl OptionalPostAuthAction { let ctx = match action { PostAuthAction::ContinueAuthorizationGrant { data } => { let grant = get_grant_by_id(conn, data).await?; - let grant = Box::new(grant.into()); + let grant = Box::new(grant); PostAuthContextInner::ContinueAuthorizationGrant { grant } } diff --git a/crates/policy/src/lib.rs b/crates/policy/src/lib.rs index 033b33bb..ceb65d58 100644 --- a/crates/policy/src/lib.rs +++ b/crates/policy/src/lib.rs @@ -18,7 +18,7 @@ #![allow(clippy::missing_errors_doc)] use anyhow::bail; -use mas_data_model::{AuthorizationGrant, StorageBackend, User}; +use mas_data_model::{AuthorizationGrant, User}; use oauth2_types::registration::VerifiedClientMetadata; use opa_wasm::Runtime; use serde::Deserialize; @@ -210,9 +210,9 @@ impl Policy { } #[tracing::instrument(skip(self))] - pub async fn evaluate_authorization_grant( + pub async fn evaluate_authorization_grant( &mut self, - authorization_grant: &AuthorizationGrant, + authorization_grant: &AuthorizationGrant, user: &User, ) -> Result { let authorization_grant = serde_json::to_value(authorization_grant)?; diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index ebe208dd..6ad9d366 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -29,11 +29,8 @@ )] use chrono::{DateTime, Utc}; -use mas_data_model::{StorageBackend, StorageBackendMarker}; -use serde::Serialize; use sqlx::migrate::Migrator; use thiserror::Error; -use ulid::Ulid; #[derive(Debug, Error)] #[error("failed to lookup {what}")] @@ -101,17 +98,6 @@ impl Clock { #[error("database query returned an inconsistent state")] pub struct DatabaseInconsistencyError; -#[derive(Serialize, Debug, Clone, PartialEq, Eq)] -pub struct PostgresqlBackend; - -impl StorageBackend for PostgresqlBackend { - type AuthorizationGrantData = Ulid; - type ClientData = Ulid; - type SessionData = Ulid; -} - -impl StorageBackendMarker for PostgresqlBackend {} - pub mod compat; pub mod oauth2; pub(crate) mod pagination; diff --git a/crates/storage/src/oauth2/access_token.rs b/crates/storage/src/oauth2/access_token.rs index d5462dd0..cf147596 100644 --- a/crates/storage/src/oauth2/access_token.rs +++ b/crates/storage/src/oauth2/access_token.rs @@ -22,12 +22,12 @@ use ulid::Ulid; use uuid::Uuid; use super::client::{lookup_client, ClientFetchError}; -use crate::{Clock, DatabaseInconsistencyError, LookupError, PostgresqlBackend}; +use crate::{Clock, DatabaseInconsistencyError, LookupError}; #[tracing::instrument( skip_all, fields( - session.id = %session.data, + %session.id, client.id = %session.client.id, user.id = %session.browser_session.user.id, access_token.id, @@ -38,7 +38,7 @@ pub async fn add_access_token( executor: impl PgExecutor<'_>, mut rng: impl Rng + Send, clock: &Clock, - session: &Session, + session: &Session, access_token: String, expires_after: Duration, ) -> Result { @@ -56,7 +56,7 @@ pub async fn add_access_token( ($1, $2, $3, $4, $5) "#, Uuid::from(id), - Uuid::from(session.data), + Uuid::from(session.id), &access_token, created_at, expires_at, @@ -113,7 +113,7 @@ impl LookupError for AccessTokenLookupError { pub async fn lookup_active_access_token( conn: &mut PgConnection, token: &str, -) -> Result<(AccessToken, Session), AccessTokenLookupError> { +) -> Result<(AccessToken, Session), AccessTokenLookupError> { let res = sqlx::query_as!( OAuth2AccessTokenLookup, r#" @@ -217,7 +217,7 @@ pub async fn lookup_active_access_token( let scope = res.scope.parse().map_err(|_e| DatabaseInconsistencyError)?; let session = Session { - data: res.oauth2_session_id.into(), + id: res.oauth2_session_id.into(), client, browser_session, scope, diff --git a/crates/storage/src/oauth2/authorization_grant.rs b/crates/storage/src/oauth2/authorization_grant.rs index b8db3c0b..39476250 100644 --- a/crates/storage/src/oauth2/authorization_grant.rs +++ b/crates/storage/src/oauth2/authorization_grant.rs @@ -31,7 +31,7 @@ use url::Url; use uuid::Uuid; use super::client::lookup_client; -use crate::{Clock, DatabaseInconsistencyError, PostgresqlBackend}; +use crate::{Clock, DatabaseInconsistencyError}; #[tracing::instrument( skip_all, @@ -57,7 +57,7 @@ pub async fn new_authorization_grant( response_mode: ResponseMode, response_type_id_token: bool, requires_consent: bool, -) -> Result, anyhow::Error> { +) -> Result { let code_challenge = code .as_ref() .and_then(|c| c.pkce.as_ref()) @@ -117,7 +117,7 @@ pub async fn new_authorization_grant( .context("could not insert oauth2 authorization grant")?; Ok(AuthorizationGrant { - data: id, + id, stage: AuthorizationGrantStage::Pending, code, redirect_uri, @@ -171,7 +171,7 @@ impl GrantLookup { async fn into_authorization_grant( self, executor: impl PgExecutor<'_>, - ) -> Result, DatabaseInconsistencyError> { + ) -> Result { let scope: Scope = self .oauth2_authorization_grant_scope .parse() @@ -247,7 +247,7 @@ impl GrantLookup { let scope = scope.clone(); let session = Session { - data: session_id.into(), + id: session_id.into(), client, browser_session, scope, @@ -337,7 +337,7 @@ impl GrantLookup { .map_err(|_e| DatabaseInconsistencyError)?; Ok(AuthorizationGrant { - data: self.oauth2_authorization_grant_id.into(), + id: self.oauth2_authorization_grant_id.into(), stage, client, code, @@ -362,7 +362,7 @@ impl GrantLookup { pub async fn get_grant_by_id( conn: &mut PgConnection, id: Ulid, -) -> Result, anyhow::Error> { +) -> Result { // TODO: handle "not found" cases let res = sqlx::query_as!( GrantLookup, @@ -430,7 +430,7 @@ pub async fn get_grant_by_id( pub async fn lookup_grant_by_code( conn: &mut PgConnection, code: &str, -) -> Result, anyhow::Error> { +) -> Result { // TODO: handle "not found" cases let res = sqlx::query_as!( GrantLookup, @@ -497,7 +497,7 @@ pub async fn lookup_grant_by_code( #[tracing::instrument( skip_all, fields( - grant.id = %grant.data, + %grant.id, client.id = %grant.client.id, session.id, user_session.id = %browser_session.id, @@ -509,9 +509,9 @@ pub async fn derive_session( executor: impl PgExecutor<'_>, mut rng: impl Rng + Send, clock: &Clock, - grant: &AuthorizationGrant, + grant: &AuthorizationGrant, browser_session: BrowserSession, -) -> Result, anyhow::Error> { +) -> Result { let created_at = clock.now(); let id = Ulid::from_datetime_with_source(created_at.into(), &mut rng); tracing::Span::current().record("session.id", tracing::field::display(id)); @@ -534,14 +534,14 @@ pub async fn derive_session( Uuid::from(id), Uuid::from(browser_session.id), created_at, - Uuid::from(grant.data), + Uuid::from(grant.id), ) .execute(executor) .await .context("could not insert oauth2 session")?; Ok(Session { - data: id, + id, browser_session, client: grant.client.clone(), scope: grant.scope.clone(), @@ -551,9 +551,9 @@ pub async fn derive_session( #[tracing::instrument( skip_all, fields( - grant.id = %grant.data, + %grant.id, client.id = %grant.client.id, - session.id = %session.data, + %session.id, user_session.id = %session.browser_session.id, user.id = %session.browser_session.user.id, ), @@ -561,9 +561,9 @@ pub async fn derive_session( )] pub async fn fulfill_grant( executor: impl PgExecutor<'_>, - mut grant: AuthorizationGrant, - session: Session, -) -> Result, anyhow::Error> { + mut grant: AuthorizationGrant, + session: Session, +) -> Result { let fulfilled_at = sqlx::query_scalar!( r#" UPDATE oauth2_authorization_grants AS og @@ -576,8 +576,8 @@ pub async fn fulfill_grant( AND os.oauth2_session_id = $2 RETURNING fulfilled_at AS "fulfilled_at!: DateTime" "#, - Uuid::from(grant.data), - Uuid::from(session.data), + Uuid::from(grant.id), + Uuid::from(session.id), ) .fetch_one(executor) .await @@ -591,15 +591,15 @@ pub async fn fulfill_grant( #[tracing::instrument( skip_all, fields( - grant.id = %grant.data, + %grant.id, client.id = %grant.client.id, ), err(Debug), )] pub async fn give_consent_to_grant( executor: impl PgExecutor<'_>, - mut grant: AuthorizationGrant, -) -> Result, sqlx::Error> { + mut grant: AuthorizationGrant, +) -> Result { sqlx::query!( r#" UPDATE oauth2_authorization_grants AS og @@ -608,7 +608,7 @@ pub async fn give_consent_to_grant( WHERE og.oauth2_authorization_grant_id = $1 "#, - Uuid::from(grant.data), + Uuid::from(grant.id), ) .execute(executor) .await?; @@ -621,7 +621,7 @@ pub async fn give_consent_to_grant( #[tracing::instrument( skip_all, fields( - grant.id = %grant.data, + %grant.id, client.id = %grant.client.id, ), err(Debug), @@ -629,8 +629,8 @@ pub async fn give_consent_to_grant( pub async fn exchange_grant( executor: impl PgExecutor<'_>, clock: &Clock, - mut grant: AuthorizationGrant, -) -> Result, anyhow::Error> { + mut grant: AuthorizationGrant, +) -> Result { let exchanged_at = clock.now(); sqlx::query!( r#" @@ -638,7 +638,7 @@ pub async fn exchange_grant( SET exchanged_at = $2 WHERE oauth2_authorization_grant_id = $1 "#, - Uuid::from(grant.data), + Uuid::from(grant.id), exchanged_at, ) .execute(executor) diff --git a/crates/storage/src/oauth2/mod.rs b/crates/storage/src/oauth2/mod.rs index d20aea05..50db0c59 100644 --- a/crates/storage/src/oauth2/mod.rs +++ b/crates/storage/src/oauth2/mod.rs @@ -25,7 +25,7 @@ use self::client::lookup_clients; use crate::{ pagination::{process_page, QueryBuilderExt}, user::lookup_active_session, - Clock, PostgresqlBackend, + Clock, }; pub mod access_token; @@ -37,7 +37,7 @@ pub mod refresh_token; #[tracing::instrument( skip_all, fields( - session.id = %session.data, + %session.id, user.id = %session.browser_session.user.id, user_session.id = %session.browser_session.id, client.id = %session.client.id, @@ -47,7 +47,7 @@ pub mod refresh_token; pub async fn end_oauth_session( executor: impl PgExecutor<'_>, clock: &Clock, - session: Session, + session: Session, ) -> Result<(), anyhow::Error> { let finished_at = clock.now(); let res = sqlx::query!( @@ -56,7 +56,7 @@ pub async fn end_oauth_session( SET finished_at = $2 WHERE oauth2_session_id = $1 "#, - Uuid::from(session.data), + Uuid::from(session.id), finished_at, ) .execute(executor) @@ -79,7 +79,7 @@ struct OAuthSessionLookup { skip_all, fields( %user.id, - user.username = user.username, + %user.username, ), err(Display), )] @@ -90,7 +90,7 @@ pub async fn get_paginated_user_oauth_sessions( after: Option, first: Option, last: Option, -) -> Result<(bool, bool, Vec>), anyhow::Error> { +) -> Result<(bool, bool, Vec), anyhow::Error> { let mut query = QueryBuilder::new( r#" SELECT @@ -157,7 +157,7 @@ pub async fn get_paginated_user_oauth_sessions( let scope = item.scope.parse()?; anyhow::Ok(Session { - data: Ulid::from(item.oauth2_session_id), + id: Ulid::from(item.oauth2_session_id), client, browser_session, scope, diff --git a/crates/storage/src/oauth2/refresh_token.rs b/crates/storage/src/oauth2/refresh_token.rs index 5433c968..60f41d14 100644 --- a/crates/storage/src/oauth2/refresh_token.rs +++ b/crates/storage/src/oauth2/refresh_token.rs @@ -24,12 +24,12 @@ use ulid::Ulid; use uuid::Uuid; use super::client::{lookup_client, ClientFetchError}; -use crate::{Clock, DatabaseInconsistencyError, LookupError, PostgresqlBackend}; +use crate::{Clock, DatabaseInconsistencyError, LookupError}; #[tracing::instrument( skip_all, fields( - session.id = %session.data, + %session.id, user.id = %session.browser_session.user.id, user_session.id = %session.browser_session.id, client.id = %session.client.id, @@ -41,7 +41,7 @@ pub async fn add_refresh_token( executor: impl PgExecutor<'_>, mut rng: impl Rng + Send, clock: &Clock, - session: &Session, + session: &Session, access_token: AccessToken, refresh_token: String, ) -> anyhow::Result { @@ -58,7 +58,7 @@ pub async fn add_refresh_token( ($1, $2, $3, $4, $5) "#, Uuid::from(id), - Uuid::from(session.data), + Uuid::from(session.id), Uuid::from(access_token.id), refresh_token, created_at, @@ -117,7 +117,7 @@ impl LookupError for RefreshTokenLookupError { pub async fn lookup_active_refresh_token( conn: &mut PgConnection, token: &str, -) -> Result<(RefreshToken, Session), RefreshTokenLookupError> { +) -> Result<(RefreshToken, Session), RefreshTokenLookupError> { let res = sqlx::query_as!( OAuth2RefreshTokenLookup, r#" @@ -248,7 +248,7 @@ pub async fn lookup_active_refresh_token( .map_err(|_e| DatabaseInconsistencyError)?; let session = Session { - data: res.oauth2_session_id.into(), + id: res.oauth2_session_id.into(), client, browser_session, scope, diff --git a/crates/templates/src/context.rs b/crates/templates/src/context.rs index bcde9836..123e462c 100644 --- a/crates/templates/src/context.rs +++ b/crates/templates/src/context.rs @@ -249,7 +249,7 @@ pub enum PostAuthContextInner { /// Continue an authorization grant ContinueAuthorizationGrant { /// The authorization grant that will be continued after authentication - grant: Box>, + grant: Box, }, /// Continue legacy login @@ -394,7 +394,7 @@ impl RegisterContext { /// Context used by the `consent.html` template #[derive(Serialize)] pub struct ConsentContext { - grant: AuthorizationGrant<()>, + grant: AuthorizationGrant, action: PostAuthAction, } @@ -411,21 +411,15 @@ impl TemplateContext for ConsentContext { impl ConsentContext { /// Constructs a context for the client consent page #[must_use] - pub fn new(grant: T, action: PostAuthAction) -> Self - where - T: Into>, - { - Self { - grant: grant.into(), - action, - } + pub fn new(grant: AuthorizationGrant, action: PostAuthAction) -> Self { + Self { grant, action } } } /// Context used by the `policy_violation.html` template #[derive(Serialize)] pub struct PolicyViolationContext { - grant: AuthorizationGrant<()>, + grant: AuthorizationGrant, action: PostAuthAction, } @@ -442,14 +436,8 @@ impl TemplateContext for PolicyViolationContext { impl PolicyViolationContext { /// Constructs a context for the policy violation page #[must_use] - pub fn new(grant: T, action: PostAuthAction) -> Self - where - T: Into>, - { - Self { - grant: grant.into(), - action, - } + pub fn new(grant: AuthorizationGrant, action: PostAuthAction) -> Self { + Self { grant, action } } }