use crate::api::{Principal, PrincipalKind, TokenVerifier};
use crate::health::BoxFuture;
use crate::inertia::{Inertia, InertiaConfig};
use crate::session::Session;
use axum::extract::rejection::FormRejection;
use axum::extract::{FromRef, OriginalUri, Query, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Form, Json, Router};
use base64::{Engine, engine::general_purpose::STANDARD, engine::general_purpose::URL_SAFE_NO_PAD};
use sea_orm::entity::prelude::*;
use sea_orm::sea_query::{Alias, ColumnDef, Expr, Query as SqlQuery, Table};
use sea_orm::{
ActiveValue::Set, Condition, ConnectionTrait, DatabaseConnection, DbErr, QueryFilter,
QuerySelect, Schema,
};
use sea_orm_migration::SchemaManager;
use serde::{Deserialize, Serialize};
use serde_json::json;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::time::Duration;
const SESSION_USER: &str = "user_id";
const SESSION_PENDING: &str = "oauth_pending";
const CODE_TTL: i64 = 600;
pub mod clients {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "oauth_clients")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
#[sea_orm(unique)]
pub client_id: String,
pub secret_hash: Option<String>,
pub name: String,
#[sea_orm(column_type = "Text")]
pub redirect_uris: String,
#[sea_orm(column_type = "Text")]
pub allowed_scopes: String,
pub created_at: i64,
pub revoked_at: Option<i64>,
#[sea_orm(default_value = false)]
pub first_party: bool,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
pub mod codes {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "oauth_codes")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
#[sea_orm(unique)]
pub code_hash: String,
pub client_id: String,
#[sea_orm(indexed)]
pub user_id: i64,
#[sea_orm(column_type = "Text")]
pub redirect_uri: String,
#[sea_orm(column_type = "Text")]
pub scopes: String,
pub code_challenge: Option<String>,
pub expires_at: i64,
pub used_at: Option<i64>,
pub claim: Option<String>,
pub replayed_at: Option<i64>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
pub mod tokens {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "oauth_tokens")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
#[sea_orm(unique)]
pub access_hash: String,
#[sea_orm(unique)]
pub refresh_hash: Option<String>,
#[sea_orm(indexed)]
pub client_id: String,
#[sea_orm(indexed)]
pub user_id: Option<i64>,
#[sea_orm(column_type = "Text")]
pub scopes: String,
pub created_at: i64,
pub access_expires_at: i64,
pub refresh_expires_at: Option<i64>,
pub revoked_at: Option<i64>,
#[sea_orm(indexed)]
pub family_id: String,
#[sea_orm(indexed)]
pub code_id: Option<i64>,
pub refresh_used_at: Option<i64>,
pub refresh_claim: Option<String>,
pub last_used_at: Option<i64>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
#[derive(Debug, thiserror::Error)]
pub enum OAuthError {
#[error("database: {0}")]
Db(#[from] DbErr),
#[error("OS random number generator failed")]
Rng,
#[error("invalid: {0}")]
Invalid(&'static str),
}
#[derive(Clone)]
pub struct NewClient {
pub client_id: String,
pub client_secret: Option<String>,
}
impl std::fmt::Debug for NewClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NewClient")
.field("client_id", &self.client_id)
.field(
"client_secret",
&self.client_secret.as_ref().map(|_| "<redacted>"),
)
.finish()
}
}
#[derive(Clone, Debug)]
pub struct ClientSpec {
pub name: String,
pub redirect_uris: Vec<String>,
pub scopes: Vec<String>,
pub confidential: bool,
pub first_party: bool,
}
impl ClientSpec {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
redirect_uris: vec![],
scopes: vec![],
confidential: false,
first_party: false,
}
}
pub fn redirect(mut self, uri: impl Into<String>) -> Self {
self.redirect_uris.push(uri.into());
self
}
pub fn scope(mut self, s: impl Into<String>) -> Self {
self.scopes.push(s.into());
self
}
pub fn confidential(mut self) -> Self {
self.confidential = true;
self
}
pub fn first_party(mut self) -> Self {
self.first_party = true;
self
}
}
#[derive(Clone)]
pub struct OAuthServer {
db: DatabaseConnection,
access_ttl: Duration,
refresh_ttl: Duration,
}
async fn add_column_if_missing<E, C>(
db: &DatabaseConnection,
table: E,
column: C,
def: ColumnDef,
) -> Result<(), DbErr>
where
E: sea_orm::sea_query::IntoTableRef + sea_orm::sea_query::IntoIden + Copy,
C: sea_orm::sea_query::IntoIden,
{
let probe = SqlQuery::select()
.column((table, column)) .from(table)
.limit(1)
.to_owned();
if db.query_all(&probe).await.is_err() {
let alter = Table::alter().table(table).add_column(def).to_owned();
if let Err(e) = SchemaManager::new(db).alter_table(alter).await
&& db.query_all(&probe).await.is_err()
{
return Err(e);
}
}
Ok(())
}
async fn mysql_has_index(db: &DatabaseConnection, table: &str, index: &str) -> Result<bool, DbErr> {
use sea_orm::ExprTrait;
use sea_orm::sea_query::Func;
let q = SqlQuery::select()
.column(Alias::new("index_name"))
.from((Alias::new("information_schema"), Alias::new("statistics")))
.and_where(Expr::col(Alias::new("table_schema")).eq(Func::cust(Alias::new("DATABASE"))))
.and_where(Expr::col(Alias::new("table_name")).eq(table))
.and_where(Expr::col(Alias::new("index_name")).eq(index))
.limit(1)
.to_owned();
Ok(!db.query_all(&q).await?.is_empty())
}
fn is_deadlock(e: &DbErr) -> bool {
let m = e.to_string();
m.contains("Deadlock") || m.contains("40P01") || m.contains("40001")
}
async fn retried<T, Fut: std::future::Future<Output = Result<T, DbErr>>>(
mut f: impl FnMut() -> Fut,
) -> Result<T, DbErr> {
let mut tries = 0u64;
loop {
match f().await {
Err(e) if tries < 5 && is_deadlock(&e) => {
tries += 1;
tokio::time::sleep(Duration::from_millis(5 * tries)).await;
}
r => return r,
}
}
}
async fn ensure_indexes<E: EntityTrait>(db: &DatabaseConnection, entity: E) -> Result<(), DbErr> {
let b = db.get_database_backend();
for mut i in Schema::new(b).create_index_from_entity(entity) {
if b != sea_orm::DbBackend::MySql {
if let Err(e) = db.execute(i.if_not_exists()).await {
if db.execute(i.if_not_exists()).await.is_err() {
return Err(e);
}
}
continue;
}
let name = i
.get_index_spec()
.get_name()
.unwrap_or_default()
.to_string();
let table = entity.table_name();
if mysql_has_index(db, table, &name).await? {
continue;
}
if let Err(e) = db.execute(&i).await
&& !mysql_has_index(db, table, &name).await?
{
return Err(e);
}
}
Ok(())
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PruneReport {
pub codes: u64,
pub tokens: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Grant {
pub id: String,
pub client_id: String,
pub client_name: String,
pub scopes: Vec<String>,
pub created_at: i64,
pub last_used_at: Option<i64>,
pub expires_at: i64,
}
const PRUNE_BATCH: u64 = 500;
const PRUNE_GRACE: i64 = 60;
const LAST_USED_EVERY: i64 = 60;
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn hash(s: &str) -> String {
Sha256::digest(s.as_bytes())
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn ct_eq(a: &str, b: &str) -> bool {
a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0
}
fn random(prefix: &str, n: usize) -> Result<String, OAuthError> {
use rand::TryRng;
let mut raw = vec![0u8; n];
rand::rngs::SysRng
.try_fill_bytes(&mut raw)
.map_err(|_| OAuthError::Rng)?;
Ok(format!("{prefix}{}", URL_SAFE_NO_PAD.encode(raw)))
}
fn split(s: &str) -> Vec<String> {
let mut v: Vec<String> = Vec::new();
for x in s.split(' ').filter(|x| !x.is_empty()) {
if !v.iter().any(|y| y == x) {
v.push(x.into());
}
}
v
}
fn pct(s: &str) -> String {
s.bytes()
.map(|b| {
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
(b as char).to_string()
} else {
format!("%{b:02X}")
}
})
.collect()
}
fn with_query(base: &str, params: &[(&str, &str)]) -> String {
let q: Vec<String> = params
.iter()
.map(|(k, v)| format!("{k}={}", pct(v)))
.collect();
let sep = if base.contains('?') { '&' } else { '?' };
format!("{base}{sep}{}", q.join("&"))
}
fn scope_ok(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 100
&& s.bytes()
.all(|b| b.is_ascii_graphic() && b != b'"' && b != b'\\')
}
fn pkce_ok(challenge: &str, verifier: &str) -> bool {
(43..=128).contains(&verifier.len())
&& verifier
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b))
&& ct_eq(
&URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())),
challenge,
)
}
fn challenge_ok(c: &str) -> bool {
c.len() == 43
&& c.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
impl clients::Model {
fn uris(&self) -> Vec<String> {
serde_json::from_str(&self.redirect_uris).unwrap_or_default()
}
fn allowed(&self) -> Vec<String> {
split(&self.allowed_scopes)
}
}
impl OAuthServer {
pub fn new(db: DatabaseConnection) -> Self {
Self {
db,
access_ttl: Duration::from_secs(3600),
refresh_ttl: Duration::from_secs(30 * 86400),
}
}
pub fn access_ttl(mut self, d: Duration) -> Self {
self.access_ttl = d;
self
}
pub fn refresh_ttl(mut self, d: Duration) -> Self {
self.refresh_ttl = d;
self
}
pub async fn ensure_tables(&self) -> Result<(), DbErr> {
let s = Schema::new(self.db.get_database_backend());
let mut a = s.create_table_from_entity(clients::Entity);
self.db.execute(a.if_not_exists()).await?;
let mut b = s.create_table_from_entity(codes::Entity);
self.db.execute(b.if_not_exists()).await?;
let mut c = s.create_table_from_entity(tokens::Entity);
self.db.execute(c.if_not_exists()).await?;
add_column_if_missing(
&self.db,
clients::Entity,
clients::Column::FirstParty,
ColumnDef::new(Alias::new("first_party"))
.boolean()
.not_null()
.default(false)
.to_owned(),
)
.await?;
add_column_if_missing(
&self.db,
tokens::Entity,
tokens::Column::LastUsedAt,
ColumnDef::new(Alias::new("last_used_at"))
.big_integer()
.null()
.to_owned(),
)
.await?;
ensure_indexes(&self.db, codes::Entity).await?;
ensure_indexes(&self.db, tokens::Entity).await
}
pub async fn create_client(
&self,
name: &str,
redirect_uris: &[&str],
scopes: &[&str],
confidential: bool,
) -> Result<NewClient, OAuthError> {
let mut spec = ClientSpec::new(name);
spec.redirect_uris = redirect_uris.iter().map(|s| String::from(*s)).collect();
spec.scopes = scopes.iter().map(|s| String::from(*s)).collect();
spec.confidential = confidential;
self.create_client_spec(spec).await
}
pub async fn create_client_spec(&self, spec: ClientSpec) -> Result<NewClient, OAuthError> {
let ClientSpec {
name,
redirect_uris,
scopes,
confidential,
first_party,
} = spec;
if name.is_empty() || name.chars().count() > 100 {
return Err(OAuthError::Invalid("name must be 1..=100 chars"));
}
if redirect_uris.len() > 20 || scopes.len() > 50 {
return Err(OAuthError::Invalid("too many redirect uris or scopes"));
}
if first_party && redirect_uris.is_empty() {
return Err(OAuthError::Invalid(
"a first-party client needs a redirect uri",
));
}
for u in &redirect_uris {
let scheme_ok = u.split_once(':').is_some_and(|(s, _)| {
s.starts_with(|c: char| c.is_ascii_alphabetic())
&& s.chars()
.all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
});
if !scheme_ok || u.contains('#') || !u.bytes().all(|b| b.is_ascii_graphic()) {
return Err(OAuthError::Invalid(
"redirect uri must be absolute, ASCII, without fragment",
));
}
}
if !scopes.iter().all(|s| scope_ok(s)) {
return Err(OAuthError::Invalid("bad scope"));
}
let client_id = random("", 16)?;
let secret = if confidential {
Some(random("rys_", 32)?)
} else {
None
};
clients::ActiveModel {
client_id: Set(client_id.clone()),
secret_hash: Set(secret.as_deref().map(hash)),
name: Set(name),
redirect_uris: Set(json!(redirect_uris).to_string()),
allowed_scopes: Set(scopes.join(" ")),
created_at: Set(now()),
first_party: Set(first_party),
..Default::default()
}
.insert(&self.db)
.await?;
Ok(NewClient {
client_id,
client_secret: secret,
})
}
async fn issue_code(
&self,
client_id: &str,
user: i64,
redirect_uri: &str,
scopes: &[String],
challenge: Option<String>,
) -> Result<String, OAuthError> {
let code = random("ryc_", 32)?;
codes::ActiveModel {
code_hash: Set(hash(&code)),
client_id: Set(client_id.into()),
user_id: Set(user),
redirect_uri: Set(redirect_uri.into()),
scopes: Set(scopes.join(" ")),
code_challenge: Set(challenge),
expires_at: Set(now() + CODE_TTL),
..Default::default()
}
.insert(&self.db)
.await?;
Ok(code)
}
pub async fn revoke_client(&self, client_id: &str) -> Result<bool, OAuthError> {
let Some(c) = self.client(client_id).await? else {
return Ok(false);
};
let t = now();
clients::Entity::update_many()
.col_expr(clients::Column::RevokedAt, Expr::value(t))
.filter(clients::Column::Id.eq(c.id))
.filter(clients::Column::RevokedAt.is_null())
.exec(&self.db)
.await?;
self.revoke_where(tokens::Column::ClientId.eq(client_id))
.await?;
Ok(true)
}
pub async fn revoke_user_tokens(&self, user_id: i64) -> Result<u64, OAuthError> {
let live: std::collections::HashSet<String> = tokens::Entity::find()
.filter(tokens::Column::UserId.eq(user_id))
.filter(tokens::Column::RevokedAt.is_null())
.all(&self.db)
.await?
.into_iter()
.map(|r| r.family_id)
.collect();
codes::Entity::update_many()
.col_expr(codes::Column::UsedAt, Expr::value(now()))
.filter(codes::Column::UserId.eq(user_id))
.filter(codes::Column::UsedAt.is_null())
.exec(&self.db)
.await?;
self.revoke_where(tokens::Column::UserId.eq(user_id))
.await?;
Ok(live.len() as u64)
}
pub async fn list_grants(&self, user_id: i64) -> Result<Vec<Grant>, OAuthError> {
let t = now();
let rows = tokens::Entity::find()
.filter(tokens::Column::UserId.eq(user_id))
.filter(tokens::Column::RevokedAt.is_null())
.all(&self.db)
.await?;
let mut fams: HashMap<String, Vec<tokens::Model>> = HashMap::new();
for r in rows {
fams.entry(r.family_id.clone()).or_default().push(r);
}
let mut out = Vec::new();
for (id, rows) in fams {
let end = |r: &tokens::Model| match (r.refresh_expires_at, r.refresh_used_at) {
(Some(e), None) => e.max(r.access_expires_at),
_ => r.access_expires_at,
};
let Some(expires_at) = rows.iter().map(end).filter(|e| *e > t).max() else {
continue;
};
let newest = rows.iter().max_by_key(|r| r.id).expect("non-empty");
let client_id = newest.client_id.clone();
let client_name = self
.client(&client_id)
.await?
.map(|c| c.name)
.unwrap_or_default();
out.push(Grant {
id,
client_id,
client_name,
scopes: split(&newest.scopes),
created_at: rows.iter().map(|r| r.created_at).min().unwrap_or(t),
last_used_at: rows.iter().filter_map(|r| r.last_used_at).max(),
expires_at,
});
}
out.sort_by(|a, b| b.created_at.cmp(&a.created_at).then(a.id.cmp(&b.id)));
Ok(out)
}
pub async fn revoke_grant(&self, user_id: i64, family_id: &str) -> Result<bool, OAuthError> {
let live = tokens::Entity::find()
.filter(tokens::Column::FamilyId.eq(family_id))
.filter(tokens::Column::UserId.eq(user_id))
.filter(tokens::Column::RevokedAt.is_null())
.one(&self.db)
.await?
.is_some();
if live {
self.revoke_where(
Condition::all()
.add(tokens::Column::FamilyId.eq(family_id))
.add(tokens::Column::UserId.eq(user_id)),
)
.await?;
}
Ok(live)
}
pub async fn prune(&self, retention: Duration) -> Result<PruneReport, OAuthError> {
let t = now();
let keep = retention.as_secs().min(i64::MAX as u64 / 4) as i64;
let (old, expired) = (t - keep, t - PRUNE_GRACE);
let dead_codes = Condition::any()
.add(
Condition::all()
.add(codes::Column::UsedAt.is_null())
.add(codes::Column::ExpiresAt.lte(expired)),
)
.add(codes::Column::UsedAt.lte(old));
let dead_tokens = Condition::any()
.add(tokens::Column::RevokedAt.lte(old))
.add(
Condition::all()
.add(tokens::Column::AccessExpiresAt.lte(expired))
.add(
Condition::any()
.add(tokens::Column::RefreshExpiresAt.is_null())
.add(tokens::Column::RefreshExpiresAt.lte(expired)),
),
);
let mut report = PruneReport::default();
loop {
let ids: Vec<i64> = codes::Entity::find()
.filter(dead_codes.clone())
.limit(PRUNE_BATCH)
.all(&self.db)
.await?
.into_iter()
.map(|r| r.id)
.collect();
report.codes += ids.len() as u64;
let full = ids.len() as u64 == PRUNE_BATCH;
retried(|| {
codes::Entity::delete_many()
.filter(codes::Column::Id.is_in(ids.clone()))
.exec(&self.db)
})
.await?;
if !full {
break;
}
}
loop {
let ids: Vec<i64> = tokens::Entity::find()
.filter(dead_tokens.clone())
.limit(PRUNE_BATCH)
.all(&self.db)
.await?
.into_iter()
.map(|r| r.id)
.collect();
report.tokens += ids.len() as u64;
let full = ids.len() as u64 == PRUNE_BATCH;
retried(|| {
tokens::Entity::delete_many()
.filter(tokens::Column::Id.is_in(ids.clone()))
.exec(&self.db)
})
.await?;
if !full {
break;
}
}
Ok(report)
}
async fn client(&self, client_id: &str) -> Result<Option<clients::Model>, DbErr> {
clients::Entity::find()
.filter(clients::Column::ClientId.eq(client_id))
.one(&self.db)
.await
}
async fn active_client(&self, client_id: &str) -> Result<Option<clients::Model>, DbErr> {
Ok(self
.client(client_id)
.await?
.filter(|c| c.revoked_at.is_none()))
}
async fn revoke_where(&self, cond: impl Into<Condition>) -> Result<(), DbErr> {
let cond: Condition = cond.into();
retried(|| {
tokens::Entity::update_many()
.col_expr(tokens::Column::RevokedAt, Expr::value(now()))
.filter(cond.clone())
.filter(tokens::Column::RevokedAt.is_null())
.exec(&self.db)
})
.await?;
Ok(())
}
async fn revoke_family(&self, family: &str) -> Result<(), DbErr> {
self.revoke_where(tokens::Column::FamilyId.eq(family)).await
}
async fn mint(
&self,
client: &str,
user: Option<i64>,
scopes: &str,
family: Option<String>,
code_id: Option<i64>,
refresh: bool,
) -> Result<(tokens::Model, String, Option<String>), Fail> {
let access = random("ryo_", 32)?;
let refresh = if refresh {
Some(random("ryr_", 32)?)
} else {
None
};
let t = now();
let new_row = tokens::ActiveModel {
access_hash: Set(hash(&access)),
refresh_hash: Set(refresh.as_deref().map(hash)),
client_id: Set(client.into()),
user_id: Set(user),
scopes: Set(scopes.into()),
created_at: Set(t),
access_expires_at: Set(t + self.access_ttl.as_secs() as i64),
refresh_expires_at: Set(refresh
.as_ref()
.map(|_| t + self.refresh_ttl.as_secs() as i64)),
family_id: Set(match family {
Some(f) => f,
None => random("", 16)?,
}),
code_id: Set(code_id),
..Default::default()
};
let row = retried(|| new_row.clone().insert(&self.db)).await?;
Ok((row, access, refresh))
}
async fn claim_code(&self, id: i64) -> Result<bool, DbErr> {
let nonce = random("", 16).map_err(|_| DbErr::Custom("rng".into()))?;
codes::Entity::update_many()
.col_expr(codes::Column::UsedAt, Expr::value(now()))
.col_expr(codes::Column::Claim, Expr::value(nonce.clone()))
.filter(codes::Column::Id.eq(id))
.filter(codes::Column::UsedAt.is_null())
.exec(&self.db)
.await?;
let row = codes::Entity::find_by_id(id).one(&self.db).await?;
Ok(row.is_some_and(|r| r.claim.as_deref() == Some(nonce.as_str())))
}
async fn claim_refresh(&self, id: i64) -> Result<bool, DbErr> {
let nonce = random("", 16).map_err(|_| DbErr::Custom("rng".into()))?;
retried(|| {
tokens::Entity::update_many()
.col_expr(tokens::Column::RefreshUsedAt, Expr::value(now()))
.col_expr(tokens::Column::RefreshClaim, Expr::value(nonce.clone()))
.filter(tokens::Column::Id.eq(id))
.filter(tokens::Column::RefreshUsedAt.is_null())
.exec(&self.db)
})
.await?;
let row = tokens::Entity::find_by_id(id).one(&self.db).await?;
Ok(row.is_some_and(|r| r.refresh_claim.as_deref() == Some(nonce.as_str())))
}
async fn code_replayed(&self, code_id: i64) -> Result<(), DbErr> {
codes::Entity::update_many()
.col_expr(codes::Column::ReplayedAt, Expr::value(now()))
.filter(codes::Column::Id.eq(code_id))
.exec(&self.db)
.await?;
self.revoke_where(tokens::Column::CodeId.eq(code_id)).await
}
async fn live_access(&self, token: &str) -> Result<Option<tokens::Model>, DbErr> {
if !token.starts_with("ryo_") {
return Ok(None);
}
let h = hash(token);
let t = now();
Ok(tokens::Entity::find()
.filter(tokens::Column::AccessHash.eq(h.as_str()))
.one(&self.db)
.await?
.filter(|r| {
r.revoked_at.is_none() && r.access_expires_at > t && ct_eq(&r.access_hash, &h)
}))
}
}
impl TokenVerifier for OAuthServer {
fn verify<'a>(&'a self, bearer: &'a str) -> BoxFuture<'a, Option<Principal>> {
Box::pin(async move {
let r = match self.live_access(bearer).await {
Ok(Some(r)) => r,
Ok(None) => return None,
Err(e) => {
tracing::error!("oauth verify: {e}");
return None;
}
};
let t = now();
if r.last_used_at.is_none_or(|l| l <= t - LAST_USED_EVERY) {
let touched = tokens::Entity::update_many()
.col_expr(tokens::Column::LastUsedAt, Expr::value(t))
.filter(tokens::Column::Id.eq(r.id))
.exec(&self.db)
.await;
if let Err(e) = touched {
tracing::warn!("oauth last_used update failed: {e}");
}
}
let client = r.user_id.is_none();
Some(Principal {
kind: if client {
PrincipalKind::OAuthClient
} else {
PrincipalKind::OAuthToken
},
id: if client {
r.client_id.clone()
} else {
r.family_id
},
user_id: r.user_id,
client_id: Some(r.client_id),
scopes: split(&r.scopes),
name: None,
})
})
}
}
struct Fail {
status: StatusCode,
error: &'static str,
desc: &'static str,
}
fn nostore(mut r: Response) -> Response {
let h = r.headers_mut();
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
h.insert(header::PRAGMA, HeaderValue::from_static("no-cache"));
r
}
impl IntoResponse for Fail {
fn into_response(self) -> Response {
let mut r = (
self.status,
Json(json!({"error": self.error, "error_description": self.desc})),
)
.into_response();
if self.status == StatusCode::UNAUTHORIZED {
r.headers_mut().insert(
header::WWW_AUTHENTICATE,
HeaderValue::from_static("Basic realm=\"oauth\""),
);
}
nostore(r)
}
}
fn bad(error: &'static str, desc: &'static str) -> Fail {
Fail {
status: StatusCode::BAD_REQUEST,
error,
desc,
}
}
fn grant() -> Fail {
bad(
"invalid_grant",
"The grant is invalid, expired, revoked or already used.",
)
}
impl From<DbErr> for Fail {
fn from(e: DbErr) -> Self {
tracing::error!("oauth: {e}");
Fail {
status: StatusCode::INTERNAL_SERVER_ERROR,
error: "server_error",
desc: "Internal error.",
}
}
}
impl From<OAuthError> for Fail {
fn from(e: OAuthError) -> Self {
tracing::error!("oauth: {e}");
Fail {
status: StatusCode::INTERNAL_SERVER_ERROR,
error: "server_error",
desc: "Internal error.",
}
}
}
type Params = HashMap<String, String>;
type Res<T> = Result<T, Fail>;
fn param<'a>(f: &'a Params, k: &str) -> Option<&'a str> {
f.get(k).map(String::as_str).filter(|v| !v.is_empty())
}
impl OAuthServer {
async fn authenticate(&self, headers: &HeaderMap, f: &Params) -> Res<clients::Model> {
let invalid = || Fail {
status: StatusCode::UNAUTHORIZED,
error: "invalid_client",
desc: "Client authentication failed.",
};
let (id, secret) = match headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
{
Some(h) if h.len() > 6 && h[..6].eq_ignore_ascii_case("basic ") => {
if f.contains_key("client_secret") {
return Err(bad(
"invalid_request",
"Use one client authentication method.",
));
}
let dec = STANDARD
.decode(h[6..].trim())
.ok()
.and_then(|b| String::from_utf8(b).ok());
let (i, s) = dec
.as_deref()
.and_then(|d| d.split_once(':'))
.ok_or_else(invalid)?;
if param(f, "client_id").is_some_and(|b| b != i) {
return Err(bad("invalid_request", "client_id mismatch."));
}
(i.to_string(), Some(s.to_string()))
}
_ => (
param(f, "client_id")
.ok_or_else(|| bad("invalid_request", "client_id is required."))?
.to_string(),
param(f, "client_secret").map(str::to_string),
),
};
let client = self.active_client(&id).await?;
let given = hash(secret.as_deref().unwrap_or(""));
let (stored, public) = match &client {
Some(c) => (
c.secret_hash.clone().unwrap_or_default(),
c.secret_hash.is_none(),
),
None => (hash("unknown-client"), false),
};
let secret_ok = if public {
secret.is_none()
} else {
secret.is_some() && ct_eq(&given, &stored)
};
match client {
Some(c) if secret_ok => Ok(c),
_ => Err(invalid()),
}
}
async fn grant(&self, headers: &HeaderMap, f: &Params) -> Res<Response> {
let client = self.authenticate(headers, f).await?;
let Some(gt) = param(f, "grant_type") else {
return Err(bad("invalid_request", "grant_type is required."));
};
let (row, access, refresh) = match gt {
"authorization_code" => self.code_grant(&client, f).await?,
"refresh_token" => self.refresh_grant(&client, f).await?,
"client_credentials" => {
if client.secret_hash.is_none() {
return Err(Fail {
status: StatusCode::BAD_REQUEST,
error: "unauthorized_client",
desc: "Public clients cannot use client_credentials.",
});
}
let scopes = requested_scopes(&client, param(f, "scope"))?;
self.mint(
&client.client_id,
None,
&scopes.join(" "),
None,
None,
false,
)
.await?
}
_ => return Err(bad("unsupported_grant_type", "Unsupported grant_type.")),
};
let mut body = json!({
"access_token": access, "token_type": "Bearer",
"expires_in": (row.access_expires_at - row.created_at).max(0), "scope": row.scopes,
});
if let Some(r) = refresh {
body["refresh_token"] = r.into();
}
Ok(nostore(Json(body).into_response()))
}
async fn code_grant(
&self,
client: &clients::Model,
f: &Params,
) -> Res<(tokens::Model, String, Option<String>)> {
let code = param(f, "code").ok_or_else(|| bad("invalid_request", "code is required."))?;
let redirect = param(f, "redirect_uri")
.ok_or_else(|| bad("invalid_request", "redirect_uri is required."))?;
let h = hash(code);
let row = codes::Entity::find()
.filter(codes::Column::CodeHash.eq(h.as_str()))
.one(&self.db)
.await?
.filter(|r| ct_eq(&r.code_hash, &h))
.ok_or_else(grant)?;
if row.client_id != client.client_id {
return Err(grant());
}
if row.used_at.is_some() {
self.code_replayed(row.id).await?;
return Err(grant());
}
if row.expires_at <= now() || row.redirect_uri != redirect {
return Err(grant());
}
match (&row.code_challenge, param(f, "code_verifier")) {
(Some(c), Some(v)) if pkce_ok(c, v) => {}
(Some(_), _) => return Err(grant()),
(None, Some(_)) => return Err(grant()),
(None, None) => {}
}
if !self.claim_code(row.id).await? {
self.code_replayed(row.id).await?;
return Err(grant());
}
let out = self
.mint(
&client.client_id,
Some(row.user_id),
&row.scopes,
None,
Some(row.id),
true,
)
.await?;
let again = codes::Entity::find_by_id(row.id).one(&self.db).await?;
if again.is_none_or(|c| c.replayed_at.is_some()) {
self.revoke_where(tokens::Column::CodeId.eq(row.id)).await?;
return Err(grant());
}
Ok(out)
}
async fn refresh_grant(
&self,
client: &clients::Model,
f: &Params,
) -> Res<(tokens::Model, String, Option<String>)> {
let tok = param(f, "refresh_token")
.ok_or_else(|| bad("invalid_request", "refresh_token is required."))?;
let h = hash(tok);
let row = tokens::Entity::find()
.filter(tokens::Column::RefreshHash.eq(h.as_str()))
.one(&self.db)
.await?
.filter(|r| r.refresh_hash.as_deref().is_some_and(|x| ct_eq(x, &h)))
.ok_or_else(grant)?;
if row.client_id != client.client_id || row.revoked_at.is_some() {
return Err(grant());
}
if row.refresh_used_at.is_some() {
self.revoke_family(&row.family_id).await?;
return Err(grant());
}
if row.refresh_expires_at.is_none_or(|e| e <= now()) {
return Err(grant());
}
let scopes = match param(f, "scope") {
None => row.scopes.clone(),
Some(s) => {
let (want, had) = (split(s), split(&row.scopes));
if !want.iter().all(|w| had.contains(w)) {
return Err(bad("invalid_scope", "Scope exceeds the original grant."));
}
want.join(" ")
}
};
let allowed = client.allowed();
let kept = split(&scopes)
.into_iter()
.filter(|s| allowed.contains(s))
.collect::<Vec<_>>();
if kept.is_empty() && !scopes.is_empty() {
return Err(grant());
}
let scopes = kept.join(" ");
if !self.claim_refresh(row.id).await? {
self.revoke_family(&row.family_id).await?;
return Err(grant());
}
let out = self
.mint(
&client.client_id,
row.user_id,
&scopes,
Some(row.family_id.clone()),
row.code_id,
true,
)
.await?;
let old = tokens::Entity::find_by_id(row.id).one(&self.db).await?;
if old.is_none_or(|o| o.revoked_at.is_some()) {
self.revoke_family(&row.family_id).await?;
return Err(grant());
}
Ok(out)
}
async fn find_token(&self, token: &str) -> Result<Option<(tokens::Model, bool)>, DbErr> {
let h = hash(token);
let row = tokens::Entity::find()
.filter(
Condition::any()
.add(tokens::Column::AccessHash.eq(h.as_str()))
.add(tokens::Column::RefreshHash.eq(h.as_str())),
)
.one(&self.db)
.await?;
Ok(row.and_then(|r| {
if ct_eq(&r.access_hash, &h) {
Some((r, true))
} else if r.refresh_hash.as_deref().is_some_and(|x| ct_eq(x, &h)) {
Some((r, false))
} else {
None
}
}))
}
}
fn requested_scopes(client: &clients::Model, s: Option<&str>) -> Res<Vec<String>> {
let want = split(s.unwrap_or(""));
let allowed = client.allowed();
if want.len() > 50 || !want.iter().all(|w| scope_ok(w) && allowed.contains(w)) {
return Err(bad("invalid_scope", "Unknown or disallowed scope."));
}
Ok(want)
}
fn form(f: Result<Form<Params>, FormRejection>) -> Res<Params> {
f.map(|Form(p)| p).map_err(|_| {
bad(
"invalid_request",
"Expected an application/x-www-form-urlencoded body.",
)
})
}
async fn token_h(
State(o): State<OAuthServer>,
headers: HeaderMap,
f: Result<Form<Params>, FormRejection>,
) -> Response {
match async { o.grant(&headers, &form(f)?).await }.await {
Ok(r) => r,
Err(e) => e.into_response(),
}
}
async fn revoke_h(
State(o): State<OAuthServer>,
headers: HeaderMap,
f: Result<Form<Params>, FormRejection>,
) -> Response {
let run = async {
let f = form(f)?;
let client = o.authenticate(&headers, &f).await?;
let tok = param(&f, "token").ok_or_else(|| bad("invalid_request", "token is required."))?;
if let Some((row, _)) = o
.find_token(tok)
.await?
.filter(|(r, _)| r.client_id == client.client_id)
{
o.revoke_family(&row.family_id).await?;
}
Ok::<_, Fail>(nostore(StatusCode::OK.into_response()))
};
run.await.unwrap_or_else(IntoResponse::into_response)
}
async fn introspect_h(
State(o): State<OAuthServer>,
headers: HeaderMap,
f: Result<Form<Params>, FormRejection>,
) -> Response {
let run = async {
let f = form(f)?;
let client = o.authenticate(&headers, &f).await?;
if client.secret_hash.is_none() {
return Err(Fail {
status: StatusCode::UNAUTHORIZED,
error: "invalid_client",
desc: "Introspection needs a confidential client.",
});
}
let tok = param(&f, "token").ok_or_else(|| bad("invalid_request", "token is required."))?;
let t = now();
let live = o
.find_token(tok)
.await?
.filter(|(r, _)| r.client_id == client.client_id && r.revoked_at.is_none());
let active = live.and_then(|(r, is_access)| {
if is_access && r.access_expires_at > t {
Some((r.access_expires_at, "Bearer", r))
} else if !is_access
&& r.refresh_used_at.is_none()
&& r.refresh_expires_at.is_some_and(|e| e > t)
{
Some((r.refresh_expires_at.unwrap_or(0), "refresh_token", r))
} else {
None
}
});
let body = match active {
None => json!({"active": false}),
Some((exp, kind, r)) => {
let mut v = json!({"active": true, "scope": r.scopes, "client_id": r.client_id, "token_type": kind, "exp": exp, "iat": r.created_at});
if let Some(u) = r.user_id {
v["sub"] = u.to_string().into();
}
v
}
};
Ok::<_, Fail>(nostore(Json(body).into_response()))
};
run.await.unwrap_or_else(IntoResponse::into_response)
}
#[derive(Deserialize)]
struct AuthzParams {
response_type: Option<String>,
client_id: Option<String>,
redirect_uri: Option<String>,
scope: Option<String>,
state: Option<String>,
code_challenge: Option<String>,
code_challenge_method: Option<String>,
prompt: Option<String>,
}
#[derive(Deserialize)]
struct Decision {
decision: String,
request_id: String,
}
struct DecisionBody(Decision);
impl<S: Send + Sync> axum::extract::FromRequest<S> for DecisionBody {
type Rejection = Response;
async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Response> {
let json = req
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("application/json"));
let d = if json {
Json::<Decision>::from_request(req, state)
.await
.map_err(IntoResponse::into_response)?
.0
} else {
Form::<Decision>::from_request(req, state)
.await
.map_err(IntoResponse::into_response)?
.0
};
Ok(DecisionBody(d))
}
}
#[derive(Serialize, Deserialize)]
struct Pending {
request_id: String,
user_id: i64,
client_id: String,
redirect_uri: String,
scopes: Vec<String>,
state: Option<String>,
challenge: Option<String>,
}
fn server_error<E: std::fmt::Display>(e: E) -> Response {
tracing::error!("oauth authorize: {e}");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
}
fn leave(headers: &HeaderMap, to: &str) -> Response {
match HeaderValue::from_str(to) {
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
Ok(v) if headers.contains_key("x-inertia") => {
(StatusCode::CONFLICT, [("x-inertia-location", v)]).into_response()
}
Ok(v) => (StatusCode::SEE_OTHER, [(header::LOCATION, v)]).into_response(),
}
}
fn error_page(i: Inertia, msg: &str) -> Response {
let mut r = i.render("OAuth/Error", json!({ "message": msg }));
if r.status() == StatusCode::OK {
*r.status_mut() = StatusCode::BAD_REQUEST;
}
r
}
fn redirect_error(h: &HeaderMap, uri: &str, code: &str, state: Option<&str>) -> Response {
let mut p = vec![("error", code)];
if let Some(s) = state {
p.push(("state", s));
}
leave(h, &with_query(uri, &p))
}
async fn authorize_get<S>(
State(o): State<OAuthServer>,
session: Session,
inertia: Inertia,
headers: HeaderMap,
OriginalUri(uri): OriginalUri,
Query(q): Query<AuthzParams>,
) -> Response
where
S: Send + Sync,
OAuthServer: FromRef<S>,
InertiaConfig: FromRef<S>,
{
let client = match o.active_client(q.client_id.as_deref().unwrap_or("")).await {
Ok(Some(c)) => c,
Ok(None) => return error_page(inertia, "Unknown application."),
Err(e) => return server_error(e),
};
let Some(ru) = q.redirect_uri.clone().filter(|u| client.uris().contains(u)) else {
return error_page(inertia, "Invalid redirect URI.");
};
let state = q.state.as_deref();
let fail = |c: &str| redirect_error(&headers, &ru, c, state);
if q.response_type.as_deref() != Some("code") {
return fail("unsupported_response_type");
}
let Ok(scopes) = requested_scopes(&client, q.scope.as_deref()) else {
return fail("invalid_scope");
};
let challenge = match (
q.code_challenge.as_deref(),
q.code_challenge_method.as_deref(),
) {
(Some(c), Some("S256")) if challenge_ok(c) => Some(c.to_string()),
(Some(_), _) => return fail("invalid_request"),
(None, _) if client.secret_hash.is_none() => return fail("invalid_request"),
(None, _) => None,
};
let user = match session.get::<i64>(SESSION_USER).await {
Ok(Some(u)) => u,
Ok(None) => {
let next = uri
.path_and_query()
.map_or("/oauth/authorize", |p| p.as_str());
return crate::inertia::redirect(&format!("/login?next={}", pct(next)));
}
Err(e) => return server_error(e),
};
if client.first_party
&& ru.starts_with("https://")
&& !split(q.prompt.as_deref().unwrap_or("")).contains(&"consent".into())
{
return match o
.issue_code(&client.client_id, user, &ru, &scopes, challenge)
.await
{
Ok(code) => {
let mut params = vec![("code", code.as_str())];
if let Some(s) = state {
params.push(("state", s));
}
leave(&headers, &with_query(&ru, ¶ms))
}
Err(e) => server_error(e),
};
}
let request_id = match random("", 16) {
Ok(r) => r,
Err(e) => return server_error(e),
};
let pending = Pending {
request_id: request_id.clone(),
user_id: user,
client_id: client.client_id.clone(),
redirect_uri: ru,
scopes: scopes.clone(),
state: q.state.clone(),
challenge,
};
if let Err(e) = session.insert(SESSION_PENDING, pending).await {
return server_error(e);
}
inertia.render(
"OAuth/Authorize",
json!({
"client": {"name": client.name},
"scopes": scopes.iter().map(|s| json!({"name": s})).collect::<Vec<_>>(),
"state": q.state, "request_id": request_id,
}),
)
}
async fn authorize_post<S>(
State(o): State<OAuthServer>,
session: Session,
inertia: Inertia,
headers: HeaderMap,
DecisionBody(d): DecisionBody,
) -> Response
where
S: Send + Sync,
OAuthServer: FromRef<S>,
InertiaConfig: FromRef<S>,
{
let user = match session.get::<i64>(SESSION_USER).await {
Ok(Some(u)) => u,
Ok(None) => return crate::inertia::redirect("/login"),
Err(e) => return server_error(e),
};
let p = match session.remove::<Pending>(SESSION_PENDING).await {
Ok(Some(p)) if p.user_id == user && ct_eq(&p.request_id, &d.request_id) => p,
Ok(_) => {
return error_page(
inertia,
"This authorization request expired. Start again from the application.",
);
}
Err(e) => return server_error(e),
};
let state = p.state.as_deref();
if d.decision != "allow" {
return redirect_error(&headers, &p.redirect_uri, "access_denied", state);
}
match o.active_client(&p.client_id).await {
Ok(Some(_)) => {}
Ok(None) => return error_page(inertia, "Unknown application."),
Err(e) => return server_error(e),
}
let issue = o.issue_code(
&p.client_id,
user,
&p.redirect_uri,
&p.scopes,
p.challenge.clone(),
);
match issue.await {
Ok(code) => {
let mut params = vec![("code", code.as_str())];
if let Some(s) = state {
params.push(("state", s));
}
leave(&headers, &with_query(&p.redirect_uri, ¶ms))
}
Err(e) => server_error(e),
}
}
impl OAuthServer {
pub fn web_router<S>() -> Router<S>
where
S: Clone + Send + Sync + 'static,
OAuthServer: FromRef<S>,
InertiaConfig: FromRef<S>,
{
Router::new().route(
"/oauth/authorize",
get(authorize_get::<S>).post(authorize_post::<S>),
)
}
pub fn token_router<S>() -> Router<S>
where
S: Clone + Send + Sync + 'static,
OAuthServer: FromRef<S>,
{
Router::new()
.route("/oauth/token", post(token_h))
.route("/oauth/revoke", post(revoke_h))
.route("/oauth/introspect", post(introspect_h))
}
#[cfg(feature = "openapi")]
pub fn web_routes<S>() -> utoipa_axum::router::OpenApiRouter<S>
where
S: Clone + Send + Sync + 'static,
OAuthServer: FromRef<S>,
InertiaConfig: FromRef<S>,
{
Self::web_router::<S>().into()
}
#[cfg(feature = "openapi")]
pub fn token_routes<S>() -> utoipa_axum::router::OpenApiRouter<S>
where
S: Clone + Send + Sync + 'static,
OAuthServer: FromRef<S>,
{
Self::token_router::<S>().into()
}
}
#[cfg(all(test, feature = "sqlite"))]
mod tests {
#[test]
fn debug_never_prints_a_client_secret() {
let c = NewClient {
client_id: "cid".into(),
client_secret: Some("super-SECRET-value".into()),
};
let shown = format!("{c:?}");
assert!(
!shown.contains("SECRET-value") && shown.contains("cid"),
"{shown}"
);
}
use super::*;
use axum::body::{Body, to_bytes};
use axum::http::Request;
use tower::ServiceExt;
const CB: &str = "https://app.example/cb";
const VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
#[derive(Clone)]
struct St {
o: OAuthServer,
i: InertiaConfig,
}
impl FromRef<St> for OAuthServer {
fn from_ref(s: &St) -> Self {
s.o.clone()
}
}
impl FromRef<St> for InertiaConfig {
fn from_ref(s: &St) -> Self {
s.i.clone()
}
}
async fn login(s: Session, axum::extract::Path(id): axum::extract::Path<i64>) -> &'static str {
s.insert(SESSION_USER, id).await.unwrap();
"ok"
}
async fn dbs() -> Vec<(&'static str, DatabaseConnection)> {
let ns = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!("ryuk-oauth-{ns}.db"));
let mut v = vec![(
"sqlite",
sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
.await
.unwrap(),
)];
for (name, var) in [
("postgres", "TEST_POSTGRES_URL"),
("mysql", "TEST_MYSQL_URL"),
] {
if let Ok(url) = std::env::var(var) {
v.push((name, sea_orm::Database::connect(url).await.unwrap()));
}
}
v
}
struct Env {
o: OAuthServer,
app: Router,
db: DatabaseConnection,
}
async fn env(db: DatabaseConnection) -> Env {
let o = OAuthServer::new(db.clone());
o.ensure_tables().await.unwrap();
o.ensure_tables().await.unwrap();
let app = Router::new()
.route("/login-as/{id}", get(login))
.merge(OAuthServer::web_router::<St>())
.merge(OAuthServer::token_router::<St>())
.layer(crate::session::session_layer())
.with_state(St {
o: o.clone(),
i: crate::inertia::Config::dev(1, "x", false, "t"),
});
Env { o, app, db }
}
struct Resp {
status: StatusCode,
headers: HeaderMap,
body: String,
}
impl Resp {
fn json(&self) -> serde_json::Value {
serde_json::from_str(&self.body).unwrap_or_else(|_| panic!("not json: {}", self.body))
}
fn err(&self) -> String {
self.json()["error"].as_str().unwrap_or("").to_string()
}
fn loc(&self) -> String {
self.headers
.get("location")
.map(|v| v.to_str().unwrap().to_string())
.unwrap_or_default()
}
}
async fn send(app: &Router, req: Request<Body>) -> Resp {
let r = app.clone().oneshot(req).await.unwrap();
let (p, b) = r.into_parts();
Resp {
status: p.status,
headers: p.headers,
body: String::from_utf8(to_bytes(b, usize::MAX).await.unwrap().to_vec()).unwrap(),
}
}
async fn post_form(app: &Router, path: &str, body: &str, extra: &[(&str, &str)]) -> Resp {
let mut r = Request::post(path).header("content-type", "application/x-www-form-urlencoded");
for (k, v) in extra {
r = r.header(*k, *v);
}
send(app, r.body(Body::from(body.to_string())).unwrap()).await
}
async fn session_for(app: &Router, uid: i64) -> String {
let r = send(
app,
Request::get(format!("/login-as/{uid}"))
.body(Body::empty())
.unwrap(),
)
.await;
r.headers["set-cookie"]
.to_str()
.unwrap()
.split(';')
.next()
.unwrap()
.to_string()
}
fn s256(v: &str) -> String {
URL_SAFE_NO_PAD.encode(Sha256::digest(v.as_bytes()))
}
fn qp(url: &str, key: &str) -> Option<String> {
let q = url.split_once('?')?.1;
q.split('&')
.find_map(|kv| kv.strip_prefix(&format!("{key}=")).map(str::to_string))
}
fn basic(id: &str, secret: &str) -> String {
format!("Basic {}", STANDARD.encode(format!("{id}:{secret}")))
}
async fn authorize(e: &Env, query: &str, decision: &str) -> Resp {
let cookie = session_for(&e.app, 42).await;
let page = send(
&e.app,
Request::get(format!("/oauth/authorize?{query}"))
.header("cookie", &cookie)
.header("x-inertia", "true")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(page.status, StatusCode::OK, "{}", page.body);
let rid = page.json()["props"]["request_id"]
.as_str()
.unwrap()
.to_string();
post_form(
&e.app,
"/oauth/authorize",
&format!("decision={decision}&request_id={rid}"),
&[("cookie", &cookie)],
)
.await
}
async fn get_code(e: &Env, cid: &str, scope: &str) -> String {
let q = format!(
"response_type=code&client_id={cid}&redirect_uri={}&scope={scope}&state=xyz&code_challenge={}&code_challenge_method=S256",
pct(CB),
s256(VERIFIER)
);
let r = authorize(e, &q, "allow").await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert!(
r.loc().starts_with(&format!("{CB}?code=ryc_")),
"{}",
r.loc()
);
assert_eq!(qp(&r.loc(), "state").as_deref(), Some("xyz"));
qp(&r.loc(), "code").unwrap()
}
fn code_body(cid: &str, code: &str, verifier: &str) -> String {
format!(
"grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={verifier}",
pct(CB)
)
}
async fn public_client(e: &Env) -> String {
e.o.create_client("Test app", &[CB], &["read", "write"], false)
.await
.unwrap()
.client_id
}
async fn tokens_for(e: &Env, cid: &str, scope: &str) -> serde_json::Value {
let code = get_code(e, cid, scope).await;
let r = post_form(
&e.app,
"/oauth/token",
&code_body(cid, &code, VERIFIER),
&[],
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
r.json()
}
#[tokio::test]
async fn auth_code_pkce_roundtrip_hashed_at_rest() {
for (name, db) in dbs().await {
let e = env(db).await;
let cid = public_client(&e).await;
let q = format!(
"response_type=code&client_id={cid}&redirect_uri={}&scope=read&code_challenge={}&code_challenge_method=S256",
pct(CB),
s256(VERIFIER)
);
let r = send(
&e.app,
Request::get(format!("/oauth/authorize?{q}"))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{name}");
assert!(
r.loc()
.starts_with("/login?next=%2Foauth%2Fauthorize%3Fresponse_type%3Dcode"),
"{name}: {}",
r.loc()
);
let code = get_code(&e, &cid, "read%20write").await;
let t = post_form(
&e.app,
"/oauth/token",
&code_body(&cid, &code, VERIFIER),
&[],
)
.await;
assert_eq!(t.status, StatusCode::OK, "{name}: {}", t.body);
assert_eq!(t.headers["cache-control"], "no-store");
let j = t.json();
assert_eq!(j["token_type"], "Bearer");
assert_eq!(j["scope"], "read write");
assert_eq!(j["expires_in"], 3600);
let (at, rt) = (
j["access_token"].as_str().unwrap(),
j["refresh_token"].as_str().unwrap(),
);
assert!(at.starts_with("ryo_") && rt.starts_with("ryr_") && at.len() == 47);
let p = e.o.verify(at).await.expect(name);
assert_eq!(
(p.kind, p.user_id, p.client_id.as_deref()),
(PrincipalKind::OAuthToken, Some(42), Some(cid.as_str()))
);
assert_eq!(p.scopes, ["read", "write"]);
assert!(e.o.verify("ryo_nope").await.is_none() && e.o.verify(rt).await.is_none());
let rows = format!(
"{:?}{:?}{:?}",
tokens::Entity::find().all(&e.db).await.unwrap(),
codes::Entity::find().all(&e.db).await.unwrap(),
clients::Entity::find().all(&e.db).await.unwrap()
);
assert!(
!rows.contains(at) && !rows.contains(rt) && !rows.contains(&code),
"{name}"
);
let again = post_form(
&e.app,
"/oauth/token",
&code_body(&cid, &code, VERIFIER),
&[],
)
.await;
assert_eq!(
(again.status, again.err()),
(StatusCode::BAD_REQUEST, "invalid_grant".into()),
"{name}"
);
assert!(e.o.verify(at).await.is_none(), "{name}: replay must revoke");
let rr = post_form(
&e.app,
"/oauth/token",
&format!("grant_type=refresh_token&client_id={cid}&refresh_token={rt}"),
&[],
)
.await;
assert_eq!(rr.err(), "invalid_grant", "{name}");
}
}
#[tokio::test]
async fn authorize_and_exchange_rejections() {
for (name, db) in dbs().await {
let e = env(db).await;
let cid = public_client(&e).await;
let ch = s256(VERIFIER);
let base = |extra: &str| {
format!(
"response_type=code&client_id={cid}&redirect_uri={}&code_challenge={ch}&code_challenge_method=S256{extra}",
pct(CB)
)
};
let page = |q: String| {
let app = e.app.clone();
async move {
let c = session_for(&app, 1).await;
send(
&app,
Request::get(format!("/oauth/authorize?{q}"))
.header("cookie", c)
.header("x-inertia", "true")
.body(Body::empty())
.unwrap(),
)
.await
}
};
for q in [
format!(
"response_type=code&client_id={cid}&redirect_uri={}",
pct("https://evil.example/cb")
),
format!(
"response_type=code&client_id={cid}&redirect_uri={}",
pct("https://app.example/cb/")
),
format!("response_type=code&client_id={cid}"),
format!("response_type=code&client_id=nope&redirect_uri={}", pct(CB)),
] {
let r = page(q.clone()).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST, "{name}: {q}");
assert!(
r.headers.get("location").is_none()
&& r.headers.get("x-inertia-location").is_none()
);
assert_eq!(r.json()["component"], "OAuth/Error");
}
for (q, err) in [
(base("&scope=admin&state=s1"), "invalid_scope"),
(
format!(
"response_type=code&client_id={cid}&redirect_uri={}&state=s1",
pct(CB)
),
"invalid_request", ),
(
format!(
"response_type=code&client_id={cid}&redirect_uri={}&code_challenge={ch}&code_challenge_method=plain&state=s1",
pct(CB)
),
"invalid_request",
),
(
base("&state=s1").replace("response_type=code", "response_type=token"),
"unsupported_response_type",
),
] {
let r = page(q.clone()).await;
assert_eq!(r.status, StatusCode::CONFLICT, "{name}: {q}"); let l = r.headers["x-inertia-location"]
.to_str()
.unwrap()
.to_string();
assert!(
l.starts_with(CB)
&& qp(&l, "error").as_deref() == Some(err)
&& qp(&l, "state").as_deref() == Some("s1"),
"{name}: {l}"
);
}
let c = session_for(&e.app, 1).await;
let r = send(
&e.app,
Request::get(format!("/oauth/authorize?{}", base("&scope=admin")))
.header("cookie", c)
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert_eq!(qp(&r.loc(), "error").as_deref(), Some("invalid_scope"));
let r = authorize(&e, &base("&state=s2"), "deny").await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert_eq!(qp(&r.loc(), "error").as_deref(), Some("access_denied"));
assert!(qp(&r.loc(), "code").is_none());
let c = session_for(&e.app, 1).await;
let r = post_form(
&e.app,
"/oauth/authorize",
"decision=allow&request_id=guess",
&[("cookie", &c)],
)
.await;
assert_eq!(r.status, StatusCode::BAD_REQUEST, "{name}");
assert!(r.loc().is_empty());
let r = post_form(
&e.app,
"/oauth/authorize",
"decision=allow&request_id=guess",
&[],
)
.await;
assert_eq!(
(r.status, r.loc().as_str()),
(StatusCode::SEE_OTHER, "/login")
);
let code = get_code(&e, &cid, "read").await;
for body in [
code_body(&cid, &code, &"A".repeat(43)),
code_body(&cid, &code, "short"),
format!(
"grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}",
pct(CB)
),
format!(
"grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={VERIFIER}",
pct("https://app.example/other")
),
] {
let r = post_form(&e.app, "/oauth/token", &body, &[]).await;
assert_eq!(
(r.status, r.err()),
(StatusCode::BAD_REQUEST, "invalid_grant".into()),
"{name}: {body}"
);
}
let other = public_client(&e).await;
let r = post_form(
&e.app,
"/oauth/token",
&code_body(&other, &code, VERIFIER),
&[],
)
.await;
assert_eq!(r.err(), "invalid_grant", "{name}: other client");
let r = post_form(
&e.app,
"/oauth/token",
&code_body(&cid, &code, VERIFIER),
&[],
)
.await;
assert_eq!(
r.status,
StatusCode::OK,
"{name}: still redeemable by the right client: {}",
r.body
);
let code = get_code(&e, &cid, "read").await;
codes::Entity::update_many()
.col_expr(codes::Column::ExpiresAt, Expr::value(now() - 1))
.filter(codes::Column::CodeHash.eq(hash(&code)))
.exec(&e.db)
.await
.unwrap();
let r = post_form(
&e.app,
"/oauth/token",
&code_body(&cid, &code, VERIFIER),
&[],
)
.await;
assert_eq!(r.err(), "invalid_grant", "{name}: expired");
let r = post_form(
&e.app,
"/oauth/token",
&format!("grant_type=password&client_id={cid}"),
&[],
)
.await;
assert_eq!(
(r.status, r.err()),
(StatusCode::BAD_REQUEST, "unsupported_grant_type".into())
);
let r = post_form(&e.app, "/oauth/token", &format!("client_id={cid}"), &[]).await;
assert_eq!(r.err(), "invalid_request");
let r = post_form(&e.app, "/oauth/token", "grant_type=authorization_code", &[]).await;
assert_eq!(r.err(), "invalid_request");
let r = post_form(
&e.app,
"/oauth/token",
"grant_type=client_credentials&client_id=nope&client_secret=x",
&[],
)
.await;
assert_eq!(
(r.status, r.err()),
(StatusCode::UNAUTHORIZED, "invalid_client".into())
);
assert_eq!(r.headers["cache-control"], "no-store");
let r = send(
&e.app,
Request::post("/oauth/token")
.header("content-type", "application/json")
.body(Body::from("{}"))
.unwrap(),
)
.await;
assert_eq!(r.err(), "invalid_request");
}
}
#[tokio::test]
async fn refresh_rotation_and_reuse_detection() {
for (name, db) in dbs().await {
let e = env(db).await;
let cid = public_client(&e).await;
let t = tokens_for(&e, &cid, "read%20write").await;
let (a1, r1) = (
t["access_token"].as_str().unwrap().to_string(),
t["refresh_token"].as_str().unwrap().to_string(),
);
let refresh = |r: &str, extra: &str| {
format!("grant_type=refresh_token&client_id={cid}&refresh_token={r}{extra}")
};
let r = post_form(&e.app, "/oauth/token", &refresh(&r1, "&scope=admin"), &[]).await;
assert_eq!(r.err(), "invalid_scope", "{name}");
let t2 = post_form(&e.app, "/oauth/token", &refresh(&r1, "&scope=read"), &[]).await;
assert_eq!(t2.status, StatusCode::OK, "{name}: {}", t2.body);
let t2 = t2.json();
assert_eq!(t2["scope"], "read");
let (a2, r2) = (
t2["access_token"].as_str().unwrap().to_string(),
t2["refresh_token"].as_str().unwrap().to_string(),
);
assert!(a2 != a1 && r2 != r1);
assert!(e.o.verify(&a2).await.is_some(), "{name}");
let other = public_client(&e).await;
let r = post_form(
&e.app,
"/oauth/token",
&format!("grant_type=refresh_token&client_id={other}&refresh_token={r2}"),
&[],
)
.await;
assert_eq!(r.err(), "invalid_grant", "{name}");
let r = post_form(&e.app, "/oauth/token", &refresh(&r1, ""), &[]).await;
assert_eq!(r.err(), "invalid_grant", "{name}");
assert!(
e.o.verify(&a2).await.is_none() && e.o.verify(&a1).await.is_none(),
"{name}: family revoked"
);
let r = post_form(&e.app, "/oauth/token", &refresh(&r2, ""), &[]).await;
assert_eq!(r.err(), "invalid_grant", "{name}: newest refresh dead too");
let t = tokens_for(&e, &cid, "read").await;
tokens::Entity::update_many()
.col_expr(tokens::Column::RefreshExpiresAt, Expr::value(now() - 1))
.filter(tokens::Column::AccessHash.eq(hash(t["access_token"].as_str().unwrap())))
.exec(&e.db)
.await
.unwrap();
let r = post_form(
&e.app,
"/oauth/token",
&refresh(t["refresh_token"].as_str().unwrap(), ""),
&[],
)
.await;
assert_eq!(r.err(), "invalid_grant", "{name}: expired");
}
}
#[tokio::test]
async fn client_credentials_revoke_introspect_expiry() {
for (name, db) in dbs().await {
let e = env(db).await;
let c =
e.o.create_client("Svc", &[], &["read", "write"], true)
.await
.unwrap();
let (id, secret) = (c.client_id.clone(), c.client_secret.clone().unwrap());
assert!(secret.starts_with("rys_"));
let (ok, wrong) = (basic(&id, &secret), basic(&id, "wrong"));
let r = post_form(
&e.app,
"/oauth/token",
"grant_type=client_credentials&scope=read",
&[("authorization", &ok)],
)
.await;
assert_eq!(r.status, StatusCode::OK, "{name}: {}", r.body);
let j = r.json();
assert!(j.get("refresh_token").is_none() && j["scope"] == "read");
let at = j["access_token"].as_str().unwrap().to_string();
let p = e.o.verify(&at).await.expect(name);
assert_eq!(
(p.kind, p.user_id, p.id),
(PrincipalKind::OAuthClient, None, id.clone())
);
let r = post_form(
&e.app,
"/oauth/token",
&format!("grant_type=client_credentials&client_id={id}&client_secret={secret}"),
&[],
)
.await;
assert_eq!(r.status, StatusCode::OK, "{name}");
for (body, h) in [
(
format!("grant_type=client_credentials&client_id={id}&client_secret=wrong"),
vec![],
),
(
format!("grant_type=client_credentials&client_id={id}"),
vec![],
),
(
"grant_type=client_credentials".to_string(),
vec![("authorization", wrong.as_str())],
),
] {
let r = post_form(&e.app, "/oauth/token", &body, &h).await;
assert_eq!(
(r.status, r.err()),
(StatusCode::UNAUTHORIZED, "invalid_client".into()),
"{name}: {body}"
);
}
let r = post_form(
&e.app,
"/oauth/token",
&format!("grant_type=client_credentials&client_secret={secret}"),
&[("authorization", &ok)],
)
.await;
assert_eq!(r.err(), "invalid_request", "{name}");
let r = post_form(
&e.app,
"/oauth/token",
"grant_type=client_credentials&scope=admin",
&[("authorization", &ok)],
)
.await;
assert_eq!(r.err(), "invalid_scope", "{name}");
let pubc = public_client(&e).await;
let r = post_form(
&e.app,
"/oauth/token",
&format!("grant_type=client_credentials&client_id={pubc}"),
&[],
)
.await;
assert_eq!(r.err(), "unauthorized_client", "{name}");
let r = post_form(
&e.app,
"/oauth/introspect",
&format!("token={at}"),
&[("authorization", &ok)],
)
.await;
let j = r.json();
assert_eq!(j["active"], true, "{name}");
assert_eq!(
(
j["client_id"].as_str(),
j["scope"].as_str(),
j["token_type"].as_str()
),
(Some(id.as_str()), Some("read"), Some("Bearer"))
);
assert!(j["exp"].as_i64().unwrap() > now() && j.get("sub").is_none());
assert_eq!(r.headers["cache-control"], "no-store");
let r = post_form(
&e.app,
"/oauth/introspect",
&format!("token={at}"),
&[("authorization", &wrong)],
)
.await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
let r = post_form(
&e.app,
"/oauth/introspect",
&format!("token={at}&client_id={pubc}"),
&[],
)
.await;
assert_eq!(
r.status,
StatusCode::UNAUTHORIZED,
"{name}: public clients cannot introspect"
);
let other =
e.o.create_client("Other", &[], &["read"], true)
.await
.unwrap();
let ob = basic(&other.client_id, &other.client_secret.unwrap());
let r = post_form(
&e.app,
"/oauth/introspect",
&format!("token={at}"),
&[("authorization", &ob)],
)
.await;
assert_eq!(
r.json(),
json!({"active": false}),
"{name}: other client's token"
);
let r = post_form(
&e.app,
"/oauth/introspect",
"token=garbage",
&[("authorization", &ok)],
)
.await;
assert_eq!(r.json(), json!({"active": false}));
let r = post_form(
&e.app,
"/oauth/revoke",
&format!("token={at}"),
&[("authorization", &ob)],
)
.await;
assert_eq!(r.status, StatusCode::OK);
assert!(
e.o.verify(&at).await.is_some(),
"{name}: foreign revoke ignored"
);
let r = post_form(
&e.app,
"/oauth/revoke",
&format!("token={at}"),
&[("authorization", &ok)],
)
.await;
assert_eq!((r.status, r.body.as_str()), (StatusCode::OK, ""), "{name}");
assert_eq!(r.headers["cache-control"], "no-store");
assert!(e.o.verify(&at).await.is_none(), "{name}");
let r = post_form(
&e.app,
"/oauth/introspect",
&format!("token={at}"),
&[("authorization", &ok)],
)
.await;
assert_eq!(r.json(), json!({"active": false}), "{name}");
let r = post_form(
&e.app,
"/oauth/revoke",
"token=ryo_unknown",
&[("authorization", &ok)],
)
.await;
assert_eq!(r.status, StatusCode::OK);
let t = post_form(
&e.app,
"/oauth/token",
"grant_type=client_credentials",
&[("authorization", &ok)],
)
.await
.json();
let at = t["access_token"].as_str().unwrap();
tokens::Entity::update_many()
.col_expr(tokens::Column::AccessExpiresAt, Expr::value(now() - 1))
.filter(tokens::Column::AccessHash.eq(hash(at)))
.exec(&e.db)
.await
.unwrap();
assert!(e.o.verify(at).await.is_none(), "{name}: expired");
let r = post_form(
&e.app,
"/oauth/introspect",
&format!("token={at}"),
&[("authorization", &ok)],
)
.await;
assert_eq!(r.json(), json!({"active": false}));
let t = post_form(
&e.app,
"/oauth/token",
"grant_type=client_credentials",
&[("authorization", &ok)],
)
.await
.json();
let at = t["access_token"].as_str().unwrap();
assert!(
e.o.revoke_client(&id).await.unwrap() && !e.o.revoke_client("nope").await.unwrap()
);
assert!(e.o.verify(at).await.is_none(), "{name}");
let r = post_form(
&e.app,
"/oauth/token",
"grant_type=client_credentials",
&[("authorization", &ok)],
)
.await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED, "{name}");
}
}
async fn join(hs: Vec<tokio::task::JoinHandle<Resp>>) -> Vec<Resp> {
let mut v = vec![];
for h in hs {
v.push(h.await.unwrap());
}
v
}
#[tokio::test]
async fn single_winner_under_concurrency() {
for (name, db) in dbs().await {
let e = env(db).await;
let cid = public_client(&e).await;
for round in 0..3 {
let code = get_code(&e, &cid, "read").await;
let rs = join(
(0..12)
.map(|_| {
let (app, b) = (e.app.clone(), code_body(&cid, &code, VERIFIER));
tokio::spawn(
async move { post_form(&app, "/oauth/token", &b, &[]).await },
)
})
.collect(),
)
.await;
let n = rs.iter().filter(|r| r.status == StatusCode::OK).count();
assert!(n <= 1, "{name} code round {round}: {n} winners");
let live = tokens::Entity::find()
.filter(tokens::Column::ClientId.eq(cid.as_str()))
.filter(tokens::Column::RevokedAt.is_null())
.all(&e.db)
.await
.unwrap();
assert!(live.len() <= 1, "{name} round {round}: {} live", live.len());
}
let t = tokens_for(&e, &cid, "read").await;
let rt = t["refresh_token"].as_str().unwrap().to_string();
let rs = join(
(0..12)
.map(|_| {
let (app, b) = (
e.app.clone(),
format!("grant_type=refresh_token&client_id={cid}&refresh_token={rt}"),
);
tokio::spawn(async move { post_form(&app, "/oauth/token", &b, &[]).await })
})
.collect(),
)
.await;
let n = rs.iter().filter(|r| r.status == StatusCode::OK).count();
assert!(n <= 1, "{name} refresh: {n} winners");
let fam = tokens::Entity::find()
.filter(tokens::Column::AccessHash.eq(hash(t["access_token"].as_str().unwrap())))
.one(&e.db)
.await
.unwrap()
.unwrap()
.family_id;
let live = tokens::Entity::find()
.filter(tokens::Column::FamilyId.eq(fam))
.filter(tokens::Column::RevokedAt.is_null())
.all(&e.db)
.await
.unwrap();
assert!(
live.is_empty(),
"{name}: losers detected reuse, family must be dead ({n} won)"
);
}
}
#[tokio::test]
async fn exactly_one_winner_without_replay_signal() {
for (name, db) in dbs().await {
let e = env(db).await;
let cid = public_client(&e).await;
let code = get_code(&e, &cid, "read").await;
let id = codes::Entity::find()
.filter(codes::Column::CodeHash.eq(hash(&code)))
.one(&e.db)
.await
.unwrap()
.unwrap()
.id;
let hs: Vec<_> = (0..16)
.map(|_| {
let o = e.o.clone();
tokio::spawn(async move { o.claim_code(id).await.unwrap() })
})
.collect();
let mut wins = 0;
for h in hs {
wins += h.await.unwrap() as u32;
}
assert_eq!(wins, 1, "{name}");
}
}
#[tokio::test]
async fn client_validation_and_long_uris() {
for (name, db) in dbs().await {
let e = env(db).await;
for uri in [
"/relative",
"https://a.example/cb#frag",
"javascript",
"https://a b",
"",
] {
assert!(
e.o.create_client("x", &[uri], &[], false).await.is_err(),
"{name}: {uri}"
);
}
assert!(e.o.create_client("", &[], &[], false).await.is_err());
assert!(
e.o.create_client("x", &[], &["bad scope"], false)
.await
.is_err()
);
let long = format!("https://a.example/{}", "x".repeat(600));
let c =
e.o.create_client("long", &[long.as_str(), "myapp:/cb"], &[], false)
.await
.unwrap();
let row = e.o.client(&c.client_id).await.unwrap().unwrap();
assert_eq!(
row.uris(),
[long, "myapp:/cb".to_string()],
"{name}: Text column"
);
assert!(c.client_secret.is_none() && row.secret_hash.is_none());
}
}
const APP_CB: &str = "myapp://callback";
const HTTPS_CB: &str = "https://app.example.com/cb";
async fn fp_client(e: &Env, uri: &str, first_party: bool) -> String {
let mut spec = ClientSpec::new("Mobile").redirect(uri).scope("read");
if first_party {
spec = spec.first_party();
}
e.o.create_client_spec(spec).await.unwrap().client_id
}
fn authz_query(cid: &str, uri: &str, extra: &str) -> String {
format!(
"response_type=code&client_id={cid}&redirect_uri={}&scope=read&state=st&code_challenge={}&code_challenge_method=S256{extra}",
pct(uri),
s256(VERIFIER)
)
}
async fn authz_get(e: &Env, q: &str, cookie: Option<&str>) -> Resp {
let mut r = Request::get(format!("/oauth/authorize?{q}"));
if let Some(c) = cookie {
r = r.header("cookie", c);
}
send(&e.app, r.body(Body::empty()).unwrap()).await
}
#[tokio::test]
async fn consent_accepts_json_bodies_like_the_inertia_client() {
for (name, db) in dbs().await {
let e = env(db).await;
let cid = fp_client(&e, APP_CB, true).await;
let cookie = session_for(&e.app, 7).await;
let q = authz_query(&cid, APP_CB, "&prompt=consent");
let page = send(
&e.app,
Request::get(format!("/oauth/authorize?{q}"))
.header("cookie", &cookie)
.header("x-inertia", "true")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(page.status, StatusCode::OK, "{name}: {}", page.body);
let rid = page.json()["props"]["request_id"]
.as_str()
.unwrap()
.to_string();
let body = serde_json::json!({ "decision": "allow", "request_id": rid }).to_string();
let r = send(
&e.app,
Request::post("/oauth/authorize")
.header("cookie", &cookie)
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap(),
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{name}: {}", r.body);
assert!(
r.loc().starts_with("myapp://callback?code=ryc_"),
"{name}: {}",
r.loc()
);
let r = send(
&e.app,
Request::post("/oauth/authorize")
.header("cookie", &cookie)
.header("content-type", "application/json")
.body(Body::from("{not json"))
.unwrap(),
)
.await;
assert!(r.status.is_client_error(), "{name}: {}", r.status);
}
}
#[tokio::test]
async fn first_party_skips_consent_over_https_roundtrip() {
for (name, db) in dbs().await {
let e = env(db).await;
let cid = fp_client(&e, HTTPS_CB, true).await;
let row = e.o.client(&cid).await.unwrap().unwrap();
assert!(row.first_party && row.uris() == [HTTPS_CB], "{name}");
let cookie = session_for(&e.app, 7).await;
let q = authz_query(&cid, HTTPS_CB, "");
let r = authz_get(&e, &q, None).await;
assert!(r.loc().starts_with("/login?next="), "{name}: {}", r.loc());
let r = authz_get(&e, &q, Some(&cookie)).await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{name}: {}", r.body);
let loc = r.loc();
assert!(
loc.starts_with("https://app.example.com/cb?code=ryc_"),
"{name}: {loc}"
);
assert!(loc.ends_with("&state=st"), "{name}: {loc}");
let code = qp(&loc, "code").unwrap();
let body = format!(
"grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={VERIFIER}",
pct(HTTPS_CB)
);
let t = post_form(&e.app, "/oauth/token", &body, &[]).await;
assert_eq!(t.status, StatusCode::OK, "{name}: {}", t.body);
let p = e.o.verify(t.json()["access_token"].as_str().unwrap()).await;
assert_eq!(p.and_then(|p| p.user_id), Some(7), "{name}");
let again = post_form(&e.app, "/oauth/token", &body, &[]).await;
assert_eq!(again.err(), "invalid_grant", "{name}");
let n = codes::Entity::find().all(&e.db).await.unwrap().len();
let hdr = |q: String| {
Request::get(format!("/oauth/authorize?{q}"))
.header("cookie", &cookie)
.header("x-inertia", "true")
.body(Body::empty())
.unwrap()
};
let r = send(
&e.app,
hdr(authz_query(&cid, HTTPS_CB, "&prompt=login%20consent")),
)
.await;
assert_eq!(r.status, StatusCode::OK, "{name}");
assert_eq!(r.json()["component"], "OAuth/Authorize");
assert_eq!(codes::Entity::find().all(&e.db).await.unwrap().len(), n);
let r = send(&e.app, hdr(authz_query(&cid, HTTPS_CB, ""))).await;
assert_eq!(r.status, StatusCode::CONFLICT, "{name}");
assert!(
r.headers["x-inertia-location"]
.to_str()
.unwrap()
.starts_with(HTTPS_CB)
);
let tp = fp_client(&e, HTTPS_CB, false).await;
assert!(!e.o.client(&tp).await.unwrap().unwrap().first_party);
let r = send(&e.app, hdr(authz_query(&tp, HTTPS_CB, ""))).await;
assert_eq!(r.json()["component"], "OAuth/Authorize", "{name}");
}
}
#[tokio::test]
async fn first_party_custom_scheme_shows_consent_then_works() {
for (name, db) in dbs().await {
let e = env(db).await;
let cid = fp_client(&e, APP_CB, true).await;
let cookie = session_for(&e.app, 7).await;
let n = codes::Entity::find().all(&e.db).await.unwrap().len();
let page = send(
&e.app,
Request::get(format!(
"/oauth/authorize?{}",
authz_query(&cid, APP_CB, "")
))
.header("cookie", &cookie)
.header("x-inertia", "true")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(page.status, StatusCode::OK, "{name}: {}", page.body);
assert_eq!(page.json()["component"], "OAuth/Authorize", "{name}");
assert_eq!(codes::Entity::find().all(&e.db).await.unwrap().len(), n);
let rid = page.json()["props"]["request_id"]
.as_str()
.unwrap()
.to_string();
let r = post_form(
&e.app,
"/oauth/authorize",
&format!("decision=allow&request_id={rid}"),
&[("cookie", &cookie)],
)
.await;
let code = qp(&r.loc(), "code").expect(name);
let body = format!(
"grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={VERIFIER}",
pct(APP_CB)
);
let t = post_form(&e.app, "/oauth/token", &body, &[]).await;
assert_eq!(t.status, StatusCode::OK, "{name}: {}", t.body);
}
}
#[tokio::test]
async fn refresh_rechecks_the_client() {
for (name, db) in dbs().await {
let e = env(db).await;
let set = |cid: String, v: &'static str| {
clients::Entity::update_many()
.col_expr(clients::Column::AllowedScopes, Expr::value(v))
.filter(clients::Column::ClientId.eq(cid))
.exec(&e.db)
};
let cid = public_client(&e).await;
let t = tokens_for(&e, &cid, "read%20write").await;
set(cid.clone(), "read").await.unwrap();
let r = refresh(&e, &cid, t["refresh_token"].as_str().unwrap()).await;
assert_eq!(r.status, StatusCode::OK, "{name}: {}", r.body);
assert_eq!(r.json()["scope"], "read", "{name}");
set(cid.clone(), "other").await.unwrap();
let r = refresh(&e, &cid, r.json()["refresh_token"].as_str().unwrap()).await;
assert_eq!(r.err(), "invalid_grant", "{name}");
let cid = public_client(&e).await;
let t = tokens_for(&e, &cid, "read").await;
clients::Entity::update_many()
.col_expr(clients::Column::RevokedAt, Expr::value(now()))
.filter(clients::Column::ClientId.eq(cid.as_str()))
.exec(&e.db)
.await
.unwrap();
let r = refresh(&e, &cid, t["refresh_token"].as_str().unwrap()).await;
assert!(r.status.is_client_error(), "{name}: {}", r.body);
}
}
#[tokio::test]
async fn first_party_keeps_every_validation() {
for (name, db) in dbs().await {
let e = env(db).await;
let cid = fp_client(&e, HTTPS_CB, true).await;
let cookie = session_for(&e.app, 7).await;
let n = codes::Entity::find().all(&e.db).await.unwrap().len();
for q in [
authz_query(&cid, "https://app.example.com/evil", ""),
authz_query(&cid, "https://app.example.com/cb/", ""),
authz_query("nope", HTTPS_CB, ""),
] {
let r = authz_get(&e, &q, Some(&cookie)).await;
assert!(r.headers.get("location").is_none(), "{name}: {q}");
assert_eq!(r.status, StatusCode::BAD_REQUEST, "{name}: {q}");
}
let ok = authz_query(&cid, HTTPS_CB, "");
for (q, err) in [
(
format!(
"response_type=code&client_id={cid}&redirect_uri={}&scope=read&state=st",
pct(HTTPS_CB)
),
"invalid_request",
),
(ok.replace("S256", "plain"), "invalid_request"),
(ok.replace("scope=read", "scope=admin"), "invalid_scope"),
(
ok.replace("response_type=code", "response_type=token"),
"unsupported_response_type",
),
] {
let r = authz_get(&e, &q, Some(&cookie)).await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{name}: {q}");
assert!(
r.loc().starts_with("https://app.example.com/cb?error=")
&& qp(&r.loc(), "error").as_deref() == Some(err)
&& qp(&r.loc(), "code").is_none(),
"{name}: {}",
r.loc()
);
}
assert_eq!(
codes::Entity::find().all(&e.db).await.unwrap().len(),
n,
"{name}"
);
let r = authz_get(&e, &ok, Some(&cookie)).await;
let code = qp(&r.loc(), "code").unwrap();
let body = format!(
"grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}&code_verifier={}",
pct(HTTPS_CB),
"A".repeat(43)
);
assert_eq!(
post_form(&e.app, "/oauth/token", &body, &[]).await.err(),
"invalid_grant",
"{name}"
);
}
}
#[tokio::test]
async fn client_spec_validation() {
for (name, db) in dbs().await {
let e = env(db).await;
let s = ClientSpec::new("x").redirect(APP_CB);
assert!(
e.o.create_client_spec(s.clone().first_party())
.await
.is_ok(),
"{name}"
);
for bad in [
ClientSpec::new("x").first_party(), ClientSpec::new(""),
s.clone().redirect("/relative"),
s.clone().redirect("myapp://cb#f"),
s.clone().scope("bad scope"),
] {
assert!(e.o.create_client_spec(bad).await.is_err(), "{name}");
}
let c =
e.o.create_client_spec(s.confidential().first_party())
.await
.unwrap();
assert!(c.client_secret.is_some(), "{name}");
let c = e.o.create_client("w", &[APP_CB], &[], false).await.unwrap();
assert!(!e.o.client(&c.client_id).await.unwrap().unwrap().first_party);
}
}
#[tokio::test]
async fn old_schema_is_upgraded() {
use sea_orm::sea_query::Query;
for (name, db) in dbs().await {
let drop = Table::drop()
.table(Alias::new("oauth_clients"))
.if_exists()
.to_owned();
db.execute(&drop).await.unwrap();
let col = |n: &str| ColumnDef::new(Alias::new(n));
let old = Table::create()
.table(Alias::new("oauth_clients"))
.col(
col("id")
.big_integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(col("client_id").string().not_null().unique_key())
.col(col("secret_hash").string().null())
.col(col("name").string().not_null())
.col(col("redirect_uris").text().not_null())
.col(col("allowed_scopes").text().not_null())
.col(col("created_at").big_integer().not_null())
.col(col("revoked_at").big_integer().null())
.to_owned();
db.execute(&old).await.unwrap();
let ins = Query::insert()
.into_table(Alias::new("oauth_clients"))
.columns(
[
"client_id",
"name",
"redirect_uris",
"allowed_scopes",
"created_at",
]
.map(Alias::new),
)
.values_panic([
"legacy".into(),
"Old".into(),
"[]".into(),
"read".into(),
1i64.into(),
])
.to_owned();
db.execute(&ins).await.unwrap();
let e = env(db).await; let c = e.o.client("legacy").await.unwrap().expect(name);
assert!(!c.first_party && c.name == "Old", "{name}");
let id = fp_client(&e, APP_CB, true).await;
assert!(
e.o.client(&id).await.unwrap().unwrap().first_party,
"{name}"
);
}
}
fn uniq() -> i64 {
chrono::Utc::now().timestamp_nanos_opt().unwrap()
}
async fn minted(e: &Env, cid: &str, uid: i64) -> (tokens::Model, String, String) {
let (row, at, rt) =
e.o.mint(cid, Some(uid), "read", None, None, true)
.await
.map_err(|_| "mint")
.unwrap();
(row, at, rt.unwrap())
}
async fn refresh(e: &Env, cid: &str, rt: &str) -> Resp {
refresh_via(&e.app, cid, rt).await
}
async fn refresh_via(app: &Router, cid: &str, rt: &str) -> Resp {
post_form(
app,
"/oauth/token",
&format!("grant_type=refresh_token&client_id={cid}&refresh_token={rt}"),
&[],
)
.await
}
async fn set_tok(db: &DatabaseConnection, id: i64, col: tokens::Column, v: Option<i64>) {
tokens::Entity::update_many()
.col_expr(col, Expr::value(v))
.filter(tokens::Column::Id.eq(id))
.exec(db)
.await
.unwrap();
}
async fn gone(db: &DatabaseConnection, id: i64) -> bool {
tokens::Entity::find_by_id(id)
.one(db)
.await
.unwrap()
.is_none()
}
#[tokio::test]
async fn grants_listing_revocation_and_last_used() {
for (name, db) in dbs().await {
let e = env(db.clone()).await;
let cid = public_client(&e).await;
let (uid, other) = (uniq(), uniq() + 1);
let (g1, at1, _rt1) = minted(&e, &cid, uid).await;
let (g2, at2, rt2) = minted(&e, &cid, uid).await;
let (_g3, at3, _) = minted(&e, &cid, other).await;
assert!(g1.last_used_at.is_none());
e.o.verify(&at1).await.expect(name);
let used = |id: i64| {
let db = db.clone();
async move {
tokens::Entity::find_by_id(id)
.one(&db)
.await
.unwrap()
.unwrap()
.last_used_at
}
};
let first = used(g1.id).await.expect("set on first verify");
set_tok(&db, g1.id, tokens::Column::LastUsedAt, Some(first - 10)).await;
e.o.verify(&at1).await.unwrap();
assert_eq!(used(g1.id).await, Some(first - 10), "{name}: within 60s");
set_tok(&db, g1.id, tokens::Column::LastUsedAt, Some(first - 100)).await;
e.o.verify(&at1).await.unwrap();
assert!(used(g1.id).await.unwrap() >= first, "{name}: refreshed");
let l = e.o.list_grants(uid).await.unwrap();
assert_eq!(l.len(), 2, "{name}");
let a = l.iter().find(|g| g.id == g1.family_id).unwrap();
assert_eq!(
(a.client_id.as_str(), a.client_name.as_str()),
(cid.as_str(), "Test app")
);
assert_eq!(a.scopes, ["read"]);
assert!(a.last_used_at.is_some() && a.expires_at > now() && a.created_at <= now());
assert!(
l.iter()
.find(|g| g.id == g2.family_id)
.unwrap()
.last_used_at
.is_none()
);
assert!(!format!("{l:?}").contains(&at1), "{name}: no secrets");
assert_eq!(e.o.list_grants(other).await.unwrap().len(), 1, "{name}");
let r = refresh(&e, &cid, &rt2).await;
assert_eq!(r.status, StatusCode::OK, "{name} {}", r.body);
let (at2b, rt2b) = (
r.json()["access_token"].as_str().unwrap().to_string(),
r.json()["refresh_token"].as_str().unwrap().to_string(),
);
assert_eq!(e.o.list_grants(uid).await.unwrap().len(), 2, "{name}");
assert!(
!e.o.revoke_grant(other, &g1.family_id).await.unwrap(),
"{name}"
);
assert!(e.o.verify(&at1).await.is_some());
assert!(
e.o.revoke_grant(uid, &g1.family_id).await.unwrap(),
"{name}"
);
assert!(
!e.o.revoke_grant(uid, &g1.family_id).await.unwrap(),
"{name}"
);
assert!(!e.o.revoke_grant(uid, "nope").await.unwrap());
assert!(e.o.verify(&at1).await.is_none(), "{name}");
let l = e.o.list_grants(uid).await.unwrap();
assert_eq!(
(l.len(), l[0].id.as_str()),
(1, g2.family_id.as_str()),
"{name}"
);
let (x, _, _) = minted(&e, &cid, uid).await;
assert_eq!(e.o.list_grants(uid).await.unwrap().len(), 2);
set_tok(&db, x.id, tokens::Column::AccessExpiresAt, Some(now() - 5)).await;
set_tok(&db, x.id, tokens::Column::RefreshExpiresAt, Some(now() - 5)).await;
assert_eq!(e.o.list_grants(uid).await.unwrap().len(), 1, "{name}");
let code =
e.o.issue_code(&cid, uid, CB, &["read".into()], None)
.await
.unwrap();
let body = format!(
"grant_type=authorization_code&client_id={cid}&code={code}&redirect_uri={}",
pct(CB)
);
assert_eq!(e.o.revoke_user_tokens(uid).await.unwrap(), 2, "{name}");
assert_eq!(e.o.revoke_user_tokens(uid).await.unwrap(), 0, "{name}");
assert!(e.o.verify(&at2).await.is_none() && e.o.verify(&at2b).await.is_none());
for rt in [&rt2, &rt2b] {
let r = refresh(&e, &cid, rt).await;
assert_eq!(
(r.status, r.err()),
(StatusCode::BAD_REQUEST, "invalid_grant".into()),
"{name}"
);
}
let r = post_form(&e.app, "/oauth/token", &body, &[]).await;
assert_eq!(r.err(), "invalid_grant", "{name}: code voided");
assert!(e.o.list_grants(uid).await.unwrap().is_empty(), "{name}");
assert!(e.o.verify(&at3).await.is_some(), "{name}");
assert_eq!(e.o.list_grants(other).await.unwrap().len(), 1);
}
}
#[tokio::test]
async fn prune_deletes_only_finished_rows() {
for (name, db) in dbs().await {
let e = env(db.clone()).await;
let cid = public_client(&e).await;
let uid = uniq();
let t = now();
let hour = Duration::from_secs(3600);
let row = || async { minted(&e, &cid, uid).await.0 };
let (live, revoked_old, revoked_new, expired, rotated_live, access_only) = (
row().await,
row().await,
row().await,
row().await,
row().await,
e.o.mint(&cid, Some(uid), "read", None, None, false)
.await
.map_err(|_| "mint")
.unwrap()
.0,
);
set_tok(
&db,
revoked_old.id,
tokens::Column::RevokedAt,
Some(t - 7200),
)
.await;
set_tok(&db, revoked_new.id, tokens::Column::RevokedAt, Some(t - 5)).await;
for c in [
tokens::Column::AccessExpiresAt,
tokens::Column::RefreshExpiresAt,
] {
set_tok(&db, expired.id, c, Some(t - 120)).await;
}
set_tok(
&db,
rotated_live.id,
tokens::Column::AccessExpiresAt,
Some(t - 5000),
)
.await;
set_tok(
&db,
rotated_live.id,
tokens::Column::RefreshUsedAt,
Some(t - 4000),
)
.await;
set_tok(
&db,
access_only.id,
tokens::Column::AccessExpiresAt,
Some(t - 120),
)
.await;
let mk_code = |used: Option<i64>, exp: i64| {
let db = db.clone();
let cid = cid.clone();
async move {
codes::ActiveModel {
code_hash: Set(hash(&format!("c{}", uniq()))),
client_id: Set(cid),
user_id: Set(uid),
redirect_uri: Set(CB.into()),
scopes: Set("read".into()),
expires_at: Set(exp),
used_at: Set(used),
..Default::default()
}
.insert(&db)
.await
.unwrap()
.id
}
};
let (c_live, c_exp, c_used_old, c_used_new) = (
mk_code(None, t + 500).await,
mk_code(None, t - 120).await,
mk_code(Some(t - 7200), t - 7000).await,
mk_code(Some(t - 5), t + 500).await,
);
let rep = e.o.prune(hour).await.unwrap();
assert!(rep.tokens >= 3 && rep.codes >= 2, "{name}: {rep:?}");
for (id, kept) in [
(live.id, true),
(revoked_old.id, false),
(revoked_new.id, true),
(expired.id, false),
(rotated_live.id, true),
(access_only.id, false),
] {
assert_eq!(!gone(&db, id).await, kept, "{name}: token {id}");
}
for (id, kept) in [
(c_live, true),
(c_exp, false),
(c_used_old, false),
(c_used_new, true),
] {
let there = codes::Entity::find_by_id(id)
.one(&db)
.await
.unwrap()
.is_some();
assert_eq!(there, kept, "{name}: code {id}");
}
assert_eq!(
e.o.prune(hour).await.unwrap().tokens,
0,
"{name}: idempotent"
);
e.o.prune(Duration::ZERO).await.unwrap();
assert!(gone(&db, revoked_new.id).await, "{name}");
assert!(
!gone(&db, live.id).await && !gone(&db, rotated_live.id).await,
"{name}"
);
}
}
#[tokio::test]
async fn prune_racing_verify_and_rotation_keeps_single_winner() {
for (name, db) in dbs().await {
let e = env(db.clone()).await;
let cid = public_client(&e).await;
let uid = uniq();
let mut grants = Vec::new();
for _ in 0..12 {
let (_, at, rt) = minted(&e, &cid, uid).await;
grants.push((at, rt));
}
for _ in 0..30 {
let (r, _, _) = minted(&e, &cid, uid).await;
set_tok(
&db,
r.id,
tokens::Column::AccessExpiresAt,
Some(now() - 600),
)
.await;
set_tok(
&db,
r.id,
tokens::Column::RefreshExpiresAt,
Some(now() - 600),
)
.await;
}
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let pruner = {
let (o, stop) = (e.o.clone(), stop.clone());
tokio::spawn(async move {
while !stop.load(std::sync::atomic::Ordering::Relaxed) {
o.prune(Duration::ZERO).await.unwrap();
tokio::task::yield_now().await;
}
})
};
let mut hs = Vec::new();
let mut solo_hs = Vec::new();
for _ in 0..12 {
let (_, _, rt) = minted(&e, &cid, uid).await;
let (app, cid) = (e.app.clone(), cid.clone());
solo_hs.push(tokio::spawn(
async move { refresh_via(&app, &cid, &rt).await },
));
}
for (at, rt) in &grants {
for _ in 0..3 {
let (app, cid, rt) = (e.app.clone(), cid.clone(), rt.clone());
hs.push(tokio::spawn(async move {
post_form(
&app,
"/oauth/token",
&format!("grant_type=refresh_token&client_id={cid}&refresh_token={rt}"),
&[],
)
.await
}));
}
let (o, at) = (e.o.clone(), at.clone());
hs.push(tokio::spawn(async move {
let _ = o.verify(&at).await;
Resp {
status: StatusCode::OK,
headers: HeaderMap::new(),
body: "{}".into(),
}
}));
}
let rs = join(hs).await;
stop.store(true, std::sync::atomic::Ordering::Relaxed);
pruner.await.unwrap();
for chunk in rs.chunks(4) {
let wins = chunk[..3]
.iter()
.filter(|r| r.status == StatusCode::OK)
.count();
assert!(wins <= 1, "{name}: {wins} winners");
assert!(
chunk[..3]
.iter()
.all(|r| r.status == StatusCode::OK || r.err() == "invalid_grant"),
"{name}: {:?}",
chunk[..3]
.iter()
.map(|r| (r.status, r.body.clone()))
.collect::<Vec<_>>()
);
}
for r in join(solo_hs).await {
assert_eq!(r.status, StatusCode::OK, "{name}: {}", r.body);
}
}
}
#[tokio::test]
async fn old_token_tables_are_upgraded_with_indexes() {
for (name, db) in dbs().await {
for t in ["oauth_tokens", "oauth_codes"] {
let drop = Table::drop().table(Alias::new(t)).if_exists().to_owned();
db.execute(&drop).await.unwrap();
}
let col = |n: &str| ColumnDef::new(Alias::new(n));
let old = Table::create()
.table(Alias::new("oauth_tokens"))
.col(
col("id")
.big_integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(col("access_hash").string().not_null().unique_key())
.col(col("refresh_hash").string().null().unique_key())
.col(col("client_id").string().not_null())
.col(col("user_id").big_integer().null())
.col(col("scopes").text().not_null())
.col(col("created_at").big_integer().not_null())
.col(col("access_expires_at").big_integer().not_null())
.col(col("refresh_expires_at").big_integer().null())
.col(col("revoked_at").big_integer().null())
.col(col("family_id").string().not_null())
.col(col("code_id").big_integer().null())
.col(col("refresh_used_at").big_integer().null())
.col(col("refresh_claim").string().null())
.to_owned();
db.execute(&old).await.unwrap();
let mut c =
Schema::new(db.get_database_backend()).create_table_from_entity(codes::Entity);
db.execute(c.if_not_exists()).await.unwrap();
let (uid, access) = (uniq(), format!("ryo_old{}", uniq()));
let t = now();
let ins = SqlQuery::insert()
.into_table(Alias::new("oauth_tokens"))
.columns(
[
"access_hash",
"client_id",
"user_id",
"scopes",
"created_at",
"access_expires_at",
"family_id",
]
.map(Alias::new),
)
.values_panic([
hash(&access).into(),
"legacy-no-client".into(),
uid.into(),
"read".into(),
t.into(),
(t + 3600).into(),
"fam-old".into(),
])
.to_owned();
db.execute(&ins).await.unwrap();
let o = OAuthServer::new(db.clone());
let hs: Vec<_> = (0..3)
.map(|_| {
let o = o.clone();
tokio::spawn(async move { o.ensure_tables().await })
})
.collect();
for h in hs {
h.await.unwrap().unwrap_or_else(|e| panic!("{name}: {e}"));
}
o.ensure_tables().await.unwrap();
let p = o.verify(&access).await.expect(name);
assert_eq!((p.user_id, p.id.as_str()), (Some(uid), "fam-old"), "{name}");
let row = tokens::Entity::find()
.filter(tokens::Column::AccessHash.eq(hash(&access)))
.one(&db)
.await
.unwrap()
.unwrap();
assert!(row.last_used_at.is_some(), "{name}");
let g = o.list_grants(uid).await.unwrap();
assert_eq!(
(g.len(), g[0].id.as_str(), g[0].client_name.as_str()),
(1, "fam-old", ""),
"{name}"
);
assert!(o.revoke_grant(uid, "fam-old").await.unwrap());
assert!(o.verify(&access).await.is_none());
for (table, col) in [
("oauth_tokens", "family_id"),
("oauth_tokens", "code_id"),
("oauth_tokens", "client_id"),
("oauth_tokens", "user_id"),
("oauth_codes", "user_id"),
] {
let idx = format!("idx-{table}-{col}");
let found = if name == "mysql" {
mysql_has_index(&db, table, &idx).await.unwrap()
} else {
let (view, col) = if name == "sqlite" {
("sqlite_master", "name")
} else {
("pg_indexes", "indexname")
};
let q = SqlQuery::select()
.column(Alias::new(col))
.from(Alias::new(view))
.and_where(sea_orm::ExprTrait::eq(
Expr::col(Alias::new(col)),
idx.as_str(),
))
.to_owned();
!db.query_all(&q).await.unwrap().is_empty()
};
assert!(found, "{name}: missing {idx}");
}
}
}
#[test]
fn primitives() {
assert!(ct_eq("abc", "abc") && !ct_eq("abc", "abd") && !ct_eq("abc", "ab"));
assert_eq!(
s256(VERIFIER),
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
);
assert!(pkce_ok(
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
VERIFIER
));
assert!(!pkce_ok("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "x"));
assert_eq!(pct("a b/?&=\u{e9}"), "a%20b%2F%3F%26%3D%C3%A9");
assert_eq!(
with_query("https://a/cb?x=1", &[("code", "c d")]),
"https://a/cb?x=1&code=c%20d"
);
assert_eq!(split("a b a"), ["a", "b"]);
let (a, b) = (random("ryo_", 32).unwrap(), random("ryo_", 32).unwrap());
assert!(a.len() == 47 && a != b);
}
}