[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:
2026-11-07 23:11:05 +01:00
parent a5190acc3b
commit 211b851c3e
17 changed files with 3005 additions and 10 deletions
+6 -1
View File
@@ -29,11 +29,16 @@ ring.workspace = true
base64.workspace = true
http.workspace = true
bytes.workspace = true
# Dev mode only: a throw-away CA for the dev hosts (the Domi CA arrives in phase 3).
rcgen.workspace = true
# Device certificate install files (PKCS#12) and their QR codes.
p12-keystore = "0.4"
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
# The offline root CLI asks for its passphrase without echo.
rpassword = "7"
[dev-dependencies]
ianitor-testkit.workspace = true
p12-keystore = "0.4"
ianitor-edge.workspace = true
rustls.workspace = true
+80
View File
@@ -48,6 +48,16 @@ pub struct Config {
pub compile: Compile,
/// Different facts for the Caddy output (only tests need this: both engines side by side).
pub compile_caddy: Option<Compile>,
/// The Domi CA; without it `tls = "domi"` certificates are expected in `cert_dir` already
/// and the certificate screens say the CA is not set up.
#[serde(default)]
pub pki: Option<PkiConfig>,
/// The web UI behind edge (sign-in through Authelia, see docs/api.md).
#[serde(default)]
pub ui: Option<UiConfig>,
/// Switching between Pingora and the Caddy fallback at runtime.
#[serde(default)]
pub engine: Option<EngineConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -280,3 +290,73 @@ fn empty_model() -> Option<ianitor_core::Model> {
)
.ok()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PkiConfig {
/// The Domi root certificate (public; may be a Nix store path). The root key is never on
/// the server.
pub root_cert: PathBuf,
/// Credential with the password that encrypts the intermediate and device keys at rest.
#[serde(default = "default_pki_password")]
pub password_credential: String,
/// How requests are approved: `manual` (`ianitor-control pki approve <code>` on the
/// server) until Custos can (docs/custos-ticket.md).
#[serde(default = "default_approval")]
pub approval: String,
/// PBKDF2 iterations for the keys control encrypts (only tests lower it).
#[serde(default = "default_kdf")]
pub kdf_iterations: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UiConfig {
/// The admin host edge serves the UI on (a host in the routes repository with
/// `auth = "forward-auth"`, upstream this API, and the proof header rule). Added to
/// `allowed_hosts`; used for device install links.
pub hostname: Option<String>,
/// Credential holding the per-boot secret edge adds as `X-Ianitor-Proof` on the admin
/// host. With it, a request carrying the proof is identified by its `Remote-User`.
pub proof_credential: Option<String>,
/// The built web UI (served at `/`).
pub static_dir: Option<PathBuf>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EngineConfig {
/// Which engine runs at boot: `pingora` or `caddy` (read by the engine-select unit).
pub file: PathBuf,
/// `systemctl` (through the polkit rule for exactly the two units) or `none`.
#[serde(default = "default_units")]
pub units: String,
#[serde(default = "default_systemctl")]
pub systemctl: PathBuf,
#[serde(default = "default_edge_unit")]
pub edge_unit: String,
#[serde(default = "default_caddy_unit")]
pub caddy_unit: String,
}
fn default_pki_password() -> String {
"pki-password".into()
}
fn default_approval() -> String {
"manual".into()
}
fn default_kdf() -> u32 {
ianitor_core::pki::KEY_KDF_ITERATIONS
}
fn default_units() -> String {
"systemctl".into()
}
fn default_systemctl() -> PathBuf {
PathBuf::from("systemctl")
}
fn default_edge_unit() -> String {
"ianitor-edge.service".into()
}
fn default_caddy_unit() -> String {
"caddy-fallback.service".into()
}
+3
View File
@@ -174,6 +174,9 @@ pub async fn run(args: &[String]) -> Result<(), String> {
caddy_admin: None,
},
compile_caddy: None,
pki: None,
ui: None,
engine: None,
};
cfg.check().map_err(|e| e.to_string())?;
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
+7
View File
@@ -174,6 +174,13 @@ impl EdgeLink {
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
}
/// Re-read the device CA bundle and allow list (works during a trial too).
pub async fn reload_devices(&self) -> Result<(), EdgeLinkError> {
self.call("POST", "/v1/device-certs/reload", None)
.await
.map(|_| ())
}
pub async fn reload_revocations(&self) -> Result<(), EdgeLinkError> {
self.call("POST", "/v1/share-revocations/reload", None)
.await
+48 -1
View File
@@ -141,6 +141,12 @@ pub struct Control {
pub tokens: Tokens,
pub shares: Shares,
pub share_key: Option<ShareKey>,
/// The Domi CA, when `[pki]` is configured.
pub pki: Option<crate::pki::Pki>,
/// Which engine serves (see `switch`).
pub engine: Mutex<crate::switch::EngineState>,
/// How control starts and stops the engines; `None` without `[engine]`.
pub units: Option<Arc<dyn crate::switch::Units>>,
records: Mutex<Vec<ApplyRecord>>,
queue: Mutex<VecDeque<Job>>,
wake: Notify,
@@ -151,7 +157,7 @@ pub struct Control {
/// False while the pause is only in memory (paused.json could not be written).
pause_saved: std::sync::atomic::AtomicBool,
/// Serialises applies with share-revocation writes and recovery.
apply_lock: tokio::sync::Mutex<()>,
pub(crate) apply_lock: tokio::sync::Mutex<()>,
}
const MAX_RECORDS: usize = 1000;
@@ -207,6 +213,21 @@ impl Control {
if share_key.is_none() {
log::warn!(target: "ianitor::control", "no usable share-link-key credential: share links cannot be made");
}
let keys = crate::pki::root_key_files(&cfg.state_dir);
if let Some(k) = keys.first() {
return Err(format!(
"{} looks like a root CA key inside the state directory; the Domi root key must never be on the server (ROADMAP §1.2). Move it to the offline machine.",
k.display()
));
}
let pki = match &cfg.pki {
Some(p) => Some(crate::pki::Pki::open(
p,
&cfg.state_dir,
cfg.credential(&p.password_credential),
)?),
None => None,
};
let records: Vec<ApplyRecord> =
read_json(&cfg.state_dir.join("applies.json"))?.unwrap_or_default();
let push: PushState = read_json(&cfg.state_dir.join("push.json"))?.unwrap_or_default();
@@ -217,6 +238,19 @@ impl Control {
repo,
edge,
share_key,
pki,
engine: Mutex::new(crate::switch::EngineState {
running: cfg
.engine
.as_ref()
.map(|e| crate::switch::read_engine_file(&e.file))
.unwrap_or_else(|| "pingora".into()),
state: "running".into(),
since: now(),
target: None,
last_error: None,
}),
units: crate::switch::units_for(cfg.engine.as_ref()),
records: Mutex::new(records),
queue: Mutex::new(VecDeque::new()),
wake: Notify::new(),
@@ -228,6 +262,11 @@ impl Control {
apply_lock: tokio::sync::Mutex::new(()),
cfg,
});
if let Ok((_, _, m)) = c.head_model()
&& let Err(f) = c.pki_prepare(&m)
{
log::error!(target: "ianitor::pki", "{}", f.reason.message);
}
c.recover().await?;
Ok(c)
}
@@ -390,6 +429,9 @@ impl Control {
/// `in_worker` is false when a request is first checked: a change that the worker may
/// still let through (after it retried the files) is queued rather than refused.
fn paused_for(&self, change: &Change, in_worker: bool) -> Option<Reason> {
if let Some(e) = self.engine_pause() {
return Some(e);
}
let p = self.paused()?;
if !in_worker && p.code == "control.files_unwritten" {
return None;
@@ -863,6 +905,11 @@ impl Control {
Ok(x) => x,
Err(f) => return self.finish(&id, "failed", Some(f.reason), Vec::new()),
};
// Domi certificates for the hosts of the new tree, before anything is committed (new
// files only: a certificate edge serves now is never replaced by a worse one).
if let Err(f) = self.pki_prepare(&plan.model) {
return self.finish(&id, "failed", Some(f.reason), Vec::new());
}
self.update(&id, |r| {
r.step("compile", "done");
r.step("write", "running");
+3
View File
@@ -14,9 +14,12 @@ pub mod engine;
pub mod hostspec;
pub mod logger;
pub mod messages;
pub mod pki;
pub mod pki_ctl;
pub mod records;
pub mod repo;
pub mod shares;
pub mod switch;
pub mod tokens;
pub mod util;
+82
View File
@@ -228,6 +228,88 @@ fn template(code: &str) -> &'static str {
"health.unavailable" => {
"Ianitor cannot read health from {engine} right now. Traffic is not affected."
}
// 3.6 PKI
"pki.waiting" => {
"Open Custos on your phone. Approve only if it shows the same code: {code}."
}
"pki.waiting.manual" => {
"Approve it on the server: run ianitor-control pki approve {code}. Approve only if the code matches."
}
"pki.renew.manual" => {
"Sign this request on the offline machine (ianitor-control ca sign), check that it shows the code {code}, then install the certificate."
}
"pki.denied" => "The request was turned down. Nothing was issued.",
"pki.expired" => "Nobody approved it in time, so the request closed. Nothing was issued.",
"pki.custos_unreachable" => "Custos is not answering, so the request could not be sent.",
"pki.device_name_taken" => {
"A device with this name already has a certificate or an open request. Use another name, or revoke the old one first."
}
"pki.device_name" => "Give the device a name of 1 to 64 characters.",
"pki.device_kind" => "Choose phone, computer or app.",
"pki.issued" => "{name} has a certificate.",
"pki.bundle_used" => {
"This download was already used or has expired. Make a new one from the device's row."
}
"pki.renew_due" => "The Domi intermediate certificate expires in {days} days, on {date}.",
"pki.renew_urgent" => {
"The Domi intermediate certificate expires in {days} days. After that, Domi certificates stop working."
}
"pki.intermediate_expired" => {
"The Domi intermediate certificate has expired. Hosts with a Domi certificate are not trusted until it is renewed."
}
"pki.renewed" => "Renewed. The Domi intermediate certificate is now valid until {date}.",
"pki.not_configured" => {
"The Domi certificate authority is not set up on this server. See docs/pki.md."
}
"pki.no_password" => {
"The password for the Domi certificate keys is missing from the server's credentials, so nothing can be issued."
}
"pki.wrong_password" => {
"The password for the Domi certificate keys does not open them. Check the pki-password credential."
}
"pki.no_intermediate" => {
"There is no Domi intermediate certificate yet, so Domi certificates cannot be issued. Set it up first in Certificates."
}
"pki.not_our_root" => {
"This certificate was not signed by the Domi root this server trusts."
}
"pki.wrong_key" => {
"This certificate was made for another request. Sign the request shown here, then try again."
}
"pki.bad_certificate" => {
"This is not a Domi intermediate certificate Ianitor can use. It must be a CA with path length 0 that is valid now."
}
"pki.request_not_found" => "There is no such request.",
"pki.request_closed" => "This request is closed. Start a new one.",
"pki.wrong_code" => "That code does not match the request.",
"pki.too_many_requests" => "Too many requests are open. Finish or cancel some first.",
"pki.device_not_found" => "There is no such device.",
"pki.device_not_valid" => {
"This device's certificate is revoked or expired, so it cannot be installed. Issue a new one."
}
"pki.revoked" => {
"Revoked. {name} can no longer reach hosts that need a device certificate."
}
// UI sign-in
"ui.no_proof" => {
"This request carries a sign-in header but did not come through Ianitor's proxy, so it was refused."
}
"ui.no_user" => "The sign-in did not say who you are. Sign in again.",
// engine switch
"engine.unmanaged" => {
"This server does not let Ianitor switch engines (no engine settings in control.toml)."
}
"engine.same" => "{engine} is already serving.",
"engine.switching" => "A switch is already running. Wait for it to finish.",
"engine.busy" => "A change is being applied. Switch when it has finished.",
"engine.switched" => "{engine} is serving now.",
"engine.switch_failed" => {
"{engine} did not start, so Ianitor went back to {previous}. Traffic is served as before."
}
"engine.caddy" => "Caddy is serving. Changes wait until you switch back to Pingora.",
"share.engine_caddy" => {
"Share links are paused while Caddy serves. They work again after switching back."
}
"internal" => "Something went wrong inside Ianitor control. Show details for more.",
_ => "Something went wrong.",
}
File diff suppressed because it is too large Load Diff
+207
View File
@@ -0,0 +1,207 @@
// 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/.
//! Control's side of the Domi CA: certificates for the hosts of every tree that is applied,
//! the device files both engines read, and what happens after an approval, a renewal or a
//! revocation.
// A refusal is built once per failed request; boxing it buys nothing.
#![allow(clippy::result_large_err)]
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use ianitor_core::TlsMode;
use crate::engine::{Control, Fail};
use crate::messages::{self, Params};
use crate::pki::PkiFail;
use crate::util::now;
/// The HTTP status for a PKI refusal.
pub fn status_of(code: &str) -> u16 {
match code {
"pki.request_not_found" | "pki.device_not_found" => 404,
"pki.bundle_used" => 410,
"pki.bad_certificate"
| "pki.not_our_root"
| "pki.wrong_key"
| "pki.device_name"
| "pki.device_kind"
| "pki.wrong_code" => 422,
"pki.too_many_requests" => 429,
_ => 409,
}
}
pub fn pki_fail(e: PkiFail) -> Fail {
match e {
PkiFail::Code(c) => Fail::new(status_of(c), c, Params::new()),
PkiFail::Internal(d) => Fail::new(500, "internal", Params::new()).detail(d),
}
}
impl Control {
pub fn pki_or_fail(&self) -> Result<&crate::pki::Pki, Fail> {
self.pki
.as_ref()
.ok_or_else(|| Fail::new(409, "pki.not_configured", Params::new()))
}
/// Every certificate directory a compiler output points at.
fn cert_dirs(&self) -> Vec<&Path> {
let mut v = vec![Path::new(&self.cfg.compile.cert_dir)];
let c = Path::new(&self.cfg.caddy_compile().cert_dir);
if c != v[0] {
v.push(c);
}
v
}
/// Before a tree goes live: server certificates for its `tls = "domi"` hosts and the
/// device files when a host needs them. Without `[pki]` nothing is issued (the files are
/// expected to be there, as in phase 2). Returns whether a file changed.
pub fn pki_prepare(&self, model: &ianitor_core::Model) -> Result<bool, Fail> {
let Some(p) = &self.pki else {
return Ok(false);
};
let t = now();
let domi: Vec<String> = model
.hosts()
.iter()
.filter(|h| h.tls == TlsMode::Domi)
.map(|h| h.hostname.to_string())
.collect();
let devices = model.hosts().iter().any(|h| h.device_certs);
let mut changed = false;
for dir in self.cert_dirs() {
let issued = p.ensure_host_certs(&domi, dir, t).map_err(|e| {
let mut f = pki_fail(e);
// The apply's reason names a host so the UI can point at it.
if let Some(h) = domi.first() {
f.reason.hostname = Some(h.clone());
}
f
})?;
if !issued.is_empty() {
log::info!(target: "ianitor::pki", "issued server certificates for {}", issued.join(", "));
changed = true;
}
if devices || dir.join(ianitor_core::compile::DEVICE_CA_FILE).exists() {
changed |= p.write_device_files(dir, t).map_err(pki_fail)?;
}
}
Ok(changed)
}
/// Every couple of seconds: act on approvals; once an hour: renew server certificates.
pub async fn pki_poller(self: Arc<Self>) {
if self.pki.is_none() {
return;
}
let mut last_renewal_check = now();
loop {
tokio::time::sleep(Duration::from_secs(2)).await;
let me = self.clone();
let polled = tokio::task::spawn_blocking(move || match &me.pki {
Some(p) => p.poll(now()),
None => Ok(Default::default()),
})
.await;
let changes = match polled {
Ok(Ok(c)) => c,
Ok(Err(e)) => {
log::error!(target: "ianitor::pki", "{e}");
continue;
}
Err(e) => {
log::error!(target: "ianitor::pki", "pki poll crashed: {e}");
continue;
}
};
let t = now();
if changes.intermediate || t.saturating_sub(last_renewal_check) >= 3600 {
last_renewal_check = t;
self.refresh_certificates(changes.intermediate).await;
}
if changes.devices {
self.devices_changed().await;
}
}
}
/// Issue what the current tree needs (after a new intermediate: everything) and reload
/// the engine that serves, under the apply lock so no trial is running.
pub async fn refresh_certificates(&self, new_intermediate: bool) {
let _lock = self.apply_lock.lock().await;
let Ok((_, _, model)) = self.head_model() else {
return;
};
match self.pki_prepare(&model) {
Ok(changed) if changed || new_intermediate => {
if new_intermediate {
log::info!(target: "ianitor::pki", "new Domi intermediate installed; certificates reissued");
}
self.reload_serving_engine().await;
}
Ok(_) => {}
Err(f) => {
log::error!(target: "ianitor::pki", "certificates not renewed: {}", f.reason.message);
}
}
}
/// The device files changed (issue or revoke): rewrite them and tell the engine at once.
pub async fn devices_changed(&self) {
let Some(p) = &self.pki else { return };
let t = now();
let mut changed = false;
for dir in self.cert_dirs() {
match p.write_device_files(dir, t) {
Ok(c) => changed |= c,
Err(e) => log::error!(target: "ianitor::pki", "device files not written: {e}"),
}
}
if !changed {
return;
}
if self.engine_running() == "caddy" {
// Caddy reads the allow list when it starts: restart it so a revocation counts.
if let Err(e) = self.restart_caddy().await {
log::error!(target: "ianitor::pki", "caddy-fallback not restarted after a device change: {e}");
}
} else if self.edge.attached()
&& let Err(e) = self.edge.reload_devices().await
{
log::error!(target: "ianitor::pki", "edge did not re-read the device certificates: {e}");
}
}
async fn reload_serving_engine(&self) {
if self.engine_running() == "caddy" {
if let Err(e) = self.restart_caddy().await {
log::error!(target: "ianitor::pki", "caddy-fallback not restarted: {e}");
}
} else if self.edge.attached()
&& let Err(e) = self.edge.reload().await
{
log::error!(target: "ianitor::pki", "edge did not reload the new certificates: {e}");
}
}
/// The code and message for a PKI request that waits for its approval.
pub fn waiting_message(&self, kind: &str, code: &str) -> (String, String) {
let manual = self.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual");
let c = match (kind, manual) {
("intermediate", _) => "pki.renew.manual",
(_, true) => "pki.waiting.manual",
(_, false) => "pki.waiting",
};
(
c.to_owned(),
messages::message(c, &messages::params([("code", code.to_owned())])),
)
}
}
+400
View File
@@ -0,0 +1,400 @@
// 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/.
//! Switching the engine at runtime (ROADMAP §1.6 as corrected 2026-11-07, §3, §4).
//!
//! Exactly one of `ianitor-edge.service` and `caddy-fallback.service` runs. Control may start,
//! stop and restart only those two, through a polkit rule scoped to exactly them (NixOS
//! module). `/var/lib/ianitor/engine` names the one to run; the `ianitor-engine-select` unit
//! reads it at boot. A switch writes the file first (so a reboot mid-switch boots the
//! target), stops the old engine, starts the new one and waits until it serves; if the new
//! one does not come up, it goes back to the old one and says so.
//!
//! Decisions (phase 3):
//! - While Caddy serves, changes are paused (`engine.caddy`): Caddy is the emergency
//! fallback, and the apply pipeline's trial, watch and revert are built on edge's admin
//! socket. Changes made then would also have no differential check.
//! - Share links are refused while Caddy serves (`share.engine_caddy`, see docs/api.md):
//! Caddy cannot check them, and control never serves visitors itself.
//! - Device revocations while Caddy serves restart caddy-fallback (Caddy reads the allow
//! list when it starts); this is why the polkit rule also allows `restart`.
//!
//! The systemd calls go through [`Units`], so tests use a fake.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::config::EngineConfig;
use crate::engine::{Control, Fail, reason};
use crate::messages::{self, Params};
use crate::records::Reason;
use crate::util::{now, write_atomic};
/// Start, stop and look at systemd units.
pub trait Units: Send + Sync {
fn start(&self, unit: &str) -> Result<(), String>;
fn stop(&self, unit: &str) -> Result<(), String>;
fn restart(&self, unit: &str) -> Result<(), String>;
fn is_active(&self, unit: &str) -> Result<bool, String>;
}
/// `systemctl --no-ask-password <verb> <unit>`, as the control user (polkit decides).
pub struct Systemctl {
pub bin: PathBuf,
}
impl Systemctl {
fn run(&self, args: &[&str]) -> Result<std::process::Output, String> {
std::process::Command::new(&self.bin)
.arg("--no-ask-password")
.args(args)
.stdin(std::process::Stdio::null())
.output()
.map_err(|e| format!("cannot run {}: {e}", self.bin.display()))
}
fn verb(&self, verb: &str, unit: &str) -> Result<(), String> {
let o = self.run(&[verb, unit])?;
if o.status.success() {
Ok(())
} else {
Err(format!(
"systemctl {verb} {unit} failed: {}",
String::from_utf8_lossy(&o.stderr).trim()
))
}
}
}
impl Units for Systemctl {
fn start(&self, unit: &str) -> Result<(), String> {
self.verb("start", unit)
}
fn stop(&self, unit: &str) -> Result<(), String> {
self.verb("stop", unit)
}
fn restart(&self, unit: &str) -> Result<(), String> {
self.verb("restart", unit)
}
fn is_active(&self, unit: &str) -> Result<bool, String> {
Ok(self.run(&["is-active", "--quiet", unit])?.status.success())
}
}
/// In-memory units for tests: records every call; `fail_start` makes a start fail.
#[derive(Default)]
pub struct FakeUnits {
pub calls: Mutex<Vec<String>>,
pub active: Mutex<HashSet<String>>,
pub fail_start: Mutex<HashSet<String>>,
}
impl Units for FakeUnits {
fn start(&self, unit: &str) -> Result<(), String> {
if let Ok(mut c) = self.calls.lock() {
c.push(format!("start {unit}"));
}
if self.fail_start.lock().is_ok_and(|f| f.contains(unit)) {
return Err(format!("{unit} failed to start"));
}
if let Ok(mut a) = self.active.lock() {
a.insert(unit.to_owned());
}
Ok(())
}
fn stop(&self, unit: &str) -> Result<(), String> {
if let Ok(mut c) = self.calls.lock() {
c.push(format!("stop {unit}"));
}
if let Ok(mut a) = self.active.lock() {
a.remove(unit);
}
Ok(())
}
fn restart(&self, unit: &str) -> Result<(), String> {
if let Ok(mut c) = self.calls.lock() {
c.push(format!("restart {unit}"));
}
Ok(())
}
fn is_active(&self, unit: &str) -> Result<bool, String> {
Ok(self.active.lock().is_ok_and(|a| a.contains(unit)))
}
}
/// Which engine serves, as control knows it.
#[derive(Debug, Clone)]
pub struct EngineState {
/// `pingora` or `caddy`.
pub running: String,
/// `running`, `switching` or `stopped`.
pub state: String,
pub since: u64,
/// The target while switching.
pub target: Option<String>,
/// Why the last switch did not happen.
pub last_error: Option<Reason>,
}
pub fn read_engine_file(p: &Path) -> String {
match std::fs::read_to_string(p) {
Ok(s) if s.trim() == "caddy" => "caddy".into(),
_ => "pingora".into(),
}
}
pub fn engine_name(e: &str) -> String {
if e == "caddy" { "Caddy" } else { "Pingora" }.into()
}
impl Control {
pub fn engine_cfg(&self) -> Option<&EngineConfig> {
self.cfg.engine.as_ref()
}
/// `pingora` or `caddy`.
pub fn engine_running(&self) -> String {
self.engine
.lock()
.map(|e| e.running.clone())
.unwrap_or_else(|_| "pingora".into())
}
pub fn engine_state(&self) -> EngineState {
self.engine
.lock()
.map(|e| e.clone())
.unwrap_or(EngineState {
running: "pingora".into(),
state: "running".into(),
since: 0,
target: None,
last_error: None,
})
}
fn set_engine(&self, f: impl FnOnce(&mut EngineState)) {
if let Ok(mut e) = self.engine.lock() {
f(&mut e);
}
}
pub async fn restart_caddy(&self) -> Result<(), String> {
let (Some(cfg), Some(units)) = (self.engine_cfg(), self.units.clone()) else {
return Err("no engine settings".into());
};
let unit = cfg.caddy_unit.clone();
tokio::task::spawn_blocking(move || units.restart(&unit))
.await
.map_err(|e| e.to_string())?
}
/// Check a switch request and start it. Answers at once; the switch runs in the
/// background (`overview.engine.state` is `switching` until it ends).
pub fn request_switch(self: &Arc<Self>, target: &str) -> Result<EngineState, Fail> {
if self.engine_cfg().is_none() || self.units.is_none() {
return Err(Fail::new(409, "engine.unmanaged", Params::new()));
}
if target != "pingora" && target != "caddy" {
return Err(Fail::new(
422,
"request.body",
messages::params([("problem", "target must be \"pingora\" or \"caddy\".".into())]),
));
}
{
let mut e = self
.engine
.lock()
.map_err(|_| Fail::new(500, "internal", Params::new()))?;
if e.state == "switching" {
return Err(Fail::new(409, "engine.switching", Params::new()));
}
if e.running == target {
return Err(Fail::new(
409,
"engine.same",
messages::params([("engine", engine_name(target))]),
));
}
e.state = "switching".into();
e.target = Some(target.to_owned());
e.last_error = None;
}
let me = self.clone();
let t = target.to_owned();
tokio::spawn(async move { me.switch(&t).await });
Ok(self.engine_state())
}
async fn switch(self: Arc<Self>, target: &str) {
// No apply runs during a switch, and none starts.
let _lock = self.apply_lock.lock().await;
let from = self.engine_running();
let res = self.switch_inner(&from, target).await;
let t = now();
match res {
Ok(()) => {
log::info!(target: "ianitor::engine", "switched from {from} to {target}");
self.set_engine(|e| {
e.running = target.to_owned();
e.state = "running".into();
e.since = t;
e.target = None;
});
}
Err(detail) => {
log::error!(target: "ianitor::engine", "switch to {target} failed: {detail}");
// Go back to what served before.
let back = self.bring_back(&from).await;
let mut r = reason(
"engine.switch_failed",
messages::params([
("engine", engine_name(target)),
("previous", engine_name(&from)),
]),
);
r.detail = Some(match back {
Ok(()) => detail,
Err(b) => format!("{detail}; going back also failed: {b}"),
});
self.set_engine(|e| {
e.running = from.clone();
e.state = "running".into();
e.target = None;
e.last_error = Some(r);
});
}
}
}
fn units_and_cfg(&self) -> Result<(Arc<dyn Units>, EngineConfig), String> {
match (self.units.clone(), self.engine_cfg().cloned()) {
(Some(u), Some(c)) => Ok((u, c)),
_ => Err("no engine settings".into()),
}
}
fn unit_of(cfg: &EngineConfig, engine: &str) -> String {
if engine == "caddy" {
cfg.caddy_unit.clone()
} else {
cfg.edge_unit.clone()
}
}
async fn blocking<T: Send + 'static>(
f: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> Result<T, String> {
tokio::task::spawn_blocking(f)
.await
.map_err(|e| e.to_string())?
}
async fn switch_inner(&self, from: &str, target: &str) -> Result<(), String> {
let (units, cfg) = self.units_and_cfg()?;
if target == "caddy" {
// Caddy starts from caddy.json: make sure it is the current tree's.
self.write_current_caddy()?;
}
write_atomic(&cfg.file, target.as_bytes(), 0o644)
.map_err(|e| format!("cannot write {}: {e}", cfg.file.display()))?;
let (old, new) = (Self::unit_of(&cfg, from), Self::unit_of(&cfg, target));
let u = units.clone();
Self::blocking(move || u.stop(&old)).await?;
let u = units.clone();
let n = new.clone();
Self::blocking(move || u.start(&n)).await?;
self.wait_serving(target, &units, &new).await
}
async fn bring_back(&self, engine: &str) -> Result<(), String> {
let (units, cfg) = self.units_and_cfg()?;
let other = if engine == "caddy" {
"pingora"
} else {
"caddy"
};
write_atomic(&cfg.file, engine.as_bytes(), 0o644).map_err(|e| e.to_string())?;
let (stop, start) = (Self::unit_of(&cfg, other), Self::unit_of(&cfg, engine));
let u = units.clone();
let _ = Self::blocking(move || u.stop(&stop)).await;
let u = units.clone();
let s = start.clone();
Self::blocking(move || u.start(&s)).await?;
self.wait_serving(engine, &units, &start).await
}
/// Until the unit is active and serves: edge answers on its admin socket, Caddy accepts
/// connections on the HTTPS address.
async fn wait_serving(
&self,
engine: &str,
units: &Arc<dyn Units>,
unit: &str,
) -> Result<(), String> {
let deadline = tokio::time::Instant::now() + Duration::from_secs(20);
let addr = if engine == "caddy" {
self.cfg.caddy_compile().https_listen
} else {
self.cfg.compile.https_listen
};
loop {
let u = units.clone();
let n = unit.to_owned();
let active = Self::blocking(move || u.is_active(&n))
.await
.unwrap_or(false);
let serving = active
&& if engine == "pingora" && self.edge.attached() {
self.edge.status().await.is_ok()
} else {
tokio::net::TcpStream::connect(addr).await.is_ok()
};
if serving {
return Ok(());
}
if tokio::time::Instant::now() > deadline {
return Err(format!("{unit} did not come up within 20 s"));
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
/// Compile the current tree for Caddy and write caddy.json (the file only ever holds a
/// kept tree, so this only matters when it is missing or older).
fn write_current_caddy(&self) -> Result<(), String> {
let (_, _, model) = self.head_model().map_err(|f| f.reason.message)?;
self.pki_prepare(&model).map_err(|f| f.reason.message)?;
let text = ianitor_core::compile::caddy(&model, &self.cfg.caddy_compile().options())
.map_err(|e| e.to_string())?;
if std::fs::read_to_string(&self.cfg.caddy.config)
.ok()
.as_deref()
!= Some(text.as_str())
{
write_atomic(&self.cfg.caddy.config, text.as_bytes(), 0o644)
.map_err(|e| e.to_string())?;
}
Ok(())
}
/// Changes wait while Caddy serves.
pub fn engine_pause(&self) -> Option<Reason> {
(self.engine_running() == "caddy").then(|| reason("engine.caddy", Params::new()))
}
}
/// What control.toml's `[engine]` asks for.
pub fn units_for(cfg: Option<&EngineConfig>) -> Option<Arc<dyn Units>> {
let c = cfg?;
match c.units.as_str() {
"systemctl" => Some(Arc::new(Systemctl {
bin: c.systemctl.clone(),
})),
_ => None,
}
}
+5 -2
View File
@@ -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");
+421
View File
@@ -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)
}
}
+194
View File
@@ -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);
}
}
+9
View File
@@ -566,6 +566,15 @@ pub fn match_code(request: &[u8]) -> String {
)
}
/// SubjectPublicKeyInfo DER of a CSR (to match a signed certificate to its request).
pub fn csr_public_key_der(csr_pem: &str) -> Result<Vec<u8>, PkiError> {
use x509_parser::prelude::FromDer;
let der = csr_der(csr_pem)?;
let (_, csr) = x509_parser::certification_request::X509CertificationRequest::from_der(&der)
.map_err(|_| PkiError::BadCsr)?;
Ok(csr.certification_request_info.subject_pki.raw.to_vec())
}
/// DER of the first PEM block of a CSR (for the match code).
pub fn csr_der(csr_pem: &str) -> Result<Vec<u8>, PkiError> {
for p in x509_parser::pem::Pem::iter_from_buffer(csr_pem.as_bytes()) {