Files
ianitor/crates/edge/tests/common/mod.rs
T

235 lines
7.5 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/.
//! 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.
//! Every edge also gets an admin socket and a share-link revocation file in its directory.
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
use ianitor_core::compile::{self, CompileOptions};
use ianitor_core::{SourceFile, TlsMode, load};
use ianitor_testkit::more::{JsonResp, unix_json};
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
use ianitor_testkit::tls::TestCa;
use rustls::RootCertStore;
/// The share-link key written as the `share-link-key` credential of every test edge.
pub const SHARE_KEY: &[u8] = b"edge-test-share-key-0123456789abcdef0123456789";
pub struct Edge {
pub child: ChildGuard,
pub http: SocketAddr,
pub https: SocketAddr,
pub dir: TempDir,
pub ca: TestCa,
pub config_text: String,
pub opts: CompileOptions,
}
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 fn admin_socket(&self) -> PathBuf {
self.dir.join("admin.sock")
}
pub fn config_path(&self) -> PathBuf {
self.dir.join("edge.json")
}
pub fn trial_path(&self) -> PathBuf {
self.dir.join("edge.json.trial")
}
pub fn revocations_path(&self) -> PathBuf {
self.dir.join("share-revocations.json")
}
/// Compile routes with this edge's options (same ports, same directories).
pub fn compile(&self, site: &str, hosts: &[(String, String)]) -> String {
compile_with(&self.dir, &self.ca, &self.opts, site, hosts)
}
/// Call the admin socket.
pub async fn admin(
&self,
method: &str,
path: &str,
body: Option<serde_json::Value>,
) -> JsonResp {
unix_json(&self.admin_socket(), method, path, body.as_ref())
.await
.unwrap_or_else(|e| panic!("admin {method} {path}: {e}\n{}", self.stderr()))
}
pub fn write_revocations(&self, epoch: u32, deny: &[String]) {
let v = serde_json::json!({ "epoch": epoch, "deny": deny });
std::fs::write(self.revocations_path(), v.to_string()).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>,
/// Fixed HTTP port (e.g. one Pebble was told to validate against).
pub http_port: Option<u16>,
}
impl Default for EdgeSpec<'_> {
fn default() -> Self {
EdgeSpec {
site: "",
hosts: Vec::new(),
secrets: Vec::new(),
log_level: "info",
extra_args: Vec::new(),
http_port: None,
}
}
}
/// Load and compile; write a Domi certificate for every `tls = "domi"` host that has none.
fn compile_with(
dir: &TempDir,
ca: &TestCa,
opts: &CompileOptions,
site: &str,
hosts: &[(String, String)],
) -> String {
let sources: Vec<SourceFile> = hosts
.iter()
.map(|(n, c)| SourceFile {
name: n,
contents: c,
})
.collect();
let model = load(
&SourceFile {
name: "ianitor.toml",
contents: site,
},
&sources,
)
.expect("valid routes");
for h in model.hosts() {
let crt = dir.join(&format!("certs/{}.crt", h.hostname));
if h.tls == TlsMode::Domi && !crt.exists() {
let leaf = ca.issue(&[h.hostname.as_str()]);
std::fs::write(&crt, leaf.cert_pem).unwrap();
std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap();
}
}
compile::edge(&model, opts).unwrap()
}
/// 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 ca = TestCa::new("Ianitor Test CA");
std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap();
for (name, value) in &spec.secrets {
std::fs::write(dir.join(&format!("creds/{name}")), value).unwrap();
}
std::fs::write(
dir.join("share-revocations.json"),
"{\"epoch\": 0, \"deny\": []}",
)
.unwrap();
let http = local(spec.http_port.unwrap_or_else(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_with(&dir, &ca, &opts, spec.site, &spec.hosts);
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.arg("--admin-socket").arg(dir.join("admin.sock"));
cmd.arg("--share-revocations")
.arg(dir.join("share-revocations.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,
opts,
}
}
/// Spawn and wait until both listeners and the admin socket 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));
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !e.admin_socket().exists() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
if !ok || !e.admin_socket().exists() || 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}"),
)
}