feat(auth): deny-by-default HTTP layer
A global middleware wraps the router and its fallback: only PUBLIC_ROUTES answer without a credential, and unknown paths look like protected ones. Adds cookie sessions with per-session CSRF, scoped Bearer tokens, the /api/auth and /api/admin handlers, Transport for client IP and Secure, and pending-token enrollment re-checked inside one store update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a90ff81650
commit
2b1bc63340
11 files changed
+2455
-79
No files matched your search
@@ -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<AuthService>,
|
||||
app: Router,
|
||||
uri: String,
|
||||
recovery: Vec<String>,
|
||||
}
|
||||
|
||||
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<Body> {
|
||||
request(Method::POST, path)
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn empty(method: Method, path: &str) -> Request<Body> {
|
||||
request(method, path).body(Body::empty()).unwrap()
|
||||
}
|
||||
|
||||
async fn send(app: &Router, req: Request<Body>) -> 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<AuthService>, 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<String> {
|
||||
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"));
|
||||
}
|
||||
Reference in new issue
Block a user