[edge] Tests first: secret never leaks, forward-auth denial never reaches upstream (red)

This commit is contained in:
2026-11-07 14:48:06 +01:00
parent a94a242c79
commit 4fe041082d
5 changed files with 489 additions and 1 deletions
+20
View File
@@ -7,8 +7,28 @@ rust-version.workspace = true
license.workspace = true license.workspace = true
publish.workspace = true publish.workspace = true
[[bin]]
name = "ianitor-edge"
path = "src/main.rs"
[dependencies] [dependencies]
ianitor-core.workspace = true ianitor-core.workspace = true
pingora = { version = "0.9.1", default-features = false, features = ["proxy", "rustls"] }
async-trait.workspace = true
tokio.workspace = true
bytes.workspace = true
http.workspace = true
log.workspace = true
rustls.workspace = true
rustls-pki-types.workspace = true
serde.workspace = true
serde_json.workspace = true
arc-swap = "1.7"
instant-acme = { version = "0.8.5", default-features = false, features = ["ring", "hyper-rustls", "rcgen"] }
x509-parser = "0.18"
[dev-dependencies]
ianitor-testkit.workspace = true
[lints] [lints]
workspace = true workspace = true
+6 -1
View File
@@ -2,4 +2,9 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this // License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
fn main() {} //! ianitor-edge binary (not implemented yet).
fn main() -> std::process::ExitCode {
eprintln!("ianitor-edge: not implemented yet");
std::process::ExitCode::from(2)
}
+125
View File
@@ -0,0 +1,125 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Runs the real `ianitor-edge` binary on 127.0.0.1 with a compiled config, a test CA for
//! `tls = "domi"` hosts and a credentials directory. stderr goes to a file the tests inspect.
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
use ianitor_core::compile::{self, CompileOptions};
use ianitor_core::{load, SourceFile, TlsMode};
use ianitor_testkit::proc::{free_port, local, wait_for_port, ChildGuard, TempDir};
use ianitor_testkit::tls::TestCa;
use rustls::RootCertStore;
pub struct Edge {
pub child: ChildGuard,
pub http: SocketAddr,
pub https: SocketAddr,
pub dir: TempDir,
pub ca: TestCa,
pub config_text: String,
}
impl Edge {
pub fn roots(&self) -> Arc<RootCertStore> {
self.ca.roots()
}
pub fn stderr(&self) -> String {
std::fs::read_to_string(self.dir.join("edge.stderr")).unwrap_or_default()
}
pub fn access_log(&self) -> String {
std::fs::read_to_string(self.dir.join("logs/access.log")).unwrap_or_default()
}
/// Everything edge wrote or was given, except the credentials themselves.
pub fn all_output(&self) -> String {
format!("{}\n{}\n{}", self.stderr(), self.access_log(), self.config_text)
}
pub fn exited(&mut self) -> Option<std::process::ExitStatus> {
self.child.0.try_wait().unwrap()
}
}
pub struct EdgeSpec<'a> {
pub site: &'a str,
pub hosts: Vec<(String, String)>,
pub secrets: Vec<(String, Vec<u8>)>,
pub log_level: &'a str,
pub extra_args: Vec<String>,
}
impl Default for EdgeSpec<'_> {
fn default() -> Self {
EdgeSpec { site: "", hosts: Vec::new(), secrets: Vec::new(), log_level: "info", extra_args: Vec::new() }
}
}
/// Compile, write certificates and credentials, start the binary. Does not wait for readiness.
pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
let dir = TempDir::new("edge");
for d in ["certs", "state", "creds", "logs"] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
let sources: Vec<SourceFile> = spec.hosts.iter().map(|(n, c)| SourceFile { name: n, contents: c }).collect();
let model = load(&SourceFile { name: "ianitor.toml", contents: spec.site }, &sources).expect("valid routes");
let ca = TestCa::new("Ianitor Test CA");
for h in model.hosts() {
if h.tls == TlsMode::Domi {
let leaf = ca.issue(&[h.hostname.as_str()]);
std::fs::write(dir.join(&format!("certs/{}.crt", h.hostname)), leaf.cert_pem).unwrap();
std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap();
}
}
for (name, value) in &spec.secrets {
std::fs::write(dir.join(&format!("creds/{name}")), value).unwrap();
}
let http = local(free_port());
let https = local(free_port());
let opts = CompileOptions {
http_listen: http,
https_listen: https,
cert_dir: dir.str("certs"),
state_dir: dir.str("state"),
access_log: dir.str("logs/access.log"),
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
};
let config_text = compile::edge(&model, &opts).unwrap();
std::fs::write(dir.join("edge.json"), &config_text).unwrap();
let stderr = std::fs::File::create(dir.join("edge.stderr")).unwrap();
let mut cmd = Command::new(env!("CARGO_BIN_EXE_ianitor-edge"));
cmd.arg("--config").arg(dir.join("edge.json"));
cmd.args(&spec.extra_args);
cmd.env("CREDENTIALS_DIRECTORY", dir.join("creds"));
cmd.env("IANITOR_LOG", spec.log_level);
cmd.stdout(Stdio::from(stderr.try_clone().unwrap())).stderr(Stdio::from(stderr));
let child = ChildGuard(cmd.spawn().expect("spawn ianitor-edge"));
Edge { child, http, https, dir, ca, config_text }
}
/// Spawn and wait until both listeners accept connections.
pub fn start(spec: EdgeSpec<'_>) -> Edge {
let mut e = spawn(spec);
let ok = wait_for_port(e.https, Duration::from_secs(20)) && wait_for_port(e.http, Duration::from_secs(5));
if !ok || e.exited().is_some() {
panic!("ianitor-edge did not start:\n{}", e.stderr());
}
e
}
pub fn host_file(hostname: &str, body: &str) -> (String, String) {
(format!("hosts/{hostname}.toml"), format!("hostname = \"{hostname}\"\ntls = \"domi\"\n{body}"))
}
+172
View File
@@ -0,0 +1,172 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Forward-auth (Authelia-compatible): a denial never reaches the upstream, the auth answer
//! goes back to the client unchanged, and an allowed request carries the identity headers
//! from the auth server and never the client's own.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod common;
use common::{host_file, start, EdgeSpec};
use ianitor_testkit::authelia::MockAuthelia;
use ianitor_testkit::client::{self, Req, WsOutcome};
use ianitor_testkit::upstream::{closed_port, Echo, WsEcho};
fn site(auth_url: &str) -> String {
format!("[forward_auth]\nurl = \"{auth_url}\"\n")
}
#[tokio::test(flavor = "multi_thread")]
async fn denial_never_reaches_the_upstream() {
let authelia = MockAuthelia::start().await;
let echo = Echo::start("app").await;
let ws = WsEcho::start().await;
let site = site(&authelia.url());
let edge = start(EdgeSpec {
site: &site,
hosts: vec![
host_file("auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url())),
host_file("wsauth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", ws.url())),
],
..Default::default()
});
let roots = edge.roots();
let go = |req: Req| {
let roots = roots.clone();
let addr = edge.https;
async move { client::https(addr, "auth.test", roots, &req).await.unwrap() }
};
// No session: browser GET is redirected to the portal, with Authelia's headers and body.
let r = go(Req::get("auth.test", "/private?x=1")).await;
assert_eq!(r.status, 302);
assert_eq!(
r.header("location"),
Some("https://auth.test/?rd=https%3A%2F%2Fauth.test%2Fprivate%3Fx%3D1")
);
assert_eq!(r.header("set-cookie"), Some("authelia_flow=1; Path=/; HttpOnly"));
assert!(r.text().contains("302 Found"));
let r = go(Req::new("HEAD", "auth.test", "/")).await;
assert_eq!(r.status, 302);
let r = go(Req::new("POST", "auth.test", "/submit?x=1").body(b"do-not-forward")).await;
assert_eq!(r.status, 401);
assert_eq!(r.text(), "401 Unauthorized");
let r = go(Req::get("auth.test", "/").header("authorization", "Bearer wrong")).await;
assert_eq!(r.status, 401);
assert_eq!(r.header("www-authenticate"), Some("Basic realm=\"Authorization Required\""));
let r = go(Req::get("auth.test", "/").header("cookie", "authelia_session=forbidden")).await;
assert_eq!(r.status, 403);
// Spoofed identity and forwarding headers do not help.
let r = go(Req::get("auth.test", "/admin")
.header("remote-user", "admin")
.header("x-forwarded-method", "GET")
.header("x-forwarded-uri", "/public")
.header("x-forwarded-host", "public.test")
.header("x-forwarded-for", "10.0.0.1"))
.await;
assert_eq!(r.status, 302);
assert!(r.header("location").unwrap().contains("auth.test%2Fadmin"), "edge sends its own X-Forwarded-*");
// A websocket upgrade without a session is denied before any upgrade happens.
match client::websocket(edge.https, "wsauth.test", roots.clone(), "wsauth.test", "/socket", &[], "hi").await.unwrap() {
WsOutcome::Refused(r) => assert_eq!(r.status, 302),
WsOutcome::Upgraded { .. } => panic!("unauthenticated websocket was upgraded"),
}
assert!(echo.proxied().is_empty(), "a denied request reached the upstream: {:?}", echo.proxied());
assert_eq!(ws.connections(), 0, "a denied websocket reached the upstream");
// What Authelia was told, per its proxy-authorization guide.
let asked = authelia.requests();
assert!(asked.len() >= 7, "{asked:?}");
let post = asked
.iter()
.find(|r| r.header("x-forwarded-method") == Some(b"POST".as_slice()))
.expect("the POST was checked");
assert_eq!(post.method, "GET", "the auth subrequest is a GET");
assert_eq!(post.path, "/api/authz/forward-auth");
assert_eq!(post.header("x-forwarded-proto"), Some(b"https".as_slice()));
assert_eq!(post.header("x-forwarded-host"), Some(b"auth.test".as_slice()));
assert_eq!(post.header("x-forwarded-uri"), Some(b"/submit?x=1".as_slice()));
assert_eq!(post.header("x-forwarded-for"), Some(b"127.0.0.1".as_slice()));
assert!(post.body.is_empty(), "the request body is not sent to the auth server");
}
#[tokio::test(flavor = "multi_thread")]
async fn allowed_request_carries_identity_from_the_auth_server_only() {
let authelia = MockAuthelia::start().await;
let echo = Echo::start("app").await;
let site = site(&authelia.url());
let edge = start(EdgeSpec {
site: &site,
hosts: vec![host_file("auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()))],
..Default::default()
});
let roots = edge.roots();
let r = client::https(
edge.https,
"auth.test",
roots.clone(),
&Req::new("POST", "auth.test", "/submit")
.header("cookie", "authelia_session=good")
.header("remote-user", "mallory")
.header("remote-groups", "root")
.body(b"form=data"),
)
.await
.unwrap();
assert_eq!(r.status, 200, "{}", r.text());
let seen = echo.proxied();
assert_eq!(seen.len(), 1);
let up = &seen[0];
assert_eq!(up.header("remote-user"), Some(b"alice".as_slice()));
assert_eq!(up.header("remote-groups"), Some(b"admins,dev".as_slice()));
assert_eq!(up.header("remote-email"), Some(b"alice@example.org".as_slice()));
assert_eq!(up.header("remote-name"), Some(b"Alice Example".as_slice()));
assert_eq!(up.body, b"form=data", "the body still reaches the upstream");
assert_eq!(up.headers.iter().filter(|(n, _)| n == "remote-user").count(), 1);
// Allowed without identity: the client's own Remote-* headers are removed, not passed on.
echo.clear();
let r = client::https(
edge.https,
"auth.test",
roots.clone(),
&Req::get("auth.test", "/").header("cookie", "authelia_session=nameless").header("remote-user", "mallory"),
)
.await
.unwrap();
assert_eq!(r.status, 200);
assert_eq!(echo.proxied()[0].header("remote-user"), None);
let r = client::https(edge.https, "auth.test", roots, &Req::get("auth.test", "/").header("authorization", "Bearer good"))
.await
.unwrap();
assert_eq!(r.status, 200);
}
#[tokio::test(flavor = "multi_thread")]
async fn unreachable_auth_server_fails_closed() {
let echo = Echo::start("app").await;
let site = site(&format!("http://127.0.0.1:{}/api/authz/forward-auth", closed_port()));
let edge = start(EdgeSpec {
site: &site,
hosts: vec![host_file("auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()))],
..Default::default()
});
let r = client::https(edge.https, "auth.test", edge.roots(), &Req::get("auth.test", "/").header("cookie", "authelia_session=good"))
.await
.unwrap();
assert_eq!(r.status, 502);
assert!(echo.proxied().is_empty());
}
+166
View File
@@ -0,0 +1,166 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! An injected secret reaches the upstream and never appears in a response, a log line, the
//! access log or the compiled config, even with the most verbose log level.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod common;
use common::{host_file, start, spawn, EdgeSpec};
use ianitor_testkit::client::{self, Req, Resp, WsOutcome};
use ianitor_testkit::upstream::{closed_port, Echo, WsEcho};
fn unique_secret() -> String {
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
format!("sekret-{}-{nanos:x}-tail", std::process::id())
}
fn assert_clean(what: &str, haystack: &[u8], secret: &str) {
let hay = String::from_utf8_lossy(haystack);
assert!(!hay.contains(secret), "secret leaked into {what}:\n{hay}");
}
fn assert_resp_clean(what: &str, r: &Resp, secret: &str) {
for (n, v) in &r.headers {
assert_clean(&format!("{what}: response header {n}"), v.as_bytes(), secret);
}
assert_clean(&format!("{what}: response body"), &r.body, secret);
}
#[tokio::test(flavor = "multi_thread")]
async fn injected_secret_never_appears_in_a_response_or_log() {
let secret = unique_secret();
let echo = Echo::start("app").await;
let ws = WsEcho::start().await;
let rule = "[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"api_key\"\n";
let edge = start(EdgeSpec {
site: "secrets = [\"api_key\"]\n",
hosts: vec![
host_file("app.test", &format!("upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}", echo.url())),
host_file("down.test", &format!("upstreams = [\"http://127.0.0.1:{}\"]\naccess_log = \"truncated\"\n{rule}", closed_port())),
host_file("ws.test", &format!("upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}", ws.url())),
],
// systemd credentials usually end with a newline; it is not part of the value.
secrets: vec![("api_key".into(), format!("{secret}\n").into_bytes())],
log_level: "trace",
..Default::default()
});
let roots = edge.roots();
let go = |sni: &'static str, req: Req| {
let roots = roots.clone();
let addr = edge.https;
async move { client::https(addr, sni, roots, &req).await.unwrap() }
};
let mut responses = Vec::new();
responses.push(("plain GET", go("app.test", Req::get("app.test", "/hello?token=abc")).await));
responses.push(("POST", go("app.test", Req::new("POST", "app.test", "/submit").body(b"payload")).await));
responses.push((
"client tries to set the header",
go("app.test", Req::get("app.test", "/").header("x-api-key", "attacker")).await,
));
responses.push(("upstream error status", go("app.test", Req::get("app.test", "/status/500")).await));
responses.push((
"upstream reflects the secret in a header",
go("app.test", Req::get("app.test", "/reflect?h=x-api-key")).await,
));
responses.push(("upstream down", go("down.test", Req::get("down.test", "/")).await));
responses.push(("unknown host", go("app.test", Req::get("nope.test", "/")).await));
let plain = client::http(edge.http, &Req::get("app.test", "/x?y=1")).await.unwrap();
responses.push(("plain HTTP redirect", plain));
for (what, r) in &responses {
assert_resp_clean(what, r, &secret);
}
assert_eq!(responses[0].1.status, 200);
assert_eq!(responses[4].1.status, 200);
assert!(responses[4].1.header("x-reflected").is_none(), "edge strips a response header carrying a secret");
assert_eq!(responses[5].1.status, 502);
match client::websocket(edge.https, "ws.test", roots.clone(), "ws.test", "/socket", &[], "ping").await.unwrap() {
WsOutcome::Upgraded { status, echo } => {
assert_eq!(status, 101);
assert_eq!(echo, "ping");
}
WsOutcome::Refused(r) => panic!("websocket refused: {r:?}"),
}
// The secret did reach the upstream, without the trailing newline, replacing the client's value.
let seen = echo.proxied();
assert!(seen.len() >= 5, "{seen:?}");
for r in &seen {
assert_eq!(r.header("x-api-key"), Some(secret.as_bytes()), "upstream request {}", r.path);
}
// Give the access log a moment to flush, then check every output channel.
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let access = edge.access_log();
assert!(access.lines().count() >= 7, "access log has the requests:\n{access}");
assert!(access.contains("\"127.0.0.0\""), "IPv4 truncated to /24:\n{access}");
assert!(!access.contains("127.0.0.1"), "full client IP must not be logged:\n{access}");
assert!(!access.contains("token=abc"), "query strings are not logged:\n{access}");
let stderr = edge.stderr();
assert!(stderr.len() > 100, "trace logging produced output:\n{stderr}");
assert_clean("stderr (trace level)", stderr.as_bytes(), &secret);
assert_clean("access log", access.as_bytes(), &secret);
assert_clean("compiled edge config", edge.config_text.as_bytes(), &secret);
}
#[tokio::test(flavor = "multi_thread")]
async fn missing_secret_stops_startup_without_leaking_others() {
let secret = unique_secret();
let echo = Echo::start("app").await;
let mut edge = spawn(EdgeSpec {
site: "secrets = [\"present\", \"absent\"]\n",
hosts: vec![host_file(
"app.test",
&format!(
"upstreams = [\"{}\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"present\"\n\
[[request_headers]]\naction = \"set\"\nname = \"X-B\"\nsecret = \"absent\"\n",
echo.url()
),
)],
secrets: vec![("present".into(), secret.clone().into_bytes())],
log_level: "trace",
..Default::default()
});
let status = wait_exit(&mut edge);
assert!(!status.success(), "edge must refuse to start");
let err = edge.stderr();
assert!(err.contains("absent"), "names the missing secret:\n{err}");
assert_clean("stderr", err.as_bytes(), &secret);
}
#[tokio::test(flavor = "multi_thread")]
async fn malformed_secret_is_rejected_without_echoing_it() {
let secret = unique_secret();
let echo = Echo::start("app").await;
let mut edge = spawn(EdgeSpec {
site: "secrets = [\"api_key\"]\n",
hosts: vec![host_file(
"app.test",
&format!("upstreams = [\"{}\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n", echo.url()),
)],
// A newline inside the value would split the header: refused.
secrets: vec![("api_key".into(), format!("{secret}\ninjected: yes\n").into_bytes())],
log_level: "trace",
..Default::default()
});
let status = wait_exit(&mut edge);
assert!(!status.success(), "edge must refuse a secret that is not a valid header value");
assert_clean("stderr", edge.stderr().as_bytes(), &secret);
}
fn wait_exit(edge: &mut common::Edge) -> std::process::ExitStatus {
for _ in 0..200 {
if let Some(s) = edge.exited() {
return s;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
panic!("edge kept running:\n{}", edge.stderr());
}