feat: argon2id passwords, session cookies, bot bearer tokens

Adds the full auth flow. Reads stay public; writes (currently only POST
/api/v1/mangas) require a CurrentUser. Both browsers and bot scripts hit
the same endpoints — they just present credentials differently.

Migration 0002_auth.sql introduces users.password_hash, a sessions
table, and an api_tokens table. Sessions and api_tokens store only
sha256(raw_token) — the raw value lives in the cookie or the
Authorization header.

New endpoints under /api/v1/auth/:
- POST /register — argon2id hash, creates a session, sets cookie.
- POST /login — verifies, rotates to a fresh session (old ones expire
  naturally so other devices stay signed in).
- POST /logout — deletes the server-side session row + clears the
  cookie via Max-Age=0.
- GET  /me — current user via the new CurrentUser extractor.
- POST /tokens — issue a bot bearer token; raw value returned exactly
  once at creation.
- DELETE /tokens/{id} — owner-only: 404 if unknown, 403 if it exists
  but belongs to another user, 204 on success.

The CurrentUser axum extractor resolves cookie first, then
Authorization: Bearer; failure → AppError::Unauthenticated (401). New
AppError variants Unauthenticated/Forbidden/Conflict carry the matching
envelope codes; the top-level match in `code()` stays exhaustive.

Backend integration coverage in tests/api_auth.rs: register sets a
HttpOnly SameSite=Lax cookie and never leaks password_hash; duplicate
username → 409; weak password → 400; login rotates the cookie; wrong
password / unknown user → 401; /me with vs without cookie; logout
invalidates the cookie; bot-token roundtrip via Bearer; user A cannot
delete user B's token (403); unknown delete → 404.

Frontend:
- lib/api/auth.ts — typed wrappers; me() returns null on 401.
- lib/session.svelte.ts — per-tab user state with a seq counter to
  guard against an in-flight /me clobbering a fresh setUser.
- lib/api/client.ts — request<T> returns undefined for 204.
- routes/login + routes/register — forms with action="javascript:void(0)"
  so the no-JS path is a no-op (avoids the hydration-race where a
  pre-attach click would submit via the browser default).
- routes/+layout.svelte — session-aware nav: spinner → user + Logout,
  or Login / Register.
- e2e/auth-flow.spec.ts — login flips the layout, logout flips back;
  bad credentials surface the API error message.

Config grows AuthConfig (cookie_secure, cookie_domain, session_ttl_days)
and CORS_ALLOWED_ORIGINS. CORS middleware is mounted in app::build and
stays a no-op (same-origin) until origins are listed.

Lockstep version bump to 0.3.0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-05-16 22:04:25 +02:00
parent ce9a01793f
commit 383cfbed3b
36 changed files with 1901 additions and 13 deletions

View File

@@ -0,0 +1,63 @@
//! `CurrentUser` axum extractor.
//!
//! Resolves a request to a logged-in user by trying, in order:
//! 1. a `mangalord_session` cookie (session lookup by `sha256(value)`);
//! 2. an `Authorization: Bearer <token>` header (api_token lookup).
//!
//! Both paths look up by hash, never by raw value. Failure to resolve
//! either way returns 401 via `AppError::Unauthenticated`.
use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum_extra::extract::cookie::CookieJar;
use axum_extra::headers::authorization::Bearer;
use axum_extra::headers::Authorization;
use axum_extra::TypedHeader;
use crate::app::AppState;
use crate::auth::token::hash_token;
use crate::domain::User;
use crate::error::AppError;
use crate::repo;
pub const SESSION_COOKIE_NAME: &str = "mangalord_session";
pub struct CurrentUser(pub User);
#[async_trait]
impl FromRequestParts<AppState> for CurrentUser {
type Rejection = AppError;
async fn from_request_parts(
parts: &mut Parts,
state: &AppState,
) -> Result<Self, Self::Rejection> {
let jar = CookieJar::from_headers(&parts.headers);
if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) {
let hash = hash_token(cookie.value());
if let Some(session) = repo::session::find_active(&state.db, &hash).await? {
if let Some(user) = repo::user::find_by_id(&state.db, session.user_id).await? {
return Ok(CurrentUser(user));
}
}
}
if let Ok(TypedHeader(Authorization(bearer))) =
TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, state).await
{
let hash = hash_token(bearer.token());
if let Some(token) = repo::api_token::find_active(&state.db, &hash).await? {
if let Some(user) = repo::user::find_by_id(&state.db, token.user_id).await? {
// Fire-and-forget would be ideal but the test harness needs
// a deterministic write so the touched timestamp shows up
// when the test inspects state. Synchronous is fine.
let _ = repo::api_token::touch_last_used(&state.db, token.id).await;
return Ok(CurrentUser(user));
}
}
}
Err(AppError::Unauthenticated)
}
}

10
backend/src/auth/mod.rs Normal file
View File

@@ -0,0 +1,10 @@
//! Authentication primitives.
//!
//! Password hashing (argon2id), opaque-token generation for sessions and
//! bot API tokens, and the `CurrentUser` axum extractor that resolves a
//! request to a logged-in user via either a session cookie or a bearer
//! token.
pub mod extractor;
pub mod password;
pub mod token;

View File

@@ -0,0 +1,59 @@
//! Argon2id password hashing.
//!
//! `hash_password` returns a PHC-encoded string suitable for storage in
//! `users.password_hash`. `verify_password` checks a candidate against a
//! stored hash. Default Argon2 params are argon2id with the crate's
//! recommended cost (m=19456 KiB, t=2, p=1) — OWASP-aligned.
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use argon2::Argon2;
use crate::error::{AppError, AppResult};
pub fn hash_password(plain: &str) -> AppResult<String> {
let salt = SaltString::generate(&mut OsRng);
Argon2::default()
.hash_password(plain.as_bytes(), &salt)
.map(|h| h.to_string())
.map_err(|e| AppError::Other(anyhow::anyhow!("password hash failed: {e}")))
}
pub fn verify_password(plain: &str, phc: &str) -> bool {
let Ok(hash) = PasswordHash::new(phc) else {
return false;
};
Argon2::default()
.verify_password(plain.as_bytes(), &hash)
.is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hash_then_verify_roundtrip() {
let phc = hash_password("correct horse battery staple").unwrap();
assert!(phc.starts_with("$argon2id$"));
assert!(verify_password("correct horse battery staple", &phc));
}
#[test]
fn verify_rejects_wrong_password() {
let phc = hash_password("hunter2").unwrap();
assert!(!verify_password("hunter3", &phc));
}
#[test]
fn verify_rejects_malformed_hash() {
assert!(!verify_password("anything", "not a real phc string"));
}
#[test]
fn hashes_are_salted() {
let a = hash_password("same").unwrap();
let b = hash_password("same").unwrap();
assert_ne!(a, b, "two hashes of the same password must differ (salt)");
}
}

68
backend/src/auth/token.rs Normal file
View File

@@ -0,0 +1,68 @@
//! High-entropy opaque tokens for sessions and bot API access.
//!
//! `generate_token` draws 32 bytes from the OS CSPRNG, encodes them as
//! URL-safe base64 (no padding), and returns the raw string alongside its
//! SHA-256 hash. Storage holds only the hash; the raw value lives in the
//! cookie or `Authorization` header. Comparison goes through
//! `constant_time_eq` to keep timing side channels off the table.
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use rand::rngs::OsRng;
use rand::RngCore;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
pub const TOKEN_BYTES: usize = 32;
pub const HASH_BYTES: usize = 32;
pub fn generate_token() -> (String, [u8; HASH_BYTES]) {
let mut raw = [0u8; TOKEN_BYTES];
OsRng.fill_bytes(&mut raw);
let encoded = URL_SAFE_NO_PAD.encode(raw);
let hash = hash_token(&encoded);
(encoded, hash)
}
pub fn hash_token(raw: &str) -> [u8; HASH_BYTES] {
let mut hasher = Sha256::new();
hasher.update(raw.as_bytes());
hasher.finalize().into()
}
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.ct_eq(b).into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generates_unique_tokens() {
let (a, _) = generate_token();
let (b, _) = generate_token();
assert_ne!(a, b);
// 32 bytes base64url-no-pad → 43 chars.
assert_eq!(a.len(), 43);
}
#[test]
fn hash_matches_generated_pair() {
let (raw, hash) = generate_token();
assert_eq!(hash_token(&raw), hash);
}
#[test]
fn hash_is_deterministic() {
assert_eq!(hash_token("abc"), hash_token("abc"));
assert_ne!(hash_token("abc"), hash_token("abd"));
}
#[test]
fn constant_time_eq_compares_correctly() {
assert!(constant_time_eq(b"abc", b"abc"));
assert!(!constant_time_eq(b"abc", b"abd"));
assert!(!constant_time_eq(b"abc", b"abcd"));
}
}