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

276 lines
11 KiB
Rust

// 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/.
//! 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;
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux; run it in WSL2",
file!()
);
}
#[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 rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
// Refused before it goes live: the proof belongs to the [ui] host behind forward-auth.
assert_eq!(rec["state"], "failed", "{rec}");
assert!(rec.to_string().contains("host.header.proof"), "{rec}");
if rec["state"] != "kept" {
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()
);
}
/// 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());
}
}