[tests] Tests first, fix round 1: proof only on the forward-auth UI host, revocations that cannot be written, root key files by content, intermediates that cannot issue, stale SNI after a failed or resumed handshake, edge re-reads the allow list, changes apply while Caddy serves, Hostname focus (red)

This commit is contained in:
2026-11-08 10:26:31 +01:00
parent e2a777882c
commit 0749119f19
6 changed files with 690 additions and 11 deletions
+10 -1
View File
@@ -102,7 +102,7 @@ describe("ROADMAP §4 flows, clicks counted", () => {
expect(clicks).toBe(3);
});
it("Share link on a host with links off: 4 clicks (open question Q1 not decided)", async () => {
it("Share link on a host with links off: 4 clicks (Mark, Q1: the accepted 4th)", async () => {
start();
await click(await screen.findByRole("button", { name: "More for photos.home.test" }));
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
@@ -169,6 +169,15 @@ describe("ROADMAP §4 flows, clicks counted", () => {
});
});
describe("focus", () => {
it("+ Host puts the cursor in Hostname, so typing right after the click lands there", async () => {
start();
await click(await screen.findByRole("button", { name: "Add a host" }));
await user.keyboard("recipes.home.test");
expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("recipes.home.test");
});
});
describe("sign-in and contact", () => {
it("a 401 without Ianitor's envelope shows the signed-out dialog", async () => {
start();
+178 -10
View File
@@ -116,19 +116,11 @@ esac
let caddy = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap();
assert!(caddy.contains("a.test"));
// While Caddy serves: changes and share links wait, the overview says so.
// While Caddy serves: changes go on (changes_apply_while_caddy_serves), share links wait.
let ov = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(ov.json["engine"]["running"], "caddy", "{}", ov.text);
assert_eq!(ov.json["paused"]["code"], "engine.caddy", "{}", ov.text);
assert!(ov.json["paused"].is_null(), "{}", ov.text);
assert_eq!(ov.json["site"]["share_links_available"], false);
let add = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": "b.test", "upstreams": ["http://127.0.0.1:9"], "tls": "domi"}})),
)
.await;
assert_eq!(add.status, 409, "{}", add.text);
let share = env
.call(
"POST",
@@ -224,4 +216,180 @@ esac
let e = env.call("GET", "/api/v1/engine", None).await;
assert_eq!(e.json["switchable"], false);
}
/// The fake systemctl that really runs Caddy for caddy-fallback.service (edge runs in this
/// process and keeps its own ports; Caddy gets others through [compile_caddy]).
fn fake_with_caddy(dir: &std::path::Path, caddy: &std::path::Path) -> String {
format!(
r#"#!/bin/sh
dir="{d}/fake/units"
mkdir -p "$dir"
[ "$1" = "--no-ask-password" ] && shift
echo "$*" >> "{d}/fake/calls.log"
case "$1:$2" in
start:caddy-fallback.service)
XDG_DATA_HOME="{d}/caddy-state" XDG_CONFIG_HOME="{d}/caddy-state" HOME="{d}/caddy-state" \
nohup "{c}" run --config "{d}/caddy/caddy.json" >> "{d}/logs/caddy.log" 2>&1 &
echo $! > "{d}/fake/caddy.pid"; touch "$dir/$2" ;;
stop:caddy-fallback.service)
[ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null; rm -f "$dir/$2" "{d}/fake/caddy.pid" ;;
start:*) touch "$dir/$2" ;;
stop:*) rm -f "$dir/$2" ;;
is-active:*) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;;
*) exit 2 ;;
esac
"#,
d = dir.display(),
c = caddy.display()
)
}
struct CaddyEnv {
env: Env,
https: std::net::SocketAddr,
}
impl Drop for CaddyEnv {
fn drop(&mut self) {
if let Ok(p) = std::fs::read_to_string(self.env.dir.join("fake/caddy.pid")) {
let _ = std::process::Command::new("kill").arg(p.trim()).status();
}
}
}
async fn env_with_caddy() -> Option<CaddyEnv> {
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
let mut env = Env::new(EnvSpec::default()).await;
let fake = env.dir.join("fake/systemctl");
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap();
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let d = |p: &str| env.dir.join(p).display().to_string();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
d("engine"),
fake.display(),
d("certs"),
d("caddy-state"),
d("logs/caddy-access.log"),
d("creds"),
d("caddy/admin.sock"),
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
Some(CaddyEnv { env, https })
}
async fn visit(env: &Env, at: std::net::SocketAddr, host: &str) -> u16 {
match ianitor_testkit::client::https(
at,
host,
env.ca.roots(),
&ianitor_testkit::client::Req::get(host, "/"),
)
.await
{
Ok(r) => r.status,
Err(_) => 0,
}
}
/// Mark, 2026-11-08: changes keep working while Caddy serves. An apply is loaded into
/// Caddy, watched through it, and kept, or reverted by loading the previous caddy.json;
/// Undo works the same way; share links stay off. Switching back brings edge up to date.
#[tokio::test(flavor = "multi_thread")]
async fn changes_apply_while_caddy_serves() {
let Some(ce) = env_with_caddy().await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let host = |h: &str, up: String| json!({"host": {"hostname": h, "upstreams": [up], "tls": "domi", "auth": "none", "share_links": true}});
assert_eq!(
env.apply("POST", "/api/v1/hosts", Some(host("a.test", echo.url())))
.await["state"],
"kept"
);
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
assert_eq!(
visit(env, ce.https, "a.test").await,
200,
"{}",
env.control_log()
);
// No pause while Caddy serves.
let ov = env.call("GET", "/api/v1/overview", None).await;
assert!(ov.json["paused"].is_null(), "{}", ov.text);
// Kept through Caddy.
let rec = env
.apply("POST", "/api/v1/hosts", Some(host("b.test", echo.url())))
.await;
assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log());
assert_eq!(visit(env, ce.https, "b.test").await, 200);
// A broken change is reverted by loading the previous caddy.json.
let broken = json!({"host": {"hostname": "c.test", "upstreams": [format!("http://127.0.0.1:{}", ianitor_testkit::upstream::closed_port())],
"tls": "domi", "auth": "none", "health_check": {"path": "/", "interval_secs": 1}}});
let rec = env.apply("POST", "/api/v1/hosts", Some(broken)).await;
assert_eq!(rec["state"], "reverted", "{rec}\n{}", env.control_log());
let caddy_json = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap();
assert!(!caddy_json.contains("c.test"));
assert_eq!(visit(env, ce.https, "a.test").await, 200);
assert_eq!(visit(env, ce.https, "b.test").await, 200);
// Undo (removes b.test) works under Caddy too.
let u = env.call("GET", "/api/v1/undo", None).await;
let target = u.json["target"]["change_id"].as_str().unwrap().to_owned();
let rec = env
.apply(
"POST",
"/api/v1/undo",
Some(json!({"target_change_id": target})),
)
.await;
assert_eq!(rec["state"], "kept", "{rec}");
assert_ne!(visit(env, ce.https, "b.test").await, 200);
// Share links stay off.
let s = env
.call(
"POST",
"/api/v1/hosts/a.test/share-links",
Some(json!({"path_prefix": "/", "expires_in_s": 86400})),
)
.await;
assert_eq!(s.status, 409, "{}", s.text);
assert_eq!(s.json["error"]["code"], "share.engine_caddy");
// Back to Pingora: edge serves what was kept under Caddy.
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "pingora"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "pingora").await;
let edge = env.edge.as_ref().unwrap();
assert_eq!(visit(env, edge.https, "a.test").await, 200);
assert_ne!(visit(env, edge.https, "b.test").await, 200);
let edge_json = std::fs::read_to_string(env.dir.join("edge/edge.json")).unwrap();
assert!(
edge_json.contains("a.test")
&& !edge_json.contains("b.test")
&& !edge_json.contains("c.test")
);
}
}
+191
View File
@@ -536,4 +536,195 @@ mod unix {
fn contains(hay: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
/// QC: the openssl step can produce intermediates that are CA + pathlen 0 but cannot
/// issue what control issues. Control installs them and reissues every Domi host.
#[tokio::test(flavor = "multi_thread")]
async fn qc_install_refuses_intermediates_that_cannot_issue() {
let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else {
return;
};
let off = ianitor_testkit::proc::TempDir::new("qc-openssl-root");
let run = |args: &[&str]| {
let o = std::process::Command::new(&openssl)
.args(args)
.current_dir(off.join("."))
.output()
.unwrap();
assert!(
o.status.success(),
"openssl {args:?}: {}",
String::from_utf8_lossy(&o.stderr)
);
};
run(&[
"req",
"-x509",
"-new",
"-newkey",
"ec",
"-pkeyopt",
"ec_paramgen_curve:P-256",
"-nodes",
"-keyout",
"domi-root.key",
"-out",
"domi-root.crt",
"-days",
"3653",
"-subj",
"/CN=Domi PKI Root/O=Fabrica Domi",
"-addext",
"basicConstraints=critical,CA:TRUE,pathlen:1",
"-addext",
"keyUsage=critical,keyCertSign,cRLSign",
]);
let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap();
let env = env_with_root(&root_pem).await;
let good = "basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\n";
let cases = [
(
"keyUsage without keyCertSign",
"basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, digitalSignature\n",
"365",
),
(
"EKU serverAuth only (devices cannot chain)",
"basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\nextendedKeyUsage = serverAuth\n",
"365",
),
("valid past the root (-days 4000)", good, "4000"),
];
let mut accepted = Vec::new();
for (label, ext, days) in cases {
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();
std::fs::write(off.join("q.csr"), r.json["csr_pem"].as_str().unwrap()).unwrap();
std::fs::write(off.join("q.ext"), ext).unwrap();
run(&[
"x509",
"-req",
"-in",
"q.csr",
"-CA",
"domi-root.crt",
"-CAkey",
"domi-root.key",
"-days",
days,
"-sha256",
"-extfile",
"q.ext",
"-out",
"q.crt",
]);
let signed = std::fs::read_to_string(off.join("q.crt")).unwrap();
let r = env
.call(
"PUT",
&format!("/api/v1/pki-requests/{rid}/certificate"),
Some(json!({"certificate_pem": signed})),
)
.await;
eprintln!("QC {label}: {} {}", r.status, r.json["state"]);
if r.status == 200 {
accepted.push(label);
}
}
assert!(
accepted.is_empty(),
"control installed unusable intermediates: {accepted:?}"
);
}
/// QC: the root key name that `ianitor-control ca init` and docs/pki.md's openssl
/// command write is `domi-root.key`.
#[test]
fn qc_root_key_check_finds_the_names_ianitor_itself_uses() {
let d = ianitor_testkit::proc::TempDir::new("qc-rootkey");
let mut missed = Vec::new();
for name in [
"domi-root.key",
"offline/domi-root.key",
"Domi_Root_CA.pem",
"ca.key",
] {
let p = d.join(name);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(
&p,
// (Split so that this file does not match the pre-commit hook itself.)
concat!("-----BEGIN ", "PRIVATE KEY-----\nx\n-----END ", "PRIVATE KEY-----\n"),
)
.unwrap();
if ianitor_control::pki::root_key_files(&d.join(".")).is_empty() {
missed.push(name);
}
std::fs::remove_file(&p).unwrap();
}
assert!(missed.is_empty(), "root_key_files missed: {missed:?}");
}
/// QC M2: a revocation that cannot be written (or not told to edge) must not answer 204 and
/// be forgotten. It answers an error, the certificates screen says so, and once the disk
/// works again (here: a restart without the fault) the allow list catches up; a repeated
/// DELETE nudges again.
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_that_cannot_be_written_is_an_error_and_catches_up() {
let (mut env, off) = env_with_pki().await;
install_intermediate(&env, &off).await;
env.kill_control();
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "domi-devices.pem")]);
let r = env
.call(
"POST",
"/api/v1/certs/devices",
Some(json!({"name": "tablet", "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!(cli(&env, &["pki", "approve", &code]).status.success());
let done = wait_request(&env, &rid, "approved").await;
let did = done["device_id"].as_str().unwrap().to_owned();
// The allow list could not be written: the screen says so.
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let c = env.call("GET", "/api/v1/certs", None).await;
if !c.json["devices_problem"].is_null() {
break;
}
assert!(Instant::now() < deadline, "no problem shown: {}", c.text);
tokio::time::sleep(Duration::from_millis(200)).await;
}
let d = env
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
.await;
assert_eq!(d.status, 503, "{}", d.text);
assert_eq!(
d.json["error"]["code"], "pki.devices_unwritten",
"{}",
d.text
);
// The disk works again.
env.kill_control();
env.start_control(None);
let d = env
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
.await;
assert_eq!(d.status, 204, "{}", d.text);
let allow =
std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap_or_default();
assert!(!allow.contains("BEGIN CERTIFICATE"), "{allow}");
let c = env.call("GET", "/api/v1/certs", None).await;
assert!(c.json["devices_problem"].is_null(), "{}", c.text);
}
}
+81
View File
@@ -191,4 +191,85 @@ mod unix {
.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());
}
}
+28
View File
@@ -236,4 +236,32 @@ mod unix {
e.stderr()
);
}
/// QC M2: a revocation must not depend on control's nudge reaching edge. Edge re-reads the
/// allow list by itself (like the share deny list), within 5 s.
#[tokio::test(flavor = "multi_thread")]
async fn edge_rereads_the_allow_list_by_itself() {
let echo = Echo::start("app").await;
let p = pki();
let (phone, phone_pem) = device(&p, "phone");
let edge = setup(&echo, &p, &[&phone_pem]).await;
let req = Req::get("locked.test", "/");
let r =
client::https_with_cert(edge.https, "locked.test", edge.roots(), &phone, &req).await;
assert_eq!(r.unwrap().status, 200);
std::fs::write(edge.dir.join("certs/domi-devices.pem"), "").unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(8);
loop {
let r = client::https_with_cert(edge.https, "locked.test", edge.roots(), &phone, &req)
.await;
if r.is_err() {
break;
}
assert!(
std::time::Instant::now() < deadline,
"edge still accepts a revoked device"
);
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
}
}
+202
View File
@@ -0,0 +1,202 @@
// QC (throw-away): the thread-local SNI that DeviceVerifier::offer_client_auth reads.
// In-memory rustls handshakes on ONE thread, with edge's own CertStore + DeviceVerifier.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use ianitor_core::pki::{self, Intermediate};
use ianitor_edge::tls::{CertStore, DeviceTrust, DeviceVerifier, certified_key};
use rustls::{ClientConfig, ClientConnection, RootCertStore, ServerConfig, ServerConnection};
use rustls_pki_types::pem::PemObject;
use rustls_pki_types::{CertificateDer, PrivateKeyDer, ServerName};
fn now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64
}
struct World {
server: Arc<ServerConfig>,
root_pem: String,
dev_chain: String,
dev_key: String,
}
fn world() -> World {
let (root, root_key) = pki::create_root(now()).unwrap();
let k = pki::generate_key().unwrap();
let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
let int_pem = pki::sign_intermediate(&root, &root_key, &csr, now()).unwrap();
let int = Intermediate::new(&int_pem, k).unwrap();
let store = Arc::new(CertStore::default());
let mut files = HashMap::new();
for h in ["open.test", "locked.test"] {
let s = pki::issue_server(&int, h, now()).unwrap();
files.insert(
h.to_owned(),
Arc::new(certified_key(s.chain_pem.as_bytes(), s.key_pem.as_bytes()).unwrap()),
);
}
store.replace_files(files);
let dev = pki::issue_device(&int, "phone", now()).unwrap();
let trust = DeviceTrust::new(
int.cert_pem().as_bytes(),
dev.cert_pem.as_bytes(),
HashSet::from(["locked.test".to_owned()]),
)
.unwrap();
let v = Arc::new(DeviceVerifier::default());
v.replace(Some(Arc::new(trust)));
let provider = Arc::new(rustls::crypto::ring::default_provider());
let mut sc = ServerConfig::builder_with_provider(provider)
.with_protocol_versions(&[&rustls::version::TLS12, &rustls::version::TLS13])
.unwrap()
.with_client_cert_verifier(v)
.with_cert_resolver(store);
sc.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
World {
server: Arc::new(sc),
root_pem: root,
dev_chain: dev.chain_pem,
dev_key: dev.key_pem,
}
}
fn client(w: &World, tls12_only: bool, cert: bool, alpn: &[&[u8]]) -> Arc<ClientConfig> {
let mut roots = RootCertStore::empty();
roots
.add(CertificateDer::from_pem_slice(w.root_pem.as_bytes()).unwrap())
.unwrap();
let provider = Arc::new(rustls::crypto::ring::default_provider());
let versions: &[&rustls::SupportedProtocolVersion] = if tls12_only {
&[&rustls::version::TLS12]
} else {
&[&rustls::version::TLS13, &rustls::version::TLS12]
};
let b = ClientConfig::builder_with_provider(provider)
.with_protocol_versions(versions)
.unwrap()
.with_root_certificates(roots);
let mut c = if cert {
let chain: Vec<CertificateDer<'static>> =
CertificateDer::pem_slice_iter(w.dev_chain.as_bytes())
.collect::<Result<_, _>>()
.unwrap();
let key = PrivateKeyDer::from_pem_slice(w.dev_key.as_bytes()).unwrap();
b.with_client_auth_cert(chain, key).unwrap()
} else {
b.with_no_client_auth()
};
c.alpn_protocols = alpn.iter().map(|a| a.to_vec()).collect();
Arc::new(c)
}
/// Returns whether the server saw a client certificate.
fn handshake(sc: &Arc<ServerConfig>, cc: &Arc<ClientConfig>, name: &str) -> Result<bool, String> {
let mut server = ServerConnection::new(sc.clone()).unwrap();
let mut client =
ClientConnection::new(cc.clone(), ServerName::try_from(name.to_owned()).unwrap()).unwrap();
for _ in 0..30 {
let mut buf = Vec::new();
while client.wants_write() {
client.write_tls(&mut buf).unwrap();
}
let mut r = &buf[..];
while !r.is_empty() {
server.read_tls(&mut r).unwrap();
}
server
.process_new_packets()
.map_err(|e| format!("server: {e}"))?;
let mut buf = Vec::new();
while server.wants_write() {
server.write_tls(&mut buf).unwrap();
}
let mut r = &buf[..];
while !r.is_empty() {
client.read_tls(&mut r).unwrap();
}
client
.process_new_packets()
.map_err(|e| format!("client: {e}"))?;
if !client.is_handshaking() && !server.is_handshaking() && !server.wants_write() {
return Ok(server.peer_certificates().is_some());
}
}
Err("handshake did not finish".into())
}
#[test]
fn baseline_tls12_device_handshake_on_a_fresh_thread() {
let w = world();
let got = handshake(
&w.server,
&client(&w, true, true, &[b"http/1.1"]),
"locked.test",
);
assert_eq!(got, Ok(true), "baseline");
}
#[test]
fn after_a_failed_handshake_on_this_thread_a_tls12_device_still_gets_in() {
let w = world();
// A client offers only an ALPN the server does not speak: rustls fails after the
// certificate resolver ran (SNI set) and before offer_client_auth (SNI never taken).
let bad = handshake(&w.server, &client(&w, false, false, &[b"foo"]), "open.test");
assert!(bad.is_err(), "poison handshake should fail: {bad:?}");
let got = handshake(
&w.server,
&client(&w, true, true, &[b"http/1.1"]),
"locked.test",
);
assert_eq!(
got,
Ok(true),
"TLS 1.2 device after a stale SNI on this thread"
);
}
#[test]
fn after_a_resumed_handshake_on_this_thread_a_tls12_device_still_gets_in() {
let w = world();
let c13 = client(&w, false, false, &[b"http/1.1"]);
assert_eq!(handshake(&w.server, &c13, "open.test"), Ok(false));
// Same client config: resumes (no certificate request, so the SNI is never taken).
assert_eq!(handshake(&w.server, &c13, "open.test"), Ok(false));
let got = handshake(
&w.server,
&client(&w, true, true, &[b"http/1.1"]),
"locked.test",
);
assert_eq!(
got,
Ok(true),
"TLS 1.2 device after a resumption on this thread"
);
}
#[test]
fn a_stale_device_name_never_opens_a_plain_host_without_a_request() {
// The fail-open direction: stale "locked.test", then a TLS 1.3 device host handshake
// without a cert must still fail.
let w = world();
let bad = handshake(
&w.server,
&client(&w, false, false, &[b"foo"]),
"locked.test",
);
assert!(bad.is_err());
let r = handshake(
&w.server,
&client(&w, false, false, &[b"http/1.1"]),
"locked.test",
);
assert!(
r.is_err(),
"no-cert handshake to the device host must fail: {r:?}"
);
}