Files
ianitor/crates/control/tests/ui_auth.rs
T

483 lines
18 KiB
Rust

// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
// License 1.0: see LICENSE (its Exhibit A is this file's notice).
//! Sign-in for the web UI (G14, tests first). The UI reaches control through edge on the
//! admin host, behind Authelia; edge adds a per-boot secret header (`X-Ianitor-Proof`, from a
//! systemd credential only edge and control can read). Control trusts `Remote-User` only on a
//! request that carries that proof: any local process can send `Remote-User` to loopback, but
//! none can send the proof. API tokens keep working for scripts.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common;
// On Windows this target has nothing to run: it shows as one *ignored* test, never as a
// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md).
#[cfg(not(unix))]
#[test]
#[ignore = "needs Linux: run it in WSL2, see CLAUDE.md"]
fn needs_linux() {}
#[cfg(unix)]
mod unix {
use crate::common::{Env, EnvSpec};
use ianitor_testkit::authelia::MockAuthelia;
use ianitor_testkit::client::{self, Req};
use serde_json::json;
const PROOF: &str = "per-boot-proof-0123456789abcdef0123456789abcdef";
async fn env(site: String) -> Env {
env_for(site, "ui.test").await
}
async fn env_for(site: String, ui_host: &str) -> Env {
let mut env = Env::new(EnvSpec {
site,
..Default::default()
})
.await;
std::fs::write(env.dir.join("creds/ui-proof"), format!("{PROOF}\n")).unwrap();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!("\n[ui]\nhostname = \"{ui_host}\"\nproof_credential = \"ui-proof\"\n");
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
env
}
#[tokio::test(flavor = "multi_thread")]
async fn a_forged_remote_user_without_the_proof_gets_401() {
let env = env(String::new()).await;
for headers in [
vec![("Remote-User", "mark")],
vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "guess")],
vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "")],
vec![("remote-user", "mark"), ("Remote-Groups", "admins")],
] {
let r = env
.call_with("GET", "/api/v1/overview", &headers, None)
.await;
assert_eq!(r.status, 401, "{headers:?}: {}", r.text);
assert_eq!(r.json["error"]["code"], "ui.no_proof", "{}", r.text);
}
// A valid API token does not make a forged identity acceptable either.
let auth = format!("Bearer {}", env.token);
let r = env
.call_with(
"GET",
"/api/v1/overview",
&[("Authorization", &auth), ("Remote-User", "mark")],
None,
)
.await;
assert_eq!(r.status, 401, "{}", r.text);
// Nothing was trusted: the log does not show the forged user as an actor.
assert!(!env.control_log().contains("by mark"));
}
#[tokio::test(flavor = "multi_thread")]
async fn the_proof_with_a_remote_user_signs_the_ui_in() {
let env = env(String::new()).await;
let ok = [("Remote-User", "mark"), ("X-Ianitor-Proof", PROOF)];
let r = env.call_with("GET", "/api/v1/overview", &ok, None).await;
assert_eq!(r.status, 200, "{}", r.text);
// Through edge the Host is the admin host's.
let r = env
.call_with(
"GET",
"/api/v1/overview",
&[
("Remote-User", "mark"),
("X-Ianitor-Proof", PROOF),
("Host", "ui.test"),
],
None,
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
// Writes need the UI header (CSRF), browser or not.
let r = env
.call_with(
"POST",
"/api/v1/tokens",
&ok,
Some(json!({"name": "from ui"})),
)
.await;
assert_eq!(r.status, 403, "{}", r.text);
assert_eq!(r.json["error"]["code"], "request.csrf");
let mut w = ok.to_vec();
w.push(("X-Ianitor-UI", "1"));
let r = env
.call_with(
"POST",
"/api/v1/tokens",
&w,
Some(json!({"name": "from ui"})),
)
.await;
assert_eq!(r.status, 201, "{}", r.text);
// The proof without a user is not a sign-in.
let r = env
.call_with(
"GET",
"/api/v1/overview",
&[("X-Ianitor-Proof", PROOF)],
None,
)
.await;
assert_eq!(r.status, 401, "{}", r.text);
assert_eq!(r.json["error"]["code"], "ui.no_user");
// API tokens still work for scripts.
let r = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(r.status, 200, "{}", r.text);
}
#[tokio::test(flavor = "multi_thread")]
async fn through_edge_authelia_decides_and_a_client_cannot_bring_its_own_proof() {
let auth = MockAuthelia::start().await;
let site = format!(
"secrets = [\"ui-proof\"]\n[forward_auth]\nurl = \"{}\"\n",
auth.url()
);
let env = env_for(site, "a.test").await;
// The admin host: forward-auth, upstream control, the proof header from the secret.
let host = json!({"host": {
"hostname": "a.test", "upstreams": [format!("http://{}", env.api)],
"tls": "domi", "auth": "forward-auth",
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
}});
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log());
let edge = env.edge.as_ref().unwrap();
let roots = env.ca.roots();
// Signed in at Authelia (mock: alice): the UI gets in.
let r = client::https(
edge.https,
"a.test",
roots.clone(),
&Req::get("a.test", "/api/v1/overview").header("cookie", "authelia_session=good"),
)
.await
.unwrap();
assert_eq!(r.status, 200, "{}", r.text());
assert!(r.text().contains("\"hosts\""), "{}", r.text());
// Not signed in: Authelia's answer, control never sees it.
let r = client::https(
edge.https,
"a.test",
roots.clone(),
&Req::get("a.test", "/api/v1/overview"),
)
.await
.unwrap();
assert_ne!(r.status, 200);
// A client that sends its own proof and user gets neither through: edge replaces
// the proof with the real one only after Authelia allowed the request, and strips
// Remote-* from clients.
let r = client::https(
edge.https,
"a.test",
roots,
&Req::get("a.test", "/api/v1/overview")
.header("x-ianitor-proof", "guess")
.header("remote-user", "mallory"),
)
.await
.unwrap();
assert_ne!(r.status, 200);
}
/// QC: an admin host (the proof header rule) without forward-auth. Edge strips Remote-*
/// only on forward-auth hosts and sets the proof on every request, so any client that
/// can reach the host names any user. Control accepts such a host file.
#[tokio::test(flavor = "multi_thread")]
async fn qc_proof_on_a_host_without_forward_auth_is_refused() {
let env = env_for("secrets = [\"ui-proof\"]\n".into(), "a.test").await;
let host = json!({"host": {
"hostname": "a.test", "upstreams": [format!("http://{}", env.api)],
"tls": "domi", "auth": "none",
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
}});
let r = env.call("POST", "/api/v1/hosts", Some(host)).await;
// Refused at the door: the proof belongs to the [ui] host behind forward-auth.
assert_eq!(r.status, 422, "{}", r.text);
assert_eq!(
r.json["errors"][0]["code"], "host.header.proof",
"{}",
r.text
);
assert!(
env.call("GET", "/api/v1/hosts/a.test", None).await.status == 404,
"the host went live"
);
if r.status != 202 {
return;
}
let edge = env.edge.as_ref().unwrap();
let r = client::https(
edge.https,
"a.test",
env.ca.roots(),
&Req::new("POST", "a.test", "/api/v1/tokens")
.body(br#"{"name":"pwned"}"#)
.header("content-type", "application/json")
.header("x-ianitor-ui", "1")
.header("remote-user", "mallory"),
)
.await
.unwrap();
eprintln!("QC POST /tokens as mallory: {} {}", r.status, r.text());
assert_ne!(
r.status,
201,
"a client minted an API token as mallory: {}",
r.text()
);
}
// ---------------------------------------------------------------- G14 option b (phase 4)
/// Control with `[ui] socket`: the UI comes in on a Unix socket in a directory only the
/// ianitor group can use; the loopback port stays for API tokens (scripts, the CLI).
async fn socket_env(site: String, ui_host: &str) -> (Env, std::path::PathBuf) {
let mut env = Env::new(EnvSpec {
site,
..Default::default()
})
.await;
std::fs::write(
env.dir.join("creds/ui-proof"),
format!(
"{PROOF}
"
),
)
.unwrap();
let sock = env.dir.join("ui.sock");
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"
[ui]
hostname = \"{ui_host}\"
proof_credential = \"ui-proof\"
socket = \"{}\"
",
sock.display()
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
for _ in 0..100 {
if sock.exists() {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
assert!(
sock.exists(),
"no UI socket:
{}",
env.control_log()
);
(env, sock)
}
async fn over_socket(sock: &std::path::Path, headers: &[(&str, &str)]) -> (u16, String) {
let mut req = Req::get("ui.test", "/api/v1/overview");
for (n, v) in headers {
req = req.header(n, v);
}
let r = client::unix(sock, &req).await.unwrap();
(r.status, r.text())
}
/// The per-boot proof alone no longer signs anyone in: off the socket it is refused even
/// when it is right, so a local process that learned it (say, by listening on control's
/// port while control restarted) gets nothing; on the socket, which only edge and Caddy
/// (group ianitor) can open, it works as before.
#[tokio::test(flavor = "multi_thread")]
async fn with_a_ui_socket_the_proof_counts_only_on_the_socket() {
use std::os::unix::fs::PermissionsExt;
let (env, sock) = socket_env(String::new(), "ui.test").await;
let mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o660, "owner and group only");
let signed = [("Remote-User", "mark"), ("X-Ianitor-Proof", PROOF)];
let r = env
.call_with("GET", "/api/v1/overview", &signed, None)
.await;
assert_eq!(r.status, 401, "the right proof over TCP: {}", r.text);
assert_eq!(r.json["error"]["code"], "ui.no_proof", "{}", r.text);
assert!(!env.control_log().contains("by mark"));
let (status, text) = over_socket(&sock, &signed).await;
assert_eq!(status, 200, "{text}");
// The socket does not replace the proof: without it, a Remote-User is still refused.
let (status, text) = over_socket(&sock, &[("Remote-User", "mark")]).await;
assert_eq!(status, 401, "{text}");
let (status, text) = over_socket(
&sock,
&[("Remote-User", "mark"), ("X-Ianitor-Proof", "guess")],
)
.await;
assert_eq!(status, 401, "{text}");
// API tokens keep working on the loopback port.
let r = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(r.status, 200, "{}", r.text);
}
/// A route file may name a socket only for the admin host, and only control's own.
#[tokio::test(flavor = "multi_thread")]
async fn a_socket_upstream_is_only_for_the_admin_host_and_controls_own_socket() {
let auth = MockAuthelia::start().await;
let site = format!(
"secrets = [\"ui-proof\"]
[forward_auth]
url = \"{}\"
",
auth.url()
);
let (env, sock) = socket_env(site, "a.test").await;
for (hostname, upstream) in [
("b.test", format!("unix:{}", sock.display())),
("a.test", "unix:/run/docker.sock".to_owned()),
] {
let host = json!({"host": {
"hostname": hostname, "upstreams": [upstream],
"tls": "domi", "auth": "forward-auth",
}});
let r = env.call("POST", "/api/v1/hosts", Some(host)).await;
assert_eq!(r.status, 422, "{hostname} {upstream}: {}", r.text);
assert_eq!(
r.json["errors"][0]["code"], "host.upstream.unix_socket",
"{}",
r.text
);
}
// The admin host on control's socket: through edge, Authelia decides, the UI gets in.
let host = json!({"host": {
"hostname": "a.test", "upstreams": [format!("unix:{}", sock.display())],
"tls": "domi", "auth": "forward-auth",
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
}});
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
assert_eq!(
rec["state"],
"kept",
"{rec}
{}",
env.control_log()
);
let edge = env.edge.as_ref().unwrap();
let r = client::https(
edge.https,
"a.test",
env.ca.roots(),
&Req::get("a.test", "/api/v1/overview").header("cookie", "authelia_session=good"),
)
.await
.unwrap();
assert_eq!(r.status, 200, "{}", r.text());
assert!(r.text().contains("\"hosts\""), "{}", r.text());
}
/// QC phase 4 (nit): a tree kept under one `[ui] socket` and read at start under another
/// is not written to the engines; the reason is logged.
#[tokio::test(flavor = "multi_thread")]
async fn a_kept_socket_upstream_that_breaks_a_changed_config_is_not_written_at_start() {
let auth = MockAuthelia::start().await;
let site = format!(
"secrets = [\"ui-proof\"]
[forward_auth]
url = \"{}\"
",
auth.url()
);
let (mut env, sock) = socket_env(site, "a.test").await;
let host = json!({"host": {
"hostname": "a.test", "upstreams": [format!("unix:{}", sock.display())],
"tls": "domi", "auth": "forward-auth",
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
}});
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
assert_eq!(
rec["state"],
"kept",
"{rec}
{}",
env.control_log()
);
env.kill_control();
// A marker in place of edge.json: a start that writes the tree to the engines replaces it.
let before = b"{\"marker\": \"left by the test\"}\n".to_vec();
std::fs::write(env.dir.join("edge/edge.json"), &before).unwrap();
let moved = env.dir.join("ui-moved.sock");
let text = std::fs::read_to_string(env.config_path())
.unwrap()
.replace(&sock.display().to_string(), &moved.display().to_string());
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
for _ in 0..100 {
if env.control_log().contains("breaks control's rules") {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
assert!(
env.control_log().contains("breaks control's rules"),
"{}",
env.control_log()
);
assert_eq!(
std::fs::read(env.dir.join("edge/edge.json")).unwrap(),
before,
"the tree was not written to the engines"
);
}
/// QC: signed in at Authelia (alice) but the client also sends a proof guess: edge must
/// replace, not append, the proof; and Remote-User must be Authelia's.
#[tokio::test(flavor = "multi_thread")]
async fn qc_signed_in_client_with_own_proof_and_user_is_alice() {
let auth = MockAuthelia::start().await;
let site = format!(
"secrets = [\"ui-proof\"]\n[forward_auth]\nurl = \"{}\"\n",
auth.url()
);
let env = env_for(site, "a.test").await;
let host = json!({"host": {
"hostname": "a.test", "upstreams": [format!("http://{}", env.api)],
"tls": "domi", "auth": "forward-auth",
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
}});
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
assert_eq!(rec["state"], "kept", "{rec}");
let edge = env.edge.as_ref().unwrap();
let r = client::https(
edge.https,
"a.test",
env.ca.roots(),
&Req::get("a.test", "/api/v1/overview")
.header("cookie", "authelia_session=good")
.header("x-ianitor-proof", "guess")
.header("remote-user", "mallory")
.header("remote-name", "Mallory"),
)
.await
.unwrap();
assert_eq!(r.status, 200, "{}", r.text());
eprintln!(
"QC viewer: {}",
r.text()[r.text().find("\"viewer\"").unwrap_or(0)..]
.chars()
.take(80)
.collect::<String>()
);
assert!(!r.text().contains("allory"), "{}", r.text());
}
}