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:
1 parent
5ad89d5be5
commit
dc8c7fa248
8 files changed
+430
-19
No files matched your search
+64
-13
@@ -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(())
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user