pub use crate::session::session_layer;
use argon2::Argon2;
use argon2::password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash};
use axum::Json;
use axum::extract::FromRequestParts;
use axum::http::{HeaderMap, StatusCode, header, request::Parts};
use axum::response::{IntoResponse, Redirect, Response};
use tower_sessions::Session;
const USER_KEY: &str = "user_id";
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
#[error("password hashing failed: {0}")]
Hash(String),
#[error("session error: {0}")]
Session(#[from] tower_sessions::session::Error),
}
impl IntoResponse for AuthError {
fn into_response(self) -> Response {
tracing::error!("{self}");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
}
}
pub fn hash_password(plain: &str) -> Result<String, AuthError> {
Argon2::default()
.hash_password(plain.as_bytes())
.map(|h| h.to_string())
.map_err(|e| AuthError::Hash(e.to_string()))
}
pub fn verify_password(plain: &str, hash: &str) -> bool {
PasswordHash::new(hash).is_ok_and(|h| {
Argon2::default()
.verify_password(plain.as_bytes(), &h)
.is_ok()
})
}
fn hash_permits() -> &'static tokio::sync::Semaphore {
static S: std::sync::OnceLock<tokio::sync::Semaphore> = std::sync::OnceLock::new();
S.get_or_init(|| {
let n = std::thread::available_parallelism().map_or(2, |n| n.get());
tokio::sync::Semaphore::new(n.max(2))
})
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Option<T> {
let _permit = hash_permits().acquire().await.ok()?;
tokio::task::spawn_blocking(f).await.ok()
}
pub async fn hash_password_async(plain: String) -> Result<String, AuthError> {
blocking(move || hash_password(&plain))
.await
.unwrap_or_else(|| Err(AuthError::Hash("hashing task failed".into())))
}
pub async fn verify_password_async(plain: String, hash: String) -> bool {
blocking(move || verify_password(&plain, &hash))
.await
.unwrap_or(false)
}
pub async fn login(session: &Session, user_id: i64) -> Result<(), AuthError> {
session.cycle_id().await?;
#[cfg(feature = "csrf")]
session.remove::<String>("csrf_token").await?;
session.insert(USER_KEY, user_id).await?;
Ok(())
}
pub async fn logout(session: &Session) {
if let Err(e) = session.flush().await {
tracing::error!("logout failed: {e}");
}
}
pub struct Auth(pub i64);
pub struct OptionalAuth(pub Option<i64>);
#[allow(clippy::result_large_err)]
async fn user_id<S: Send + Sync>(parts: &mut Parts, state: &S) -> Result<Option<i64>, Response> {
let session = Session::from_request_parts(parts, state)
.await
.map_err(|(c, m)| (c, m).into_response())?;
session
.get::<i64>(USER_KEY)
.await
.map_err(|e| AuthError::from(e).into_response())
}
fn wants_json(h: &HeaderMap) -> bool {
!h.contains_key("x-inertia")
&& h.get(header::ACCEPT)
.and_then(|v| v.to_str().ok())
.is_some_and(|a| a.contains("json"))
}
impl<S: Send + Sync> FromRequestParts<S> for Auth {
type Rejection = Response;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Response> {
match user_id(parts, state).await? {
Some(id) => Ok(Auth(id)),
None if wants_json(&parts.headers) => Err((
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({"message": "Unauthenticated."})),
)
.into_response()),
None => Err(Redirect::to("/login").into_response()),
}
}
}
impl<S: Send + Sync> FromRequestParts<S> for OptionalAuth {
type Rejection = Response;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Response> {
Ok(OptionalAuth(user_id(parts, state).await?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{Router, body::Body, http::Request, routing::get};
use tower::ServiceExt;
#[test]
fn hash_round_trip() {
let h = hash_password("pw").unwrap();
assert!(verify_password("pw", &h));
assert!(!verify_password("nope", &h));
assert!(!verify_password("pw", "garbage"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn async_hashing_does_not_starve_the_runtime() {
let h = hash_password_async("pw".into()).await.unwrap();
assert!(h.starts_with("$argon2"));
let jobs: Vec<_> = (0..64)
.map(|i| {
let h = h.clone();
tokio::spawn(async move {
let pw = if i % 2 == 0 { "pw" } else { "bad" };
(i, verify_password_async(pw.into(), h).await)
})
})
.collect();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
let ping = tokio::time::timeout(
std::time::Duration::from_millis(500),
tokio::spawn(async { 1 }),
)
.await;
assert_eq!(ping.expect("runtime starved").unwrap(), 1);
for j in jobs {
let (i, ok) = j.await.unwrap();
assert_eq!(ok, i % 2 == 0);
}
assert!(!verify_password_async("pw".into(), "garbage".into()).await);
}
#[cfg(feature = "csrf")]
#[tokio::test]
async fn login_rotates_the_csrf_token() {
use axum::middleware::from_fn_with_state;
let app = Router::new()
.route("/tok", get(|| async { "x" }))
.route(
"/login",
get(|s: Session| async move { login(&s, 7).await.unwrap() }),
)
.layer(from_fn_with_state(
crate::csrf::Csrf::new(&[]),
crate::csrf::middleware,
))
.layer(session_layer());
let call = |path: &'static str, cookie: String| {
let app = app.clone();
async move {
let r = get_with(app, path, &[("cookie", &cookie)]).await;
let (mut sess, mut xsrf) = (None, String::new());
for v in r.headers().get_all(header::SET_COOKIE) {
let c = v.to_str().unwrap().split(';').next().unwrap().to_string();
match c.strip_prefix("XSRF-TOKEN=") {
Some(t) => xsrf = t.to_string(),
None => sess = Some(c),
}
}
(sess, xsrf)
}
};
let (sess, before) = call("/tok", String::new()).await;
let sess = sess.unwrap();
let (sess2, _) = call("/login", sess).await;
let (_, after) = call("/tok", sess2.unwrap()).await;
assert!(!before.is_empty() && !after.is_empty());
assert_ne!(before, after, "csrf token must be re-minted after login");
}
fn app() -> Router {
Router::new()
.route("/me", get(|Auth(id): Auth| async move { id.to_string() }))
.route(
"/opt",
get(|OptionalAuth(id): OptionalAuth| async move { format!("{id:?}") }),
)
.route(
"/login",
get(|s: Session| async move { login(&s, 7).await.unwrap() }),
)
.layer(session_layer())
}
async fn get_with(app: Router, path: &str, headers: &[(&str, &str)]) -> Response {
let mut r = Request::get(path);
for (k, v) in headers {
r = r.header(*k, *v);
}
app.oneshot(r.body(Body::empty()).unwrap()).await.unwrap()
}
async fn body(r: Response) -> Vec<u8> {
axum::body::to_bytes(r.into_body(), 1024)
.await
.unwrap()
.to_vec()
}
#[tokio::test]
async fn rejections() {
let r = get_with(app(), "/me", &[("accept", "text/html")]).await;
assert_eq!(r.status(), StatusCode::SEE_OTHER);
assert_eq!(r.headers()["location"], "/login");
let r = get_with(app(), "/me", &[("accept", "application/json")]).await;
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
let r = get_with(
app(),
"/me",
&[("accept", "application/json"), ("x-inertia", "true")],
)
.await;
assert_eq!(r.status(), StatusCode::SEE_OTHER);
assert_eq!(body(get_with(app(), "/opt", &[]).await).await, b"None");
}
#[tokio::test]
async fn login_then_access() {
let app = app();
let r = get_with(app.clone(), "/login", &[]).await;
let c = r.headers()[header::SET_COOKIE]
.to_str()
.unwrap()
.to_string();
assert!(c.contains("HttpOnly") && c.contains("SameSite=Lax") && !c.contains("Secure"));
let cookie = c.split(';').next().unwrap();
let r = get_with(app, "/me", &[("cookie", cookie)]).await;
assert_eq!(body(r).await, b"7");
}
}