pub mod authorize;
pub mod client;
pub mod extractors;
pub mod token;
pub use authorize::{create_authorization_code, AuthorizeRequest, PkceMethod};
pub use client::{create_client, NewClient};
pub use extractors::{has_scope, require_scope, OAuthAuth, OAuthClientAuth};
pub use token::{
exchange_token, revoke_access_token, revoke_refresh_token, TokenRequest, TokenResponse,
};
use larust_core::AppError;
use larust_orm::Backend;
use sqlx::AnyPool;
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) async fn ensure_tables(pool: &AnyPool) -> Result<(), AppError> {
let statements: &[&str] = match larust_orm::backend() {
Backend::Sqlite => &[
"CREATE TABLE IF NOT EXISTS oauth_clients (\
id INTEGER PRIMARY KEY AUTOINCREMENT, \
client_id TEXT NOT NULL UNIQUE, \
client_secret_hash TEXT, \
name TEXT NOT NULL, \
redirect_uri TEXT NOT NULL, \
is_confidential INTEGER NOT NULL, \
created_at INTEGER NOT NULL\
)",
"CREATE TABLE IF NOT EXISTS oauth_auth_codes (\
id INTEGER PRIMARY KEY AUTOINCREMENT, \
code_hash TEXT NOT NULL UNIQUE, \
client_id TEXT NOT NULL, \
user_id INTEGER NOT NULL, \
redirect_uri TEXT NOT NULL, \
scopes TEXT NOT NULL, \
code_challenge TEXT NOT NULL, \
expires_at INTEGER NOT NULL\
)",
"CREATE TABLE IF NOT EXISTS oauth_access_tokens (\
id INTEGER PRIMARY KEY AUTOINCREMENT, \
token_hash TEXT NOT NULL UNIQUE, \
client_id TEXT NOT NULL, \
user_id INTEGER, \
scopes TEXT NOT NULL, \
revoked INTEGER NOT NULL DEFAULT 0, \
expires_at INTEGER NOT NULL\
)",
"CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (\
id INTEGER PRIMARY KEY AUTOINCREMENT, \
token_hash TEXT NOT NULL UNIQUE, \
access_token_id INTEGER NOT NULL, \
revoked INTEGER NOT NULL DEFAULT 0, \
expires_at INTEGER NOT NULL\
)",
],
Backend::MySql => &[
"CREATE TABLE IF NOT EXISTS oauth_clients (\
id INTEGER PRIMARY KEY AUTO_INCREMENT, \
client_id VARCHAR(255) NOT NULL UNIQUE, \
client_secret_hash VARCHAR(255), \
name VARCHAR(255) NOT NULL, \
redirect_uri VARCHAR(2048) NOT NULL, \
is_confidential INTEGER NOT NULL, \
created_at INTEGER NOT NULL\
)",
"CREATE TABLE IF NOT EXISTS oauth_auth_codes (\
id INTEGER PRIMARY KEY AUTO_INCREMENT, \
code_hash VARCHAR(255) NOT NULL UNIQUE, \
client_id VARCHAR(255) NOT NULL, \
user_id INTEGER NOT NULL, \
redirect_uri VARCHAR(2048) NOT NULL, \
scopes VARCHAR(2000) NOT NULL, \
code_challenge VARCHAR(255) NOT NULL, \
expires_at INTEGER NOT NULL\
)",
"CREATE TABLE IF NOT EXISTS oauth_access_tokens (\
id INTEGER PRIMARY KEY AUTO_INCREMENT, \
token_hash VARCHAR(255) NOT NULL UNIQUE, \
client_id VARCHAR(255) NOT NULL, \
user_id INTEGER, \
scopes VARCHAR(2000) NOT NULL, \
revoked INTEGER NOT NULL DEFAULT 0, \
expires_at INTEGER NOT NULL\
)",
"CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (\
id INTEGER PRIMARY KEY AUTO_INCREMENT, \
token_hash VARCHAR(255) NOT NULL UNIQUE, \
access_token_id INTEGER NOT NULL, \
revoked INTEGER NOT NULL DEFAULT 0, \
expires_at INTEGER NOT NULL\
)",
],
Backend::Postgres => &[
"CREATE TABLE IF NOT EXISTS oauth_clients (\
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
client_id TEXT NOT NULL UNIQUE, \
client_secret_hash TEXT, \
name TEXT NOT NULL, \
redirect_uri TEXT NOT NULL, \
is_confidential INTEGER NOT NULL, \
created_at INTEGER NOT NULL\
)",
"CREATE TABLE IF NOT EXISTS oauth_auth_codes (\
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
code_hash TEXT NOT NULL UNIQUE, \
client_id TEXT NOT NULL, \
user_id INTEGER NOT NULL, \
redirect_uri TEXT NOT NULL, \
scopes TEXT NOT NULL, \
code_challenge TEXT NOT NULL, \
expires_at INTEGER NOT NULL\
)",
"CREATE TABLE IF NOT EXISTS oauth_access_tokens (\
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
token_hash TEXT NOT NULL UNIQUE, \
client_id TEXT NOT NULL, \
user_id INTEGER, \
scopes TEXT NOT NULL, \
revoked INTEGER NOT NULL DEFAULT 0, \
expires_at INTEGER NOT NULL\
)",
"CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (\
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
token_hash TEXT NOT NULL UNIQUE, \
access_token_id INTEGER NOT NULL, \
revoked INTEGER NOT NULL DEFAULT 0, \
expires_at INTEGER NOT NULL\
)",
],
};
for statement in statements {
sqlx::query(statement)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
}
Ok(())
}
pub(crate) fn now_unix_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock is before the Unix epoch")
.as_secs() as i64
}
pub(crate) fn hash_secret(secret: &str) -> String {
use sha2::{Digest, Sha256};
use std::fmt::Write as _;
let digest = Sha256::digest(secret.as_bytes());
let mut hex = String::with_capacity(digest.len() * 2);
for byte in digest {
let _ = write!(hex, "{byte:02x}");
}
hex
}
pub(crate) fn constant_time_eq(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (x, y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
diff == 0
}
pub(crate) fn random_secret() -> String {
use rand::Rng;
use std::fmt::Write as _;
let mut bytes = [0u8; 32];
rand::thread_rng().fill(&mut bytes[..]);
let mut hex = String::with_capacity(bytes.len() * 2);
for byte in bytes {
let _ = write!(hex, "{byte:02x}");
}
hex
}
#[derive(Debug)]
pub enum OAuthError {
InvalidRequest(String),
InvalidClient(String),
InvalidGrant(String),
UnauthorizedClient(String),
UnsupportedGrantType(String),
InvalidScope(String),
Internal(AppError),
}
impl OAuthError {
fn code(&self) -> &'static str {
match self {
OAuthError::InvalidRequest(_) => "invalid_request",
OAuthError::InvalidClient(_) => "invalid_client",
OAuthError::InvalidGrant(_) => "invalid_grant",
OAuthError::UnauthorizedClient(_) => "unauthorized_client",
OAuthError::UnsupportedGrantType(_) => "unsupported_grant_type",
OAuthError::InvalidScope(_) => "invalid_scope",
OAuthError::Internal(_) => "server_error",
}
}
fn description(&self) -> &str {
match self {
OAuthError::InvalidRequest(message)
| OAuthError::InvalidClient(message)
| OAuthError::InvalidGrant(message)
| OAuthError::UnauthorizedClient(message)
| OAuthError::UnsupportedGrantType(message)
| OAuthError::InvalidScope(message) => message,
OAuthError::Internal(_) => "an internal error occurred",
}
}
}
impl From<AppError> for OAuthError {
fn from(error: AppError) -> Self {
OAuthError::Internal(error)
}
}
impl axum::response::IntoResponse for OAuthError {
fn into_response(self) -> axum::response::Response {
if let OAuthError::Internal(error) = self {
return error.into_response();
}
let status = axum::http::StatusCode::BAD_REQUEST;
let body = serde_json::json!({
"error": self.code(),
"error_description": self.description(),
});
(status, axum::Json(body)).into_response()
}
}
#[cfg(test)]
pub(crate) mod test_support {
pub async fn connect_test_db() {
let dir = tempfile::tempdir().unwrap().keep();
let database_url = format!("sqlite://{}/test.sqlite", dir.display());
larust_orm::connect(&database_url).await.unwrap();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::authorize::{create_authorization_code, AuthorizeRequest, PkceMethod};
use crate::client::{create_client, find_client};
use crate::extractors::test_fixtures::{get_with_auth, router};
use crate::token::{exchange_token, revoke_access_token, TokenRequest};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use sha2::{Digest, Sha256};
#[tokio::test]
async fn passport_crate_behaves_correctly_across_every_scenario() {
test_support::connect_test_db().await;
let confidential = create_client("Server App", "https://app.test/callback", true)
.await
.unwrap();
assert_eq!(confidential.client_id.len(), 64);
let secret = confidential
.client_secret
.clone()
.expect("confidential client must get a secret");
assert_eq!(secret.len(), 64);
let public = create_client("Mobile App", "myapp://callback", false)
.await
.unwrap();
assert!(public.client_secret.is_none());
assert_ne!(confidential.client_id, public.client_id);
let pool = larust_orm::pool().unwrap();
let found = find_client(pool, &confidential.client_id)
.await
.unwrap()
.expect("just-created confidential client should be found");
assert_eq!(found.redirect_uri, "https://app.test/callback");
assert!(found.is_confidential);
assert!(found.client_secret_hash.is_some());
let found_public = find_client(pool, &public.client_id)
.await
.unwrap()
.expect("just-created public client should be found");
assert!(!found_public.is_confidential);
assert!(found_public.client_secret_hash.is_none());
assert!(find_client(pool, "does-not-exist").await.unwrap().is_none());
let redirect_uri = "https://app.test/callback";
fn authorize_request(client_id: &str, redirect_uri: &str) -> AuthorizeRequest {
AuthorizeRequest {
client_id: client_id.to_string(),
redirect_uri: redirect_uri.to_string(),
user_id: 1,
scopes: vec!["read-posts".to_string()],
code_challenge: "a-real-challenge-value".to_string(),
code_challenge_method: PkceMethod::S256,
}
}
let throwaway_code =
create_authorization_code(authorize_request(&confidential.client_id, redirect_uri))
.await
.unwrap();
assert_eq!(throwaway_code.len(), 64);
let error = create_authorization_code(authorize_request("not-a-real-client", redirect_uri))
.await
.unwrap_err();
assert!(matches!(error, OAuthError::InvalidClient(_)));
let error = create_authorization_code(authorize_request(
&confidential.client_id,
"https://evil.test/callback",
))
.await
.unwrap_err();
assert!(matches!(error, OAuthError::InvalidRequest(_)));
let mut plain_request = authorize_request(&confidential.client_id, redirect_uri);
plain_request.code_challenge_method = PkceMethod::Plain;
let error = create_authorization_code(plain_request).await.unwrap_err();
assert!(matches!(error, OAuthError::InvalidRequest(_)));
let mut empty_challenge = authorize_request(&confidential.client_id, redirect_uri);
empty_challenge.code_challenge = String::new();
let error = create_authorization_code(empty_challenge)
.await
.unwrap_err();
assert!(matches!(error, OAuthError::InvalidRequest(_)));
fn pkce_pair() -> (String, String) {
let verifier = random_secret();
let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
(verifier, challenge)
}
let (verifier, challenge) = pkce_pair();
let code = create_authorization_code(AuthorizeRequest {
client_id: confidential.client_id.clone(),
redirect_uri: redirect_uri.to_string(),
user_id: 42,
scopes: vec!["read-posts".to_string(), "write-posts".to_string()],
code_challenge: challenge,
code_challenge_method: PkceMethod::S256,
})
.await
.unwrap();
let wrong_verifier_result = exchange_token(TokenRequest::AuthorizationCode {
code: code.clone(),
redirect_uri: redirect_uri.to_string(),
client_id: confidential.client_id.clone(),
code_verifier: "not-the-real-verifier".to_string(),
})
.await;
assert!(matches!(
wrong_verifier_result,
Err(OAuthError::InvalidGrant(_))
));
let response = exchange_token(TokenRequest::AuthorizationCode {
code: code.clone(),
redirect_uri: redirect_uri.to_string(),
client_id: confidential.client_id.clone(),
code_verifier: verifier.clone(),
})
.await
.unwrap();
assert_eq!(response.token_type, "Bearer");
assert_eq!(response.scope, "read-posts write-posts");
assert!(response.refresh_token.is_some());
let replay_result = exchange_token(TokenRequest::AuthorizationCode {
code,
redirect_uri: redirect_uri.to_string(),
client_id: confidential.client_id.clone(),
code_verifier: verifier,
})
.await;
assert!(matches!(replay_result, Err(OAuthError::InvalidGrant(_))));
let cc_response = exchange_token(TokenRequest::ClientCredentials {
client_id: confidential.client_id.clone(),
client_secret: secret.clone(),
scope: Some("admin".to_string()),
})
.await
.unwrap();
assert!(cc_response.refresh_token.is_none());
assert_eq!(cc_response.scope, "admin");
let wrong_secret_result = exchange_token(TokenRequest::ClientCredentials {
client_id: confidential.client_id.clone(),
client_secret: "not-the-real-secret".to_string(),
scope: None,
})
.await;
assert!(matches!(
wrong_secret_result,
Err(OAuthError::InvalidClient(_))
));
let public_cc_result = exchange_token(TokenRequest::ClientCredentials {
client_id: public.client_id.clone(),
client_secret: "anything".to_string(),
scope: None,
})
.await;
assert!(matches!(
public_cc_result,
Err(OAuthError::UnauthorizedClient(_))
));
let refreshed = exchange_token(TokenRequest::RefreshToken {
refresh_token: response.refresh_token.clone().unwrap(),
client_id: confidential.client_id.clone(),
})
.await
.unwrap();
assert_ne!(refreshed.access_token, response.access_token);
assert_ne!(refreshed.refresh_token, response.refresh_token);
assert_eq!(refreshed.scope, "read-posts write-posts");
let reuse_old_refresh_result = exchange_token(TokenRequest::RefreshToken {
refresh_token: response.refresh_token.clone().unwrap(),
client_id: confidential.client_id.clone(),
})
.await;
assert!(matches!(
reuse_old_refresh_result,
Err(OAuthError::InvalidGrant(_))
));
revoke_access_token(&refreshed.access_token).await.unwrap();
let revoked_refresh_result = exchange_token(TokenRequest::RefreshToken {
refresh_token: refreshed.refresh_token.clone().unwrap(),
client_id: confidential.client_id.clone(),
})
.await;
assert!(matches!(
revoked_refresh_result,
Err(OAuthError::InvalidGrant(_))
));
let (fresh_verifier, fresh_challenge) = pkce_pair();
let fresh_code = create_authorization_code(AuthorizeRequest {
client_id: confidential.client_id.clone(),
redirect_uri: redirect_uri.to_string(),
user_id: 99,
scopes: vec!["read-posts".to_string()],
code_challenge: fresh_challenge,
code_challenge_method: PkceMethod::S256,
})
.await
.unwrap();
let extractor_tokens = exchange_token(TokenRequest::AuthorizationCode {
code: fresh_code,
redirect_uri: redirect_uri.to_string(),
client_id: confidential.client_id.clone(),
code_verifier: fresh_verifier,
})
.await
.unwrap();
let api_router = router();
let (status, _) = get_with_auth(&api_router, "/me", None).await;
assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
let (status, _) = get_with_auth(&api_router, "/me", Some("not-bearer-shaped")).await;
assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
let (status, _) = get_with_auth(&api_router, "/me", Some("Bearer not-a-real-token")).await;
assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
let (status, body) = get_with_auth(
&api_router,
"/me",
Some(&format!("Bearer {}", extractor_tokens.access_token)),
)
.await;
assert_eq!(status, axum::http::StatusCode::OK);
assert_eq!(body, "99:read-posts");
let (status, _) = get_with_auth(
&api_router,
"/me",
Some(&format!("Bearer {}", cc_response.access_token)),
)
.await;
assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
let (status, body) = get_with_auth(
&api_router,
"/client",
Some(&format!("Bearer {}", cc_response.access_token)),
)
.await;
assert_eq!(status, axum::http::StatusCode::OK);
assert!(body.contains(&confidential.client_id));
assert!(body.contains("\"has_admin\":true"));
revoke_access_token(&extractor_tokens.access_token)
.await
.unwrap();
let (status, _) = get_with_auth(
&api_router,
"/me",
Some(&format!("Bearer {}", extractor_tokens.access_token)),
)
.await;
assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
let (status, _) = get_with_auth(
&api_router,
"/client",
Some(&format!("Bearer {}", cc_response.access_token)),
)
.await;
assert_eq!(status, axum::http::StatusCode::OK);
}
#[test]
fn hash_secret_is_deterministic_and_sensitive_to_input() {
assert_eq!(hash_secret("abc"), hash_secret("abc"));
assert_ne!(hash_secret("abc"), hash_secret("abd"));
}
#[test]
fn random_secret_produces_64_hex_characters_and_is_never_repeated() {
let a = random_secret();
let b = random_secret();
assert_eq!(a.len(), 64);
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
assert_ne!(a, b);
}
#[test]
fn constant_time_eq_matches_identical_strings() {
assert!(constant_time_eq("abc123", "abc123"));
}
#[test]
fn constant_time_eq_rejects_a_single_differing_character() {
assert!(!constant_time_eq("abc123", "abc124"));
}
#[test]
fn constant_time_eq_rejects_differing_lengths() {
assert!(!constant_time_eq("abc", "abcd"));
}
#[test]
fn oauth_error_renders_the_exact_rfc_6749_json_shape() {
let error = OAuthError::InvalidGrant("the authorization code is invalid".to_string());
assert_eq!(error.code(), "invalid_grant");
assert_eq!(error.description(), "the authorization code is invalid");
}
}