diff --git a/Cargo.lock b/Cargo.lock index c3d5f51..7f7bdc4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9,11 +9,16 @@ dependencies = [ "acaua-core", "axum", "clap", + "http-body-util", + "ipnet", "mime_guess", "rust-embed", "serde", "serde_json", + "tempfile", "tokio", + "totp-rs", + "tower", "tower-http", "tracing", "tracing-subscriber", @@ -1312,6 +1317,12 @@ dependencies = [ "generic-array", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "is_terminal_polyfill" version = "1.70.2" diff --git a/crates/acaua-cli/Cargo.toml b/crates/acaua-cli/Cargo.toml index 9e556eb..fe759de 100644 --- a/crates/acaua-cli/Cargo.toml +++ b/crates/acaua-cli/Cargo.toml @@ -16,11 +16,18 @@ path = "src/main.rs" acaua-core = { path = "../acaua-core" } axum = "0.8" clap = { version = "4", features = ["derive"] } +ipnet = "2" mime_guess = "2" rust-embed = "8" serde = { version = "1", features = ["derive"] } serde_json = "1" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal"] } -tower-http = { version = "0.6", features = ["compression-gzip", "cors", "trace"] } +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tower-http = { version = "0.6", features = ["compression-gzip", "trace"] } tracing = "0.1" tracing-subscriber = "0.3" + +[dev-dependencies] +http-body-util = "0.1" +tempfile = "3" +totp-rs = { version = "6.0.0", features = ["otpauth"] } +tower = { version = "0.5", features = ["util"] } diff --git a/crates/acaua-cli/src/auth_http.rs b/crates/acaua-cli/src/auth_http.rs new file mode 100644 index 0000000..a0901aa --- /dev/null +++ b/crates/acaua-cli/src/auth_http.rs @@ -0,0 +1,891 @@ +//! The HTTP face of authentication: the global gate and the `/api/auth` and +//! `/api/admin` handlers. Decisions about accounts stay in `acaua_core::auth`. +//! +//! The session token travels only in the cookie, and that cookie is only ever +//! built from a `NewSession` the core issued. Request structs here hold +//! passwords and codes, so none of them derives `Debug`. + +use crate::web::{access_of, is_public, is_public_asset, Access, AppState}; +use acaua_core::auth::{ + csrf_matches, csrf_token, NewSession, PendingMfa, Principal, Role, Scope, TotpEnrollment, Via, +}; +use acaua_core::{AcauaError, AuthFailure}; +use axum::extract::rejection::JsonRejection; +use axum::extract::{ConnectInfo, FromRequest, FromRequestParts, Query, Request, State}; +use axum::http::request::Parts; +use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use axum::{Extension, Json}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub const MAX_BODY_BYTES: usize = 64 * 1024; +pub const ARGON2_CONCURRENCY: usize = 8; +const SESSION_COOKIE: &str = "acaua_session"; +const CSRF_HEADER: &str = "x-acaua-csrf"; +const PENDING_HEADER: &str = "x-acaua-pending"; +const LOGIN_PAGE: &str = "/login.html"; +const AUDIT_DEFAULT: usize = 200; +const AUDIT_MAX: usize = 1000; + +/// A clock before 1970 fails closed: everything looks expired. +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(u64::MAX) +} + +// ---- Errors --------------------------------------------------------------- + +pub enum ApiError { + Core(AcauaError), + Fixed(StatusCode, &'static str), +} + +impl From for ApiError { + fn from(e: AcauaError) -> Self { + ApiError::Core(e) + } +} + +impl From for ApiError { + fn from(f: AuthFailure) -> Self { + ApiError::Core(f.into()) + } +} + +fn internal() -> ApiError { + ApiError::Fixed(StatusCode::INTERNAL_SERVER_ERROR, "internal error") +} + +fn error_response(status: StatusCode, message: &str) -> Response { + (status, Json(serde_json::json!({ "error": message }))).into_response() +} + +fn failure_response(f: &AuthFailure) -> Response { + use AuthFailure as F; + let (status, message) = match f { + F::InvalidCredentials => (StatusCode::UNAUTHORIZED, "invalid credentials"), + F::Throttled { retry_after_secs } => { + let mut r = error_response(StatusCode::TOO_MANY_REQUESTS, "too many attempts"); + r.headers_mut() + .insert(header::RETRY_AFTER, HeaderValue::from(*retry_after_secs)); + return r; + } + F::SetupRequired => (StatusCode::CONFLICT, "setup required"), + F::BootstrapInvalid => (StatusCode::UNAUTHORIZED, "invalid setup code"), + F::LastAdmin => (StatusCode::CONFLICT, "the last administrator must remain"), + F::MfaMandatory => (StatusCode::CONFLICT, "MFA is mandatory for administrators"), + F::EnrollmentNotStarted => (StatusCode::CONFLICT, "no enrollment in progress"), + F::UsernameTaken => (StatusCode::CONFLICT, "username is already in use"), + F::UserNotFound | F::NotFound => (StatusCode::NOT_FOUND, "not found"), + F::ReauthRequired => (StatusCode::FORBIDDEN, "recent authentication required"), + F::Forbidden => (StatusCode::FORBIDDEN, "forbidden"), + other => { + tracing::error!(error = %other, "authentication backend failure"); + (StatusCode::INTERNAL_SERVER_ERROR, "internal error") + } + }; + error_response(status, message) +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + match self { + ApiError::Fixed(status, message) => error_response(status, message), + ApiError::Core(AcauaError::Auth(f)) => failure_response(&f), + // Written by the core's validators; never echoes the input. + ApiError::Core(AcauaError::InvalidInput(message)) => { + error_response(StatusCode::BAD_REQUEST, &message) + } + ApiError::Core(other) => { + tracing::error!(error = %other, "request failed"); + error_response(StatusCode::INTERNAL_SERVER_ERROR, "internal error") + } + } + } +} + +/// `Json`, with fixed refusals: a parser message could quote the input. +pub struct JsonBody(pub T); + +impl FromRequest for JsonBody { + type Rejection = ApiError; + + async fn from_request(req: Request, state: &S) -> Result { + Json::::from_request(req, state) + .await + .map(|Json(v)| JsonBody(v)) + .map_err(|e: JsonRejection| { + let status = e.status(); + let message = match status { + StatusCode::PAYLOAD_TOO_LARGE => "request body too large", + StatusCode::UNSUPPORTED_MEDIA_TYPE => "expected application/json", + _ => "invalid request", + }; + ApiError::Fixed(status, message) + }) + } +} + +// ---- Blocking work -------------------------------------------------------- + +/// Store and audit calls take a file lock and fsync. +pub async fn blocking(f: F) -> Result +where + T: Send + 'static, + F: FnOnce() -> Result + Send + 'static, +{ + match tokio::task::spawn_blocking(f).await { + Ok(result) => result.map_err(ApiError::Core), + Err(_) => Err(internal()), + } +} + +/// As `blocking`, for calls that run Argon2: its memory cost multiplies with +/// concurrency, so only a few run at a time. +async fn hashing(state: &AppState, f: F) -> Result +where + T: Send + 'static, + F: FnOnce() -> Result + Send + 'static, +{ + let _permit = state.argon2.acquire().await.map_err(|_| internal())?; + blocking(f).await +} + +// ---- Credentials ---------------------------------------------------------- + +/// The client address `Transport` allows us to believe. +#[derive(Clone, Copy)] +pub struct ClientIp(IpAddr); + +/// A session token proved valid by the gate. No `Debug`: it is a credential. +#[derive(Clone)] +pub struct SessionToken(String); + +#[derive(Clone)] +pub struct PendingToken(String); + +/// The `Principal` the gate authenticated. The only way a handler gets one. +#[derive(Clone)] +pub struct Auth(pub Principal); + +impl FromRequestParts for Auth { + type Rejection = ApiError; + + async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { + parts + .extensions + .get::() + .cloned() + .ok_or_else(unauthenticated) + } +} + +fn unauthenticated() -> ApiError { + ApiError::Fixed(StatusCode::UNAUTHORIZED, "authentication required") +} + +fn forbidden() -> ApiError { + AuthFailure::Forbidden.into() +} + +fn session_cookie_value(headers: &HeaderMap) -> Option { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .find_map(|pair| { + let (name, value) = pair.trim().split_once('=')?; + (name == SESSION_COOKIE && !value.is_empty()).then(|| value.to_string()) + }) +} + +enum Credential { + Bearer(String), + Cookie(String), +} + +/// An `Authorization` header decides alone: a bad one never falls back to the +/// cookie. Only API tokens are valid there, so a session cannot skip CSRF. +fn credential(headers: &HeaderMap) -> Result, ApiError> { + if let Some(value) = headers.get(header::AUTHORIZATION) { + let text = value.to_str().map_err(|_| unauthenticated())?; + return match text.split_once(' ') { + Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") => { + Ok(Some(Credential::Bearer(token.trim().to_string()))) + } + _ => Err(unauthenticated()), + }; + } + Ok(session_cookie_value(headers).map(Credential::Cookie)) +} + +fn is_safe(method: &Method) -> bool { + matches!(*method, Method::GET | Method::HEAD) +} + +pub fn require_admin(p: &Principal) -> Result<(), ApiError> { + if p.role == Role::Admin && p.scope == Scope::Admin { + Ok(()) + } else { + Err(forbidden()) + } +} + +/// A refused request. Browsers navigating to a page go to the login; the rest +/// get the same 401, so unknown paths cannot be told from protected ones. +fn deny(method: &Method, path: &str, headers: &HeaderMap) -> Response { + let wants_html = headers + .get(header::ACCEPT) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.contains("text/html")); + if is_safe(method) && wants_html && !path.starts_with("/api/") { + let mut r = StatusCode::SEE_OTHER.into_response(); + r.headers_mut() + .insert(header::LOCATION, HeaderValue::from_static(LOGIN_PAGE)); + return r; + } + unauthenticated().into_response() +} + +/// Wraps the whole router, fallback included, so anything not listed in +/// `PUBLIC_ROUTES` needs a credential from the moment it exists. +pub async fn require_auth(State(state): State, mut req: Request, next: Next) -> Response { + let method = req.method().clone(); + let path = req.uri().path().to_string(); + let peer = req + .extensions() + .get::>() + .map(|c| c.0.ip()) + .unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED)); + let ip = state.transport.client_ip(peer, req.headers()); + req.extensions_mut().insert(ClientIp(ip)); + + let mut response = if is_public(&method, &path) { + next.run(req).await + } else { + match gate(&state, &method, &path, &mut req).await { + Ok(()) => next.run(req).await, + Err(Refusal::Unauthenticated) => deny(&method, &path, req.headers()), + Err(Refusal::Other(e)) => e.into_response(), + } + }; + if !is_public_asset(&method, &path) { + response + .headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + } + response +} + +enum Refusal { + Unauthenticated, + Other(ApiError), +} + +impl From for Refusal { + fn from(e: ApiError) -> Self { + Refusal::Other(e) + } +} + +async fn gate( + state: &AppState, + method: &Method, + path: &str, + req: &mut Request, +) -> Result<(), Refusal> { + let access = access_of(method, path); + + if access == Access::SessionOrPending { + if let Some(value) = req.headers().get(PENDING_HEADER) { + let token = value + .to_str() + .map_err(|_| Refusal::Unauthenticated)? + .to_string(); + let auth = state.auth.clone(); + let checked = token.clone(); + let now = unix_now(); + authenticated(blocking(move || auth.pending_user(&checked, now)).await)?; + // A custom header is never sent by a cross-site form: no CSRF here. + req.extensions_mut().insert(PendingToken(token)); + return Ok(()); + } + } + + let cred = credential(req.headers()) + .map_err(|_| Refusal::Unauthenticated)? + .ok_or(Refusal::Unauthenticated)?; + let now = unix_now(); + let auth = state.auth.clone(); + let principal = match &cred { + Credential::Bearer(token) => { + let token = token.clone(); + authenticated(blocking(move || auth.authenticate_token(&token, now)).await)? + } + Credential::Cookie(token) => { + let token = token.clone(); + authenticated(blocking(move || auth.authenticate_session(&token, now)).await)? + } + }; + + if let Credential::Cookie(token) = &cred { + if !is_safe(method) { + let sent = req + .headers() + .get(CSRF_HEADER) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + if !csrf_matches(token, sent) { + return Err(ApiError::Fixed(StatusCode::FORBIDDEN, "invalid CSRF token").into()); + } + } + } + + if principal.via == Via::Token && !is_safe(method) && principal.scope != Scope::Admin { + return Err(forbidden().into()); + } + match access { + Access::Authenticated => {} + Access::Session | Access::SessionOrPending => { + if principal.via != Via::Session { + return Err(forbidden().into()); + } + } + Access::Admin => require_admin(&principal)?, + } + + if let Credential::Cookie(token) = cred { + req.extensions_mut().insert(SessionToken(token)); + } + req.extensions_mut().insert(Auth(principal)); + Ok(()) +} + +/// A rejected credential is a plain 401. A backend failure stays a 500: it +/// still refuses, but must not look like a logout. +fn authenticated(result: Result) -> Result { + result.map_err(|e| match e { + ApiError::Core(AcauaError::Auth(AuthFailure::InvalidCredentials)) => { + Refusal::Unauthenticated + } + other => Refusal::Other(other), + }) +} + +// ---- Cookies and login replies -------------------------------------------- + +fn with_cookie(mut response: Response, cookie: String) -> Response { + match HeaderValue::from_str(&cookie) { + Ok(value) => { + response.headers_mut().append(header::SET_COOKIE, value); + response + } + Err(_) => internal().into_response(), + } +} + +fn cookie_attrs(state: &AppState) -> &'static str { + if state.transport.cookie_secure() { + "; Path=/; HttpOnly; SameSite=Strict; Secure" + } else { + "; Path=/; HttpOnly; SameSite=Strict" + } +} + +fn clear_cookie(state: &AppState, response: Response) -> Response { + let attrs = cookie_attrs(state); + with_cookie(response, format!("{SESSION_COOKIE}=; Max-Age=0{attrs}")) +} + +/// The session reply. The token leaves the server only as this cookie. +fn session_reply(state: &AppState, session: &NewSession) -> Response { + let attrs = cookie_attrs(state); + let max_age = session.expires_at.saturating_sub(unix_now()); + let reply = Json(serde_json::json!({ + "step": "session", + "expires_at": session.expires_at, + })); + with_cookie( + reply.into_response(), + format!( + "{SESSION_COOKIE}={}; Max-Age={max_age}{attrs}", + session.token + ), + ) +} + +fn pending_reply(step: &str, pending: &PendingMfa) -> Response { + Json(serde_json::json!({ + "step": step, + "pending": pending.token, + "expires_at": pending.expires_at, + })) + .into_response() +} + +fn step_reply(state: &AppState, step: &acaua_core::auth::LoginStep) -> Response { + use acaua_core::auth::LoginStep as L; + match step { + L::Session(s) => session_reply(state, s), + L::MfaRequired(p) => pending_reply("mfa_required", p), + L::MfaEnrollRequired(p) => pending_reply("mfa_enroll_required", p), + L::PasswordChangeRequired(p) => pending_reply("password_change_required", p), + } +} + +// ---- Public handlers ------------------------------------------------------ + +#[derive(Serialize)] +pub struct StateReply { + setup_required: bool, + authenticated: bool, + #[serde(skip_serializing_if = "Option::is_none")] + username: Option, + #[serde(skip_serializing_if = "Option::is_none")] + role: Option, + #[serde(skip_serializing_if = "Option::is_none")] + csrf: Option, +} + +pub async fn auth_state( + State(state): State, + headers: HeaderMap, +) -> Result, ApiError> { + let token = session_cookie_value(&headers); + let auth = state.auth.clone(); + let now = unix_now(); + blocking(move || { + let setup_required = !auth.has_admin()?; + let session = token.and_then(|t| { + let p = auth.authenticate_session(&t, now).ok()?; + Some((p, csrf_token(&t))) + }); + Ok(Json(match session { + Some((p, csrf)) => StateReply { + setup_required, + authenticated: true, + username: Some(p.username), + role: Some(p.role), + csrf: Some(csrf), + }, + None => StateReply { + setup_required, + authenticated: false, + username: None, + role: None, + csrf: None, + }, + })) + }) + .await +} + +#[derive(Deserialize)] +pub struct BootstrapBody { + code: String, + username: String, + password: String, +} + +pub async fn bootstrap( + State(state): State, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + let pending = hashing(&state, move || { + auth.complete_bootstrap(&b.code, &b.username, &b.password, now) + }) + .await?; + Ok(pending_reply("mfa_enroll_required", &pending)) +} + +#[derive(Deserialize)] +pub struct LoginBody { + username: String, + password: String, +} + +pub async fn login( + State(state): State, + Extension(ClientIp(ip)): Extension, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + let step = hashing(&state, move || { + auth.login(&b.username, &b.password, ip, now) + }) + .await?; + Ok(step_reply(&state, &step)) +} + +#[derive(Deserialize)] +pub struct MfaBody { + pending: String, + code: String, +} + +pub async fn mfa( + State(state): State, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + let step = blocking(move || auth.confirm_mfa(&b.pending, &b.code, now)).await?; + Ok(step_reply(&state, &step)) +} + +#[derive(Deserialize)] +pub struct RequiredPasswordBody { + ticket: String, + current: String, + new: String, +} + +pub async fn password_change_required( + State(state): State, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + let session = hashing(&state, move || { + auth.change_required_password(&b.ticket, &b.current, &b.new, now) + }) + .await?; + Ok(session_reply(&state, &session)) +} + +// ---- Session handlers ----------------------------------------------------- + +fn ok_reply() -> Response { + Json(serde_json::json!({ "ok": true })).into_response() +} + +/// The session behind a `Via::Session` principal. +fn session_token(parts: &axum::http::Extensions) -> Result { + parts + .get::() + .map(|t| t.0.clone()) + .ok_or_else(unauthenticated) +} + +pub async fn logout(State(state): State, req: Request) -> Result { + let token = session_token(req.extensions())?; + let auth = state.auth.clone(); + let now = unix_now(); + blocking(move || auth.logout(&token, now)).await?; + Ok(clear_cookie(&state, ok_reply())) +} + +#[derive(Deserialize)] +pub struct ReauthBody { + password: String, + code: Option, +} + +pub async fn reauth( + State(state): State, + Auth(p): Auth, + Extension(SessionToken(token)): Extension, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + hashing(&state, move || { + auth.reauthenticate(&p.user_id, &token, &b.password, b.code.as_deref(), now) + }) + .await?; + Ok(ok_reply()) +} + +#[derive(Deserialize)] +pub struct PasswordBody { + current: String, + new: String, +} + +pub async fn change_password( + State(state): State, + Auth(p): Auth, + Extension(SessionToken(token)): Extension, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + hashing(&state, move || { + auth.change_password(&p.user_id, &b.current, &b.new, Some(&token), now) + }) + .await?; + Ok(ok_reply()) +} + +/// Who is enrolling: the first-login pending token, or a session that +/// reauthenticated recently. +pub enum EnrollActor { + Pending(String), + Session(Principal), +} + +impl FromRequestParts for EnrollActor { + type Rejection = ApiError; + + async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { + if let Some(PendingToken(token)) = parts.extensions.get::() { + return Ok(EnrollActor::Pending(token.clone())); + } + let Auth(p) = parts + .extensions + .get::() + .cloned() + .ok_or_else(unauthenticated)?; + if !p.recent_auth { + return Err(AuthFailure::ReauthRequired.into()); + } + Ok(EnrollActor::Session(p)) + } +} + +#[derive(Serialize)] +pub struct EnrollReply { + uri: String, + qr_png_base64: String, + manual_key: String, +} + +impl From for EnrollReply { + fn from(e: TotpEnrollment) -> Self { + Self { + uri: e.uri, + qr_png_base64: e.qr_png_base64, + manual_key: e.manual_key, + } + } +} + +pub async fn enroll_start( + State(state): State, + actor: EnrollActor, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + let enrollment = blocking(move || match actor { + EnrollActor::Pending(token) => auth.start_enrollment_pending(&token, now), + EnrollActor::Session(p) => auth.start_enrollment(&p.user_id, now), + }) + .await?; + Ok(Json(EnrollReply::from(enrollment)).into_response()) +} + +#[derive(Deserialize)] +pub struct CodeBody { + code: String, +} + +pub async fn enroll_confirm( + State(state): State, + actor: EnrollActor, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + let from_session = matches!(actor, EnrollActor::Session(_)); + let codes = blocking(move || match actor { + EnrollActor::Pending(token) => auth.confirm_enrollment_pending(&token, &b.code, now), + EnrollActor::Session(p) => auth.confirm_enrollment(&p.user_id, &b.code, now), + }) + .await?; + let reply = Json(serde_json::json!({ "recovery_codes": codes })).into_response(); + // Activation ends every session of the user, this one too. + Ok(if from_session { + clear_cookie(&state, reply) + } else { + reply + }) +} + +pub async fn mfa_disable( + State(state): State, + Auth(p): Auth, + Extension(SessionToken(token)): Extension, +) -> Result { + if !p.recent_auth { + return Err(AuthFailure::ReauthRequired.into()); + } + let auth = state.auth.clone(); + let now = unix_now(); + blocking(move || auth.disable_mfa(&p.username, &p.user_id, Some(&token), now)).await?; + Ok(ok_reply()) +} + +#[derive(Deserialize)] +pub struct OwnerQuery { + user_id: Option, +} + +/// The core's listings take no actor: the check lives here. +fn listing_target(p: &Principal, asked: Option) -> Result { + match asked { + Some(id) if id != p.user_id => { + require_admin(p)?; + Ok(id) + } + _ => Ok(p.user_id.clone()), + } +} + +pub async fn sessions_list( + State(state): State, + Auth(p): Auth, + Query(q): Query, +) -> Result { + let target = listing_target(&p, q.user_id)?; + let auth = state.auth.clone(); + let now = unix_now(); + let list = blocking(move || auth.list_sessions(&target, now)).await?; + Ok(Json(list).into_response()) +} + +#[derive(Deserialize)] +pub struct IdBody { + id: String, +} + +pub async fn sessions_revoke( + State(state): State, + Auth(p): Auth, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + blocking(move || auth.revoke_session(&p, &b.id, now)).await?; + Ok(ok_reply()) +} + +pub async fn tokens_list( + State(state): State, + Auth(p): Auth, + Query(q): Query, +) -> Result { + let target = listing_target(&p, q.user_id)?; + let auth = state.auth.clone(); + let now = unix_now(); + let list = blocking(move || auth.list_tokens(&target, now)).await?; + Ok(Json(list).into_response()) +} + +#[derive(Deserialize)] +pub struct TokenBody { + name: String, + scope: Scope, + expires_at: u64, +} + +pub async fn tokens_create( + State(state): State, + Auth(p): Auth, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + let made = + blocking(move || auth.create_api_token(&p, &b.name, b.scope, b.expires_at, now)).await?; + Ok(Json(serde_json::json!({ + "id": made.id, + "name": made.name, + "token": made.token, + "scope": made.scope, + "expires_at": made.expires_at, + })) + .into_response()) +} + +pub async fn tokens_revoke( + State(state): State, + Auth(p): Auth, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + blocking(move || auth.revoke_token(&p, &b.id, now)).await?; + Ok(ok_reply()) +} + +// ---- Admin handlers (the gate already ran `require_admin`) ---------------- + +pub async fn users_list(State(state): State) -> Result { + let auth = state.auth.clone(); + let list = blocking(move || auth.list_users()).await?; + Ok(Json(list).into_response()) +} + +#[derive(Deserialize)] +pub struct NewUserBody { + username: String, + password: String, + role: Role, +} + +pub async fn users_create( + State(state): State, + Auth(p): Auth, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + let id = hashing(&state, move || { + auth.create_user(&p.username, &b.username, &b.password, b.role, now) + }) + .await?; + Ok(Json(serde_json::json!({ "id": id })).into_response()) +} + +#[derive(Deserialize)] +pub struct RoleBody { + id: String, + role: Role, +} + +pub async fn users_set_role( + State(state): State, + Auth(p): Auth, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + blocking(move || auth.set_role(&p.username, &b.id, b.role, now)).await?; + Ok(ok_reply()) +} + +pub async fn users_delete( + State(state): State, + Auth(p): Auth, + JsonBody(b): JsonBody, +) -> Result { + let auth = state.auth.clone(); + let now = unix_now(); + blocking(move || auth.delete_user(&p.username, &b.id, now)).await?; + Ok(ok_reply()) +} + +#[derive(Deserialize)] +pub struct AuditQuery { + limit: Option, +} + +pub async fn audit( + State(state): State, + Query(q): Query, +) -> Result { + let limit = q.limit.unwrap_or(AUDIT_DEFAULT).clamp(1, AUDIT_MAX); + let auth = state.auth.clone(); + let list = blocking(move || auth.audit_tail(limit)).await?; + Ok(Json(list).into_response()) +} diff --git a/crates/acaua-cli/src/main.rs b/crates/acaua-cli/src/main.rs index 09bbc01..05ed173 100644 --- a/crates/acaua-cli/src/main.rs +++ b/crates/acaua-cli/src/main.rs @@ -1,3 +1,5 @@ +mod auth_http; +mod transport; mod web; use acaua_core::{doctor, update, zeek}; diff --git a/crates/acaua-cli/src/transport.rs b/crates/acaua-cli/src/transport.rs new file mode 100644 index 0000000..8625f35 --- /dev/null +++ b/crates/acaua-cli/src/transport.rs @@ -0,0 +1,122 @@ +//! How requests reach the daemon: this decides which client address can be +//! believed and whether cookies may be marked `Secure`. + +use axum::http::HeaderMap; +use ipnet::IpNet; +use std::net::IpAddr; +use std::path::PathBuf; + +// `Tls` and `Proxy` have no reader outside tests until `from_env` and TLS +// serving exist. +#[allow(dead_code)] +#[derive(Debug, Clone)] +pub enum Transport { + Local, + Tls { cert: PathBuf, key: PathBuf }, + Proxy { trusted: Vec }, +} + +impl Transport { + /// The address to throttle and audit. `X-Forwarded-For` counts only when + /// the peer is a trusted proxy, and then the answer is the rightmost hop + /// that is not itself trusted: everything left of it is client-supplied. + pub fn client_ip(&self, peer: IpAddr, headers: &HeaderMap) -> IpAddr { + let peer = peer.to_canonical(); + let Transport::Proxy { trusted } = self else { + return peer; + }; + let is_trusted = |ip: &IpAddr| trusted.iter().any(|net| net.contains(ip)); + if !is_trusted(&peer) { + return peer; + } + let mut hops: Vec<&str> = Vec::new(); + for value in headers.get_all("x-forwarded-for") { + let Ok(text) = value.to_str() else { + return peer; + }; + hops.extend(text.split(',')); + } + for hop in hops.iter().rev() { + let Ok(ip) = hop.trim().parse::() else { + return peer; + }; + let ip = ip.to_canonical(); + if !is_trusted(&ip) { + return ip; + } + } + peer + } + + pub fn cookie_secure(&self) -> bool { + !matches!(self, Transport::Local) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn proxy() -> Transport { + Transport::Proxy { + trusted: vec!["10.0.0.0/8".parse().unwrap()], + } + } + + fn xff(value: &str) -> HeaderMap { + let mut h = HeaderMap::new(); + h.insert("x-forwarded-for", value.parse().unwrap()); + h + } + + fn ip(s: &str) -> IpAddr { + s.parse().unwrap() + } + + #[test] + fn forwarded_for_counts_only_from_a_trusted_proxy() { + let forged = xff("203.0.113.9"); + assert_eq!( + Transport::Local.client_ip(ip("192.0.2.1"), &forged), + ip("192.0.2.1") + ); + let tls = Transport::Tls { + cert: "c".into(), + key: "k".into(), + }; + assert_eq!(tls.client_ip(ip("192.0.2.1"), &forged), ip("192.0.2.1")); + assert_eq!( + proxy().client_ip(ip("192.0.2.1"), &forged), + ip("192.0.2.1"), + "untrusted peer" + ); + assert_eq!( + proxy().client_ip(ip("10.0.0.1"), &forged), + ip("203.0.113.9") + ); + } + + #[test] + fn rightmost_untrusted_hop_wins_over_a_forged_left_side() { + let h = xff("1.1.1.1, 203.0.113.9, 10.0.0.2"); + assert_eq!(proxy().client_ip(ip("10.0.0.1"), &h), ip("203.0.113.9")); + } + + #[test] + fn malformed_or_missing_header_falls_back_to_the_peer() { + for h in [xff("not-an-ip"), HeaderMap::new(), xff("10.0.0.2")] { + assert_eq!(proxy().client_ip(ip("10.0.0.1"), &h), ip("10.0.0.1")); + } + } + + #[test] + fn only_local_cookies_lack_secure() { + assert!(!Transport::Local.cookie_secure()); + assert!(proxy().cookie_secure()); + assert!(Transport::Tls { + cert: "c".into(), + key: "k".into() + } + .cookie_secure()); + } +} diff --git a/crates/acaua-cli/src/web.rs b/crates/acaua-cli/src/web.rs index 3731a1e..948a69f 100644 --- a/crates/acaua-cli/src/web.rs +++ b/crates/acaua-cli/src/web.rs @@ -1,22 +1,27 @@ +use crate::auth_http::{self, blocking, require_auth, ApiError, JsonBody}; +use crate::transport::Transport; +use acaua_core::auth::AuthService; use acaua_core::fusion::Alert; use acaua_core::storage::{DatasetSummary, Storage}; use acaua_core::update::UpdateStatus; use acaua_core::zeek::{self, AnalysisReport}; use acaua_core::{update, Result}; use axum::body::Body; -use axum::extract::{Query, State}; -use axum::http::{header, StatusCode, Uri}; +use axum::extract::{DefaultBodyLimit, Query, State}; +use axum::http::{header, Method, StatusCode, Uri}; +use axum::middleware::from_fn_with_state; use axum::response::{IntoResponse, Response}; -use axum::routing::{get, post}; +use axum::routing::{delete, get, patch, post, MethodRouter}; use axum::{Json, Router}; use rust_embed::RustEmbed; use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use std::net::SocketAddr; use std::path::PathBuf; -use std::sync::Arc; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use tokio::net::TcpListener; +use tokio::sync::Semaphore; use tower_http::compression::CompressionLayer; -use tower_http::cors::CorsLayer; use tower_http::trace::TraceLayer; const LOGO: &[u8] = include_bytes!("../../../logo.png"); @@ -26,15 +31,211 @@ const LOGO: &[u8] = include_bytes!("../../../logo.png"); struct Assets; #[derive(Clone)] -struct AppState { +pub struct AppState { storage: Arc, - last_report: Arc>>, + last_report: Arc>>, + pub auth: Arc, + pub transport: Arc, + pub argon2: Arc, +} + +impl AppState { + pub fn new(storage: Arc, auth: Arc, transport: Transport) -> Self { + Self { + storage, + last_report: Arc::new(Mutex::new(None)), + auth, + transport: Arc::new(transport), + argon2: Arc::new(Semaphore::new(auth_http::ARGON2_CONCURRENCY)), + } + } + + /// The report is replaced whole, so a poisoned lock still holds a valid one. + fn report(&self) -> MutexGuard<'_, Option> { + self.last_report + .lock() + .unwrap_or_else(PoisonError::into_inner) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Verb { + Get, + Post, + Patch, + Delete, +} + +impl Verb { + /// `HEAD` follows `GET`, as in the router. + fn matches(self, method: &Method) -> bool { + match self { + Verb::Get => *method == Method::GET || *method == Method::HEAD, + Verb::Post => *method == Method::POST, + Verb::Patch => *method == Method::PATCH, + Verb::Delete => *method == Method::DELETE, + } + } +} + +/// What a non-public route asks of the caller. There is no public level on +/// purpose: a route is public only by being written into `PUBLIC_ROUTES`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Access { + /// Any session or token; a read token still cannot mutate. + Authenticated, + /// A browser session: an API token, whatever its scope, is refused. + Session, + /// As `Session`, or the pending token of a first login. + SessionOrPending, + /// Administrator role, and Admin scope when through a token. + Admin, +} + +pub struct RouteDef { + pub verb: Verb, + pub path: &'static str, + pub access: Access, + handler: fn() -> MethodRouter, +} + +const fn route( + verb: Verb, + path: &'static str, + access: Access, + handler: fn() -> MethodRouter, +) -> RouteDef { + RouteDef { + verb, + path, + access, + handler, + } +} + +/// The one source of routes: `build_app` registers exactly these. Access for +/// entries also in `PUBLIC_ROUTES` is never consulted. +pub const ALL_ROUTES: &[RouteDef] = { + use auth_http as a; + use Access::{Admin, Authenticated, Session, SessionOrPending}; + use Verb::{Delete, Get, Patch, Post}; + &[ + route(Get, "/api/health", Authenticated, || get(health)), + route(Get, "/login.html", Authenticated, || get(asset)), + route(Get, "/login.js", Authenticated, || get(asset)), + route(Get, "/app.css", Authenticated, || get(asset)), + route(Get, "/logo.png", Authenticated, || get(logo)), + route(Get, "/i18n.js", Authenticated, || get(asset)), + route(Get, "/i18n-en.js", Authenticated, || get(asset)), + route(Get, "/api/auth/state", Authenticated, || get(a::auth_state)), + route(Post, "/api/auth/bootstrap", Authenticated, || { + post(a::bootstrap) + }), + route(Post, "/api/auth/login", Authenticated, || post(a::login)), + route(Post, "/api/auth/mfa", Authenticated, || post(a::mfa)), + route( + Post, + "/api/auth/password-change-required", + Authenticated, + || post(a::password_change_required), + ), + route(Post, "/api/auth/logout", Session, || post(a::logout)), + route(Post, "/api/auth/reauth", Session, || post(a::reauth)), + route(Post, "/api/auth/password", Session, || { + post(a::change_password) + }), + route(Post, "/api/auth/mfa/disable", Session, || { + post(a::mfa_disable) + }), + route(Post, "/api/auth/enroll/start", SessionOrPending, || { + post(a::enroll_start) + }), + route(Post, "/api/auth/enroll/confirm", SessionOrPending, || { + post(a::enroll_confirm) + }), + route(Get, "/api/auth/sessions", Authenticated, || { + get(a::sessions_list) + }), + route(Delete, "/api/auth/sessions", Authenticated, || { + delete(a::sessions_revoke) + }), + route(Get, "/api/auth/tokens", Authenticated, || { + get(a::tokens_list) + }), + route(Post, "/api/auth/tokens", Session, || post(a::tokens_create)), + route(Delete, "/api/auth/tokens", Authenticated, || { + delete(a::tokens_revoke) + }), + route(Get, "/api/admin/users", Admin, || get(a::users_list)), + route(Post, "/api/admin/users", Admin, || post(a::users_create)), + route(Patch, "/api/admin/users", Admin, || { + patch(a::users_set_role) + }), + route(Delete, "/api/admin/users", Admin, || { + delete(a::users_delete) + }), + route(Get, "/api/admin/audit", Admin, || get(a::audit)), + route(Post, "/api/analyze", Admin, || post(analyze)), + route(Get, "/api/status", Authenticated, || get(status)), + route(Get, "/api/alerts", Authenticated, || get(alerts)), + route(Get, "/api/update", Authenticated, || get(update_check)), + route(Get, "/relatorio", Authenticated, || get(report_page)), + ] +}; + +/// Everything reachable without a credential. Exact matches only. +pub const PUBLIC_ROUTES: &[(Verb, &str)] = &[ + (Verb::Get, "/api/health"), + (Verb::Get, "/login.html"), + (Verb::Get, "/login.js"), + (Verb::Get, "/app.css"), + (Verb::Get, "/logo.png"), + (Verb::Get, "/i18n.js"), + (Verb::Get, "/i18n-en.js"), + (Verb::Get, "/api/auth/state"), + (Verb::Post, "/api/auth/bootstrap"), + (Verb::Post, "/api/auth/login"), + (Verb::Post, "/api/auth/mfa"), + (Verb::Post, "/api/auth/password-change-required"), +]; + +pub fn is_public(method: &Method, path: &str) -> bool { + PUBLIC_ROUTES + .iter() + .any(|(verb, p)| *p == path && verb.matches(method)) +} + +/// The public files: shared, cacheable, and holding nothing per-user. +pub fn is_public_asset(method: &Method, path: &str) -> bool { + !path.starts_with("/api/") && is_public(method, path) +} + +/// Paths outside the table (the asset fallback) need a credential too. +pub fn access_of(method: &Method, path: &str) -> Access { + ALL_ROUTES + .iter() + .find(|r| r.path == path && r.verb.matches(method)) + .map_or(Access::Authenticated, |r| r.access) +} + +pub fn build_app(state: AppState) -> Router { + let mut router = Router::new(); + for r in ALL_ROUTES { + router = router.route(r.path, (r.handler)()); + } + router + .fallback(asset) + // Bounds every `Json` extractor before anything looks at the input. + .layer(DefaultBodyLimit::max(auth_http::MAX_BODY_BYTES)) + .layer(from_fn_with_state(state.clone(), require_auth)) + .with_state(state) + .layer(CompressionLayer::new()) + .layer(TraceLayer::new_for_http()) } #[derive(Serialize)] struct Health { status: &'static str, - version: &'static str, } #[derive(Serialize)] @@ -55,26 +256,27 @@ struct AnalyzeRequest { } async fn health() -> Json { - Json(Health { - status: "ok", - version: env!("CARGO_PKG_VERSION"), - }) + Json(Health { status: "ok" }) } -async fn status(State(state): State) -> Json { - Json(Status { +async fn status(State(state): State) -> std::result::Result, ApiError> { + let storage = state.storage.clone(); + let dataset = blocking(move || { + Ok(storage + .summary() + .unwrap_or_else(|_| DatasetSummary::empty())) + }) + .await?; + Ok(Json(Status { version: env!("CARGO_PKG_VERSION"), mode: "serve", - dataset: state - .storage - .summary() - .unwrap_or_else(|_| DatasetSummary::empty()), - }) + dataset, + })) } async fn alerts(State(state): State) -> Json> { - let report_lock = state.last_report.lock().unwrap(); - let list = report_lock + let list = state + .report() .as_ref() .map(|r| r.alerts.clone()) .unwrap_or_default(); @@ -83,23 +285,25 @@ async fn alerts(State(state): State) -> Json> { async fn analyze( State(state): State, - Json(request): Json, -) -> std::result::Result, (StatusCode, Json)> { - zeek::analyze_dir(&request.path, state.storage.root()) - .map(|report| { - if let Ok(mut lock) = state.last_report.lock() { - *lock = Some(report.clone()); - } - Json(report) - }) - .map_err(|error| { - ( - StatusCode::BAD_REQUEST, - Json(ErrorBody { - error: error.to_string(), - }), - ) - }) + JsonBody(request): JsonBody, +) -> Response { + let root = state.storage.root().to_path_buf(); + let outcome = + tokio::task::spawn_blocking(move || zeek::analyze_dir(&request.path, &root)).await; + match outcome { + Ok(Ok(report)) => { + *state.report() = Some(report.clone()); + Json(report).into_response() + } + Ok(Err(error)) => ( + StatusCode::BAD_REQUEST, + Json(ErrorBody { + error: error.to_string(), + }), + ) + .into_response(), + Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), + } } /// Executive report of the latest analysis (`?tlp=` picks the TLP label). @@ -107,7 +311,7 @@ async fn report_page( State(state): State, Query(query): Query>, ) -> Response { - let lock = state.last_report.lock().unwrap(); + let lock = state.report(); let Some(report) = lock.as_ref() else { return ( StatusCode::NOT_FOUND, @@ -124,17 +328,19 @@ async fn report_page( ([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response() } -async fn update_check() -> std::result::Result, (StatusCode, Json)> { - update::check(env!("CARGO_PKG_VERSION")) - .map(Json) - .map_err(|error| { - ( - StatusCode::BAD_GATEWAY, - Json(ErrorBody { - error: error.to_string(), - }), - ) - }) +async fn update_check() -> Response { + let outcome = tokio::task::spawn_blocking(|| update::check(env!("CARGO_PKG_VERSION"))).await; + match outcome { + Ok(Ok(status)) => Json::(status).into_response(), + Ok(Err(error)) => ( + StatusCode::BAD_GATEWAY, + Json(ErrorBody { + error: error.to_string(), + }), + ) + .into_response(), + Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), + } } async fn logo() -> impl IntoResponse { @@ -180,27 +386,23 @@ async fn shutdown_signal() { pub async fn serve(bind: &str, data_dir: PathBuf) -> Result<()> { let _ = tracing_subscriber::fmt().try_init(); std::fs::create_dir_all(&data_dir)?; - let state = AppState { - storage: Arc::new(Storage::open(&data_dir)?), - last_report: Arc::new(std::sync::Mutex::new(None)), - }; - let app = Router::new() - .route("/api/health", get(health)) - .route("/api/status", get(status)) - .route("/api/alerts", get(alerts)) - .route("/api/analyze", post(analyze)) - .route("/api/update", get(update_check)) - .route("/relatorio", get(report_page)) - .route("/logo.png", get(logo)) - .fallback(asset) - .with_state(state) - .layer(CompressionLayer::new()) - .layer(CorsLayer::new()) - .layer(TraceLayer::new_for_http()); + let auth = Arc::new(AuthService::open(&data_dir, None)?); + if let Some(code) = auth.ensure_bootstrap(auth_http::unix_now())? { + eprintln!("Acauã: código de configuração inicial (válido por 1 hora): {code}"); + } + let state = AppState::new(Arc::new(Storage::open(&data_dir)?), auth, Transport::Local); + let app = build_app(state); let listener = TcpListener::bind(bind).await?; println!("Acauã listening on http://{bind}"); - axum::serve(listener, app) - .with_graceful_shutdown(shutdown_signal()) - .await?; + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(shutdown_signal()) + .await?; Ok(()) } + +#[cfg(test)] +#[path = "web_tests.rs"] +mod tests; diff --git a/crates/acaua-cli/src/web_tests.rs b/crates/acaua-cli/src/web_tests.rs new file mode 100644 index 0000000..aba01c3 --- /dev/null +++ b/crates/acaua-cli/src/web_tests.rs @@ -0,0 +1,950 @@ +use super::*; +use acaua_core::auth::{AuthService, LoginStep, Role, Scope}; +use axum::body::to_bytes; +use axum::http::{HeaderMap, Method, Request}; +use std::net::{IpAddr, SocketAddr}; +use tower::ServiceExt; + +const PW: &str = "correct horse battery staple"; +const PW2: &str = "another long enough passphrase"; + +fn now() -> u64 { + crate::auth_http::unix_now() +} + +fn peer() -> IpAddr { + "192.0.2.10".parse().unwrap() +} + +struct H { + _dir: tempfile::TempDir, + auth: Arc, + app: Router, + uri: String, + recovery: Vec, +} + +struct Reply { + status: StatusCode, + headers: HeaderMap, + body: String, +} + +impl Reply { + fn json(&self) -> serde_json::Value { + serde_json::from_str(&self.body).unwrap() + } +} + +fn request(method: Method, path: &str) -> axum::http::request::Builder { + let peer = SocketAddr::new(peer(), 4000); + let mut b = Request::builder().method(method).uri(path); + b.extensions_mut() + .unwrap() + .insert(axum::extract::ConnectInfo(peer)); + b +} + +fn post_json(path: &str, body: serde_json::Value) -> Request { + request(Method::POST, path) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body.to_string())) + .unwrap() +} + +fn empty(method: Method, path: &str) -> Request { + request(method, path).body(Body::empty()).unwrap() +} + +async fn send(app: &Router, req: Request) -> Reply { + let res = app.clone().oneshot(req).await.unwrap(); + let status = res.status(); + let headers = res.headers().clone(); + let bytes = to_bytes(res.into_body(), 4 * 1024 * 1024).await.unwrap(); + Reply { + status, + headers, + body: String::from_utf8_lossy(&bytes).into_owned(), + } +} + +fn totp(uri: &str, unix: u64) -> String { + totp_rs::Totp::from_url(uri) + .unwrap() + .generate(unix) + .to_string() +} + +fn fresh(transport: Transport) -> (tempfile::TempDir, Arc, Router) { + let dir = tempfile::tempdir().unwrap(); + let auth = Arc::new(AuthService::open(dir.path(), None).unwrap()); + let state = AppState::new( + Arc::new(Storage::open(dir.path()).unwrap()), + auth.clone(), + transport, + ); + (dir, auth, build_app(state)) +} + +/// Server with `root` (admin, MFA active) and analyst `ana` (no MFA). +fn harness(transport: Transport) -> H { + let (dir, auth, app) = fresh(transport); + let t = now(); + let code = auth.ensure_bootstrap(t).unwrap().unwrap(); + let pending = auth.complete_bootstrap(&code, "root", PW, t).unwrap(); + let e = auth.start_enrollment_pending(&pending.token, t).unwrap(); + let recovery = auth + .confirm_enrollment_pending(&pending.token, &totp(&e.uri, t), t) + .unwrap(); + auth.create_user("root", "ana", PW, Role::Analyst, t) + .unwrap(); + H { + _dir: dir, + auth, + app, + uri: e.uri, + recovery, + } +} + +fn cookie_pair(headers: &HeaderMap) -> Option { + headers + .get(header::SET_COOKIE) + .map(|v| v.to_str().unwrap().split(';').next().unwrap().to_string()) +} + +impl H { + async fn login(&self, user: &str) -> Reply { + send( + &self.app, + post_json( + "/api/auth/login", + serde_json::json!({"username": user, "password": PW}), + ), + ) + .await + } + + async fn analyst_cookie(&self) -> String { + let r = self.login("ana").await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + cookie_pair(&r.headers).unwrap() + } + + async fn admin_cookie(&self) -> String { + let r = self.login("root").await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(r.json()["step"], "mfa_required"); + let code = totp(&self.uri, now() + 30); + let m = send( + &self.app, + post_json( + "/api/auth/mfa", + serde_json::json!({"pending": r.json()["pending"], "code": code}), + ), + ) + .await; + assert_eq!(m.status, StatusCode::OK, "{}", m.body); + cookie_pair(&m.headers).unwrap() + } + + async fn csrf(&self, cookie: &str) -> String { + let r = send( + &self.app, + request(Method::GET, "/api/auth/state") + .header(header::COOKIE, cookie) + .body(Body::empty()) + .unwrap(), + ) + .await; + r.json()["csrf"].as_str().unwrap().to_string() + } + + /// A token of `root`, minted through the service. + async fn admin_token(&self, scope: Scope) -> String { + let cookie = self.admin_cookie().await; + self.token_from(&cookie, scope) + } + + /// A TOTP step works once, so a second token reuses the login's session. + fn token_from(&self, cookie: &str, scope: Scope) -> String { + let session = cookie.split_once('=').unwrap().1.to_string(); + let t = now(); + let id = self.auth.authenticate_session(&session, t).unwrap().user_id; + self.auth + .reauthenticate(&id, &session, PW, Some(&self.recovery[0]), t) + .unwrap(); + let p = self.auth.authenticate_session(&session, t).unwrap(); + self.auth + .create_api_token(&p, "t", scope, t + 3600, t) + .unwrap() + .token + } + + /// Mutation with cookie and CSRF. + async fn mutate( + &self, + cookie: &str, + method: Method, + path: &str, + body: serde_json::Value, + ) -> Reply { + let csrf = self.csrf(cookie).await; + send( + &self.app, + request(method, path) + .header(header::COOKIE, cookie) + .header("x-acaua-csrf", csrf) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + } +} + +fn verb_method(v: Verb) -> Method { + match v { + Verb::Get => Method::GET, + Verb::Post => Method::POST, + Verb::Patch => Method::PATCH, + Verb::Delete => Method::DELETE, + } +} + +fn is_closed(r: &Reply) -> bool { + r.status == StatusCode::UNAUTHORIZED || r.status == StatusCode::SEE_OTHER +} + +#[tokio::test] +async fn every_route_is_closed_by_default() { + let (_d, _a, app) = fresh(Transport::Local); + let mut checked = 0; + for route in ALL_ROUTES { + if PUBLIC_ROUTES.contains(&(route.verb, route.path)) { + continue; + } + let r = send(&app, empty(verb_method(route.verb), route.path)).await; + assert!(is_closed(&r), "{} answered {}", route.path, r.status); + checked += 1; + } + assert!(checked >= 15, "only {checked} protected routes"); + for path in [ + "/relatorio", + "/", + "/index.html", + "/app.js", + "/nao/existe", + "/api/nada", + ] { + let r = send(&app, empty(Method::GET, path)).await; + assert!(is_closed(&r), "{path} answered {}", r.status); + } + // A wrong method on a public path must not reveal the route with a 405. + let r = send(&app, empty(Method::POST, "/api/health")).await; + assert!(is_closed(&r), "POST /api/health answered {}", r.status); + let r = send(&app, empty(Method::DELETE, "/login.html")).await; + assert!(is_closed(&r)); +} + +#[test] +fn every_public_route_is_registered_and_the_list_is_exact() { + for entry in PUBLIC_ROUTES { + assert!( + ALL_ROUTES.iter().any(|r| (r.verb, r.path) == *entry), + "{} not registered", + entry.1 + ); + } + let mut paths: Vec<&str> = PUBLIC_ROUTES.iter().map(|e| e.1).collect(); + paths.sort_unstable(); + assert_eq!( + paths, + [ + "/api/auth/bootstrap", + "/api/auth/login", + "/api/auth/mfa", + "/api/auth/password-change-required", + "/api/auth/state", + "/api/health", + "/app.css", + "/i18n-en.js", + "/i18n.js", + "/login.html", + "/login.js", + "/logo.png", + ] + ); +} + +#[tokio::test] +async fn unknown_paths_answer_exactly_like_protected_ones() { + let (_d, _a, app) = fresh(Transport::Local); + for accept in ["application/json", "text/html"] { + let ask = |p: &str| { + request(Method::GET, p) + .header(header::ACCEPT, accept) + .body(Body::empty()) + .unwrap() + }; + let known = send(&app, ask("/relatorio")).await; + let unknown = send(&app, ask("/talvez-exista")).await; + assert_eq!(known.status, unknown.status); + assert_eq!(known.body, unknown.body); + assert_eq!( + known.headers.get(header::LOCATION), + unknown.headers.get(header::LOCATION) + ); + } +} + +#[tokio::test] +async fn public_route_without_an_asset_is_404_and_assets_are_served() { + let (_d, _a, app) = fresh(Transport::Local); + let r = send(&app, empty(Method::GET, "/login.html")).await; + assert_eq!(r.status, StatusCode::NOT_FOUND); + for path in ["/app.css", "/logo.png", "/i18n.js", "/i18n-en.js"] { + let r = send(&app, empty(Method::GET, path)).await; + assert_eq!(r.status, StatusCode::OK, "{path}"); + } +} + +#[tokio::test] +async fn health_has_no_details() { + let (_d, _a, app) = fresh(Transport::Local); + let r = send(&app, empty(Method::GET, "/api/health")).await; + assert_eq!(r.status, StatusCode::OK); + assert_eq!(r.body, r#"{"status":"ok"}"#); + assert!(!r.body.contains("version")); +} + +#[tokio::test] +async fn html_request_redirects_to_login_api_gets_401() { + let (_d, _a, app) = fresh(Transport::Local); + let html = request(Method::GET, "/relatorio") + .header(header::ACCEPT, "text/html,application/xhtml+xml") + .body(Body::empty()) + .unwrap(); + let r = send(&app, html).await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + assert_eq!(r.headers[header::LOCATION], "/login.html"); + let api = request(Method::GET, "/api/status") + .header(header::ACCEPT, "text/html") + .body(Body::empty()) + .unwrap(); + assert_eq!(send(&app, api).await.status, StatusCode::UNAUTHORIZED); + let r = send(&app, empty(Method::GET, "/relatorio")).await; + assert_eq!(r.status, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn cookie_flags() { + for (transport, secure) in [ + (Transport::Local, false), + ( + Transport::Tls { + cert: "c".into(), + key: "k".into(), + }, + true, + ), + ( + Transport::Proxy { + trusted: vec!["10.0.0.0/8".parse().unwrap()], + }, + true, + ), + ] { + let h = harness(transport); + let r = h.login("ana").await; + let set = r.headers[header::SET_COOKIE].to_str().unwrap().to_string(); + assert!(set.contains("HttpOnly"), "{set}"); + assert!(set.contains("SameSite=Strict"), "{set}"); + assert!(set.contains("Path=/"), "{set}"); + assert_eq!(set.contains("Secure"), secure, "{set}"); + // The session token travels only in the cookie. + let token = cookie_pair(&r.headers).unwrap(); + assert!(!r.body.contains(token.split_once('=').unwrap().1)); + } +} + +#[tokio::test] +async fn csrf_required_for_cookie_mutation() { + let h = harness(Transport::Local); + let cookie = h.admin_cookie().await; + let bare = request(Method::POST, "/api/analyze") + .header(header::COOKIE, &cookie) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(r#"{"path":"/nao/existe"}"#)) + .unwrap(); + assert_eq!(send(&h.app, bare).await.status, StatusCode::FORBIDDEN); + let wrong = request(Method::POST, "/api/analyze") + .header(header::COOKIE, &cookie) + .header("x-acaua-csrf", "wrong") + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(r#"{"path":"/nao/existe"}"#)) + .unwrap(); + assert_eq!(send(&h.app, wrong).await.status, StatusCode::FORBIDDEN); + let good = h + .mutate( + &cookie, + Method::POST, + "/api/analyze", + serde_json::json!({"path": "/nao/existe"}), + ) + .await; + assert_eq!(good.status, StatusCode::BAD_REQUEST, "{}", good.body); + let token = h.token_from(&cookie, Scope::Admin); + let bearer = request(Method::POST, "/api/analyze") + .header(header::AUTHORIZATION, format!("Bearer {token}")) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(r#"{"path":"/nao/existe"}"#)) + .unwrap(); + assert_eq!(send(&h.app, bearer).await.status, StatusCode::BAD_REQUEST); +} + +#[tokio::test] +async fn session_token_is_not_accepted_as_bearer() { + let h = harness(Transport::Local); + let cookie = h.analyst_cookie().await; + let session = cookie.split_once('=').unwrap().1; + let r = send( + &h.app, + request(Method::GET, "/api/status") + .header(header::AUTHORIZATION, format!("Bearer {session}")) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(r.status, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn analyst_forbidden_on_admin_routes() { + let h = harness(Transport::Local); + let cookie = h.analyst_cookie().await; + let csrf = h.csrf(&cookie).await; + for route in ALL_ROUTES.iter().filter(|r| r.access == Access::Admin) { + let r = send( + &h.app, + request(verb_method(route.verb), route.path) + .header(header::COOKIE, &cookie) + .header("x-acaua-csrf", &csrf) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(r.status, StatusCode::FORBIDDEN, "{}", route.path); + } + let status = send( + &h.app, + request(Method::GET, "/api/status") + .header(header::COOKIE, &cookie) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(status.status, StatusCode::OK); +} + +#[tokio::test] +async fn read_token_forbidden_on_admin_routes_and_every_mutation() { + let h = harness(Transport::Local); + let token = h.admin_token(Scope::Read).await; + let bearer = format!("Bearer {token}"); + for route in ALL_ROUTES { + let public = PUBLIC_ROUTES.contains(&(route.verb, route.path)); + if public || (route.access != Access::Admin && route.verb == Verb::Get) { + continue; + } + let r = send( + &h.app, + request(verb_method(route.verb), route.path) + .header(header::AUTHORIZATION, &bearer) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(r.status, StatusCode::FORBIDDEN, "{}", route.path); + } + for path in [ + "/api/status", + "/api/alerts", + "/relatorio", + "/api/auth/tokens", + ] { + let r = send( + &h.app, + request(Method::GET, path) + .header(header::AUTHORIZATION, &bearer) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert!( + r.status != StatusCode::UNAUTHORIZED && r.status != StatusCode::FORBIDDEN, + "{path}" + ); + } +} + +#[tokio::test] +async fn forwarded_for_ignored_unless_proxy() { + let h = harness(Transport::Local); + let mut last = None; + for i in 0..21 { + // Distinct unknown names, so only the per-IP limit can answer. + let req = request(Method::POST, "/api/auth/login") + .header(header::CONTENT_TYPE, "application/json") + .header("x-forwarded-for", format!("203.0.113.{i}")) + .body(Body::from( + serde_json::json!({"username": format!("ghost{i}"), "password": "x"}).to_string(), + )) + .unwrap(); + last = Some(send(&h.app, req).await); + } + let last = last.unwrap(); + assert_eq!(last.status, StatusCode::TOO_MANY_REQUESTS); + assert!(last.headers.contains_key(header::RETRY_AFTER)); + let audit = h.auth.audit_tail(5).unwrap(); + assert!(audit + .iter() + .all(|e| !serde_json::to_string(e).unwrap().contains("203.0.113"))); +} + +#[tokio::test] +async fn auth_responses_have_no_store() { + let h = harness(Transport::Local); + let replies = [ + send(&h.app, empty(Method::GET, "/api/auth/state")).await, + h.login("ana").await, + send( + &h.app, + post_json( + "/api/auth/login", + serde_json::json!({"username": "ana", "password": "nope"}), + ), + ) + .await, + send(&h.app, empty(Method::POST, "/api/auth/logout")).await, + send(&h.app, empty(Method::GET, "/api/status")).await, + ]; + for r in replies { + assert_eq!(r.headers[header::CACHE_CONTROL], "no-store", "{}", r.body); + } +} + +#[tokio::test] +async fn secrets_absent_from_responses() { + let h = harness(Transport::Local); + let token = h.admin_token(Scope::Admin).await; + let bearer = format!("Bearer {token}"); + for path in [ + "/api/admin/users", + "/api/admin/audit", + "/api/auth/sessions", + "/api/auth/tokens", + ] { + let r = send( + &h.app, + request(Method::GET, path) + .header(header::AUTHORIZATION, &bearer) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(r.status, StatusCode::OK, "{path}: {}", r.body); + for leak in [ + "$argon2", + "password_hash", + "token_hash", + "totp_sealed", + "recovery_hashes", + &token, + ] { + assert!(!r.body.contains(leak), "{leak} in {path}"); + } + } +} + +#[tokio::test] +async fn login_failures_are_identical_and_open_no_session() { + let h = harness(Transport::Local); + let attempt = |user: &str| { + post_json( + "/api/auth/login", + serde_json::json!({"username": user, "password": "wrong password"}), + ) + }; + let unknown = send(&h.app, attempt("ghost")).await; + let wrong = send(&h.app, attempt("ana")).await; + assert_eq!(unknown.status, StatusCode::UNAUTHORIZED); + assert_eq!(unknown.status, wrong.status); + assert_eq!(unknown.body, wrong.body); + assert!(!unknown.headers.contains_key(header::SET_COOKIE)); + assert!(!wrong.headers.contains_key(header::SET_COOKIE)); + let id = h + .auth + .list_users() + .unwrap() + .into_iter() + .find(|u| u.username == "ana") + .unwrap() + .id; + assert!(h.auth.list_sessions(&id, now()).unwrap().is_empty()); + // A cookie the client chose is never honoured or served back. + let r = send( + &h.app, + request(Method::GET, "/api/status") + .header(header::COOKIE, "acaua_session=chosen-by-attacker") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(r.status, StatusCode::UNAUTHORIZED); + assert!(!r.headers.contains_key(header::SET_COOKIE)); +} + +#[tokio::test] +async fn oversized_body_is_refused_before_processing() { + let (_d, _a, app) = fresh(Transport::Local); + let huge = "a".repeat(70 * 1024); + let r = send( + &app, + post_json( + "/api/auth/login", + serde_json::json!({"username": huge, "password": "x"}), + ), + ) + .await; + assert_eq!(r.status, StatusCode::PAYLOAD_TOO_LARGE); + assert!(!r.body.contains(&huge[..100])); +} + +#[tokio::test] +async fn first_login_enrolls_with_a_pending_token_only() { + let (_d, auth, app) = fresh(Transport::Local); + let code = auth.ensure_bootstrap(now()).unwrap().unwrap(); + let boot = send( + &app, + post_json( + "/api/auth/bootstrap", + serde_json::json!({"code": code, "username": "root", "password": PW}), + ), + ) + .await; + assert_eq!(boot.status, StatusCode::OK, "{}", boot.body); + assert!(!boot.headers.contains_key(header::SET_COOKIE)); + let pending = boot.json()["pending"].as_str().unwrap().to_string(); + + let anon = send(&app, empty(Method::POST, "/api/auth/enroll/start")).await; + assert_eq!(anon.status, StatusCode::UNAUTHORIZED); + let forged = request(Method::POST, "/api/auth/enroll/start") + .header("x-acaua-pending", "forged") + .body(Body::empty()) + .unwrap(); + assert_eq!(send(&app, forged).await.status, StatusCode::UNAUTHORIZED); + // The pending token opens enrollment and nothing else. + let other = request(Method::GET, "/api/status") + .header("x-acaua-pending", &pending) + .body(Body::empty()) + .unwrap(); + assert_eq!(send(&app, other).await.status, StatusCode::UNAUTHORIZED); + + let start = request(Method::POST, "/api/auth/enroll/start") + .header("x-acaua-pending", &pending) + .body(Body::empty()) + .unwrap(); + let start = send(&app, start).await; + assert_eq!(start.status, StatusCode::OK, "{}", start.body); + let uri = start.json()["uri"].as_str().unwrap().to_string(); + let confirm = request(Method::POST, "/api/auth/enroll/confirm") + .header("x-acaua-pending", &pending) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from( + serde_json::json!({"code": totp(&uri, now())}).to_string(), + )) + .unwrap(); + let confirm = send(&app, confirm).await; + assert_eq!(confirm.status, StatusCode::OK, "{}", confirm.body); + assert!(!confirm.json()["recovery_codes"] + .as_array() + .unwrap() + .is_empty()); + assert!(!confirm.headers.contains_key(header::SET_COOKIE)); + + // MFA is active now: the same token cannot enroll again. + let again = request(Method::POST, "/api/auth/enroll/start") + .header("x-acaua-pending", &pending) + .body(Body::empty()) + .unwrap(); + assert_eq!(send(&app, again).await.status, StatusCode::UNAUTHORIZED); + + let mfa = send( + &app, + post_json( + "/api/auth/mfa", + serde_json::json!({"pending": pending, "code": totp(&uri, now() + 30)}), + ), + ) + .await; + assert_eq!(mfa.status, StatusCode::OK, "{}", mfa.body); + assert!(cookie_pair(&mfa.headers).is_some()); +} + +#[tokio::test] +async fn enrolling_or_disabling_from_a_session_needs_recent_reauth() { + let h = harness(Transport::Local); + let cookie = h.analyst_cookie().await; + let start = "/api/auth/enroll/start"; + let disable = "/api/auth/mfa/disable"; + let nothing = serde_json::json!({}); + assert_eq!( + h.mutate(&cookie, Method::POST, start, nothing.clone()) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + h.mutate(&cookie, Method::POST, disable, nothing.clone()) + .await + .status, + StatusCode::FORBIDDEN + ); + let bad = h + .mutate( + &cookie, + Method::POST, + "/api/auth/reauth", + serde_json::json!({"password": "wrong password"}), + ) + .await; + assert_eq!(bad.status, StatusCode::UNAUTHORIZED); + let ok = h + .mutate( + &cookie, + Method::POST, + "/api/auth/reauth", + serde_json::json!({"password": PW}), + ) + .await; + assert_eq!(ok.status, StatusCode::OK, "{}", ok.body); + let r = h + .mutate(&cookie, Method::POST, start, nothing.clone()) + .await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!( + h.mutate(&cookie, Method::POST, disable, nothing) + .await + .status, + StatusCode::OK + ); +} + +#[tokio::test] +async fn confirm_from_a_session_ends_it_and_clears_the_cookie() { + let h = harness(Transport::Local); + let cookie = h.analyst_cookie().await; + h.mutate( + &cookie, + Method::POST, + "/api/auth/reauth", + serde_json::json!({"password": PW}), + ) + .await; + let start = h + .mutate( + &cookie, + Method::POST, + "/api/auth/enroll/start", + serde_json::json!({}), + ) + .await; + let uri = start.json()["uri"].as_str().unwrap().to_string(); + let r = h + .mutate( + &cookie, + Method::POST, + "/api/auth/enroll/confirm", + serde_json::json!({"code": totp(&uri, now())}), + ) + .await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert!(r.headers[header::SET_COOKIE] + .to_str() + .unwrap() + .contains("Max-Age=0")); +} + +#[tokio::test] +async fn required_password_change_opens_the_session_through_the_public_route() { + let h = harness(Transport::Local); + let temp = h.auth.reset_admin("root", now()).unwrap(); + let login = send( + &h.app, + post_json( + "/api/auth/login", + serde_json::json!({"username": "root", "password": temp}), + ), + ) + .await; + assert_eq!( + login.json()["step"], + "mfa_enroll_required", + "{}", + login.body + ); + let pending = login.json()["pending"].as_str().unwrap().to_string(); + let t = now(); + let e = h.auth.start_enrollment_pending(&pending, t).unwrap(); + h.auth + .confirm_enrollment_pending(&pending, &totp(&e.uri, t), t) + .unwrap(); + let mfa = send( + &h.app, + post_json( + "/api/auth/mfa", + serde_json::json!({"pending": pending, "code": totp(&e.uri, t + 30)}), + ), + ) + .await; + assert_eq!( + mfa.json()["step"], + "password_change_required", + "{}", + mfa.body + ); + assert!(!mfa.headers.contains_key(header::SET_COOKIE)); + let ticket = mfa.json()["pending"].as_str().unwrap().to_string(); + let done = send( + &h.app, + post_json( + "/api/auth/password-change-required", + serde_json::json!({"ticket": ticket, "current": temp, "new": PW2}), + ), + ) + .await; + assert_eq!(done.status, StatusCode::OK, "{}", done.body); + assert!(cookie_pair(&done.headers).is_some()); +} + +#[tokio::test] +async fn listings_are_limited_to_the_requester_unless_admin() { + let h = harness(Transport::Local); + let users = h.auth.list_users().unwrap(); + let root = users + .iter() + .find(|u| u.username == "root") + .unwrap() + .id + .clone(); + let cookie = h.analyst_cookie().await; + for base in ["/api/auth/sessions", "/api/auth/tokens"] { + let ask = |path: String, c: &str| { + request(Method::GET, &path) + .header(header::COOKIE, c) + .body(Body::empty()) + .unwrap() + }; + let own = send(&h.app, ask(base.to_string(), &cookie)).await; + assert_eq!(own.status, StatusCode::OK); + let other = send(&h.app, ask(format!("{base}?user_id={root}"), &cookie)).await; + assert_eq!(other.status, StatusCode::FORBIDDEN, "{base}"); + } + let admin = h.admin_cookie().await; + let ana = users + .iter() + .find(|u| u.username == "ana") + .unwrap() + .id + .clone(); + let r = send( + &h.app, + request(Method::GET, &format!("/api/auth/sessions?user_id={ana}")) + .header(header::COOKIE, &admin) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(r.status, StatusCode::OK); + assert_eq!(r.json().as_array().unwrap().len(), 1); +} + +#[tokio::test] +async fn logout_ends_the_session() { + let h = harness(Transport::Local); + let cookie = h.analyst_cookie().await; + let r = h + .mutate( + &cookie, + Method::POST, + "/api/auth/logout", + serde_json::json!({}), + ) + .await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert!(r.headers[header::SET_COOKIE] + .to_str() + .unwrap() + .contains("Max-Age=0")); + let after = send( + &h.app, + request(Method::GET, "/api/status") + .header(header::COOKIE, &cookie) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(after.status, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn token_lifecycle_needs_reauth_and_returns_the_secret_once() { + let h = harness(Transport::Local); + let cookie = h.analyst_cookie().await; + let body = serde_json::json!({"name": "ci", "scope": "read", "expires_at": now() + 3600}); + let early = h + .mutate(&cookie, Method::POST, "/api/auth/tokens", body.clone()) + .await; + assert_eq!(early.status, StatusCode::FORBIDDEN); + h.mutate( + &cookie, + Method::POST, + "/api/auth/reauth", + serde_json::json!({"password": PW}), + ) + .await; + let made = h + .mutate(&cookie, Method::POST, "/api/auth/tokens", body) + .await; + assert_eq!(made.status, StatusCode::OK, "{}", made.body); + let id = made.json()["id"].as_str().unwrap().to_string(); + let secret = made.json()["token"].as_str().unwrap().to_string(); + let gone = h + .mutate( + &cookie, + Method::DELETE, + "/api/auth/tokens", + serde_json::json!({"id": id}), + ) + .await; + assert_eq!(gone.status, StatusCode::OK, "{}", gone.body); + let r = send( + &h.app, + request(Method::GET, "/api/status") + .header(header::AUTHORIZATION, format!("Bearer {secret}")) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(r.status, StatusCode::UNAUTHORIZED); +} + +#[test] +fn login_step_debug_never_prints_the_token() { + let step = LoginStep::MfaRequired(acaua_core::auth::PendingMfa { + token: "s3cret".to_string(), + expires_at: 1, + }); + assert!(!format!("{step:?}").contains("s3cret")); +} diff --git a/crates/acaua-core/src/auth/mod.rs b/crates/acaua-core/src/auth/mod.rs index 927ee12..61deca4 100644 --- a/crates/acaua-core/src/auth/mod.rs +++ b/crates/acaua-core/src/auth/mod.rs @@ -12,9 +12,9 @@ pub mod tokens; pub use audit::{AuditEntry, AuditEvent, AuditLog}; pub use secrets::{hash_token, random_token, Secrets}; -pub use service::{AuthService, LoginStep, NewSession, PendingMfa, TotpEnrollment}; +pub use service::{AuthService, LoginStep, NewSession, PendingMfa, TotpEnrollment, UserView}; pub use store::{ApiToken, AuthState, AuthStore, Bootstrap, Role, Scope, Session, User}; -pub use tokens::{NewToken, Principal, SessionView, TokenView, Via}; +pub use tokens::{csrf_matches, csrf_token, NewToken, Principal, SessionView, TokenView, Via}; use crate::error::Result; use fs2::FileExt; diff --git a/crates/acaua-core/src/auth/service.rs b/crates/acaua-core/src/auth/service.rs index e2256f9..f7ee06a 100644 --- a/crates/acaua-core/src/auth/service.rs +++ b/crates/acaua-core/src/auth/service.rs @@ -87,6 +87,17 @@ impl std::fmt::Debug for TotpEnrollment { } } +/// Listing view of an account: no hash, no secret. +#[derive(Debug, Clone, Serialize)] +pub struct UserView { + pub id: String, + pub username: String, + pub role: Role, + pub created_at: u64, + pub mfa_enabled: bool, + pub must_change_password: bool, +} + #[derive(Serialize, Deserialize)] struct PendingClaims { purpose: String, @@ -141,6 +152,15 @@ fn validate_username(username: &str) -> Result { Ok(name) } +/// With a pending token's epoch: the account must still be the one the token +/// was issued for, and must still have no active second factor. +fn check_pending_epoch(u: &User, pending_epoch: Option) -> Result<()> { + match pending_epoch { + Some(epoch) if u.auth_epoch != epoch || u.totp_sealed.is_some() => Err(invalid()), + _ => Ok(()), + } +} + fn has_admin(st: &AuthState) -> bool { st.users.iter().any(|u| u.role == Role::Admin) } @@ -564,8 +584,31 @@ impl AuthService { } /// Starts (or restarts) enrollment. An active secret stays in force until - /// `confirm_enrollment` replaces it. + /// `confirm_enrollment` replaces it. Callers must have checked that the + /// actor may do this; a pending token goes through + /// `start_enrollment_pending`. pub fn start_enrollment(&self, user_id: &str, _now: u64) -> Result { + self.start_enrollment_guarded(user_id, None) + } + + /// Enrollment with only a pending token. `pending_user` alone would leave + /// a gap: the token is re-checked inside the update that stores the secret. + pub fn start_enrollment_pending(&self, pending: &str, now: u64) -> Result { + let claims = self.open_pending(pending, PENDING_PURPOSE, now)?; + self.start_enrollment_guarded(&claims.user_id, Some(claims.epoch)) + } + + fn start_enrollment_guarded( + &self, + user_id: &str, + pending_epoch: Option, + ) -> Result { + let missing = || -> AcauaError { + match pending_epoch { + Some(_) => invalid(), + None => AuthFailure::UserNotFound.into(), + } + }; let name = self .store .read(|st| { @@ -574,7 +617,7 @@ impl AuthService { .find(|u| u.id == user_id) .map(|u| u.username.clone()) })? - .ok_or(AuthFailure::UserNotFound)?; + .ok_or_else(missing)?; let secret = new_totp_secret(); let (uri, qr_png_base64) = totp_uri_and_qr(&secret, &name)?; let manual_key = manual_key(&uri).ok_or_else(|| { @@ -582,7 +625,9 @@ impl AuthService { })?; let sealed = self.secrets.seal(&secret)?; self.store.update(|st| { - user_or_missing(st, user_id)?.totp_pending_sealed = Some(sealed); + let u = user_mut(st, user_id).ok_or_else(missing)?; + check_pending_epoch(u, pending_epoch)?; + u.totp_pending_sealed = Some(sealed); Ok(()) })?; self.log("mfa.enroll.start", Some(&name), None, true, None)?; @@ -595,11 +640,38 @@ impl AuthService { /// Activates the started secret and returns the recovery codes, shown only /// here. The accepted step is spent, so finishing a login needs a later - /// code. Ends every session of the user. + /// code. Ends every session of the user. A pending token goes through + /// `confirm_enrollment_pending`. pub fn confirm_enrollment(&self, user_id: &str, code: &str, now: u64) -> Result> { + self.confirm_enrollment_guarded(user_id, None, code, now) + } + + /// As `start_enrollment_pending`: two racing requests get one activation, + /// and the loser cannot replace the factor the winner just set. + pub fn confirm_enrollment_pending( + &self, + pending: &str, + code: &str, + now: u64, + ) -> Result> { + let claims = self.open_pending(pending, PENDING_PURPOSE, now)?; + self.confirm_enrollment_guarded(&claims.user_id, Some(claims.epoch), code, now) + } + + fn confirm_enrollment_guarded( + &self, + user_id: &str, + pending_epoch: Option, + code: &str, + now: u64, + ) -> Result> { let (texts, hashes) = new_recovery_codes(); let (name, accepted) = self.store.update(|st| { - let u = user_or_missing(st, user_id)?; + let u = match pending_epoch { + Some(_) => user_mut(st, user_id).ok_or_else(invalid)?, + None => user_or_missing(st, user_id)?, + }; + check_pending_epoch(u, pending_epoch)?; let sealed = u .totp_pending_sealed .clone() @@ -626,6 +698,23 @@ impl AuthService { Ok(texts) } + /// Every account, without credentials. Authorization is the caller's. + pub fn list_users(&self) -> Result> { + self.store.read(|st| { + st.users + .iter() + .map(|u| UserView { + id: u.id.clone(), + username: u.username.clone(), + role: u.role, + created_at: u.created_at, + mfa_enabled: u.totp_sealed.is_some(), + must_change_password: u.must_change_password, + }) + .collect() + }) + } + /// `actor` names who acted, for the audit log. Authorization is the /// caller's. Returns the new user's id. pub fn create_user( diff --git a/crates/acaua-core/src/auth/service_tests.rs b/crates/acaua-core/src/auth/service_tests.rs index c44693a..323e699 100644 --- a/crates/acaua-core/src/auth/service_tests.rs +++ b/crates/acaua-core/src/auth/service_tests.rs @@ -945,3 +945,94 @@ fn change_password_clears_flag_and_refuses_the_same_password() { .unwrap(); assert!(!flag); } + +// ---- Enrollment through a pending token: re-checked inside the update ---- + +fn first_admin(s: &AuthService) -> PendingMfa { + let code = s.ensure_bootstrap(T0).unwrap().unwrap(); + s.complete_bootstrap(&code, "root", PW, T0).unwrap() +} + +fn root_id(s: &AuthService) -> String { + s.store + .read(|st| { + st.users + .iter() + .find(|u| u.username == "root") + .unwrap() + .id + .clone() + }) + .unwrap() +} + +fn code_from_uri(uri: &str, unix: u64) -> String { + totp_rs::Totp::from_url(uri) + .unwrap() + .generate(unix) + .to_string() +} + +#[test] +fn pending_enrollment_activates_mfa_and_then_refuses_the_token() { + let dir = tempfile::tempdir().unwrap(); + let s = AuthService::open(dir.path(), None).unwrap(); + let pending = first_admin(&s); + let e = s.start_enrollment_pending(&pending.token, T0).unwrap(); + let codes = s + .confirm_enrollment_pending(&pending.token, &code_from_uri(&e.uri, T0), T0) + .unwrap(); + assert!(!codes.is_empty()); + // A password alone can never replace a second factor that is now active. + assert!(s.start_enrollment_pending(&pending.token, T0).is_err()); + assert!(s + .confirm_enrollment_pending(&pending.token, &code_from_uri(&e.uri, T0 + 30), T0 + 30) + .is_err()); + // The same token still finishes the login, with a later code. + let step = s + .confirm_mfa(&pending.token, &code_from_uri(&e.uri, T0 + 30), T0 + 30) + .unwrap(); + assert!(matches!(step, LoginStep::Session(_))); +} + +#[test] +fn pending_enrollment_refuses_a_stale_epoch_and_other_purposes() { + let dir = tempfile::tempdir().unwrap(); + let s = AuthService::open(dir.path(), None).unwrap(); + let pending = first_admin(&s); + let e = s.start_enrollment_pending(&pending.token, T0).unwrap(); + let id = root_id(&s); + s.store + .update(|st| { + st.users.iter_mut().find(|u| u.id == id).unwrap().auth_epoch += 1; + Ok(()) + }) + .unwrap(); + assert!(s.start_enrollment_pending(&pending.token, T0).is_err()); + assert!(s + .confirm_enrollment_pending(&pending.token, &code_from_uri(&e.uri, T0), T0) + .is_err()); + assert!(s.start_enrollment_pending("forged", T0).is_err()); +} + +#[test] +fn list_users_exposes_no_secret_material() { + let dir = tempfile::tempdir().unwrap(); + let s = AuthService::open(dir.path(), None).unwrap(); + first_admin(&s); + let json = serde_json::to_string(&s.list_users().unwrap()).unwrap(); + assert!(json.contains("root")); + for leak in ["password_hash", "recovery", "totp_", "$argon2"] { + assert!(!json.contains(leak), "{leak} in {json}"); + } +} + +#[test] +fn csrf_value_is_bound_to_the_session_and_is_not_its_token_hash() { + let a = crate::auth::tokens::csrf_token("session-a"); + assert_ne!(a, crate::auth::tokens::csrf_token("session-b")); + assert_ne!(a, hash_token("session-a")); + assert!(crate::auth::tokens::csrf_matches("session-a", &a)); + assert!(!crate::auth::tokens::csrf_matches("session-b", &a)); + assert!(!crate::auth::tokens::csrf_matches("session-a", "")); +} diff --git a/crates/acaua-core/src/auth/tokens.rs b/crates/acaua-core/src/auth/tokens.rs index ba023d1..aa70392 100644 --- a/crates/acaua-core/src/auth/tokens.rs +++ b/crates/acaua-core/src/auth/tokens.rs @@ -85,6 +85,17 @@ pub struct TokenView { pub expires_at: u64, } +/// The anti-CSRF value of a session. Derived from the session token with a +/// domain prefix, so it needs no storage, dies with the session, and differs +/// from the digest kept in the store. +pub fn csrf_token(session_token: &str) -> String { + hash_token(&format!("acaua-csrf:{session_token}")) +} + +pub fn csrf_matches(session_token: &str, candidate: &str) -> bool { + ct_eq(&csrf_token(session_token), candidate) +} + fn ct_eq(a: &str, b: &str) -> bool { a.as_bytes().ct_eq(b.as_bytes()).into() }