feat(auth): explicit transport modes

ACAUA_TRANSPORT (local, tls, proxy) is now required; a missing or invalid
value stops the daemon. local refuses a non-loopback ACAUA_PUBLISHED, tls
serves HTTPS via axum-server/rustls, proxy needs ACAUA_TRUSTED_PROXIES.
HSTS is sent in tls and proxy modes. The image defaults to local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 20:03:00 -03:00
1 parent 5ad89d5be5
commit dc8c7fa248
8 files changed
+430 -19

No files matched your search

+162 -4
View File
@@ -1,14 +1,12 @@
//! How requests reach the daemon: this decides which client address can be
//! believed and whether cookies may be marked `Secure`.
use acaua_core::{AcauaError, Result};
use axum::http::HeaderMap;
use ipnet::IpNet;
use std::net::IpAddr;
use std::net::{IpAddr, SocketAddr};
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,
@@ -17,6 +15,71 @@ pub enum Transport {
}
impl Transport {
/// Reads the mode from the environment. There is no default: a daemon
/// that guesses how it is exposed can end up serving plain HTTP on a
/// network by accident.
pub fn from_env(env: &impl Fn(&str) -> Option<String>) -> Result<Transport> {
let get = |name: &str| env(name).filter(|v| !v.trim().is_empty());
let required = |mode: &str, name: &str| {
get(name).ok_or_else(|| {
AcauaError::InvalidInput(format!("ACAUA_TRANSPORT={mode} requires {name}"))
})
};
let mode = get("ACAUA_TRANSPORT").ok_or_else(|| {
AcauaError::InvalidInput(
"ACAUA_TRANSPORT is not set; choose one of: local, tls, proxy".into(),
)
})?;
match mode.trim() {
"local" => {
if let Some(published) = env("ACAUA_PUBLISHED") {
let loopback = published
.trim()
.parse::<SocketAddr>()
.is_ok_and(|addr| addr.ip().to_canonical().is_loopback());
if !loopback {
return Err(AcauaError::InvalidInput(format!(
"ACAUA_TRANSPORT=local refuses ACAUA_PUBLISHED={published}: \
the dashboard would be reachable over plain HTTP from the network. \
Publish on 127.0.0.1 or [::1], or set ACAUA_TRANSPORT to tls or proxy"
)));
}
}
Ok(Transport::Local)
}
"tls" => Ok(Transport::Tls {
cert: required("tls", "ACAUA_TLS_CERT")?.into(),
key: required("tls", "ACAUA_TLS_KEY")?.into(),
}),
"proxy" => {
let list = required("proxy", "ACAUA_TRUSTED_PROXIES")?;
let mut trusted = Vec::new();
for item in list.split(',').map(str::trim).filter(|i| !i.is_empty()) {
let net = item.parse::<IpNet>().map_err(|_| {
AcauaError::InvalidInput(format!(
"ACAUA_TRUSTED_PROXIES: `{item}` is not a CIDR such as 10.0.0.0/8"
))
})?;
trusted.push(net);
}
if trusted.is_empty() {
return Err(AcauaError::InvalidInput(
"ACAUA_TRANSPORT=proxy requires ACAUA_TRUSTED_PROXIES".into(),
));
}
Ok(Transport::Proxy { trusted })
}
other => Err(AcauaError::InvalidInput(format!(
"ACAUA_TRANSPORT=`{other}` is not valid; choose one of: local, tls, proxy"
))),
}
}
/// Browsers should be pinned to HTTPS only when HTTPS is what they use.
pub fn hsts(&self) -> bool {
!matches!(self, Transport::Local)
}
/// 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.
@@ -109,6 +172,101 @@ mod tests {
}
}
fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
move |k| {
pairs
.iter()
.find(|(name, _)| *name == k)
.map(|(_, v)| (*v).to_string())
}
}
fn err(pairs: &[(&str, &str)]) -> String {
Transport::from_env(&env(pairs)).unwrap_err().to_string()
}
#[test]
fn missing_or_invalid_mode_fails() {
assert!(err(&[]).contains("ACAUA_TRANSPORT"));
let bad = err(&[("ACAUA_TRANSPORT", "xyz")]);
assert!(bad.contains("xyz") && bad.contains("local"), "{bad}");
assert!(err(&[("ACAUA_TRANSPORT", "")]).contains("ACAUA_TRANSPORT"));
}
#[test]
fn local_refuses_non_loopback_publish() {
let local = |published: &'static str| {
Transport::from_env(&env(&[
("ACAUA_TRANSPORT", "local"),
("ACAUA_PUBLISHED", published),
]))
};
for bad in [
"0.0.0.0:8787",
"192.168.1.5:8787",
"[::]:8787",
"garbage",
"",
] {
let e = local(bad).unwrap_err().to_string();
assert!(e.contains("ACAUA_PUBLISHED"), "{bad}: {e}");
}
for ok in ["127.0.0.1:8787", "[::1]:8787", "127.0.0.2:80"] {
assert!(matches!(local(ok), Ok(Transport::Local)), "{ok}");
}
assert!(matches!(
Transport::from_env(&env(&[("ACAUA_TRANSPORT", "local")])),
Ok(Transport::Local)
));
}
#[test]
fn tls_requires_cert_and_key() {
assert!(err(&[("ACAUA_TRANSPORT", "tls")]).contains("ACAUA_TLS_CERT"));
assert!(
err(&[("ACAUA_TRANSPORT", "tls"), ("ACAUA_TLS_CERT", "/c.pem")])
.contains("ACAUA_TLS_KEY")
);
assert!(
err(&[("ACAUA_TRANSPORT", "tls"), ("ACAUA_TLS_KEY", "/k.pem")])
.contains("ACAUA_TLS_CERT")
);
let t = Transport::from_env(&env(&[
("ACAUA_TRANSPORT", "tls"),
("ACAUA_TLS_CERT", "/c.pem"),
("ACAUA_TLS_KEY", "/k.pem"),
]))
.unwrap();
assert!(matches!(t, Transport::Tls { cert, key }
if cert.as_path() == std::path::Path::new("/c.pem") && key.as_path() == std::path::Path::new("/k.pem")));
}
#[test]
fn proxy_requires_trusted_list() {
let base = ("ACAUA_TRANSPORT", "proxy");
assert!(err(&[base]).contains("ACAUA_TRUSTED_PROXIES"));
assert!(err(&[base, ("ACAUA_TRUSTED_PROXIES", " , ")]).contains("ACAUA_TRUSTED_PROXIES"));
let bad = err(&[base, ("ACAUA_TRUSTED_PROXIES", "10.0.0.0/8,nope")]);
assert!(bad.contains("nope"), "{bad}");
let t = Transport::from_env(&env(&[
base,
("ACAUA_TRUSTED_PROXIES", "10.0.0.0/8, 172.18.0.2/32"),
]))
.unwrap();
assert!(matches!(t, Transport::Proxy { trusted } if trusted.len() == 2));
}
#[test]
fn hsts_only_in_tls_and_proxy() {
assert!(!Transport::Local.hsts());
assert!(proxy().hsts());
assert!(Transport::Tls {
cert: "c".into(),
key: "k".into()
}
.hsts());
}
#[test]
fn only_local_cookies_lack_secure() {
assert!(!Transport::Local.cookie_secure());
+64 -13
View File
@@ -5,20 +5,24 @@ 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 acaua_core::{update, AcauaError, Result};
use axum::body::Body;
use axum::extract::Request;
use axum::extract::{DefaultBodyLimit, Query, State};
use axum::http::{header, Method, StatusCode, Uri};
use axum::middleware::from_fn_with_state;
use axum::http::{header, HeaderValue, Method, StatusCode, Uri};
use axum::middleware::{from_fn_with_state, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, patch, post, MethodRouter};
use axum::{Json, Router};
use axum_server::tls_rustls::RustlsConfig;
use axum_server::Handle;
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::sync::Semaphore;
use tower_http::compression::CompressionLayer;
@@ -233,11 +237,25 @@ pub fn build_app(state: AppState) -> Router {
// 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))
.layer(from_fn_with_state(state.clone(), hsts))
.with_state(state)
.layer(CompressionLayer::new())
.layer(TraceLayer::new_for_http())
}
/// Adds `Strict-Transport-Security` when the transport is HTTPS. It sits
/// outside `require_auth`, so refusals carry it too.
async fn hsts(State(state): State<AppState>, req: Request, next: Next) -> Response {
let mut response = next.run(req).await;
if state.transport.hsts() {
response.headers_mut().insert(
header::STRICT_TRANSPORT_SECURITY,
HeaderValue::from_static("max-age=31536000"),
);
}
response
}
#[derive(Serialize)]
struct Health {
status: &'static str,
@@ -389,22 +407,55 @@ async fn shutdown_signal() {
}
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())?;
let _ = tracing_subscriber::fmt().try_init();
std::fs::create_dir_all(&data_dir)?;
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.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(shutdown_signal())
.await?;
let tls = match &transport {
Transport::Tls { cert, key } => Some((cert.clone(), key.clone())),
_ => None,
};
let state = AppState::new(Arc::new(Storage::open(&data_dir)?), auth, transport);
let service = build_app(state).into_make_service_with_connect_info::<SocketAddr>();
match tls {
None => {
let listener = TcpListener::bind(bind).await?;
println!("Acauã listening on http://{bind}");
axum::serve(listener, service)
.with_graceful_shutdown(shutdown_signal())
.await?;
}
Some((cert, key)) => {
let addr: SocketAddr = bind.parse().map_err(|_| {
AcauaError::InvalidInput(format!(
"--bind `{bind}` must be an IP:port when ACAUA_TRANSPORT=tls"
))
})?;
let config = RustlsConfig::from_pem_file(&cert, &key)
.await
.map_err(|e| {
AcauaError::InvalidInput(format!(
"cannot load ACAUA_TLS_CERT/ACAUA_TLS_KEY: {e}"
))
})?;
let handle = Handle::new();
let stopper = handle.clone();
tokio::spawn(async move {
shutdown_signal().await;
stopper.graceful_shutdown(Some(Duration::from_secs(10)));
});
println!("Acauã listening on https://{bind}");
axum_server::bind_rustls(addr, config)
.handle(handle)
.serve(service)
.await?;
}
}
Ok(())
}
+27
View File
@@ -339,6 +339,33 @@ async fn html_request_redirects_to_login_api_gets_401() {
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn hsts_header_only_in_tls_and_proxy() {
for (transport, hsts) 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 (_d, _a, app) = fresh(transport);
let r = send(&app, empty(Method::GET, "/api/health")).await;
assert_eq!(
r.headers.contains_key(header::STRICT_TRANSPORT_SECURITY),
hsts
);
}
}
#[tokio::test]
async fn cookie_flags() {
for (transport, secure) in [