Files
ianitor/crates/edge/tests/acme_pebble.rs
T

232 lines
8.7 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/.
//! ACME end to end against Pebble (Let's Encrypt's test ACME server) on 127.0.0.1:
//! edge creates an account, answers the HTTP-01 challenge on its HTTP listener, obtains a
//! certificate, stores it with private permissions and serves it by SNI, next to a host with a
//! Domi (test CA) certificate. Needs `pebble` and `pebble-challtestsrv` on PATH; without them
//! the test fails unless `IANITOR_ALLOW_SKIP=1`.
//!
//! This is not Let's Encrypt staging: that needs a public domain and DNS.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common;
// On Windows this target has nothing to run: it shows as one *ignored* test, never as a
// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md).
#[cfg(not(unix))]
#[test]
#[ignore = "needs Linux (Pingora runner, Caddy, Pebble): run it in WSL2, see CLAUDE.md"]
fn needs_linux() {}
#[cfg(unix)]
mod unix {
use std::os::unix::fs::PermissionsExt;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::common::{EdgeSpec, host_file, spawn};
use ianitor_testkit::client::{self, Req};
use ianitor_testkit::proc::{
ChildGuard, TempDir, free_port, local, require_binary, wait_for_port,
};
use ianitor_testkit::tls::{TestCa, roots_from_pem};
use ianitor_testkit::upstream::Echo;
#[tokio::test(flavor = "multi_thread")]
async fn certificate_is_obtained_from_pebble_and_served() {
let (Some(pebble), Some(challtestsrv)) = (
require_binary("pebble"),
require_binary("pebble-challtestsrv"),
) else {
return;
};
let dir = TempDir::new("pebble");
// Pebble's own HTTPS endpoint needs a certificate; our test CA signs one for 127.0.0.1.
let ca = TestCa::new("Pebble Listener CA");
let leaf = ca.issue(&["127.0.0.1"]);
std::fs::write(dir.join("pebble.crt"), &leaf.cert_pem).unwrap();
std::fs::write(dir.join("pebble.key"), &leaf.key_pem).unwrap();
std::fs::write(dir.join("listener-ca.pem"), &ca.cert_pem).unwrap();
let (acme_port, mgmt_port, dns_port, cts_mgmt, tls_port) = (
free_port(),
free_port(),
free_port(),
free_port(),
free_port(),
);
let edge_http = free_port();
let config = serde_json::json!({ "pebble": {
"listenAddress": format!("127.0.0.1:{acme_port}"),
"managementListenAddress": format!("127.0.0.1:{mgmt_port}"),
"certificate": dir.str("pebble.crt"),
"privateKey": dir.str("pebble.key"),
"httpPort": edge_http,
"tlsPort": tls_port,
"ocspResponderURL": "",
"externalAccountBindingRequired": false,
"domainBlocklist": [],
"retryAfter": { "authz": 1, "order": 1 },
"profiles": { "default": { "description": "test", "validityPeriod": 7_776_000 } }
}});
std::fs::write(dir.join("pebble.json"), config.to_string()).unwrap();
let log = std::fs::File::create(dir.join("pebble.log")).unwrap();
// Fake DNS: every name resolves to 127.0.0.1, so Pebble validates against edge.
let _cts = ChildGuard(
Command::new(challtestsrv)
.args(["-defaultIPv4", "127.0.0.1", "-defaultIPv6", ""])
.args(["-dns01", &format!("127.0.0.1:{dns_port}")])
.args(["-management", &format!("127.0.0.1:{cts_mgmt}")])
.args(["-http01", "", "-https01", "", "-tlsalpn01", "", "-doh", ""])
.stdout(Stdio::from(log.try_clone().unwrap()))
.stderr(Stdio::from(log.try_clone().unwrap()))
.spawn()
.unwrap(),
);
let _pebble = ChildGuard(
Command::new(pebble)
.arg("-config")
.arg(dir.join("pebble.json"))
.args(["-dnsserver", &format!("127.0.0.1:{dns_port}")])
.env("PEBBLE_VA_NOSLEEP", "1")
.env("PEBBLE_WFE_NONCEREJECT", "0")
.env("PEBBLE_AUTHZREUSE", "0")
.stdout(Stdio::from(log.try_clone().unwrap()))
.stderr(Stdio::from(log))
.spawn()
.unwrap(),
);
assert!(
wait_for_port(local(acme_port), Duration::from_secs(20)),
"pebble did not start"
);
assert!(wait_for_port(local(mgmt_port), Duration::from_secs(5)));
// Edge starts after Pebble, so its first ACME round succeeds.
let echo_acme = Echo::start("acme-upstream").await;
let echo_domi = Echo::start("domi-upstream").await;
let site = format!(
"[acme]\nemail = \"admin@example.org\"\ndirectory = \"https://127.0.0.1:{acme_port}/dir\"\n"
);
let mut edge = spawn(EdgeSpec {
site: &site,
hosts: vec![
(
"hosts/acme.test.toml".into(),
format!(
"hostname = \"acme.test\"\ntls = \"letsencrypt\"\nupstreams = [\"{}\"]\n",
echo_acme.url()
),
),
host_file(
"domi.test",
&format!("upstreams = [\"{}\"]\n", echo_domi.url()),
),
],
log_level: "debug",
extra_args: vec!["--acme-root".into(), dir.str("listener-ca.pem")],
http_port: Some(edge_http),
..Default::default()
});
assert!(
wait_for_port(edge.http, Duration::from_secs(20)),
"edge HTTP listener:\n{}",
edge.stderr()
);
// The root Pebble signs with (generated at Pebble start).
let root = client::https(
local(mgmt_port),
"127.0.0.1",
ca.roots(),
&Req::get(&format!("127.0.0.1:{mgmt_port}"), "/roots/0"),
)
.await
.unwrap();
assert_eq!(root.status, 200);
let pebble_roots = roots_from_pem(&root.text());
let deadline = Instant::now() + Duration::from_secs(90);
let served = loop {
if let Ok(r) = client::https(
edge.https,
"acme.test",
pebble_roots.clone(),
&Req::get("acme.test", "/via-acme"),
)
.await
{
break r;
}
if Instant::now() > deadline || edge.exited().is_some() {
panic!(
"no ACME certificate served in time.\n--- edge ---\n{}\n--- pebble ---\n{}",
edge.stderr(),
std::fs::read_to_string(dir.join("pebble.log")).unwrap_or_default()
);
}
tokio::time::sleep(Duration::from_millis(500)).await;
};
assert_eq!(served.status, 200);
assert!(served.text().contains("acme-upstream"), "{}", served.text());
assert!(
edge.stderr().contains("acme.test: certificate issued"),
"{}",
edge.stderr()
);
assert!(
edge.stderr()
.contains("answered HTTP-01 challenge for acme.test"),
"the challenge was really validated"
);
// The Domi host keeps working with its own CA next to the ACME host.
let r = client::https(
edge.https,
"domi.test",
edge.roots(),
&Req::get("domi.test", "/"),
)
.await
.unwrap();
assert_eq!(r.status, 200);
assert!(r.text().contains("domi-upstream"));
// Stored with private permissions.
let acme_dir = edge.dir.join("state/acme");
for f in ["acme.test.key", "acme.test.crt"] {
let mode = std::fs::metadata(acme_dir.join(f))
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o600, "{f} has mode {mode:o}");
}
let account = std::fs::read_dir(&acme_dir)
.unwrap()
.map(|e| e.unwrap().path())
.find(|p| {
p.file_name()
.unwrap()
.to_string_lossy()
.starts_with("account-")
})
.expect("account file stored");
assert_eq!(
std::fs::metadata(account).unwrap().permissions().mode() & 0o777,
0o600
);
assert!(
!edge.stderr().contains("PRIVATE KEY"),
"no key material in the log"
);
}
}