[control] Tests first: Domi CA flows through the API (offline-signed intermediate, domi host chains, device approval by code, one-time install, revocation, no root key) and UI sign-in that refuses a forged Remote-User (red)
This commit is contained in:
@@ -66,6 +66,8 @@ pub struct EnvSpec {
|
||||
pub watch_secs: u64,
|
||||
pub site: String,
|
||||
pub remote: Option<String>,
|
||||
/// Appended to control.toml (extra sections such as [pki]).
|
||||
pub extra_config: String,
|
||||
}
|
||||
|
||||
impl Default for EnvSpec {
|
||||
@@ -74,6 +76,7 @@ impl Default for EnvSpec {
|
||||
watch_secs: 2,
|
||||
site: String::new(),
|
||||
remote: None,
|
||||
extra_config: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -202,7 +205,7 @@ caddy_credentials_dir = "{creds}"
|
||||
certs = d("certs"),
|
||||
edge_state = d("edge-state"),
|
||||
log = d("logs/access.log"),
|
||||
);
|
||||
) + &spec.extra_config;
|
||||
std::fs::write(self.dir.join("control.toml"), text).unwrap();
|
||||
}
|
||||
|
||||
@@ -254,7 +257,7 @@ caddy_credentials_dir = "{creds}"
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
|
||||
fn command(&self) -> Command {
|
||||
pub fn command(&self) -> Command {
|
||||
let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control"));
|
||||
c.env_remove("IANITOR_TEST_CRASH_AT");
|
||||
c.env_remove("IANITOR_TEST_FAIL_WRITE");
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
// 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/.
|
||||
|
||||
//! The Domi CA through control (ROADMAP §6 phase 3, tests first): the first intermediate is
|
||||
//! signed offline from control's CSR and installed; `tls = "domi"` hosts then get server
|
||||
//! certificates that chain to the root; device certificates need the match code; the install
|
||||
//! file works once; revocation takes the device off the allow list; no root key file is ever
|
||||
//! in the state directory, and control refuses to start with one there.
|
||||
|
||||
#![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 std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::common::{Env, EnvSpec};
|
||||
use ianitor_core::pki;
|
||||
use ianitor_testkit::client::{self, Req};
|
||||
use ianitor_testkit::upstream::Echo;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const PASSWORD: &str = "intermediate-test-password-123";
|
||||
|
||||
fn now() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64
|
||||
}
|
||||
|
||||
/// The offline side: a root that lives only in this test's memory (and its cert file).
|
||||
struct Offline {
|
||||
root_pem: String,
|
||||
root_key: pki::KeyPair,
|
||||
}
|
||||
|
||||
async fn env_with_pki() -> (Env, Offline) {
|
||||
let (root_pem, root_key) = pki::create_root(now()).unwrap();
|
||||
// Only the root certificate goes next to control; the key stays in this test.
|
||||
let extra = |dir: &Path| {
|
||||
format!(
|
||||
"\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n",
|
||||
dir.join("offline-root.crt").display()
|
||||
)
|
||||
};
|
||||
let mut env = Env::new(EnvSpec::default()).await;
|
||||
std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap();
|
||||
std::fs::write(env.dir.join("creds/pki-password"), PASSWORD).unwrap();
|
||||
let text = std::fs::read_to_string(env.config_path()).unwrap() + &extra(&env.dir.join("."));
|
||||
std::fs::write(env.config_path(), text).unwrap();
|
||||
env.start_control(None);
|
||||
(env, Offline { root_pem, root_key })
|
||||
}
|
||||
|
||||
async fn wait_request(env: &Env, id: &str, want: &str) -> Value {
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
loop {
|
||||
let r = env
|
||||
.call("GET", &format!("/api/v1/pki-requests/{id}"), None)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
if r.json["state"] == want {
|
||||
return r.json;
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
panic!(
|
||||
"request {id} is {} not {want}\n{}",
|
||||
r.json["state"],
|
||||
env.control_log()
|
||||
);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn cli(env: &Env, args: &[&str]) -> std::process::Output {
|
||||
env.command()
|
||||
.args(args)
|
||||
.arg("--config")
|
||||
.arg(env.config_path())
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Renew (first intermediate), sign offline, install with the CLI.
|
||||
async fn install_intermediate(env: &Env, off: &Offline) -> Value {
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/certs/intermediate/renewal",
|
||||
Some(json!({})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
||||
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
|
||||
// The code the UI shows is the one the offline signer computes from the CSR.
|
||||
assert_eq!(
|
||||
r.json["match_code"].as_str().unwrap(),
|
||||
pki::match_code(&pki::csr_der(&csr).unwrap())
|
||||
);
|
||||
let r2 = env
|
||||
.call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None)
|
||||
.await;
|
||||
assert_eq!(r2.status, 200);
|
||||
assert_eq!(r2.text, csr);
|
||||
let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
|
||||
let f = env.dir.join("signed.crt");
|
||||
std::fs::write(&f, &signed).unwrap();
|
||||
let out = cli(env, &["pki", "install", f.to_str().unwrap()]);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
wait_request(env, &rid, "approved").await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn first_intermediate_from_an_offline_signature_then_domi_hosts_chain_to_the_root() {
|
||||
let (env, off) = env_with_pki().await;
|
||||
let ov = env.call("GET", "/api/v1/overview", None).await;
|
||||
assert_eq!(ov.json["intermediate"]["state"], "missing", "{}", ov.text);
|
||||
|
||||
// Before an intermediate exists a domi host cannot get a certificate.
|
||||
let echo = Echo::start("domi").await;
|
||||
let host = json!({"host": {"hostname": "fresh.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}});
|
||||
let rec = env.apply("POST", "/api/v1/hosts", Some(host.clone())).await;
|
||||
assert_eq!(rec["state"], "failed", "{rec}");
|
||||
assert_eq!(rec["reason"]["code"], "pki.no_intermediate", "{rec}");
|
||||
|
||||
install_intermediate(&env, &off).await;
|
||||
let ov = env.call("GET", "/api/v1/overview", None).await;
|
||||
assert_eq!(ov.json["intermediate"]["state"], "ok", "{}", ov.text);
|
||||
assert!(ov.json["intermediate"]["days_left"].as_i64().unwrap() >= 364);
|
||||
|
||||
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
|
||||
assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log());
|
||||
// The served certificate chains to the Domi root (only the root is trusted here).
|
||||
let roots = ianitor_testkit::tls::roots_from_pem(&off.root_pem);
|
||||
let edge = env.edge.as_ref().unwrap();
|
||||
let r = client::https(
|
||||
edge.https,
|
||||
"fresh.test",
|
||||
roots,
|
||||
&Req::get("fresh.test", "/"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.status, 200);
|
||||
let crt = std::fs::read_to_string(env.dir.join("certs/fresh.test.crt")).unwrap();
|
||||
let info = pki::inspect(&crt).unwrap();
|
||||
assert_eq!(info.dns_names, vec!["fresh.test".to_owned()]);
|
||||
assert_eq!(
|
||||
(info.not_after - now()) / 86_400,
|
||||
i64::from(pki::SERVER_DAYS) - 1
|
||||
);
|
||||
|
||||
// No root key anywhere control writes.
|
||||
let key_pem = off.root_key.serialize_pem();
|
||||
let body: String = key_pem
|
||||
.lines()
|
||||
.filter(|l| !l.starts_with("-----"))
|
||||
.collect();
|
||||
for d in ["state", "certs", "edge", "caddy", "edge-state"] {
|
||||
for f in walk(&env.dir.join(d)) {
|
||||
let bytes = std::fs::read(&f).unwrap();
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
assert!(
|
||||
!text.contains(&body[..40]),
|
||||
"root key material in {}",
|
||||
f.display()
|
||||
);
|
||||
assert!(
|
||||
!contains(&bytes, &off.root_key.serialize_der()),
|
||||
"root key DER in {}",
|
||||
f.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
// The intermediate key is only stored encrypted.
|
||||
let k = std::fs::read_to_string(env.dir.join("state/pki/intermediate.key")).unwrap();
|
||||
assert!(k.contains(concat!("IANITOR ENCRYPTED ", "PRIVATE KEY")));
|
||||
assert!(!k.contains(concat!("BEGIN ", "PRIVATE KEY")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_wrong_certificate_is_not_installed() {
|
||||
let (env, off) = env_with_pki().await;
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/certs/intermediate/renewal",
|
||||
Some(json!({})),
|
||||
)
|
||||
.await;
|
||||
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
||||
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
|
||||
// Signed by another root.
|
||||
let (other, other_key) = pki::create_root(now()).unwrap();
|
||||
let wrong = pki::sign_intermediate(&other, &other_key, &csr, now()).unwrap();
|
||||
let r = env
|
||||
.call(
|
||||
"PUT",
|
||||
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||
Some(json!({"certificate_pem": wrong})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
assert_eq!(r.json["error"]["code"], "pki.not_our_root");
|
||||
// For another key.
|
||||
let k = pki::generate_key().unwrap();
|
||||
let other_csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
|
||||
let wrong =
|
||||
pki::sign_intermediate(&off.root_pem, &off.root_key, &other_csr, now()).unwrap();
|
||||
let r = env
|
||||
.call(
|
||||
"PUT",
|
||||
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||
Some(json!({"certificate_pem": wrong})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
assert_eq!(r.json["error"]["code"], "pki.wrong_key");
|
||||
// A leaf is not an intermediate.
|
||||
let r = env
|
||||
.call(
|
||||
"PUT",
|
||||
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||
Some(json!({"certificate_pem": "garbage"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 422, "{}", r.text);
|
||||
let st = env
|
||||
.call("GET", &format!("/api/v1/pki-requests/{rid}"), None)
|
||||
.await;
|
||||
assert_eq!(st.json["state"], "waiting");
|
||||
// The right one through the API works too.
|
||||
let good = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
|
||||
let r = env
|
||||
.call(
|
||||
"PUT",
|
||||
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||
Some(json!({"certificate_pem": good})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
assert_eq!(r.json["state"], "approved");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn device_certificate_needs_the_match_code_and_installs_once() {
|
||||
let (env, off) = env_with_pki().await;
|
||||
install_intermediate(&env, &off).await;
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/certs/devices",
|
||||
Some(json!({"name": "Mark's phone", "kind": "phone"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
||||
let code = r.json["match_code"].as_str().unwrap().to_owned();
|
||||
assert_eq!(code.len(), 8, "{code}");
|
||||
// The same name again while it waits: refused.
|
||||
let again = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/certs/devices",
|
||||
Some(json!({"name": "mark's PHONE", "kind": "phone"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(again.status, 409, "{}", again.text);
|
||||
assert_eq!(again.json["error"]["code"], "pki.device_name_taken");
|
||||
|
||||
// A wrong code does nothing.
|
||||
let wrong = if code.starts_with('0') {
|
||||
"11 11 11"
|
||||
} else {
|
||||
"00 00 00"
|
||||
};
|
||||
let out = cli(&env, &["pki", "approve", wrong]);
|
||||
assert!(!out.status.success());
|
||||
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||
let st = env
|
||||
.call("GET", &format!("/api/v1/pki-requests/{rid}"), None)
|
||||
.await;
|
||||
assert_eq!(st.json["state"], "waiting");
|
||||
|
||||
let out = cli(&env, &["pki", "approve", &code]);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
let done = wait_request(&env, &rid, "approved").await;
|
||||
let did = done["device_id"].as_str().unwrap().to_owned();
|
||||
|
||||
let certs = env.call("GET", "/api/v1/certs", None).await;
|
||||
assert_eq!(certs.status, 200, "{}", certs.text);
|
||||
assert_eq!(certs.json["root"]["offline"], true);
|
||||
let dev = certs.json["devices"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|d| d["id"] == did.as_str())
|
||||
.unwrap()
|
||||
.clone();
|
||||
assert_eq!(dev["state"], "valid");
|
||||
assert_eq!(dev["name"], "Mark's phone");
|
||||
|
||||
// The allow list both engines read has it.
|
||||
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
|
||||
assert!(allow.contains("BEGIN CERTIFICATE"));
|
||||
|
||||
// One-time install file.
|
||||
let b = env
|
||||
.call(
|
||||
"POST",
|
||||
&format!("/api/v1/certs/devices/{did}/bundle"),
|
||||
Some(json!({"format": "qr"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(b.status, 200, "{}", b.text);
|
||||
let url = b.json["download_url"].as_str().unwrap().to_owned();
|
||||
let password = b.json["one_time_password"].as_str().unwrap().to_owned();
|
||||
assert!(b.json["qr_svg"].as_str().unwrap().starts_with("<?xml"));
|
||||
let path = url
|
||||
.split_once("/api/v1/")
|
||||
.map(|(_, p)| format!("/api/v1/{p}"))
|
||||
.unwrap();
|
||||
// No token needed for the download itself (the link is the secret) ...
|
||||
let d = env.call_with("GET", &path, &[], None).await;
|
||||
assert_eq!(d.status, 200, "{}", d.text);
|
||||
assert_eq!(d.header("content-type"), Some("application/x-pkcs12"));
|
||||
let ks = p12_keystore::KeyStore::from_pkcs12(
|
||||
&d.body,
|
||||
&password,
|
||||
p12_keystore::Pkcs12ImportPolicy::Strict,
|
||||
)
|
||||
.unwrap();
|
||||
let (_, chain) = ks.private_key_chain().unwrap();
|
||||
assert_eq!(chain.certs().len(), 3, "leaf, intermediate, root");
|
||||
// ... and it works only once.
|
||||
let d = env.call_with("GET", &path, &[], None).await;
|
||||
assert_eq!(d.status, 410, "{}", d.text);
|
||||
assert_eq!(d.json["error"]["code"], "pki.bundle_used");
|
||||
|
||||
// Revoke: off the allow list, no new install file.
|
||||
let r = env
|
||||
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
|
||||
.await;
|
||||
assert_eq!(r.status, 204, "{}", r.text);
|
||||
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
|
||||
assert!(!allow.contains("BEGIN CERTIFICATE"), "{allow}");
|
||||
let b = env
|
||||
.call(
|
||||
"POST",
|
||||
&format!("/api/v1/certs/devices/{did}/bundle"),
|
||||
Some(json!({"format": "p12"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(b.status, 409, "{}", b.text);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn control_refuses_to_start_with_a_root_key_in_its_state_dir() {
|
||||
let (mut env, off) = env_with_pki().await;
|
||||
env.kill_control();
|
||||
std::fs::write(env.dir.join("state/root.key"), off.root_key.serialize_pem()).unwrap();
|
||||
let out = env
|
||||
.command()
|
||||
.arg("--config")
|
||||
.arg(env.config_path())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!out.status.success());
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(err.contains("root"), "{err}");
|
||||
// And the message never prints the key.
|
||||
assert!(!err.contains("PRIVATE KEY"), "{err}");
|
||||
}
|
||||
|
||||
fn walk(dir: &Path) -> Vec<std::path::PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![dir.to_path_buf()];
|
||||
while let Some(d) = stack.pop() {
|
||||
let Ok(rd) = std::fs::read_dir(&d) else {
|
||||
continue;
|
||||
};
|
||||
for e in rd.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
stack.push(p);
|
||||
} else {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user