diff --git a/backend/Cargo.lock b/backend/Cargo.lock index cee1996..a09e0a7 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -32,6 +32,18 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -120,6 +132,31 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum-extra" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c794b30c904f0a1c2fb7740f7df7f7972dfaa14ef6f57cb6178dc63e5dca2f04" +dependencies = [ + "axum", + "axum-core", + "bytes", + "cookie", + "fastrand", + "futures-util", + "headers", + "http", + "http-body", + "http-body-util", + "mime", + "multer", + "pin-project-lite", + "serde", + "tower", + "tower-layer", + "tower-service", +] + [[package]] name = "axum-macros" version = "0.4.2" @@ -152,6 +189,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -224,6 +270,17 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -290,6 +347,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + [[package]] name = "digest" version = "0.10.7" @@ -328,6 +394,15 @@ dependencies = [ "serde", ] +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -535,6 +610,30 @@ dependencies = [ "hashbrown 0.15.5", ] +[[package]] +name = "headers" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" +dependencies = [ + "base64", + "bytes", + "headers-core", + "http", + "httpdate", + "mime", + "sha1", +] + +[[package]] +name = "headers-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" +dependencies = [ + "http", +] + [[package]] name = "heck" version = "0.5.0" @@ -895,20 +994,27 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] name = "mangalord" -version = "0.2.0" +version = "0.3.0" dependencies = [ "anyhow", + "argon2", "async-trait", "axum", + "axum-extra", + "base64", "chrono", "dotenvy", "http-body-util", "mime", + "rand", "serde", "serde_json", + "sha2", "sqlx", + "subtle", "tempfile", "thiserror 1.0.69", + "time", "tokio", "tower", "tower-http", @@ -965,6 +1071,23 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -990,6 +1113,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "num-conv" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" + [[package]] name = "num-integer" version = "0.1.46" @@ -1055,6 +1184,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -1118,6 +1258,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1759,6 +1905,37 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.3" diff --git a/backend/Cargo.toml b/backend/Cargo.toml index a832976..d2d29db 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mangalord" -version = "0.2.0" +version = "0.3.0" edition = "2021" [lib] @@ -26,6 +26,13 @@ thiserror = "1" anyhow = "1" async-trait = "0.1" dotenvy = "0.15" +argon2 = "0.5" +rand = "0.8" +sha2 = "0.10" +subtle = "2" +base64 = "0.22" +axum-extra = { version = "0.9", features = ["cookie", "typed-header"] } +time = "0.3" [dev-dependencies] tempfile = "3" diff --git a/backend/migrations/0002_auth.sql b/backend/migrations/0002_auth.sql new file mode 100644 index 0000000..bc18056 --- /dev/null +++ b/backend/migrations/0002_auth.sql @@ -0,0 +1,30 @@ +-- Auth: passwords on users, server-side sessions, and bot API tokens. +-- +-- Sessions and api_tokens both store sha256(raw_token) as bytea. The raw +-- token is held by the client (cookie for sessions, Authorization bearer +-- header for tokens); the server only ever sees the hash at rest, so a +-- read of the DB does not yield reusable credentials. + +ALTER TABLE users ADD COLUMN password_hash text NOT NULL; + +CREATE TABLE sessions ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash bytea NOT NULL UNIQUE, + created_at timestamptz NOT NULL DEFAULT now(), + expires_at timestamptz NOT NULL +); + +CREATE INDEX sessions_user_idx ON sessions (user_id); +CREATE INDEX sessions_expires_idx ON sessions (expires_at); + +CREATE TABLE api_tokens ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name text NOT NULL, + token_hash bytea NOT NULL UNIQUE, + created_at timestamptz NOT NULL DEFAULT now(), + last_used_at timestamptz +); + +CREATE INDEX api_tokens_user_idx ON api_tokens (user_id, created_at DESC); diff --git a/backend/src/api/auth.rs b/backend/src/api/auth.rs new file mode 100644 index 0000000..7c997b0 --- /dev/null +++ b/backend/src/api/auth.rs @@ -0,0 +1,207 @@ +//! Authentication endpoints — register, login, logout, current-user, and +//! bot API token management. Session cookies are HttpOnly + SameSite=Lax +//! and rotate on login (a fresh session row is created; old sessions +//! expire naturally rather than being explicitly invalidated, so other +//! devices keep their existing logins). + +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use axum::response::IntoResponse; +use axum::routing::{delete, get, post}; +use axum::{Json, Router}; +use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite}; +use chrono::{Duration, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::app::AppState; +use crate::auth::extractor::{CurrentUser, SESSION_COOKIE_NAME}; +use crate::auth::password::{hash_password, verify_password}; +use crate::auth::token::{generate_token, hash_token}; +use crate::config::AuthConfig; +use crate::domain::{ApiToken, User}; +use crate::error::{AppError, AppResult}; +use crate::repo; + +pub fn routes() -> Router { + Router::new() + .route("/auth/register", post(register)) + .route("/auth/login", post(login)) + .route("/auth/logout", post(logout)) + .route("/auth/me", get(me)) + .route("/auth/tokens", post(create_token)) + .route("/auth/tokens/:id", delete(delete_token)) +} + +#[derive(Debug, Deserialize)] +pub struct Credentials { + pub username: String, + pub password: String, +} + +#[derive(Debug, Serialize)] +pub struct AuthResponse { + pub user: User, +} + +#[derive(Debug, Deserialize)] +pub struct CreateTokenInput { + pub name: String, +} + +#[derive(Debug, Serialize)] +pub struct CreatedTokenResponse { + #[serde(flatten)] + pub token: ApiToken, + /// Raw bearer token — returned exactly once at creation. + pub bearer: String, +} + +async fn register( + State(state): State, + jar: CookieJar, + Json(input): Json, +) -> AppResult { + let username = input.username.trim(); + validate_username(username)?; + validate_password(&input.password)?; + + let pwhash = hash_password(&input.password)?; + let user = repo::user::create(&state.db, username, &pwhash).await?; + let jar = start_session(&state, &user, jar).await?; + Ok((StatusCode::CREATED, jar, Json(AuthResponse { user }))) +} + +async fn login( + State(state): State, + jar: CookieJar, + Json(input): Json, +) -> AppResult { + let username = input.username.trim(); + if username.is_empty() || input.password.is_empty() { + return Err(AppError::InvalidInput( + "username and password are required".into(), + )); + } + + let user = repo::user::find_by_username(&state.db, username) + .await? + .ok_or(AppError::Unauthenticated)?; + if !verify_password(&input.password, &user.password_hash) { + return Err(AppError::Unauthenticated); + } + + let jar = start_session(&state, &user, jar).await?; + Ok((StatusCode::OK, jar, Json(AuthResponse { user }))) +} + +async fn logout( + State(state): State, + jar: CookieJar, +) -> AppResult { + if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) { + let hash = hash_token(cookie.value()); + repo::session::delete_by_token_hash(&state.db, &hash).await?; + } + let jar = jar.add(build_expired_cookie(&state.auth)); + Ok((StatusCode::NO_CONTENT, jar)) +} + +async fn me(CurrentUser(user): CurrentUser) -> AppResult> { + Ok(Json(AuthResponse { user })) +} + +async fn create_token( + State(state): State, + CurrentUser(user): CurrentUser, + Json(input): Json, +) -> AppResult { + let name = input.name.trim(); + if name.is_empty() { + return Err(AppError::InvalidInput("token name is required".into())); + } + let (raw, hash) = generate_token(); + let token = repo::api_token::create(&state.db, user.id, name, &hash).await?; + Ok(( + StatusCode::CREATED, + Json(CreatedTokenResponse { token, bearer: raw }), + )) +} + +async fn delete_token( + State(state): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> AppResult { + match repo::api_token::find_owner(&state.db, id).await? { + None => Err(AppError::NotFound), + Some(owner) if owner != user.id => Err(AppError::Forbidden), + Some(_) => { + repo::api_token::delete(&state.db, id).await?; + Ok(StatusCode::NO_CONTENT) + } + } +} + +async fn start_session( + state: &AppState, + user: &User, + jar: CookieJar, +) -> AppResult { + let (raw, hash) = generate_token(); + let expires_at = Utc::now() + Duration::days(state.auth.session_ttl_days); + repo::session::create(&state.db, user.id, &hash, expires_at).await?; + Ok(jar.add(build_session_cookie(raw, &state.auth))) +} + +fn build_session_cookie(raw: String, cfg: &AuthConfig) -> Cookie<'static> { + let mut builder = Cookie::build((SESSION_COOKIE_NAME, raw)) + .http_only(true) + .secure(cfg.cookie_secure) + .same_site(SameSite::Lax) + .path("/") + .max_age(time::Duration::days(cfg.session_ttl_days)); + if let Some(domain) = &cfg.cookie_domain { + builder = builder.domain(domain.clone()); + } + builder.build() +} + +fn build_expired_cookie(cfg: &AuthConfig) -> Cookie<'static> { + let mut builder = Cookie::build((SESSION_COOKIE_NAME, "")) + .http_only(true) + .secure(cfg.cookie_secure) + .same_site(SameSite::Lax) + .path("/") + .max_age(time::Duration::seconds(0)); + if let Some(domain) = &cfg.cookie_domain { + builder = builder.domain(domain.clone()); + } + builder.build() +} + +fn validate_username(u: &str) -> AppResult<()> { + if u.is_empty() { + return Err(AppError::InvalidInput("username is required".into())); + } + if u.len() < 3 || u.len() > 32 { + return Err(AppError::InvalidInput( + "username must be 3-32 characters".into(), + )); + } + if !u.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-') { + return Err(AppError::InvalidInput( + "username may only contain letters, digits, _ and -".into(), + )); + } + Ok(()) +} + +fn validate_password(p: &str) -> AppResult<()> { + if p.len() < 8 { + return Err(AppError::InvalidInput( + "password must be at least 8 characters".into(), + )); + } + Ok(()) +} diff --git a/backend/src/api/mangas.rs b/backend/src/api/mangas.rs index 6061196..90f4e85 100644 --- a/backend/src/api/mangas.rs +++ b/backend/src/api/mangas.rs @@ -6,6 +6,7 @@ use uuid::Uuid; use crate::api::pagination::PagedResponse; use crate::app::AppState; +use crate::auth::extractor::CurrentUser; use crate::domain::manga::{Manga, NewManga}; use crate::error::{AppError, AppResult}; use crate::repo; @@ -54,6 +55,7 @@ async fn get_one( async fn create( State(state): State, + CurrentUser(_user): CurrentUser, Json(input): Json, ) -> AppResult> { if input.title.trim().is_empty() { diff --git a/backend/src/api/mod.rs b/backend/src/api/mod.rs index 078f32b..978a2e2 100644 --- a/backend/src/api/mod.rs +++ b/backend/src/api/mod.rs @@ -1,3 +1,4 @@ +pub mod auth; pub mod files; pub mod health; pub mod mangas; @@ -12,4 +13,5 @@ pub fn routes() -> Router { .merge(health::routes()) .merge(mangas::routes()) .merge(files::routes()) + .merge(auth::routes()) } diff --git a/backend/src/app.rs b/backend/src/app.rs index 844ad92..4345b29 100644 --- a/backend/src/app.rs +++ b/backend/src/app.rs @@ -1,17 +1,20 @@ use std::sync::Arc; +use axum::http::{HeaderName, HeaderValue, Method}; use axum::Router; use sqlx::postgres::PgPoolOptions; use sqlx::PgPool; +use tower_http::cors::{AllowOrigin, CorsLayer}; use tower_http::trace::TraceLayer; -use crate::config::Config; +use crate::config::{AuthConfig, Config}; use crate::storage::{LocalStorage, Storage}; #[derive(Clone)] pub struct AppState { pub db: PgPool, pub storage: Arc, + pub auth: AuthConfig, } pub async fn build(config: Config) -> anyhow::Result { @@ -23,7 +26,8 @@ pub async fn build(config: Config) -> anyhow::Result { let storage: Arc = Arc::new(LocalStorage::new(config.storage_dir.clone())); - Ok(router(AppState { db, storage })) + let state = AppState { db, storage, auth: config.auth.clone() }; + Ok(router(state).layer(cors_layer(&config.cors_allowed_origins))) } /// Build a router from a pre-assembled state. Used by integration tests @@ -34,3 +38,22 @@ pub fn router(state: AppState) -> Router { .with_state(state) .layer(TraceLayer::new_for_http()) } + +fn cors_layer(allowed_origins: &[String]) -> CorsLayer { + if allowed_origins.is_empty() { + // Same-origin only — no CORS headers emitted. + return CorsLayer::new(); + } + let origins: Vec = allowed_origins + .iter() + .filter_map(|o| HeaderValue::from_str(o).ok()) + .collect(); + CorsLayer::new() + .allow_origin(AllowOrigin::list(origins)) + .allow_credentials(true) + .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE]) + .allow_headers([ + HeaderName::from_static("content-type"), + HeaderName::from_static("authorization"), + ]) +} diff --git a/backend/src/auth/extractor.rs b/backend/src/auth/extractor.rs new file mode 100644 index 0000000..40d7bec --- /dev/null +++ b/backend/src/auth/extractor.rs @@ -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 ` 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 for CurrentUser { + type Rejection = AppError; + + async fn from_request_parts( + parts: &mut Parts, + state: &AppState, + ) -> Result { + 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::>::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) + } +} diff --git a/backend/src/auth/mod.rs b/backend/src/auth/mod.rs new file mode 100644 index 0000000..4574379 --- /dev/null +++ b/backend/src/auth/mod.rs @@ -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; diff --git a/backend/src/auth/password.rs b/backend/src/auth/password.rs new file mode 100644 index 0000000..7afd308 --- /dev/null +++ b/backend/src/auth/password.rs @@ -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 { + 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)"); + } +} diff --git a/backend/src/auth/token.rs b/backend/src/auth/token.rs new file mode 100644 index 0000000..81f5f20 --- /dev/null +++ b/backend/src/auth/token.rs @@ -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")); + } +} diff --git a/backend/src/config.rs b/backend/src/config.rs index 179e717..cf35734 100644 --- a/backend/src/config.rs +++ b/backend/src/config.rs @@ -1,10 +1,29 @@ use std::path::PathBuf; +#[derive(Clone, Debug)] +pub struct AuthConfig { + pub cookie_secure: bool, + pub cookie_domain: Option, + pub session_ttl_days: i64, +} + +impl Default for AuthConfig { + fn default() -> Self { + Self { + cookie_secure: true, + cookie_domain: None, + session_ttl_days: 30, + } + } +} + #[derive(Clone, Debug)] pub struct Config { pub database_url: String, pub bind_address: String, pub storage_dir: PathBuf, + pub auth: AuthConfig, + pub cors_allowed_origins: Vec, } impl Config { @@ -17,6 +36,37 @@ impl Config { storage_dir: std::env::var("STORAGE_DIR") .unwrap_or_else(|_| "./data/storage".to_string()) .into(), + auth: AuthConfig { + cookie_secure: env_bool("COOKIE_SECURE", true), + cookie_domain: std::env::var("COOKIE_DOMAIN") + .ok() + .filter(|s| !s.is_empty()), + session_ttl_days: env_i64("SESSION_TTL_DAYS", 30), + }, + cors_allowed_origins: std::env::var("CORS_ALLOWED_ORIGINS") + .ok() + .map(|s| { + s.split(',') + .map(|o| o.trim().to_string()) + .filter(|o| !o.is_empty()) + .collect() + }) + .unwrap_or_default(), }) } } + +fn env_bool(name: &str, default: bool) -> bool { + match std::env::var(name).ok().as_deref() { + Some("1") | Some("true") | Some("TRUE") | Some("yes") => true, + Some("0") | Some("false") | Some("FALSE") | Some("no") => false, + _ => default, + } +} + +fn env_i64(name: &str, default: i64) -> i64 { + std::env::var(name) + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(default) +} diff --git a/backend/src/domain/api_token.rs b/backend/src/domain/api_token.rs new file mode 100644 index 0000000..8972df9 --- /dev/null +++ b/backend/src/domain/api_token.rs @@ -0,0 +1,15 @@ +use chrono::{DateTime, Utc}; +use serde::Serialize; +use sqlx::FromRow; +use uuid::Uuid; + +#[derive(Debug, Clone, Serialize, FromRow)] +pub struct ApiToken { + pub id: Uuid, + pub user_id: Uuid, + pub name: String, + #[serde(skip)] + pub token_hash: Vec, + pub created_at: DateTime, + pub last_used_at: Option>, +} diff --git a/backend/src/domain/mod.rs b/backend/src/domain/mod.rs index 0264a39..02e983d 100644 --- a/backend/src/domain/mod.rs +++ b/backend/src/domain/mod.rs @@ -1,9 +1,13 @@ +pub mod api_token; pub mod bookmark; pub mod chapter; pub mod manga; +pub mod session; pub mod user; +pub use api_token::ApiToken; pub use bookmark::Bookmark; pub use chapter::Chapter; pub use manga::Manga; +pub use session::Session; pub use user::User; diff --git a/backend/src/domain/session.rs b/backend/src/domain/session.rs new file mode 100644 index 0000000..ab9037b --- /dev/null +++ b/backend/src/domain/session.rs @@ -0,0 +1,12 @@ +use chrono::{DateTime, Utc}; +use sqlx::FromRow; +use uuid::Uuid; + +#[derive(Debug, Clone, FromRow)] +pub struct Session { + pub id: Uuid, + pub user_id: Uuid, + pub token_hash: Vec, + pub created_at: DateTime, + pub expires_at: DateTime, +} diff --git a/backend/src/domain/user.rs b/backend/src/domain/user.rs index efb2f10..7a4bf6d 100644 --- a/backend/src/domain/user.rs +++ b/backend/src/domain/user.rs @@ -7,5 +7,7 @@ use uuid::Uuid; pub struct User { pub id: Uuid, pub username: String, + #[serde(skip)] + pub password_hash: String, pub created_at: DateTime, } diff --git a/backend/src/error.rs b/backend/src/error.rs index d372a29..04fd322 100644 --- a/backend/src/error.rs +++ b/backend/src/error.rs @@ -11,6 +11,12 @@ pub enum AppError { NotFound, #[error("invalid input: {0}")] InvalidInput(String), + #[error("unauthenticated")] + Unauthenticated, + #[error("forbidden")] + Forbidden, + #[error("conflict: {0}")] + Conflict(String), #[error(transparent)] Database(#[from] sqlx::Error), #[error(transparent)] @@ -29,6 +35,9 @@ impl AppError { match self { AppError::NotFound => "not_found", AppError::InvalidInput(_) => "invalid_input", + AppError::Unauthenticated => "unauthenticated", + AppError::Forbidden => "forbidden", + AppError::Conflict(_) => "conflict", AppError::Database(sqlx::Error::RowNotFound) => "not_found", AppError::Database(_) => "internal_error", AppError::Storage(StorageError::NotFound) => "not_found", @@ -45,6 +54,9 @@ impl IntoResponse for AppError { let (status, message) = match &self { AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), AppError::InvalidInput(msg) => (StatusCode::BAD_REQUEST, msg.clone()), + AppError::Unauthenticated => (StatusCode::UNAUTHORIZED, "unauthenticated".to_string()), + AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()), + AppError::Conflict(msg) => (StatusCode::CONFLICT, msg.clone()), AppError::Database(sqlx::Error::RowNotFound) => { (StatusCode::NOT_FOUND, "not found".to_string()) } @@ -72,6 +84,9 @@ mod tests { fn codes_are_stable() { assert_eq!(AppError::NotFound.code(), "not_found"); assert_eq!(AppError::InvalidInput("x".into()).code(), "invalid_input"); + assert_eq!(AppError::Unauthenticated.code(), "unauthenticated"); + assert_eq!(AppError::Forbidden.code(), "forbidden"); + assert_eq!(AppError::Conflict("x".into()).code(), "conflict"); assert_eq!(AppError::Storage(StorageError::BadKey).code(), "bad_file_key"); assert_eq!(AppError::Storage(StorageError::NotFound).code(), "not_found"); assert_eq!(AppError::Database(sqlx::Error::RowNotFound).code(), "not_found"); diff --git a/backend/src/lib.rs b/backend/src/lib.rs index 89dec77..dfe8a7a 100644 --- a/backend/src/lib.rs +++ b/backend/src/lib.rs @@ -1,5 +1,6 @@ pub mod api; pub mod app; +pub mod auth; pub mod config; pub mod domain; pub mod error; diff --git a/backend/src/repo/api_token.rs b/backend/src/repo/api_token.rs new file mode 100644 index 0000000..87f9121 --- /dev/null +++ b/backend/src/repo/api_token.rs @@ -0,0 +1,69 @@ +//! Bot API token persistence. `token_hash` is sha256 of the raw bearer +//! token; the raw value is shown to the user once at creation and never +//! stored. + +use sqlx::PgPool; +use uuid::Uuid; + +use crate::domain::ApiToken; +use crate::error::AppResult; + +pub async fn create( + pool: &PgPool, + user_id: Uuid, + name: &str, + token_hash: &[u8], +) -> AppResult { + let row = sqlx::query_as::<_, ApiToken>( + r#" + INSERT INTO api_tokens (user_id, name, token_hash) + VALUES ($1, $2, $3) + RETURNING id, user_id, name, token_hash, created_at, last_used_at + "#, + ) + .bind(user_id) + .bind(name) + .bind(token_hash) + .fetch_one(pool) + .await?; + Ok(row) +} + +pub async fn find_active(pool: &PgPool, token_hash: &[u8]) -> AppResult> { + let row = sqlx::query_as::<_, ApiToken>( + r#" + SELECT id, user_id, name, token_hash, created_at, last_used_at + FROM api_tokens + WHERE token_hash = $1 + "#, + ) + .bind(token_hash) + .fetch_optional(pool) + .await?; + Ok(row) +} + +pub async fn touch_last_used(pool: &PgPool, id: Uuid) -> AppResult<()> { + sqlx::query("UPDATE api_tokens SET last_used_at = now() WHERE id = $1") + .bind(id) + .execute(pool) + .await?; + Ok(()) +} + +pub async fn find_owner(pool: &PgPool, id: Uuid) -> AppResult> { + let row: Option<(Uuid,)> = + sqlx::query_as("SELECT user_id FROM api_tokens WHERE id = $1") + .bind(id) + .fetch_optional(pool) + .await?; + Ok(row.map(|(uid,)| uid)) +} + +pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> { + sqlx::query("DELETE FROM api_tokens WHERE id = $1") + .bind(id) + .execute(pool) + .await?; + Ok(()) +} diff --git a/backend/src/repo/mod.rs b/backend/src/repo/mod.rs index 5e18302..ee1d37f 100644 --- a/backend/src/repo/mod.rs +++ b/backend/src/repo/mod.rs @@ -1 +1,4 @@ +pub mod api_token; pub mod manga; +pub mod session; +pub mod user; diff --git a/backend/src/repo/session.rs b/backend/src/repo/session.rs new file mode 100644 index 0000000..0ff9ef1 --- /dev/null +++ b/backend/src/repo/session.rs @@ -0,0 +1,53 @@ +//! Session persistence. `token_hash` is sha256 of the raw cookie value; +//! the raw value never hits the DB. + +use chrono::{DateTime, Utc}; +use sqlx::PgPool; +use uuid::Uuid; + +use crate::domain::Session; +use crate::error::AppResult; + +pub async fn create( + pool: &PgPool, + user_id: Uuid, + token_hash: &[u8], + expires_at: DateTime, +) -> AppResult { + let row = sqlx::query_as::<_, Session>( + r#" + INSERT INTO sessions (user_id, token_hash, expires_at) + VALUES ($1, $2, $3) + RETURNING id, user_id, token_hash, created_at, expires_at + "#, + ) + .bind(user_id) + .bind(token_hash) + .bind(expires_at) + .fetch_one(pool) + .await?; + Ok(row) +} + +/// Returns the session iff `token_hash` matches and it hasn't expired. +pub async fn find_active(pool: &PgPool, token_hash: &[u8]) -> AppResult> { + let row = sqlx::query_as::<_, Session>( + r#" + SELECT id, user_id, token_hash, created_at, expires_at + FROM sessions + WHERE token_hash = $1 AND expires_at > now() + "#, + ) + .bind(token_hash) + .fetch_optional(pool) + .await?; + Ok(row) +} + +pub async fn delete_by_token_hash(pool: &PgPool, token_hash: &[u8]) -> AppResult<()> { + sqlx::query("DELETE FROM sessions WHERE token_hash = $1") + .bind(token_hash) + .execute(pool) + .await?; + Ok(()) +} diff --git a/backend/src/repo/user.rs b/backend/src/repo/user.rs new file mode 100644 index 0000000..79e1bd0 --- /dev/null +++ b/backend/src/repo/user.rs @@ -0,0 +1,57 @@ +//! User persistence. + +use sqlx::PgPool; +use uuid::Uuid; + +use crate::domain::User; +use crate::error::{AppError, AppResult}; + +pub async fn create(pool: &PgPool, username: &str, password_hash: &str) -> AppResult { + let result = sqlx::query_as::<_, User>( + r#" + INSERT INTO users (username, password_hash) + VALUES ($1, $2) + RETURNING id, username, password_hash, created_at + "#, + ) + .bind(username) + .bind(password_hash) + .fetch_one(pool) + .await; + + match result { + Ok(user) => Ok(user), + Err(e) if is_unique_violation(&e) => { + Err(AppError::Conflict("username is already taken".into())) + } + Err(e) => Err(AppError::Database(e)), + } +} + +pub async fn find_by_username(pool: &PgPool, username: &str) -> AppResult> { + let row = sqlx::query_as::<_, User>( + r#"SELECT id, username, password_hash, created_at FROM users WHERE username = $1"#, + ) + .bind(username) + .fetch_optional(pool) + .await?; + Ok(row) +} + +pub async fn find_by_id(pool: &PgPool, id: Uuid) -> AppResult> { + let row = sqlx::query_as::<_, User>( + r#"SELECT id, username, password_hash, created_at FROM users WHERE id = $1"#, + ) + .bind(id) + .fetch_optional(pool) + .await?; + Ok(row) +} + +fn is_unique_violation(err: &sqlx::Error) -> bool { + if let sqlx::Error::Database(db_err) = err { + db_err.code().as_deref() == Some("23505") + } else { + false + } +} diff --git a/backend/tests/api_auth.rs b/backend/tests/api_auth.rs new file mode 100644 index 0000000..1a876e5 --- /dev/null +++ b/backend/tests/api_auth.rs @@ -0,0 +1,281 @@ +mod common; + +use axum::http::{header, StatusCode}; +use serde_json::json; +use sqlx::PgPool; +use tower::ServiceExt; + +fn creds(username: &str) -> serde_json::Value { + json!({ "username": username, "password": "hunter2hunter2" }) +} + +#[sqlx::test(migrations = "./migrations")] +async fn register_creates_user_and_sets_session_cookie(pool: PgPool) { + let h = common::harness(pool); + let resp = h + .app + .oneshot(common::post_json( + "/api/v1/auth/register", + creds("alice"), + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::CREATED); + + let cookie_header = resp + .headers() + .get(header::SET_COOKIE) + .expect("Set-Cookie present") + .to_str() + .unwrap() + .to_string(); + assert!(cookie_header.starts_with("mangalord_session=")); + assert!(cookie_header.contains("HttpOnly")); + assert!(cookie_header.contains("SameSite=Lax")); + assert!(cookie_header.contains("Path=/")); + // In the test harness cookie_secure is false; production has Secure. + assert!(!cookie_header.contains("Secure")); + + let body = common::body_json(resp).await; + assert_eq!(body["user"]["username"], "alice"); + assert!(body["user"]["id"].as_str().is_some()); + assert!( + body["user"].get("password_hash").is_none(), + "password_hash must never leak to the API" + ); +} + +#[sqlx::test(migrations = "./migrations")] +async fn register_rejects_duplicate_username_with_conflict(pool: PgPool) { + let h = common::harness(pool); + let _ = h + .app + .clone() + .oneshot(common::post_json("/api/v1/auth/register", creds("alice"))) + .await + .unwrap(); + let resp = h + .app + .oneshot(common::post_json("/api/v1/auth/register", creds("alice"))) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::CONFLICT); + let body = common::body_json(resp).await; + assert_eq!(body["error"]["code"], "conflict"); +} + +#[sqlx::test(migrations = "./migrations")] +async fn register_rejects_short_password(pool: PgPool) { + let h = common::harness(pool); + let resp = h + .app + .oneshot(common::post_json( + "/api/v1/auth/register", + json!({ "username": "alice", "password": "short" }), + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::BAD_REQUEST); + let body = common::body_json(resp).await; + assert_eq!(body["error"]["code"], "invalid_input"); +} + +#[sqlx::test(migrations = "./migrations")] +async fn login_succeeds_and_rotates_session(pool: PgPool) { + let h = common::harness(pool); + let _ = h + .app + .clone() + .oneshot(common::post_json("/api/v1/auth/register", creds("alice"))) + .await + .unwrap(); + + let resp = h + .app + .oneshot(common::post_json("/api/v1/auth/login", creds("alice"))) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let cookie = common::extract_session_cookie(&resp).expect("login sets a cookie"); + assert!(cookie.starts_with("mangalord_session=")); +} + +#[sqlx::test(migrations = "./migrations")] +async fn login_rejects_wrong_password(pool: PgPool) { + let h = common::harness(pool); + let _ = h + .app + .clone() + .oneshot(common::post_json("/api/v1/auth/register", creds("alice"))) + .await + .unwrap(); + + let resp = h + .app + .oneshot(common::post_json( + "/api/v1/auth/login", + json!({ "username": "alice", "password": "wrongpassword" }), + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); + let body = common::body_json(resp).await; + assert_eq!(body["error"]["code"], "unauthenticated"); +} + +#[sqlx::test(migrations = "./migrations")] +async fn login_rejects_unknown_user(pool: PgPool) { + let h = common::harness(pool); + let resp = h + .app + .oneshot(common::post_json("/api/v1/auth/login", creds("ghost"))) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); +} + +#[sqlx::test(migrations = "./migrations")] +async fn me_returns_user_with_valid_cookie(pool: PgPool) { + let h = common::harness(pool); + let (username, cookie) = common::register_user(&h.app).await; + + let resp = h + .app + .oneshot(common::get_with_cookie("/api/v1/auth/me", &cookie)) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let body = common::body_json(resp).await; + assert_eq!(body["user"]["username"], username); +} + +#[sqlx::test(migrations = "./migrations")] +async fn me_returns_401_without_cookie(pool: PgPool) { + let h = common::harness(pool); + let resp = h + .app + .oneshot(common::get("/api/v1/auth/me")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); +} + +#[sqlx::test(migrations = "./migrations")] +async fn logout_clears_session(pool: PgPool) { + let h = common::harness(pool); + let (_, cookie) = common::register_user(&h.app).await; + + let resp = h + .app + .clone() + .oneshot(common::post_json_with_cookie( + "/api/v1/auth/logout", + json!({}), + &cookie, + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::NO_CONTENT); + + // Same cookie no longer works. + let resp = h + .app + .oneshot(common::get_with_cookie("/api/v1/auth/me", &cookie)) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); +} + +#[sqlx::test(migrations = "./migrations")] +async fn create_and_use_bot_token(pool: PgPool) { + let h = common::harness(pool); + let (_, cookie) = common::register_user(&h.app).await; + + let resp = h + .app + .clone() + .oneshot(common::post_json_with_cookie( + "/api/v1/auth/tokens", + json!({ "name": "ci-bot" }), + &cookie, + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::CREATED); + let body = common::body_json(resp).await; + assert_eq!(body["name"], "ci-bot"); + let bearer = body["bearer"] + .as_str() + .expect("raw bearer in response") + .to_string(); + assert!(body["token_hash"].is_null(), "token_hash must not leak"); + + // Use the bearer to hit /me — should authenticate. + let resp = h + .app + .oneshot(common::get_with_bearer("/api/v1/auth/me", &bearer)) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); +} + +#[sqlx::test(migrations = "./migrations")] +async fn user_a_cannot_delete_user_b_token(pool: PgPool) { + let h = common::harness(pool); + let (_, cookie_a) = common::register_user(&h.app).await; + let (_, cookie_b) = common::register_user(&h.app).await; + + let resp = h + .app + .clone() + .oneshot(common::post_json_with_cookie( + "/api/v1/auth/tokens", + json!({ "name": "alice-bot" }), + &cookie_a, + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::CREATED); + let body = common::body_json(resp).await; + let token_id = body["id"].as_str().unwrap().to_string(); + + // User B attempts to delete user A's token → 403. + let resp = h + .app + .clone() + .oneshot(common::delete_with_cookie( + &format!("/api/v1/auth/tokens/{token_id}"), + &cookie_b, + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::FORBIDDEN); + let body = common::body_json(resp).await; + assert_eq!(body["error"]["code"], "forbidden"); + + // User A succeeds. + let resp = h + .app + .oneshot(common::delete_with_cookie( + &format!("/api/v1/auth/tokens/{token_id}"), + &cookie_a, + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::NO_CONTENT); +} + +#[sqlx::test(migrations = "./migrations")] +async fn delete_unknown_token_is_404(pool: PgPool) { + let h = common::harness(pool); + let (_, cookie) = common::register_user(&h.app).await; + let resp = h + .app + .oneshot(common::delete_with_cookie( + "/api/v1/auth/tokens/00000000-0000-0000-0000-000000000000", + &cookie, + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::NOT_FOUND); +} diff --git a/backend/tests/api_mangas.rs b/backend/tests/api_mangas.rs index 7c532bb..b21f419 100644 --- a/backend/tests/api_mangas.rs +++ b/backend/tests/api_mangas.rs @@ -20,13 +20,15 @@ async fn list_is_empty_initially(pool: PgPool) { #[sqlx::test(migrations = "./migrations")] async fn create_then_list_roundtrip(pool: PgPool) { let h = common::harness(pool); + let (_, cookie) = common::register_user(&h.app).await; let created = h .app .clone() - .oneshot(common::post_json( + .oneshot(common::post_json_with_cookie( "/api/v1/mangas", json!({ "title": "Berserk", "author": "Kentaro Miura", "description": null }), + &cookie, )) .await .unwrap(); @@ -46,6 +48,7 @@ async fn create_then_list_roundtrip(pool: PgPool) { #[sqlx::test(migrations = "./migrations")] async fn search_filters_by_title_and_author(pool: PgPool) { let h = common::harness(pool); + let (_, cookie) = common::register_user(&h.app).await; for (title, author) in [ ("One Piece", "Eiichiro Oda"), @@ -55,9 +58,10 @@ async fn search_filters_by_title_and_author(pool: PgPool) { let _ = h .app .clone() - .oneshot(common::post_json( + .oneshot(common::post_json_with_cookie( "/api/v1/mangas", json!({ "title": title, "author": author }), + &cookie, )) .await .unwrap(); @@ -96,11 +100,13 @@ async fn search_filters_by_title_and_author(pool: PgPool) { #[sqlx::test(migrations = "./migrations")] async fn create_rejects_empty_title_with_envelope(pool: PgPool) { let h = common::harness(pool); + let (_, cookie) = common::register_user(&h.app).await; let resp = h .app - .oneshot(common::post_json( + .oneshot(common::post_json_with_cookie( "/api/v1/mangas", json!({ "title": " ", "author": null }), + &cookie, )) .await .unwrap(); @@ -111,6 +117,22 @@ async fn create_rejects_empty_title_with_envelope(pool: PgPool) { assert!(!msg.is_empty(), "message should be non-empty"); } +#[sqlx::test(migrations = "./migrations")] +async fn create_requires_authentication(pool: PgPool) { + let h = common::harness(pool); + let resp = h + .app + .oneshot(common::post_json( + "/api/v1/mangas", + json!({ "title": "Berserk" }), + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); + let body = common::body_json(resp).await; + assert_eq!(body["error"]["code"], "unauthenticated"); +} + #[sqlx::test(migrations = "./migrations")] async fn get_unknown_id_is_404_with_envelope(pool: PgPool) { let h = common::harness(pool); diff --git a/backend/tests/common/mod.rs b/backend/tests/common/mod.rs index b948652..7b8a1bd 100644 --- a/backend/tests/common/mod.rs +++ b/backend/tests/common/mod.rs @@ -6,13 +6,16 @@ use std::sync::Arc; use axum::body::Body; -use axum::http::Request; +use axum::http::{header, Request}; use axum::Router; use http_body_util::BodyExt; +use serde_json::json; use sqlx::PgPool; use tempfile::TempDir; +use tower::ServiceExt; use mangalord::app::{router, AppState}; +use mangalord::config::AuthConfig; use mangalord::storage::LocalStorage; pub struct Harness { @@ -26,6 +29,7 @@ pub fn harness(pool: PgPool) -> Harness { let state = AppState { db: pool, storage: Arc::new(LocalStorage::new(storage_dir.path())), + auth: AuthConfig { cookie_secure: false, ..AuthConfig::default() }, }; Harness { app: router(state), _storage_dir: storage_dir } } @@ -39,11 +43,107 @@ pub fn get(uri: &str) -> Request { Request::builder().uri(uri).body(Body::empty()).unwrap() } +pub fn get_with_cookie(uri: &str, cookie: &str) -> Request { + Request::builder() + .uri(uri) + .header(header::COOKIE, cookie) + .body(Body::empty()) + .unwrap() +} + +pub fn get_with_bearer(uri: &str, token: &str) -> Request { + Request::builder() + .uri(uri) + .header(header::AUTHORIZATION, format!("Bearer {token}")) + .body(Body::empty()) + .unwrap() +} + pub fn post_json(uri: &str, body: serde_json::Value) -> Request { Request::builder() .method("POST") .uri(uri) - .header("content-type", "application/json") + .header(header::CONTENT_TYPE, "application/json") .body(Body::from(body.to_string())) .unwrap() } + +pub fn post_json_with_cookie( + uri: &str, + body: serde_json::Value, + cookie: &str, +) -> Request { + Request::builder() + .method("POST") + .uri(uri) + .header(header::CONTENT_TYPE, "application/json") + .header(header::COOKIE, cookie) + .body(Body::from(body.to_string())) + .unwrap() +} + +pub fn post_json_with_bearer( + uri: &str, + body: serde_json::Value, + token: &str, +) -> Request { + Request::builder() + .method("POST") + .uri(uri) + .header(header::CONTENT_TYPE, "application/json") + .header(header::AUTHORIZATION, format!("Bearer {token}")) + .body(Body::from(body.to_string())) + .unwrap() +} + +pub fn delete_with_cookie(uri: &str, cookie: &str) -> Request { + Request::builder() + .method("DELETE") + .uri(uri) + .header(header::COOKIE, cookie) + .body(Body::empty()) + .unwrap() +} + +/// Extracts the `mangalord_session` cookie from a response's Set-Cookie +/// headers as a `name=value` pair suitable for use in a follow-up `Cookie` +/// request header. Returns `None` if no such cookie was set. +pub fn extract_session_cookie(response: &axum::response::Response) -> Option { + response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .find_map(|v| { + let s = v.to_str().ok()?; + if s.starts_with("mangalord_session=") { + let end = s.find(';').unwrap_or(s.len()); + Some(s[..end].to_string()) + } else { + None + } + }) +} + +/// Register a brand-new user and return (username, session cookie value). +/// The username is unique per call so tests can run in parallel against a +/// single DB without colliding. +pub async fn register_user(app: &Router) -> (String, String) { + // 12-hex-digit suffix keeps the username under the 32-char cap. + let suffix: String = uuid::Uuid::new_v4().simple().to_string().chars().take(12).collect(); + let username = format!("u-{suffix}"); + let resp = app + .clone() + .oneshot(post_json( + "/api/v1/auth/register", + json!({ "username": username, "password": "hunter2hunter2" }), + )) + .await + .unwrap(); + assert_eq!( + resp.status(), + axum::http::StatusCode::CREATED, + "register failed in test harness" + ); + let cookie = extract_session_cookie(&resp).expect("session cookie on register"); + (username, cookie) +} diff --git a/frontend/e2e/auth-flow.spec.ts b/frontend/e2e/auth-flow.spec.ts new file mode 100644 index 0000000..4051e86 --- /dev/null +++ b/frontend/e2e/auth-flow.spec.ts @@ -0,0 +1,102 @@ +import { test, expect, type Page } from '@playwright/test'; + +// Mocks the auth endpoints at the network level so the journey is +// deterministic and doesn't require a live backend. + +const userFixture = { + id: 'user-1', + username: 'alice', + created_at: '2026-01-01T00:00:00Z' +}; +const emptyPage = { items: [], page: { limit: 50, offset: 0, total: null } }; + +async function stubAnonymousThenAuthenticated(page: Page) { + let loggedIn = false; + await page.route('**/api/v1/auth/me', async (route) => { + if (loggedIn) { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ user: userFixture }) + }); + } else { + await route.fulfill({ + status: 401, + contentType: 'application/json', + body: JSON.stringify({ + error: { code: 'unauthenticated', message: 'unauthenticated' } + }) + }); + } + }); + await page.route('**/api/v1/auth/login', async (route) => { + loggedIn = true; + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ user: userFixture }) + }); + }); + await page.route('**/api/v1/auth/logout', async (route) => { + loggedIn = false; + await route.fulfill({ status: 204 }); + }); + await page.route('**/api/v1/mangas*', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(emptyPage) + }); + }); +} + +test('login then logout flips the layout between authenticated and anonymous', async ({ + page +}) => { + await stubAnonymousThenAuthenticated(page); + + await page.goto('/'); + // Initially anonymous → Login / Register links visible. + await expect(page.getByTestId('nav-login')).toBeVisible(); + + // Log in. + await page.goto('/login'); + await page.getByTestId('login-username').fill('alice'); + await page.getByTestId('login-password').fill('hunter2hunter2'); + await page.getByTestId('login-submit').click(); + + // Authenticated → username + Logout button. + await expect(page.getByTestId('session-user')).toContainText('alice'); + await expect(page.getByRole('button', { name: 'Logout' })).toBeVisible(); + + // Log out. + await page.getByRole('button', { name: 'Logout' }).click(); + await expect(page).toHaveURL(/\/login$/); + await expect(page.getByTestId('nav-login')).toBeVisible(); +}); + +test('login surfaces the API error message on bad credentials', async ({ page }) => { + await page.route('**/api/v1/auth/me', async (route) => { + await route.fulfill({ + status: 401, + contentType: 'application/json', + body: JSON.stringify({ error: { code: 'unauthenticated', message: 'unauthenticated' } }) + }); + }); + await page.route('**/api/v1/auth/login', async (route) => { + await route.fulfill({ + status: 401, + contentType: 'application/json', + body: JSON.stringify({ + error: { code: 'unauthenticated', message: 'unauthenticated' } + }) + }); + }); + + await page.goto('/login'); + await page.getByTestId('login-username').fill('alice'); + await page.getByTestId('login-password').fill('wrongpassword'); + await page.getByTestId('login-submit').click(); + + await expect(page.getByTestId('login-error')).toBeVisible(); +}); diff --git a/frontend/e2e/manga-list.spec.ts b/frontend/e2e/manga-list.spec.ts index ad4d8ae..19e00e5 100644 --- a/frontend/e2e/manga-list.spec.ts +++ b/frontend/e2e/manga-list.spec.ts @@ -1,4 +1,4 @@ -import { test, expect } from '@playwright/test'; +import { test, expect, type Page } from '@playwright/test'; // These E2E tests run against the SvelteKit dev server, which proxies /api // to the backend. Playwright starts vite via `webServer` (see @@ -9,7 +9,18 @@ import { test, expect } from '@playwright/test'; const emptyPage = { items: [], page: { limit: 50, offset: 0, total: null } }; +async function mockAnonymous(page: Page) { + await page.route('**/api/v1/auth/me', async (route) => { + await route.fulfill({ + status: 401, + contentType: 'application/json', + body: JSON.stringify({ error: { code: 'unauthenticated', message: 'unauthenticated' } }) + }); + }); +} + test('home page renders the Mangalord heading and search input', async ({ page }) => { + await mockAnonymous(page); await page.route('**/api/v1/mangas*', async (route) => { await route.fulfill({ status: 200, @@ -25,6 +36,7 @@ test('home page renders the Mangalord heading and search input', async ({ page } }); test('search updates the manga list', async ({ page }) => { + await mockAnonymous(page); let lastSearch: string | null = null; await page.route('**/api/v1/mangas*', async (route) => { const url = new URL(route.request().url()); diff --git a/frontend/package.json b/frontend/package.json index 49506cb..8db5bd5 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "mangalord-frontend", - "version": "0.2.0", + "version": "0.3.0", "private": true, "type": "module", "scripts": { diff --git a/frontend/src/lib/api/auth.test.ts b/frontend/src/lib/api/auth.test.ts new file mode 100644 index 0000000..4b741d8 --- /dev/null +++ b/frontend/src/lib/api/auth.test.ts @@ -0,0 +1,142 @@ +import { + describe, + it, + expect, + vi, + beforeEach, + afterEach, + type MockInstance +} from 'vitest'; +import { + register, + login, + logout, + me, + createToken, + deleteToken +} from './auth'; + +function ok(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' } + }); +} + +function noContent(): Response { + return new Response(null, { status: 204 }); +} + +function envelope(status: number, code: string, message: string): Response { + return new Response(JSON.stringify({ error: { code, message } }), { + status, + headers: { 'content-type': 'application/json' } + }); +} + +const userFixture = { + id: 'user-1', + username: 'alice', + created_at: '2026-01-01T00:00:00Z' +}; + +describe('auth api client', () => { + let fetchSpy: MockInstance; + + beforeEach(() => { + fetchSpy = vi.spyOn(globalThis, 'fetch'); + }); + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('register POSTs JSON to /v1/auth/register and returns the user', async () => { + fetchSpy.mockResolvedValueOnce(ok({ user: userFixture }, 201)); + const user = await register({ username: 'alice', password: 'hunter2hunter2' }); + expect(user).toEqual(userFixture); + const url = fetchSpy.mock.calls[0][0] as string; + expect(url).toMatch(/\/v1\/auth\/register$/); + const init = fetchSpy.mock.calls[0][1] as RequestInit; + expect(init.method).toBe('POST'); + expect(JSON.parse(init.body as string)).toEqual({ + username: 'alice', + password: 'hunter2hunter2' + }); + }); + + it('register surfaces 409 conflict via ApiError.code', async () => { + fetchSpy.mockResolvedValueOnce(envelope(409, 'conflict', 'username is already taken')); + await expect( + register({ username: 'alice', password: 'hunter2hunter2' }) + ).rejects.toMatchObject({ status: 409, code: 'conflict' }); + }); + + it('login POSTs JSON to /v1/auth/login and returns the user', async () => { + fetchSpy.mockResolvedValueOnce(ok({ user: userFixture })); + const user = await login({ username: 'alice', password: 'hunter2hunter2' }); + expect(user).toEqual(userFixture); + const url = fetchSpy.mock.calls[0][0] as string; + expect(url).toMatch(/\/v1\/auth\/login$/); + }); + + it('login surfaces 401 unauthenticated via ApiError.code', async () => { + fetchSpy.mockResolvedValueOnce(envelope(401, 'unauthenticated', 'unauthenticated')); + await expect( + login({ username: 'alice', password: 'wrong' }) + ).rejects.toMatchObject({ status: 401, code: 'unauthenticated' }); + }); + + it('logout POSTs to /v1/auth/logout and handles 204', async () => { + fetchSpy.mockResolvedValueOnce(noContent()); + await expect(logout()).resolves.toBeUndefined(); + const url = fetchSpy.mock.calls[0][0] as string; + expect(url).toMatch(/\/v1\/auth\/logout$/); + const init = fetchSpy.mock.calls[0][1] as RequestInit; + expect(init.method).toBe('POST'); + }); + + it('me returns the user on 200', async () => { + fetchSpy.mockResolvedValueOnce(ok({ user: userFixture })); + await expect(me()).resolves.toEqual(userFixture); + }); + + it('me returns null on 401 (anonymous user)', async () => { + fetchSpy.mockResolvedValueOnce(envelope(401, 'unauthenticated', 'unauthenticated')); + await expect(me()).resolves.toBeNull(); + }); + + it('me re-throws non-401 errors', async () => { + fetchSpy.mockResolvedValueOnce(envelope(500, 'internal_error', 'internal error')); + await expect(me()).rejects.toMatchObject({ status: 500 }); + }); + + it('createToken POSTs to /v1/auth/tokens and returns CreatedToken with bearer', async () => { + fetchSpy.mockResolvedValueOnce( + ok( + { + id: 't1', + user_id: 'user-1', + name: 'ci-bot', + created_at: '2026-01-01T00:00:00Z', + last_used_at: null, + bearer: 'raw-token-abc' + }, + 201 + ) + ); + const t = await createToken('ci-bot'); + expect(t.name).toBe('ci-bot'); + expect(t.bearer).toBe('raw-token-abc'); + const url = fetchSpy.mock.calls[0][0] as string; + expect(url).toMatch(/\/v1\/auth\/tokens$/); + }); + + it('deleteToken DELETEs to /v1/auth/tokens/{id} and handles 204', async () => { + fetchSpy.mockResolvedValueOnce(noContent()); + await expect(deleteToken('t1')).resolves.toBeUndefined(); + const url = fetchSpy.mock.calls[0][0] as string; + expect(url).toMatch(/\/v1\/auth\/tokens\/t1$/); + const init = fetchSpy.mock.calls[0][1] as RequestInit; + expect(init.method).toBe('DELETE'); + }); +}); diff --git a/frontend/src/lib/api/auth.ts b/frontend/src/lib/api/auth.ts new file mode 100644 index 0000000..dbc0515 --- /dev/null +++ b/frontend/src/lib/api/auth.ts @@ -0,0 +1,72 @@ +import { ApiError, request } from './client'; + +export type User = { + id: string; + username: string; + created_at: string; +}; + +export type Credentials = { + username: string; + password: string; +}; + +type AuthResponse = { user: User }; + +export async function register(creds: Credentials): Promise { + const r = await request('/v1/auth/register', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(creds) + }); + return r.user; +} + +export async function login(creds: Credentials): Promise { + const r = await request('/v1/auth/login', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(creds) + }); + return r.user; +} + +export async function logout(): Promise { + await request('/v1/auth/logout', { method: 'POST' }); +} + +/** + * Returns the current user, or `null` if no valid session. + * Re-throws any non-401 error. + */ +export async function me(): Promise { + try { + const r = await request('/v1/auth/me'); + return r.user; + } catch (e) { + if (e instanceof ApiError && e.status === 401) return null; + throw e; + } +} + +export type ApiToken = { + id: string; + user_id: string; + name: string; + created_at: string; + last_used_at: string | null; +}; + +export type CreatedToken = ApiToken & { bearer: string }; + +export async function createToken(name: string): Promise { + return request('/v1/auth/tokens', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ name }) + }); +} + +export async function deleteToken(id: string): Promise { + await request(`/v1/auth/tokens/${encodeURIComponent(id)}`, { method: 'DELETE' }); +} diff --git a/frontend/src/lib/api/client.ts b/frontend/src/lib/api/client.ts index 2ce3ad0..de135e6 100644 --- a/frontend/src/lib/api/client.ts +++ b/frontend/src/lib/api/client.ts @@ -42,6 +42,9 @@ export async function request(path: string, init?: RequestInit): Promise { } throw new ApiError(res.status, code, message); } + if (res.status === 204) { + return undefined as T; + } return (await res.json()) as T; } diff --git a/frontend/src/lib/session.svelte.ts b/frontend/src/lib/session.svelte.ts new file mode 100644 index 0000000..cd72d91 --- /dev/null +++ b/frontend/src/lib/session.svelte.ts @@ -0,0 +1,33 @@ +// Per-tab session state for the currently logged-in user. +// +// Only mutated client-side (onMount / form submits) so the module-level +// instance can't leak across SSR requests — SSR always renders the +// `loaded === false` state, and the client refreshes after hydration. + +import { me, type User } from './api/auth'; + +class SessionStore { + user = $state(null); + loaded = $state(false); + // Bumped on every explicit setUser so an in-flight refresh started before + // a login/logout can't clobber the fresh state when it resolves. + private seq = 0; + + async refresh(): Promise { + const seq = this.seq; + try { + const u = await me(); + if (seq === this.seq) this.user = u; + } finally { + this.loaded = true; + } + } + + setUser(user: User | null): void { + this.seq++; + this.user = user; + this.loaded = true; + } +} + +export const session = new SessionStore(); diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte index 212acad..b2b7ff4 100644 --- a/frontend/src/routes/+layout.svelte +++ b/frontend/src/routes/+layout.svelte @@ -1,13 +1,47 @@
-
@@ -18,10 +52,20 @@ header { padding: 1rem; border-bottom: 1px solid #ddd; + display: flex; + justify-content: space-between; + align-items: center; + gap: 1rem; } - nav a { + nav a, + .session a { margin-right: 1rem; } + .session { + display: flex; + align-items: center; + gap: 0.5rem; + } main { padding: 1rem; max-width: 64rem; diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelte index 41f2cf4..af66094 100644 --- a/frontend/src/routes/+page.svelte +++ b/frontend/src/routes/+page.svelte @@ -29,6 +29,7 @@ e.preventDefault(); load(); }} + action="javascript:void(0)" > + import { goto } from '$app/navigation'; + import { login } from '$lib/api/auth'; + import { session } from '$lib/session.svelte'; + + let username = $state(''); + let password = $state(''); + let error: string | null = $state(null); + let submitting = $state(false); + + async function submit(e: SubmitEvent) { + e.preventDefault(); + error = null; + submitting = true; + try { + const user = await login({ username, password }); + session.setUser(user); + await goto('/'); + } catch (e) { + error = (e as Error).message; + } finally { + submitting = false; + } + } + + +

Log in

+
+ + + + {#if error} +

{error}

+ {/if} +
+

+ No account? Register. +

+ + diff --git a/frontend/src/routes/register/+page.svelte b/frontend/src/routes/register/+page.svelte new file mode 100644 index 0000000..fb5a25f --- /dev/null +++ b/frontend/src/routes/register/+page.svelte @@ -0,0 +1,75 @@ + + +

Register

+
+ + + + {#if error} +

{error}

+ {/if} +
+

+ Already have an account? Log in. +

+ +