1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-07-28 11:02:02 +03:00

WIP: repository pattern for upstream oauth2 links

This commit is contained in:
Quentin Gliech
2022-12-30 10:16:22 +01:00
parent aa1cfcefc4
commit 5969b574e2
14 changed files with 419 additions and 287 deletions

View File

@ -12,19 +12,71 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use mas_data_model::{UpstreamOAuthLink, UpstreamOAuthProvider, User};
use rand::Rng;
use sqlx::{PgExecutor, QueryBuilder};
use rand::RngCore;
use sqlx::{PgConnection, QueryBuilder};
use tracing::{info_span, Instrument};
use ulid::Ulid;
use uuid::Uuid;
use crate::{
pagination::{process_page, QueryBuilderExt},
pagination::{process_page, Page, QueryBuilderExt},
Clock, DatabaseError, LookupResultExt,
};
#[async_trait]
pub trait UpstreamOAuthLinkRepository: Send + Sync {
type Error;
/// Lookup an upstream OAuth link by its ID
async fn lookup(&mut self, id: Ulid) -> Result<Option<UpstreamOAuthLink>, Self::Error>;
/// Find an upstream OAuth link for a provider by its subject
async fn find_by_subject(
&mut self,
upstream_oauth_provider: &UpstreamOAuthProvider,
subject: &str,
) -> Result<Option<UpstreamOAuthLink>, Self::Error>;
/// Add a new upstream OAuth link
async fn add(
&mut self,
rng: &mut (dyn RngCore + Send),
clock: &Clock,
upstream_oauth_provider: &UpstreamOAuthProvider,
subject: String,
) -> Result<UpstreamOAuthLink, Self::Error>;
/// Associate an upstream OAuth link to a user
async fn associate_to_user(
&mut self,
upstream_oauth_link: &UpstreamOAuthLink,
user: &User,
) -> Result<(), Self::Error>;
/// Get a paginated list of upstream OAuth links
async fn list_paginated(
&mut self,
user: &User,
before: Option<Ulid>,
after: Option<Ulid>,
first: Option<usize>,
last: Option<usize>,
) -> Result<Page<UpstreamOAuthLink>, Self::Error>;
}
pub struct PgUpstreamOAuthLinkRepository<'c> {
conn: &'c mut PgConnection,
}
impl<'c> PgUpstreamOAuthLinkRepository<'c> {
pub fn new(conn: &'c mut PgConnection) -> Self {
Self { conn }
}
}
#[derive(sqlx::FromRow)]
struct LinkLookup {
upstream_oauth_link_id: Uuid,
@ -46,197 +98,203 @@ impl From<LinkLookup> for UpstreamOAuthLink {
}
}
#[tracing::instrument(
skip_all,
fields(upstream_oauth_link.id = %id),
err,
)]
pub async fn lookup_link(
executor: impl PgExecutor<'_>,
id: Ulid,
) -> Result<Option<UpstreamOAuthLink>, DatabaseError> {
let res = sqlx::query_as!(
LinkLookup,
r#"
SELECT
upstream_oauth_link_id,
upstream_oauth_provider_id,
user_id,
subject,
created_at
FROM upstream_oauth_links
WHERE upstream_oauth_link_id = $1
"#,
Uuid::from(id),
)
.fetch_one(executor)
.await
.to_option()?
.map(Into::into);
#[async_trait]
impl<'c> UpstreamOAuthLinkRepository for PgUpstreamOAuthLinkRepository<'c> {
type Error = DatabaseError;
Ok(res)
}
#[tracing::instrument(
skip_all,
fields(upstream_oauth_link.id = %id),
err,
)]
async fn lookup(&mut self, id: Ulid) -> Result<Option<UpstreamOAuthLink>, Self::Error> {
let res = sqlx::query_as!(
LinkLookup,
r#"
SELECT
upstream_oauth_link_id,
upstream_oauth_provider_id,
user_id,
subject,
created_at
FROM upstream_oauth_links
WHERE upstream_oauth_link_id = $1
"#,
Uuid::from(id),
)
.fetch_one(&mut *self.conn)
.await
.to_option()?
.map(Into::into);
#[tracing::instrument(
skip_all,
fields(
upstream_oauth_link.subject = subject,
%upstream_oauth_provider.id,
%upstream_oauth_provider.issuer,
%upstream_oauth_provider.client_id,
),
err,
)]
pub async fn lookup_link_by_subject(
executor: impl PgExecutor<'_>,
upstream_oauth_provider: &UpstreamOAuthProvider,
subject: &str,
) -> Result<Option<UpstreamOAuthLink>, DatabaseError> {
let res = sqlx::query_as!(
LinkLookup,
r#"
SELECT
upstream_oauth_link_id,
upstream_oauth_provider_id,
user_id,
subject,
created_at
FROM upstream_oauth_links
WHERE upstream_oauth_provider_id = $1
AND subject = $2
"#,
Uuid::from(upstream_oauth_provider.id),
subject,
)
.fetch_one(executor)
.await
.to_option()?
.map(Into::into);
Ok(res)
}
Ok(res)
}
#[tracing::instrument(
skip_all,
fields(
upstream_oauth_link.subject = subject,
%upstream_oauth_provider.id,
%upstream_oauth_provider.issuer,
%upstream_oauth_provider.client_id,
),
err,
)]
async fn find_by_subject(
&mut self,
upstream_oauth_provider: &UpstreamOAuthProvider,
subject: &str,
) -> Result<Option<UpstreamOAuthLink>, Self::Error> {
let res = sqlx::query_as!(
LinkLookup,
r#"
SELECT
upstream_oauth_link_id,
upstream_oauth_provider_id,
user_id,
subject,
created_at
FROM upstream_oauth_links
WHERE upstream_oauth_provider_id = $1
AND subject = $2
"#,
Uuid::from(upstream_oauth_provider.id),
subject,
)
.fetch_one(&mut *self.conn)
.await
.to_option()?
.map(Into::into);
#[tracing::instrument(
skip_all,
fields(
upstream_oauth_link.id,
upstream_oauth_link.subject = subject,
%upstream_oauth_provider.id,
%upstream_oauth_provider.issuer,
%upstream_oauth_provider.client_id,
),
err,
)]
pub async fn add_link(
executor: impl PgExecutor<'_>,
mut rng: impl Rng + Send,
clock: &Clock,
upstream_oauth_provider: &UpstreamOAuthProvider,
subject: String,
) -> Result<UpstreamOAuthLink, DatabaseError> {
let created_at = clock.now();
let id = Ulid::from_datetime_with_source(created_at.into(), &mut rng);
tracing::Span::current().record("upstream_oauth_link.id", tracing::field::display(id));
Ok(res)
}
sqlx::query!(
r#"
INSERT INTO upstream_oauth_links (
upstream_oauth_link_id,
upstream_oauth_provider_id,
user_id,
subject,
created_at
) VALUES ($1, $2, NULL, $3, $4)
"#,
Uuid::from(id),
Uuid::from(upstream_oauth_provider.id),
&subject,
created_at,
)
.execute(executor)
.await?;
#[tracing::instrument(
skip_all,
fields(
upstream_oauth_link.id,
upstream_oauth_link.subject = subject,
%upstream_oauth_provider.id,
%upstream_oauth_provider.issuer,
%upstream_oauth_provider.client_id,
),
err,
)]
async fn add(
&mut self,
rng: &mut (dyn RngCore + Send),
clock: &Clock,
upstream_oauth_provider: &UpstreamOAuthProvider,
subject: String,
) -> Result<UpstreamOAuthLink, Self::Error> {
let created_at = clock.now();
let id = Ulid::from_datetime_with_source(created_at.into(), rng);
tracing::Span::current().record("upstream_oauth_link.id", tracing::field::display(id));
Ok(UpstreamOAuthLink {
id,
provider_id: upstream_oauth_provider.id,
user_id: None,
subject,
created_at,
})
}
#[tracing::instrument(
skip_all,
fields(
%upstream_oauth_link.id,
%upstream_oauth_link.subject,
%user.id,
%user.username,
),
err,
)]
pub async fn associate_link_to_user(
executor: impl PgExecutor<'_>,
upstream_oauth_link: &UpstreamOAuthLink,
user: &User,
) -> Result<(), sqlx::Error> {
sqlx::query!(
r#"
UPDATE upstream_oauth_links
SET user_id = $1
WHERE upstream_oauth_link_id = $2
"#,
Uuid::from(user.id),
Uuid::from(upstream_oauth_link.id),
)
.execute(executor)
.await?;
Ok(())
}
#[tracing::instrument(
skip_all,
fields(%user.id, %user.username),
err
)]
pub async fn get_paginated_user_links(
executor: impl PgExecutor<'_>,
user: &User,
before: Option<Ulid>,
after: Option<Ulid>,
first: Option<usize>,
last: Option<usize>,
) -> Result<(bool, bool, Vec<UpstreamOAuthLink>), DatabaseError> {
let mut query = QueryBuilder::new(
r#"
SELECT
upstream_oauth_link_id,
upstream_oauth_provider_id,
user_id,
subject,
created_at
FROM upstream_oauth_links
"#,
);
query
.push(" WHERE user_id = ")
.push_bind(Uuid::from(user.id))
.generate_pagination("upstream_oauth_link_id", before, after, first, last)?;
let span = info_span!(
"Fetch paginated upstream OAuth 2.0 user links",
db.statement = query.sql()
);
let page: Vec<LinkLookup> = query
.build_query_as()
.fetch_all(executor)
.instrument(span)
sqlx::query!(
r#"
INSERT INTO upstream_oauth_links (
upstream_oauth_link_id,
upstream_oauth_provider_id,
user_id,
subject,
created_at
) VALUES ($1, $2, NULL, $3, $4)
"#,
Uuid::from(id),
Uuid::from(upstream_oauth_provider.id),
&subject,
created_at,
)
.execute(&mut *self.conn)
.await?;
let (has_previous_page, has_next_page, page) = process_page(page, first, last)?;
Ok(UpstreamOAuthLink {
id,
provider_id: upstream_oauth_provider.id,
user_id: None,
subject,
created_at,
})
}
let page: Vec<_> = page.into_iter().map(Into::into).collect();
Ok((has_previous_page, has_next_page, page))
#[tracing::instrument(
skip_all,
fields(
%upstream_oauth_link.id,
%upstream_oauth_link.subject,
%user.id,
%user.username,
),
err,
)]
async fn associate_to_user(
&mut self,
upstream_oauth_link: &UpstreamOAuthLink,
user: &User,
) -> Result<(), Self::Error> {
sqlx::query!(
r#"
UPDATE upstream_oauth_links
SET user_id = $1
WHERE upstream_oauth_link_id = $2
"#,
Uuid::from(user.id),
Uuid::from(upstream_oauth_link.id),
)
.execute(&mut *self.conn)
.await?;
Ok(())
}
#[tracing::instrument(
skip_all,
fields(%user.id, %user.username),
err
)]
async fn list_paginated(
&mut self,
user: &User,
before: Option<Ulid>,
after: Option<Ulid>,
first: Option<usize>,
last: Option<usize>,
) -> Result<Page<UpstreamOAuthLink>, Self::Error> {
let mut query = QueryBuilder::new(
r#"
SELECT
upstream_oauth_link_id,
upstream_oauth_provider_id,
user_id,
subject,
created_at
FROM upstream_oauth_links
"#,
);
query
.push(" WHERE user_id = ")
.push_bind(Uuid::from(user.id))
.generate_pagination("upstream_oauth_link_id", before, after, first, last)?;
let span = info_span!(
"Fetch paginated upstream OAuth 2.0 user links",
db.statement = query.sql()
);
let page: Vec<LinkLookup> = query
.build_query_as()
.fetch_all(&mut *self.conn)
.instrument(span)
.await?;
let (has_previous_page, has_next_page, edges) = process_page(page, first, last)?;
let edges: Vec<_> = edges.into_iter().map(Into::into).collect();
Ok(Page {
has_next_page,
has_previous_page,
edges,
})
}
}

View File

@ -17,10 +17,7 @@ mod provider;
mod session;
pub use self::{
link::{
add_link, associate_link_to_user, get_paginated_user_links, lookup_link,
lookup_link_by_subject,
},
link::{PgUpstreamOAuthLinkRepository, UpstreamOAuthLinkRepository},
provider::{add_provider, get_paginated_providers, get_providers, lookup_provider},
session::{
add_session, complete_session, consume_session, lookup_session, lookup_session_on_link,