diff --git a/crates/acaua-cli/src/auth_http.rs b/crates/acaua-cli/src/auth_http.rs index 148bd9c..00896d9 100644 --- a/crates/acaua-cli/src/auth_http.rs +++ b/crates/acaua-cli/src/auth_http.rs @@ -80,6 +80,7 @@ fn failure_response(f: &AuthFailure) -> Response { 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::MfaNotEnabled => (StatusCode::CONFLICT, "MFA is not enabled"), 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"), @@ -153,8 +154,19 @@ where T: Send + 'static, F: FnOnce() -> Result + Send + 'static, { - let _permit = state.argon2.acquire().await.map_err(|_| internal())?; - blocking(f).await + // The permit moves into the closure: a dropped request cancels this future + // but not the blocking task, whose Argon2 run must keep its slot to the end. + let permit = state + .argon2 + .clone() + .acquire_owned() + .await + .map_err(|_| internal())?; + blocking(move || { + let _permit = permit; + f() + }) + .await } // ---- Credentials ---------------------------------------------------------- @@ -460,6 +472,8 @@ pub struct StateReply { #[serde(skip_serializing_if = "Option::is_none")] role: Option, #[serde(skip_serializing_if = "Option::is_none")] + mfa_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] csrf: Option, } @@ -480,6 +494,7 @@ pub async fn auth_state( Some((p, csrf)) => StateReply { setup_required, authenticated: true, + mfa_enabled: Some(auth.mfa_enabled(&p.user_id)?), username: Some(p.username), role: Some(p.role), csrf: Some(csrf), @@ -489,6 +504,7 @@ pub async fn auth_state( authenticated: false, username: None, role: None, + mfa_enabled: None, csrf: None, }, })) diff --git a/crates/acaua-cli/src/main.rs b/crates/acaua-cli/src/main.rs index a9039e0..5811f98 100644 --- a/crates/acaua-cli/src/main.rs +++ b/crates/acaua-cli/src/main.rs @@ -46,8 +46,9 @@ enum Command { #[derive(Subcommand)] enum AuthAction { - /// Resets an administrator: removes MFA and sessions, prints a temporary - /// password once. The next login enrolls MFA again and changes the password. + /// Resets an account: removes MFA, sessions and tokens, prints a temporary + /// password once. The next login changes the password; an administrator + /// also enrolls MFA again. Reset { #[arg(long)] username: String, @@ -73,9 +74,11 @@ async fn run(cli: Cli) -> acaua_core::Result<()> { } => { let key = web::secret_key_file(&|name| std::env::var(name).ok()); let auth = acaua_core::auth::AuthService::open(&data_dir, key.as_deref())?; - let temp = auth.reset_admin(&username, auth_http::unix_now())?; + let temp = auth.reset_account(&username, auth_http::unix_now())?; println!("Senha temporária (exibida uma única vez): {temp}"); - println!("O próximo login exige novo cadastro de MFA e troca de senha."); + println!( + "O próximo login exige troca de senha e, para administradores, novo cadastro de MFA." + ); Ok(()) } Command::Analyze { diff --git a/crates/acaua-cli/src/transport.rs b/crates/acaua-cli/src/transport.rs index eb4dc3d..7acc758 100644 --- a/crates/acaua-cli/src/transport.rs +++ b/crates/acaua-cli/src/transport.rs @@ -75,6 +75,30 @@ impl Transport { } } + /// `local` means plain HTTP for this machine only. In a container the + /// daemon must listen on all interfaces to be published at all, so there + /// `ACAUA_PUBLISHED` decides (see `from_env`); elsewhere the bind does. + pub fn check_bind(&self, bind: &str, env: &impl Fn(&str) -> Option) -> Result<()> { + if !matches!(self, Transport::Local) || env("ACAUA_RUNTIME").as_deref() == Some("container") + { + return Ok(()); + } + let loopback = match bind.parse::() { + Ok(addr) => addr.ip().to_canonical().is_loopback(), + Err(_) => bind + .rsplit_once(':') + .is_some_and(|(host, _)| host.eq_ignore_ascii_case("localhost")), + }; + if loopback { + return Ok(()); + } + Err(AcauaError::InvalidInput(format!( + "ACAUA_TRANSPORT=local refuses --bind {bind}: the dashboard would be reachable \ + over plain HTTP from the network. Bind to 127.0.0.1 or [::1], or set \ + ACAUA_TRANSPORT to tls or proxy" + ))) + } + /// Browsers should be pinned to HTTPS only when HTTPS is what they use. pub fn hsts(&self) -> bool { !matches!(self, Transport::Local) @@ -136,6 +160,37 @@ mod tests { s.parse().unwrap() } + #[test] + fn local_mode_refuses_a_network_bind_outside_a_container() { + let bare = |_: &str| None; + let local = Transport::Local; + for ok in [ + "127.0.0.1:8787", + "[::1]:8787", + "localhost:8787", + "127.9.9.9:1", + ] { + assert!(local.check_bind(ok, &bare).is_ok(), "{ok}"); + } + for bad in [ + "0.0.0.0:8787", + "[::]:8787", + "192.0.2.1:8787", + "example.org:80", + "nonsense", + ] { + let err = local.check_bind(bad, &bare).unwrap_err().to_string(); + assert!(err.contains("--bind"), "{err}"); + } + // In the image ACAUA_PUBLISHED is the control, not the bind. + let container = |n: &str| (n == "ACAUA_RUNTIME").then(|| "container".to_string()); + assert!(local.check_bind("0.0.0.0:8787", &container).is_ok()); + let other = |n: &str| (n == "ACAUA_RUNTIME").then(|| "host".to_string()); + assert!(local.check_bind("0.0.0.0:8787", &other).is_err()); + // Other modes protect the network themselves. + assert!(proxy().check_bind("0.0.0.0:8787", &bare).is_ok()); + } + #[test] fn forwarded_for_counts_only_from_a_trusted_proxy() { let forged = xff("203.0.113.9"); diff --git a/crates/acaua-cli/src/web.rs b/crates/acaua-cli/src/web.rs index 1ea5019..cd739dc 100644 --- a/crates/acaua-cli/src/web.rs +++ b/crates/acaua-cli/src/web.rs @@ -10,7 +10,7 @@ use axum::body::Body; use axum::extract::Request; use axum::extract::{DefaultBodyLimit, Query, State}; use axum::http::{header, HeaderValue, Method, StatusCode, Uri}; -use axum::middleware::{from_fn_with_state, Next}; +use axum::middleware::{from_fn, from_fn_with_state, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, patch, post, MethodRouter}; use axum::{Json, Router}; @@ -238,6 +238,7 @@ pub fn build_app(state: AppState) -> Router { .layer(DefaultBodyLimit::max(auth_http::MAX_BODY_BYTES)) .layer(from_fn_with_state(state.clone(), require_auth)) .layer(from_fn_with_state(state.clone(), hsts)) + .layer(from_fn(security_headers)) .with_state(state) .layer(CompressionLayer::new()) .layer(TraceLayer::new_for_http()) @@ -256,6 +257,34 @@ async fn hsts(State(state): State, req: Request, next: Next) -> Respon response } +/// `style-src 'unsafe-inline'` is the narrowest that works: the report carries +/// its stylesheet inline and Paged.js adds `