use crate::client::find_client;
use crate::{ensure_tables, hash_secret, now_unix_secs, random_secret, OAuthError};
use sqlx::AnyPool;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PkceMethod {
S256,
Plain,
}
impl PkceMethod {
pub fn parse(raw: &str) -> Option<Self> {
match raw {
"S256" => Some(PkceMethod::S256),
"plain" => Some(PkceMethod::Plain),
_ => None,
}
}
}
pub struct AuthorizeRequest {
pub client_id: String,
pub redirect_uri: String,
pub user_id: i64,
pub scopes: Vec<String>,
pub code_challenge: String,
pub code_challenge_method: PkceMethod,
}
const AUTH_CODE_TTL_SECS: i64 = 600;
pub async fn create_authorization_code(request: AuthorizeRequest) -> Result<String, OAuthError> {
if request.code_challenge_method != PkceMethod::S256 {
return Err(OAuthError::InvalidRequest(
"code_challenge_method must be S256 - \"plain\" is never accepted".to_string(),
));
}
if request.code_challenge.is_empty() {
return Err(OAuthError::InvalidRequest(
"code_challenge is required".to_string(),
));
}
let pool = larust_orm::pool()?;
ensure_tables(pool).await?;
let client = find_client(pool, &request.client_id)
.await?
.ok_or_else(|| OAuthError::InvalidClient("unknown client_id".to_string()))?;
if client.redirect_uri != request.redirect_uri {
return Err(OAuthError::InvalidRequest(
"redirect_uri does not match the client's registered redirect URI".to_string(),
));
}
let code = random_secret();
insert_code(pool, &code, &request).await?;
Ok(code)
}
async fn insert_code(
pool: &AnyPool,
code: &str,
request: &AuthorizeRequest,
) -> Result<(), OAuthError> {
let backend = larust_orm::backend();
let insert_sql = format!(
"INSERT INTO oauth_auth_codes (code_hash, client_id, user_id, redirect_uri, scopes, \
code_challenge, expires_at) VALUES ({}, {}, {}, {}, {}, {}, {})",
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),
larust_orm::placeholder(backend, 6),
larust_orm::placeholder(backend, 7),
);
sqlx::query(&insert_sql)
.bind(hash_secret(code))
.bind(&request.client_id)
.bind(request.user_id)
.bind(&request.redirect_uri)
.bind(request.scopes.join(" "))
.bind(&request.code_challenge)
.bind(now_unix_secs() + AUTH_CODE_TTL_SECS)
.execute(pool)
.await
.map_err(|source| larust_core::AppError::Internal(Box::new(source)))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pkce_method_parse_recognizes_both_rfc_values_and_rejects_anything_else() {
assert_eq!(PkceMethod::parse("S256"), Some(PkceMethod::S256));
assert_eq!(PkceMethod::parse("plain"), Some(PkceMethod::Plain));
assert_eq!(PkceMethod::parse("whatever"), None);
assert_eq!(PkceMethod::parse(""), None);
}
}