fix(auth): close unauthenticated lockout and tighten the daemon's edges

Key login failures by username and client address with decay, plus a loose
per-username limit that delays every address by a bounded time. Refused
attempts write nothing. Unknown usernames share the code path. MFA and session
password checks keep a persistent user-bound count that needs a password or a
session to reach.

Also: local mode refuses a non-loopback bind outside a container; security
headers on every response; the Argon2 permit lives as long as the blocking
task; a required password change rechecks role, MFA and epoch; auth reset
works for any user; mfa_enabled in /api/auth/state; disabling MFA that is off
is refused with no side effects; StateCorrupt keeps only line and column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 21:03:27 -03:00
1 parent 3e4c4201e5
commit 348e61ca95
10 files changed
+725 -199

No files matched your search

+18 -2
View File
@@ -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<T, AcauaError> + 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<Role>,
#[serde(skip_serializing_if = "Option::is_none")]
mfa_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
csrf: Option<String>,
}
@@ -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,
},
}))
+7 -4
View File
@@ -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 {
+55
View File
@@ -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<String>) -> Result<()> {
if !matches!(self, Transport::Local) || env("ACAUA_RUNTIME").as_deref() == Some("container")
{
return Ok(());
}
let loopback = match bind.parse::<SocketAddr>() {
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");
+31 -1
View File
@@ -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<AppState>, 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 `<style>` elements while it paginates.
/// Scripts stay same-origin only. `data:` images are the report's embedded logo
/// and the MFA QR code.
pub(crate) const CSP: &str = "default-src 'none'; script-src 'self'; \
style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; \
connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'";
/// On every response, refusals included.
async fn security_headers(req: Request, next: Next) -> Response {
let mut response = next.run(req).await;
let headers = response.headers_mut();
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(CSP),
);
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
headers.insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
response
}
#[derive(Serialize)]
struct Health {
status: &'static str,
@@ -418,6 +447,7 @@ pub async fn serve(bind: &str, data_dir: PathBuf) -> Result<()> {
// Decide the exposure before touching the data directory or printing a
// setup code: a refusal must leave nothing behind.
let transport = Transport::from_env(&|name| std::env::var(name).ok())?;
transport.check_bind(bind, &|name| std::env::var(name).ok())?;
let _ = tracing_subscriber::fmt().try_init();
std::fs::create_dir_all(&data_dir)?;
let auth = Arc::new(AuthService::open(
+38 -2
View File
@@ -770,11 +770,12 @@ async fn enrolling_or_disabling_from_a_session_needs_recent_reauth() {
.mutate(&cookie, Method::POST, start, nothing.clone())
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
// Past the reauth check; this analyst never activated MFA.
assert_eq!(
h.mutate(&cookie, Method::POST, disable, nothing)
.await
.status,
StatusCode::OK
StatusCode::CONFLICT
);
}
@@ -816,7 +817,7 @@ async fn confirm_from_a_session_ends_it_and_clears_the_cookie() {
#[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 temp = h.auth.reset_account("root", now()).unwrap();
let login = send(
&h.app,
post_json(
@@ -1144,3 +1145,38 @@ fn secret_key_file_comes_from_the_environment() {
Some(PathBuf::from("/run/secrets/acaua_key"))
);
}
#[tokio::test]
async fn every_response_carries_the_security_headers() {
let h = harness(Transport::Local);
for path in ["/login.html", "/api/health", "/api/alerts", "/nope"] {
let r = send(&h.app, empty(Method::GET, path)).await;
let get = |name: header::HeaderName| r.headers.get(name).unwrap().to_str().unwrap();
let csp = get(header::CONTENT_SECURITY_POLICY);
assert!(csp.contains("frame-ancestors 'none'"), "{path}");
assert!(csp.contains("script-src 'self'"), "{path}");
assert!(!csp.contains("script-src 'self' 'unsafe"), "{path}");
assert_eq!(get(header::X_FRAME_OPTIONS), "DENY", "{path}");
assert_eq!(get(header::X_CONTENT_TYPE_OPTIONS), "nosniff", "{path}");
assert_eq!(get(header::REFERRER_POLICY), "no-referrer", "{path}");
}
}
#[tokio::test]
async fn auth_state_tells_whether_mfa_is_on() {
let h = harness(Transport::Local);
let anon = send(&h.app, empty(Method::GET, "/api/auth/state")).await;
assert!(anon.json().get("mfa_enabled").is_none());
let state = |c: &str| {
request(Method::GET, "/api/auth/state")
.header(header::COOKIE, c)
.body(Body::empty())
.unwrap()
};
let cookie = h.analyst_cookie().await;
let off = send(&h.app, state(&cookie)).await;
assert_eq!(off.json()["mfa_enabled"], serde_json::json!(false));
let cookie = h.admin_cookie().await;
let on = send(&h.app, state(&cookie)).await;
assert_eq!(on.json()["mfa_enabled"], serde_json::json!(true));
}