use crate::client::find_client;
use crate::{
constant_time_eq, ensure_tables, hash_secret, now_unix_secs, random_secret, OAuthError,
};
use larust_core::AppError;
use sqlx::AnyPool;
const ACCESS_TOKEN_TTL_SECS: i64 = 3600;
const REFRESH_TOKEN_TTL_SECS: i64 = 30 * 24 * 3600;
pub enum TokenRequest {
AuthorizationCode {
code: String,
redirect_uri: String,
client_id: String,
code_verifier: String,
},
ClientCredentials {
client_id: String,
client_secret: String,
scope: Option<String>,
},
RefreshToken {
refresh_token: String,
client_id: String,
},
}
#[derive(Debug, serde::Serialize)]
pub struct TokenResponse {
pub access_token: String,
pub token_type: &'static str,
pub expires_in: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
pub scope: String,
}
pub async fn exchange_token(request: TokenRequest) -> Result<TokenResponse, OAuthError> {
let pool = larust_orm::pool()?;
ensure_tables(pool).await?;
match request {
TokenRequest::AuthorizationCode {
code,
redirect_uri,
client_id,
code_verifier,
} => {
exchange_authorization_code(pool, &code, &redirect_uri, &client_id, &code_verifier)
.await
}
TokenRequest::ClientCredentials {
client_id,
client_secret,
scope,
} => exchange_client_credentials(pool, &client_id, &client_secret, scope.as_deref()).await,
TokenRequest::RefreshToken {
refresh_token,
client_id,
} => exchange_refresh_token(pool, &refresh_token, &client_id).await,
}
}
async fn exchange_authorization_code(
pool: &AnyPool,
code: &str,
redirect_uri: &str,
client_id: &str,
code_verifier: &str,
) -> Result<TokenResponse, OAuthError> {
let backend = larust_orm::backend();
let code_hash = hash_secret(code);
let select_sql = format!(
"SELECT client_id, user_id, redirect_uri, scopes, code_challenge, expires_at \
FROM oauth_auth_codes WHERE code_hash = {}",
larust_orm::placeholder(backend, 1)
);
let row: Option<(String, i64, String, String, String, i64)> = sqlx::query_as(&select_sql)
.bind(&code_hash)
.fetch_optional(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let Some((row_client_id, user_id, row_redirect_uri, scopes, code_challenge, expires_at)) = row
else {
return Err(OAuthError::InvalidGrant(
"the authorization code is invalid".to_string(),
));
};
if expires_at <= now_unix_secs() {
return Err(OAuthError::InvalidGrant(
"the authorization code has expired".to_string(),
));
}
if row_client_id != client_id {
return Err(OAuthError::InvalidGrant(
"the authorization code was not issued to this client".to_string(),
));
}
if row_redirect_uri != redirect_uri {
return Err(OAuthError::InvalidGrant(
"redirect_uri does not match the one used to request this code".to_string(),
));
}
if !verify_pkce(code_verifier, &code_challenge) {
return Err(OAuthError::InvalidGrant(
"code_verifier does not match the original code_challenge".to_string(),
));
}
let delete_sql = format!(
"DELETE FROM oauth_auth_codes WHERE code_hash = {}",
larust_orm::placeholder(backend, 1)
);
let deleted = sqlx::query(&delete_sql)
.bind(&code_hash)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
if deleted.rows_affected() != 1 {
return Err(OAuthError::InvalidGrant(
"the authorization code has already been used".to_string(),
));
}
issue_tokens(pool, &row_client_id, Some(user_id), &scopes, true).await
}
async fn exchange_client_credentials(
pool: &AnyPool,
client_id: &str,
client_secret: &str,
scope: Option<&str>,
) -> Result<TokenResponse, OAuthError> {
let client = find_client(pool, client_id)
.await?
.ok_or_else(|| OAuthError::InvalidClient("unknown client_id".to_string()))?;
if !client.is_confidential {
return Err(OAuthError::UnauthorizedClient(
"this client has no secret and cannot use the client_credentials grant".to_string(),
));
}
let secret_hash = client
.client_secret_hash
.as_deref()
.expect("a confidential client always has a secret hash");
let verified = larust_auth::verify_password(secret_hash, client_secret)?;
if !verified {
return Err(OAuthError::InvalidClient(
"client_secret is incorrect".to_string(),
));
}
issue_tokens(pool, client_id, None, scope.unwrap_or(""), false).await
}
type RefreshTokenRow = (i64, i64, i64, i64, String, Option<i64>, String);
async fn exchange_refresh_token(
pool: &AnyPool,
refresh_token: &str,
client_id: &str,
) -> Result<TokenResponse, OAuthError> {
let backend = larust_orm::backend();
let token_hash = hash_secret(refresh_token);
let select_sql = format!(
"SELECT r.id, r.access_token_id, r.revoked, r.expires_at, \
a.client_id, a.user_id, a.scopes \
FROM oauth_refresh_tokens r \
JOIN oauth_access_tokens a ON a.id = r.access_token_id \
WHERE r.token_hash = {}",
larust_orm::placeholder(backend, 1)
);
let row: Option<RefreshTokenRow> = sqlx::query_as(&select_sql)
.bind(&token_hash)
.fetch_optional(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let Some((refresh_id, access_token_id, revoked, expires_at, row_client_id, user_id, scopes)) =
row
else {
return Err(OAuthError::InvalidGrant(
"the refresh token is invalid".to_string(),
));
};
if revoked != 0 {
return Err(OAuthError::InvalidGrant(
"the refresh token has already been used or revoked".to_string(),
));
}
if expires_at <= now_unix_secs() {
return Err(OAuthError::InvalidGrant(
"the refresh token has expired".to_string(),
));
}
if row_client_id != client_id {
return Err(OAuthError::InvalidGrant(
"the refresh token was not issued to this client".to_string(),
));
}
revoke_refresh_row(pool, refresh_id).await?;
revoke_access_row(pool, access_token_id).await?;
issue_tokens(pool, &row_client_id, user_id, &scopes, true).await
}
async fn issue_tokens(
pool: &AnyPool,
client_id: &str,
user_id: Option<i64>,
scopes: &str,
with_refresh: bool,
) -> Result<TokenResponse, OAuthError> {
let backend = larust_orm::backend();
let access_token = random_secret();
let access_expires_at = now_unix_secs() + ACCESS_TOKEN_TTL_SECS;
let insert_access_sql = format!(
"INSERT INTO oauth_access_tokens (token_hash, client_id, user_id, scopes, revoked, \
expires_at) VALUES ({}, {}, {}, {}, 0, {})",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
larust_orm::placeholder(backend, 3),
larust_orm::placeholder(backend, 4),
larust_orm::placeholder(backend, 5),
);
sqlx::query(&insert_access_sql)
.bind(hash_secret(&access_token))
.bind(client_id)
.bind(user_id)
.bind(scopes)
.bind(access_expires_at)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let access_token_id = find_access_token_id(pool, &access_token).await?;
let refresh_token = if with_refresh {
let refresh_token = random_secret();
let insert_refresh_sql = format!(
"INSERT INTO oauth_refresh_tokens (token_hash, access_token_id, revoked, \
expires_at) VALUES ({}, {}, 0, {})",
larust_orm::placeholder(backend, 1),
larust_orm::placeholder(backend, 2),
larust_orm::placeholder(backend, 3),
);
sqlx::query(&insert_refresh_sql)
.bind(hash_secret(&refresh_token))
.bind(access_token_id)
.bind(now_unix_secs() + REFRESH_TOKEN_TTL_SECS)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Some(refresh_token)
} else {
None
};
Ok(TokenResponse {
access_token,
token_type: "Bearer",
expires_in: ACCESS_TOKEN_TTL_SECS,
refresh_token,
scope: scopes.to_string(),
})
}
async fn find_access_token_id(pool: &AnyPool, plaintext_token: &str) -> Result<i64, AppError> {
let select_sql = format!(
"SELECT id FROM oauth_access_tokens WHERE token_hash = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
let (id,): (i64,) = sqlx::query_as(&select_sql)
.bind(hash_secret(plaintext_token))
.fetch_one(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(id)
}
fn verify_pkce(code_verifier: &str, code_challenge: &str) -> bool {
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use sha2::{Digest, Sha256};
let digest = Sha256::digest(code_verifier.as_bytes());
let computed = URL_SAFE_NO_PAD.encode(digest);
constant_time_eq(&computed, code_challenge)
}
async fn revoke_access_row(pool: &AnyPool, id: i64) -> Result<(), AppError> {
let sql = format!(
"UPDATE oauth_access_tokens SET revoked = 1 WHERE id = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
sqlx::query(&sql)
.bind(id)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
async fn revoke_refresh_row(pool: &AnyPool, id: i64) -> Result<(), AppError> {
let sql = format!(
"UPDATE oauth_refresh_tokens SET revoked = 1 WHERE id = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
sqlx::query(&sql)
.bind(id)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub async fn revoke_access_token(token: &str) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_tables(pool).await?;
let token_hash = hash_secret(token);
let select_sql = format!(
"SELECT id FROM oauth_access_tokens WHERE token_hash = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
let row: Option<(i64,)> = sqlx::query_as(&select_sql)
.bind(&token_hash)
.fetch_optional(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let Some((access_token_id,)) = row else {
return Ok(());
};
revoke_access_row(pool, access_token_id).await?;
let revoke_refresh_sql = format!(
"UPDATE oauth_refresh_tokens SET revoked = 1 WHERE access_token_id = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
sqlx::query(&revoke_refresh_sql)
.bind(access_token_id)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub async fn revoke_refresh_token(token: &str) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_tables(pool).await?;
let sql = format!(
"UPDATE oauth_refresh_tokens SET revoked = 1 WHERE token_hash = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
sqlx::query(&sql)
.bind(hash_secret(token))
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}