- horoscope-api: Swiss Ephemeris natal charts, timezone/place resolution, POST /v1/natal and POST /v1/synastry - backend: users with roles, email/password and Google login, saved charts, synastries and invites, analyses with credit ledger, public shares, admin - shared crates: astro-engine, db (migrations), horoscope-client, service-kit - docker-compose with postgres, legacy Java project for reference Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
255 lines
8.9 KiB
Rust
255 lines
8.9 KiB
Rust
//! Sessions, passwords and the request guards.
|
|
//!
|
|
//! A session is an opaque random token. The client receives it as an
|
|
//! HttpOnly cookie (`sf_session`) and in the login response body (for
|
|
//! non-browser clients, sent back as `Authorization: Bearer <token>`); the
|
|
//! database keeps only its SHA-256 hash, so sessions can be revoked.
|
|
|
|
use std::collections::HashMap;
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::{Duration, Instant};
|
|
|
|
use argon2::Argon2;
|
|
use argon2::password_hash::rand_core::OsRng;
|
|
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
|
|
use axum::extract::FromRequestParts;
|
|
use axum::http::header::{AUTHORIZATION, USER_AGENT};
|
|
use axum::http::request::Parts;
|
|
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
|
|
use db::{Role, User};
|
|
use serde::Serialize;
|
|
use sqlx::PgPool;
|
|
use time::OffsetDateTime;
|
|
use uuid::Uuid;
|
|
|
|
use crate::AppState;
|
|
use crate::config::Config;
|
|
use crate::error::ApiError;
|
|
|
|
pub const SESSION_COOKIE: &str = "sf_session";
|
|
pub const MIN_PASSWORD_LEN: usize = 10;
|
|
pub const MAX_PASSWORD_LEN: usize = 256;
|
|
|
|
// --- guards ------------------------------------------------------------------------
|
|
|
|
/// Guard: a logged-in user (401 otherwise).
|
|
#[derive(Debug, Clone)]
|
|
pub struct AuthUser {
|
|
pub user: User,
|
|
pub session_id: Uuid,
|
|
}
|
|
|
|
impl AuthUser {
|
|
pub fn id(&self) -> Uuid {
|
|
self.user.id
|
|
}
|
|
|
|
pub fn require(&self, role: Role) -> Result<(), ApiError> {
|
|
if self.user.has_role(role) {
|
|
Ok(())
|
|
} else {
|
|
Err(ApiError::Forbidden(format!("the '{}' role is required", role.as_str())))
|
|
}
|
|
}
|
|
}
|
|
|
|
fn session_token(parts: &Parts) -> Option<String> {
|
|
if let Some(value) = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok())
|
|
&& let Some(token) = value.strip_prefix("Bearer ")
|
|
{
|
|
return Some(token.trim().to_string());
|
|
}
|
|
CookieJar::from_headers(&parts.headers).get(SESSION_COOKIE).map(|c| c.value().to_string())
|
|
}
|
|
|
|
impl FromRequestParts<Arc<AppState>> for AuthUser {
|
|
type Rejection = ApiError;
|
|
|
|
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
|
let token = session_token(parts).ok_or(ApiError::Unauthorized)?;
|
|
let (session_id, user) = db::user_by_session(&state.db, &token).await?.ok_or(ApiError::Unauthorized)?;
|
|
Ok(AuthUser { user, session_id })
|
|
}
|
|
}
|
|
|
|
/// Guard: a logged-in user with the admin role (401 / 403 otherwise).
|
|
pub struct AdminUser(pub AuthUser);
|
|
|
|
impl FromRequestParts<Arc<AppState>> for AdminUser {
|
|
type Rejection = ApiError;
|
|
|
|
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
|
let user = AuthUser::from_request_parts(parts, state).await?;
|
|
user.require(Role::Admin)?;
|
|
Ok(AdminUser(user))
|
|
}
|
|
}
|
|
|
|
pub fn user_agent(parts_headers: &axum::http::HeaderMap) -> Option<String> {
|
|
parts_headers.get(USER_AGENT).and_then(|v| v.to_str().ok()).map(|s| s.chars().take(300).collect())
|
|
}
|
|
|
|
// --- sessions ----------------------------------------------------------------------
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct SessionInfo {
|
|
pub token: String,
|
|
#[serde(with = "time::serde::rfc3339")]
|
|
pub expires_at: OffsetDateTime,
|
|
}
|
|
|
|
pub async fn create_session(
|
|
pool: &PgPool,
|
|
config: &Config,
|
|
user_id: Uuid,
|
|
user_agent: Option<String>,
|
|
) -> Result<SessionInfo, ApiError> {
|
|
let token = db::new_token();
|
|
let expires_at = OffsetDateTime::now_utc() + time::Duration::days(config.session_ttl_days);
|
|
sqlx::query("INSERT INTO sessions (id, user_id, token_hash, expires_at, user_agent) VALUES ($1, $2, $3, $4, $5)")
|
|
.bind(Uuid::now_v7())
|
|
.bind(user_id)
|
|
.bind(db::token_hash(&token))
|
|
.bind(expires_at)
|
|
.bind(user_agent)
|
|
.execute(pool)
|
|
.await?;
|
|
sqlx::query("UPDATE users SET last_login_at = now() WHERE id = $1").bind(user_id).execute(pool).await?;
|
|
// Housekeeping: drop this user's expired sessions.
|
|
sqlx::query("DELETE FROM sessions WHERE user_id = $1 AND expires_at <= now()").bind(user_id).execute(pool).await?;
|
|
Ok(SessionInfo { token, expires_at })
|
|
}
|
|
|
|
pub fn session_cookie(config: &Config, session: &SessionInfo) -> Cookie<'static> {
|
|
let mut cookie = Cookie::build((SESSION_COOKIE, session.token.clone()))
|
|
.path("/")
|
|
.http_only(true)
|
|
.secure(config.cookie_secure)
|
|
.same_site(SameSite::Lax)
|
|
.max_age(time::Duration::days(config.session_ttl_days))
|
|
.build();
|
|
if let Some(domain) = &config.cookie_domain {
|
|
cookie.set_domain(domain.clone());
|
|
}
|
|
cookie
|
|
}
|
|
|
|
pub fn removal_cookie(config: &Config) -> Cookie<'static> {
|
|
let mut cookie = Cookie::build((SESSION_COOKIE, "")).path("/").max_age(time::Duration::ZERO).build();
|
|
if let Some(domain) = &config.cookie_domain {
|
|
cookie.set_domain(domain.clone());
|
|
}
|
|
cookie
|
|
}
|
|
|
|
// --- passwords ---------------------------------------------------------------------
|
|
|
|
pub fn validate_password(password: &str) -> Result<(), ApiError> {
|
|
let len = password.chars().count();
|
|
if len < MIN_PASSWORD_LEN {
|
|
return Err(ApiError::BadRequest(format!("the password must be at least {MIN_PASSWORD_LEN} characters long")));
|
|
}
|
|
if len > MAX_PASSWORD_LEN {
|
|
return Err(ApiError::BadRequest(format!("the password must be at most {MAX_PASSWORD_LEN} characters long")));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Argon2id hash (PHC string); CPU-heavy, so it runs on the blocking pool.
|
|
pub async fn hash_password(password: String) -> Result<String, ApiError> {
|
|
tokio::task::spawn_blocking(move || {
|
|
let salt = SaltString::generate(&mut OsRng);
|
|
Argon2::default().hash_password(password.as_bytes(), &salt).map(|h| h.to_string())
|
|
})
|
|
.await
|
|
.map_err(|e| ApiError::Internal(e.to_string()))?
|
|
.map_err(|e| ApiError::Internal(format!("password hashing: {e}")))
|
|
}
|
|
|
|
pub async fn verify_password(password: String, hash: String) -> Result<bool, ApiError> {
|
|
tokio::task::spawn_blocking(move || {
|
|
let parsed = PasswordHash::new(&hash).map_err(|e| e.to_string())?;
|
|
Ok::<bool, String>(Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok())
|
|
})
|
|
.await
|
|
.map_err(|e| ApiError::Internal(e.to_string()))?
|
|
.map_err(|e| ApiError::Internal(format!("stored password hash: {e}")))
|
|
}
|
|
|
|
/// A precomputed hash verified when the e-mail is unknown, so the response
|
|
/// time does not reveal which addresses are registered.
|
|
pub static DUMMY_HASH: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
|
|
let salt = SaltString::generate(&mut OsRng);
|
|
Argon2::default().hash_password(b"dummy password", &salt).expect("hashing works").to_string()
|
|
});
|
|
|
|
// --- brute-force protection ----------------------------------------------------------
|
|
|
|
/// Counts failed logins per e-mail address in a sliding window (in memory,
|
|
/// per backend instance).
|
|
pub struct LoginLimiter {
|
|
max_failures: u32,
|
|
window: Duration,
|
|
failures: Mutex<HashMap<String, (u32, Instant)>>,
|
|
}
|
|
|
|
impl LoginLimiter {
|
|
pub fn new(max_failures: u32, window: Duration) -> Self {
|
|
Self { max_failures, window, failures: Mutex::new(HashMap::new()) }
|
|
}
|
|
|
|
pub fn check(&self, key: &str) -> Result<(), ApiError> {
|
|
let mut map = self.failures.lock().expect("limiter lock");
|
|
match map.get(key) {
|
|
Some(&(count, since)) if since.elapsed() < self.window && count >= self.max_failures => {
|
|
Err(ApiError::TooManyRequests)
|
|
}
|
|
Some(&(_, since)) if since.elapsed() >= self.window => {
|
|
map.remove(key);
|
|
Ok(())
|
|
}
|
|
_ => Ok(()),
|
|
}
|
|
}
|
|
|
|
pub fn failed(&self, key: &str) {
|
|
let mut map = self.failures.lock().expect("limiter lock");
|
|
if map.len() > 100_000 {
|
|
let window = self.window;
|
|
map.retain(|_, (_, since)| since.elapsed() < window);
|
|
}
|
|
let entry = map.entry(key.to_string()).or_insert((0, Instant::now()));
|
|
entry.0 += 1;
|
|
}
|
|
|
|
pub fn succeeded(&self, key: &str) {
|
|
self.failures.lock().expect("limiter lock").remove(key);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[tokio::test]
|
|
async fn password_roundtrip() {
|
|
let hash = hash_password("correct horse battery".into()).await.unwrap();
|
|
assert!(hash.starts_with("$argon2id$"));
|
|
assert!(verify_password("correct horse battery".into(), hash.clone()).await.unwrap());
|
|
assert!(!verify_password("wrong password!!".into(), hash).await.unwrap());
|
|
assert!(validate_password("short").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn limiter_blocks_after_failures() {
|
|
let limiter = LoginLimiter::new(2, Duration::from_secs(60));
|
|
assert!(limiter.check("a").is_ok());
|
|
limiter.failed("a");
|
|
limiter.failed("a");
|
|
assert!(limiter.check("a").is_err());
|
|
assert!(limiter.check("b").is_ok());
|
|
limiter.succeeded("a");
|
|
assert!(limiter.check("a").is_ok());
|
|
}
|
|
}
|