fix(link): the app believes only public authorities, only their hosts, and only while a certificate lasts

The review of P15 B3 found the relay could steer three things it must not.

- A certificate is now checked against the public roots the program
  ships, for the app's wildcard, when it is issued and every time it is
  read from disk; a lifetime over 100 days is refused (no public
  authority issues one), and the renewal is planned no later than two
  thirds of the life or 60 days. A kept certificate that fails is
  ignored and ordered again. Only a test builds a CertTrust of its own
  roots.
- The ACME client sends a request only to a directory on a host compiled
  into the app (Let's Encrypt production and staging, Google Trust
  Services, ZeroSSL, Buypass, SSL.com): the relay still picks which and
  in what order, but cannot name a new host. A kept account is used only
  if its directory is on the list too. http is a direct dependency now
  (it was a dev-dependency, and already in the tree): the host is read
  with the parser the ACME library uses.
- The resolver refuses a certificate at its end, sleeps stop at it, and
  the state stops saying "Connected" when it has ended.
- The certificate work waits for the line, so it is for the name the
  relay accepted (a first claim that finds the name taken picks another);
  web.rs starts the door only once the name is settled.
- A line that held under 60 s does not reset the backoff; one that held
  is redialled after 0 to 30 s, so a relay restart is not met by every
  app in the same second.
- What the relay and the authority say is shown as a short quoted detail
  with control and invisible characters removed, in the app's own words.
- The kept address is read once, not from the key file every frame; the
  folder is synced after a private file is renamed into place.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 14:59:57 -07:00
1 parent 14c1a26bfc
commit b90df7158a
12 files changed
+1440 -128

No files matched your search

+146 -5
View File
@@ -34,6 +34,8 @@ struct Server {
orders: Vec<Order>,
ari_gets: u32,
refuse_orders: bool,
/// What a refusal says in its detail (else a short one).
detail: Option<String>,
certs: HashMap<usize, String>,
}
@@ -81,6 +83,12 @@ fn json(status: u16, extra: Vec<(&'static str, String)>, v: serde_json::Value) -
}
impl FakeAcme {
fn roots(&self) -> rustls::RootCertStore {
let mut roots = rustls::RootCertStore::empty();
roots.add(self.ca.der().clone()).unwrap();
roots
}
async fn handle(&self, method: &str, path: &str, body: &[u8]) -> Reply {
let nonce = {
let mut s = self.state.lock().unwrap();
@@ -124,7 +132,7 @@ impl FakeAcme {
return with_nonce(json(
429,
vec![],
serde_json::json!({"type":"urn:ietf:params:acme:error:rateLimited","detail":"too many certificates already issued"}),
serde_json::json!({"type":"urn:ietf:params:acme:error:rateLimited","detail":s.detail.clone().unwrap_or_else(|| "too many certificates already issued".into())}),
));
}
let thumb = s.accounts[protected["kid"].as_str().unwrap()].clone();
@@ -348,9 +356,11 @@ async fn rig(window: (i64, i64)) -> Rig {
});
let dir = tempfile::tempdir().unwrap();
let a2 = acme.clone();
let issuer = AcmeIssuer::new(dir.path()).with_http(Arc::new(move || {
Some(Box::new(Http(a2.clone())) as Box<dyn HttpClient>)
}));
let issuer = AcmeIssuer::new(dir.path())
.with_directory_hosts_for_tests(&["acme.test"])
.with_http(Arc::new(move || {
Some(Box::new(Http(a2.clone())) as Box<dyn HttpClient>)
}));
let (key, _) = relay::proto::AppKey::generate();
let name = n("ledger-accrual-tally-mint");
let line = env.connect(name, &key, true).await.unwrap();
@@ -403,7 +413,15 @@ async fn an_order_goes_through_account_proof_finalize_and_download() {
assert!(issued.key_pem.contains("PRIVATE KEY"));
// The certificate and key go together (the store checks it).
assert!(
certs::StoredCert::new("ledger-accrual-tally-mint", "fake", &issued, &ident, None).is_ok()
certs::StoredCert::new(
"ledger-accrual-tally-mint",
"fake",
&issued,
&ident,
None,
&certs::CertTrust::for_tests(r.acme.roots())
)
.is_ok()
);
// The account is kept in a private file, with no contact in it.
@@ -551,3 +569,126 @@ async fn a_refusal_comes_back_in_the_authoritys_words() {
.unwrap();
assert!(err.contains("too many certificates"), "{err}");
}
fn order_for(r: &Rig, authority: &Authority) -> OrderRequest<'static> {
// The proof is never reached by the tests that use this: they stop at
// the directory.
struct Never;
impl DnsProof for Never {
fn publish<'a>(&'a self, _: &'a str) -> BoxFuture<'a, Result<(), String>> {
Box::pin(async { Err("not reached".into()) })
}
fn clear(&self) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
}
static NEVER: Never = Never;
OrderRequest {
authority: Box::leak(Box::new(authority.clone())),
identifier: format!("*.{}.{DOMAIN}", r.name),
replaces: None,
dns: &NEVER,
}
}
/// WB-link-4 (INVARIANT 6): the relay's list can name any directory, and
/// the app contacts only a host compiled into it: no request is made for
/// any other, however it is spelled.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_directory_on_a_host_the_app_does_not_know_is_refused_before_any_request() {
let r = rig((60, 120)).await;
let reached = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (a2, seen) = (r.acme.clone(), reached.clone());
// The default list: no host of a test in it.
let issuer = AcmeIssuer::new(r.dir.path()).with_http(Arc::new(move || {
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Some(Box::new(Http(a2.clone())) as Box<dyn HttpClient>)
}));
for directory in [
"https://acme.test/dir",
"https://evil.example/directory",
"http://acme-v02.api.letsencrypt.org/directory",
"https://acme-v02.api.letsencrypt.org@evil.example/directory",
"https://acme-v02.api.letsencrypt.org:8443/directory",
"https://acme-v02.api.letsencrypt.org.evil.example/directory",
"https://evil.example\\@acme-v02.api.letsencrypt.org/directory",
"https://127.0.0.1:9/directory",
"not an address",
] {
let mut a = authority(false);
a.directory = directory.into();
let err = issuer.issue(order_for(&r, &a)).await.err().unwrap();
assert!(err.contains("does not use it"), "{directory}: {err}");
}
assert_eq!(
reached.load(std::sync::atomic::Ordering::SeqCst),
0,
"not one request was made"
);
assert!(r.acme.state.lock().unwrap().new_accounts.is_empty());
}
/// WB-link-4 (INVARIANT 6): an account kept for a directory that is not on
/// the list is not used; a new one is made at the authority named.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_kept_account_for_an_unlisted_directory_is_not_used() {
let r = rig((60, 120)).await;
let order = |r: &Rig| OrderRequest {
authority: Box::leak(Box::new(authority(false))),
identifier: format!("*.{}.{DOMAIN}", r.name),
replaces: None,
dns: Box::leak(Box::new(Proof(r.line.handle()))),
};
r.issuer.issue(order(&r)).await.unwrap();
assert_eq!(r.acme.state.lock().unwrap().new_accounts.len(), 1);
// The same account file, as if the relay had once had it made at another
// host.
let file = r.dir.path().join("acme/fake.json");
let mut kept: serde_json::Value =
serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
assert_eq!(kept["directory"], format!("{BASE}/dir"));
kept["directory"] = "https://evil.example/dir".into();
std::fs::write(&file, serde_json::to_vec(&kept).unwrap()).unwrap();
r.issuer.issue(order(&r)).await.unwrap();
assert_eq!(
r.acme.state.lock().unwrap().new_accounts.len(),
2,
"the account kept for another host was left alone and a new one made"
);
}
/// WB-link-5: what an authority says is a short, plain, quoted detail in
/// the app's own words, never its text as it came.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn what_the_authority_says_is_short_plain_and_quoted() {
let r = rig((60, 120)).await;
r.acme.state.lock().unwrap().refuse_orders = true;
r.acme.state.lock().unwrap().detail = Some(format!(
"pay now\u{7}\n\u{202e}{}",
"give us your password ".repeat(500)
));
let proof = Proof(r.line.handle());
let err = r
.issuer
.issue(OrderRequest {
authority: &authority(false),
identifier: format!("*.{}.{DOMAIN}", r.name),
replaces: None,
dns: &proof,
})
.await
.err()
.unwrap();
assert!(
err.chars().count() < 260,
"{} characters",
err.chars().count()
);
assert!(
!err.chars().any(|c| c.is_control() || c == '\u{202e}'),
"{err:?}"
);
assert!(err.contains("too many certificates"), "{err}");
assert!(err.contains("It said \u{201c}pay now give us"), "{err}");
assert!(err.contains("\u{2026}\u{201d}"), "{err}");
}
+194 -1
View File
@@ -6,7 +6,7 @@
mod support;
use ledger_link::{Dial, Step, Trouble};
use ledger_link::{CertTrust, Dial, Step, Trouble};
use std::sync::atomic::Ordering;
use std::time::Duration;
use support::*;
@@ -592,3 +592,196 @@ async fn a_stalled_handshake_is_dropped_and_no_door_means_no_service() {
w.link.set_door(Some(w.door.target.clone()));
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
}
/// WB-link-4 (INVARIANTS 7 and 8 of certs.rs): the relay names the
/// authorities, so a certificate from one it made up is refused (the
/// program trusts the public roots, not the relay's list): nothing is
/// stored or served, the state says so, and a lifetime over the cap is
/// refused too.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_certificate_from_an_authority_the_relay_made_up_is_never_stored_or_served() {
let mut w = world(LIST, |_| {}).await;
// The real program's trust: the public roots. The fake authority is
// not one of them.
w.remake(|cfg| cfg.trust = CertTrust::public().unwrap());
w.link.turn_on().unwrap();
let s = until(&w.link, "the refusal is said", |s| {
s.cert_trouble
.as_deref()
.is_some_and(|t| t.contains("public certificate authority"))
})
.await;
assert_ne!(s.step(), Step::Connected);
assert!(s.cert_expires.is_none());
assert!(!w.dir.path().join("link/cert.json").exists());
assert!(w.fake.orders() >= 1);
// Nobody is served a certificate from it.
assert!(w.assistant(&w.host()).await.is_err());
w.link.turn_off();
// A certificate from an authority the program does trust, but that
// lives over 100 days, is refused as well.
w.remake(|_| {});
w.fake.state.lock().unwrap().lifetime = 101 * 86_400;
w.link.turn_on().unwrap();
let s = until(&w.link, "the lifetime is refused", |s| {
s.cert_trouble
.as_deref()
.is_some_and(|t| t.contains("100 days"))
})
.await;
assert!(s.cert_expires.is_none());
assert!(!w.dir.path().join("link/cert.json").exists());
}
/// WB-link-4 (INVARIANT 7): a certificate kept on disk that the program
/// would not trust is discarded and ordered again, and "a new address"
/// does not bring it back.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_stored_certificate_from_a_made_up_authority_is_discarded_and_ordered_again() {
let mut w = world(LIST, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
assert_eq!(w.fake.orders(), 1);
w.link.turn_off();
// The file is there, from the authority the test trusts; a program that
// trusts only the public roots reads it as no certificate at all.
assert!(w.dir.path().join("link/cert.json").exists());
w.remake(|cfg| cfg.trust = CertTrust::public().unwrap());
w.link.turn_on().unwrap();
until(&w.link, "it orders again", |s| {
s.cert_trouble
.as_deref()
.is_some_and(|t| t.contains("public certificate authority"))
})
.await;
assert!(w.fake.orders() >= 2, "the stored one was not believed");
assert!(w.link.status().cert_expires.is_none());
// A new address carries on the same way: nothing is loaded from the
// file that fails.
w.link.new_address().unwrap();
until(&w.link, "the refusal again", |s| {
s.cert_trouble.is_some() && s.line_up
})
.await;
assert!(w.link.status().cert_expires.is_none());
assert!(w.assistant(&w.host()).await.is_err());
}
/// WB-link-3: a first claim that finds the name taken picks another, and
/// the address, the certificate and the door all follow the one that was
/// claimed.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_name_taken_on_the_first_claim_settles_before_the_certificate_and_the_address() {
let w = world(LIST, |_| {}).await;
// The identity is made, and somebody else (another key) takes its name
// first.
let dir = w.dir.path().join("link");
let id = ledger_link::identity::Identity::load_or_create(&dir).unwrap();
let taken = id.name();
let (other, _) = relay::proto::AppKey::generate();
let _held = w.env.connect(taken, &other, true).await.unwrap();
w.link.turn_on().unwrap();
w.link.wait_settled(Duration::from_secs(20)).unwrap();
let settled = w.link.status();
assert!(settled.claimed);
let address = settled.address.clone().unwrap();
let host = address.trim_start_matches("https://").to_owned();
let name = host.split_once('.').unwrap().1.to_owned();
assert_ne!(name, format!("{taken}.{DOMAIN}"), "another name was picked");
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
// Every certificate order was for the name that was claimed.
{
let st = w.fake.state.lock().unwrap();
assert!(!st.orders.is_empty());
for o in &st.orders {
assert_eq!(o.identifier, format!("*.{name}"));
}
}
assert_eq!(w.link.status().address.as_deref(), Some(address.as_str()));
assert_eq!(w.link.kept_address().as_deref(), Some(address.as_str()));
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
}
/// WB-link-4 (INVARIANT 9 of certs.rs): a certificate is not served after
/// its end, even when it cannot be renewed, and the state says it is gone.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_expired_certificate_is_not_served_and_the_state_says_so() {
// Renewals that fail are tried again only after an hour: nothing but
// the end of the certificate wakes the app.
let w = world(LIST, |t| {
t.cert_retry_min = Duration::from_secs(3600);
t.cert_retry_max = Duration::from_secs(3600);
t.ari_recheck = Duration::from_secs(3600);
})
.await;
w.fake.state.lock().unwrap().lifetime = 3;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let host = w.host();
{
let mut st = w.fake.state.lock().unwrap();
st.fail.insert("first".into());
st.fail.insert("second".into());
}
// Served while it lasts ...
let early = w.link.status().cert_expires.unwrap();
// ... and, once it has ended, neither served nor said to be in place.
until(&w.link, "the certificate has ended", |s| {
s.cert_expires.is_none()
})
.await;
assert!(ledger_link::certs::now() >= early);
assert_ne!(w.link.status().step(), Step::Connected);
assert!(w.assistant(&host).await.is_err());
}
/// WB-link-5 (text.rs): what a certificate authority says to the app does
/// not reach the window unbounded.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_authority_that_shouts_is_shown_short_and_plain() {
let w = world(LIST, |_| {}).await;
{
let mut st = w.fake.state.lock().unwrap();
st.fail.insert("first".into());
st.fail.insert("second".into());
st.say = Some(format!("send money\u{7}\n\u{202e}{}", "now ".repeat(5000)));
}
w.link.turn_on().unwrap();
let s = until(&w.link, "the trouble is said", |s| s.cert_trouble.is_some()).await;
let words = s.problem().unwrap();
assert!(
words.chars().count() < 1200,
"{} characters",
words.chars().count()
);
assert!(
!words.chars().any(|c| c.is_control() || c == '\u{202e}'),
"{words:?}"
);
assert!(words.contains("send money"));
assert!(words.starts_with("Wanderbooks could not get a certificate yet."));
}
/// The window asks for the kept address every frame: it is read from the
/// folder once, not each time (the key lives in the same file).
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_kept_address_is_read_once_not_every_frame() {
let w = world(LIST, |_| {}).await;
assert!(w.link.kept_address().is_none(), "before the first start");
w.link.turn_on().unwrap();
until(&w.link, "claimed", |s| s.claimed).await;
let first = w.link.kept_address().unwrap();
w.link.turn_off();
// With the file gone, the answer is still the one held: nothing reads
// the folder again.
for f in std::fs::read_dir(w.dir.path().join("link")).unwrap() {
let f = f.unwrap().path();
if f.is_file() {
std::fs::remove_file(f).unwrap();
}
}
assert_eq!(w.link.kept_address().as_deref(), Some(first.as_str()));
}
+28 -4
View File
@@ -11,7 +11,7 @@ use futures::future::BoxFuture;
use hickory_proto::op::{Message, Query};
use hickory_proto::rr::{Name as DnsName, RData, RecordType};
use ledger_link::certs::{Issued, Issuer, OrderRequest};
use ledger_link::{Dial, DoorTarget, Link, LinkConfig, LinkStatus, Timing};
use ledger_link::{CertTrust, Dial, DoorTarget, Link, LinkConfig, LinkStatus, Timing};
use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose};
use relay::proto::{Authority, Caller};
use rustls::RootCertStore;
@@ -42,6 +42,8 @@ pub struct FakeState {
pub fail: std::collections::HashSet<String>,
/// Seconds the certificate lasts from now.
pub lifetime: i64,
/// What a refusal says, when it is not the fixed words.
pub say: Option<String>,
/// The renewal window the authority suggests, as seconds from now.
pub window: Option<(i64, i64)>,
}
@@ -96,6 +98,7 @@ impl Fake {
orders: vec![],
fail: Default::default(),
lifetime: 3600,
say: None,
window: None,
}),
})
@@ -124,7 +127,7 @@ fn proof_value() -> String {
impl Issuer for Fake {
fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result<Issued, String>> {
Box::pin(async move {
let (fails, lifetime) = {
let (fails, lifetime, say) = {
let mut st = self.state.lock().unwrap();
st.orders.push(Order {
authority: req.authority.id.clone(),
@@ -132,10 +135,14 @@ impl Issuer for Fake {
replaces: req.replaces.is_some(),
had_binding: req.authority.binding.is_some(),
});
(st.fail.contains(&req.authority.id), st.lifetime)
(
st.fail.contains(&req.authority.id),
st.lifetime,
st.say.clone(),
)
};
if fails {
return Err("the fake authority says no".into());
return Err(say.unwrap_or_else(|| "the fake authority says no".into()));
}
// The proof goes to the relay, and the authority reads it from
// the relay's own DNS, as a real one does.
@@ -369,6 +376,8 @@ pub fn fast() -> Timing {
order_timeout: Duration::from_secs(10),
ari_recheck: Duration::from_secs(1),
wake_gap: Duration::from_secs(30),
line_stable: Duration::from_millis(300),
redial_spread: Duration::from_millis(200),
}
}
@@ -402,6 +411,7 @@ pub fn config(w: &World) -> LinkConfig {
dial: Dial::Addr(w.tap.addr),
relay_tls: w.env.line_tls(),
issuer: w.fake.clone(),
trust: CertTrust::for_tests(w.fake.roots()),
timing: fast(),
}
}
@@ -429,6 +439,7 @@ pub async fn world_with(
dial: Dial::Addr(tap.addr),
relay_tls: env.line_tls(),
issuer: fake.clone(),
trust: CertTrust::for_tests(fake.roots()),
timing: fast(),
};
timing(&mut cfg.timing);
@@ -446,6 +457,19 @@ pub async fn world_with(
}
impl World {
/// The link made again with `change` applied to its setup (the same
/// folder, relay and authority).
pub fn remake(&mut self, change: impl FnOnce(&mut LinkConfig)) {
let mut cfg = config(self);
change(&mut cfg);
let old = std::mem::replace(
&mut self.link,
Link::start_on(tokio::runtime::Handle::current(), cfg),
);
drop(old);
self.link.set_door(Some(self.door.target.clone()));
}
/// A second link on the same folder (the app was restarted).
pub fn restart(&mut self, timing: impl FnOnce(&mut Timing)) {
let mut cfg = config(self);