Merge branch 't3/p15-b3-web-assistants': the app's side of the relay (P15 B3)

Buypass is left out of the compiled-in directory hosts: its directory
could not be confirmed from its own documentation.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 15:05:16 -07:00
commit 0759089790
37 files changed
+10182 -26

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
[package]
name = "ledger-link"
version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "wanderbooks: the app's side of the relay (plan P15 B3): its own name and key, the one outbound line, its own TLS and certificate, and the renewals."
[dependencies]
# The relay crate's `proto`, `names`, `mux` and `client` modules are the
# app's side of the protocol too; one definition of the wire, never a copy.
relay = { path = "../relay" }
futures = "0.3"
# The certificate authority's protocol (RFC 8555) and ARI (RFC 9773). No
# default features: `ring` is the crypto the rest of the tree uses (the
# default, aws-lc-rs, needs a C toolchain at build time).
instant-acme = { version = "0.8", default-features = false, features = ["ring", "hyper-rustls", "time", "x509-parser"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "sync", "net", "time"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
tokio-util = "0.7"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
base64 = "0.22"
ring = "0.17"
x509-parser = "0.18"
zeroize = "1"
http = "1"
webpki-root-certs = "1"
# Owner-only DACLs for the key and certificate files (the helper the token
# files use).
[target.'cfg(windows)'.dependencies]
ledger-store = { path = "../ledger-store" }
[dev-dependencies]
tempfile = "3"
rcgen = { version = "0.14", default-features = false, features = ["ring", "pem", "x509-parser"] }
hickory-proto = { version = "0.26", default-features = false, features = ["std"] }
tokio = { version = "1", features = ["test-util"] }
http-body-util = "0.1"
bytes = "1"
async-trait = "0.1"
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
sha2 = "0.10"
time = "0.3"
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
[lints]
workspace = true
+487
View File
@@ -0,0 +1,487 @@
//! The ACME client: an [`Issuer`] over `instant-acme` (RFC 8555, DNS-01,
//! wildcard, and RFC 9773 renewal information).
//!
//! ```text
//! GOAL: order a wildcard certificate for the app's own name from
//! whichever authority the relay lists, proving the name through
//! the relay's DNS and nowhere else, keeping the account and
//! certificate keys on this machine.
//! SOURCE: WB-link-4 (certificates), D-87; RFC 8555 (ACME; DNS-01 in
//! section 8.4; external account binding in section 7.3.4),
//! RFC 9773 (ARI).
//! INVARIANTS:
//! 1. One account per authority, made on first use and kept in a
//! private file (private.rs); its contact list is empty: the app
//! gives an authority no name, address or email of the person.
//! 2. The certificate key is made by the client library for each order
//! and returned to the caller; it is not sent anywhere.
//! 3. Only the DNS-01 challenge is used, and only its value is sent to
//! the relay (which publishes it for the app's own name); the relay
//! never orders.
//! 4. An authority that needs an account binding gets the credential
//! the relay gave this app; none is invented or reused across
//! authorities.
//! 5. Every failure comes back in the app's own words, chosen from the
//! kind of failure; what the authority said is only a short quoted
//! detail at the end (text.rs), never a bare code and never the
//! authority's text on its own.
//! 6. The app sends a request only to an authority's directory on a host
//! from [`DIRECTORY_HOSTS`], which is compiled in: the relay chooses
//! which of them and in what order, but cannot name a new host, so it
//! cannot make the app send requests to any server it likes. An
//! authority on another host, over http, with a port or with a name
//! and password in its address, is skipped and said so. A kept
//! account is only used if the directory it was made at is on the list
//! too. Adding a brand-new authority takes a new release of the app;
//! that is the price of the relay not being trusted with the choice of
//! where the app sends its requests (plan p15-app-and-relay.md 5).
//! SCENARIOS:
//! 1. Against an in-process authority (`tests/acme.rs`): account,
//! order, proof, finalize and download work; the second order reuses
//! the account; a renewal names the certificate it replaces; the
//! authority's renewal window is read.
//! 2. An authority on a host that is not in the list is refused before
//! any request; the hosts in the list are accepted; the authority's
//! words are bounded and plain (unit tests here).
//! ```
use crate::certs::{DnsProof, Issued, Issuer, OrderRequest, leaf_der};
use crate::private;
use crate::text::detail;
use base64::Engine as _;
use futures::future::BoxFuture;
use instant_acme::{
Account, AccountCredentials, AuthorizationStatus, CertificateIdentifier, ChallengeType,
ExternalAccountKey, HttpClient, Identifier, NewAccount, NewOrder, OrderStatus, RetryPolicy,
};
use relay::proto::Authority;
use rustls::pki_types::CertificateDer;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use zeroize::Zeroizing;
/// How to make the HTTP client an account speaks through. The default is
/// the platform's roots; tests give one that reaches an in-process
/// authority.
pub type HttpFactory = Arc<dyn Fn() -> Option<Box<dyn HttpClient>> + Send + Sync>;
/// The hosts an authority's ACME directory may be on (INVARIANT 6), each
/// from the authority's own documentation. The relay's list says which of
/// these to use; a host that is not here is never contacted.
pub const DIRECTORY_HOSTS: &[(&str, &str)] = &[
// https://letsencrypt.org/docs/acme-protocol-updates/
("acme-v02.api.letsencrypt.org", "Let's Encrypt"),
// https://letsencrypt.org/docs/staging-environment/
(
"acme-staging-v02.api.letsencrypt.org",
"Let's Encrypt (staging)",
),
// https://cloud.google.com/certificate-manager/docs/public-ca-tutorial
("dv.acme-v02.api.pki.goog", "Google Trust Services"),
(
"dv.acme-v02.test-api.pki.goog",
"Google Trust Services (test)",
),
// https://zerossl.com/documentation/acme/
("acme.zerossl.com", "ZeroSSL"),
// https://www.ssl.com/guide/ssl-tls-certificate-issuance-and-revocation-with-acme/
("acme.ssl.com", "SSL.com"),
];
/// The ACME client.
pub struct AcmeIssuer {
dir: PathBuf,
hosts: Vec<String>,
http: HttpFactory,
/// How long an order may take to be ready or issued.
patience: Duration,
}
impl AcmeIssuer {
/// A client keeping its accounts in `dir` (the link folder).
pub fn new(dir: &Path) -> Self {
AcmeIssuer {
dir: dir.join("acme"),
hosts: DIRECTORY_HOSTS
.iter()
.map(|(h, _)| (*h).to_owned())
.collect(),
http: Arc::new(|| None),
patience: Duration::from_secs(120),
}
}
/// Accept directories on these hosts instead of [`DIRECTORY_HOSTS`]
/// (tests: a stand-in authority on localhost). Nothing in the program
/// calls this; the relay cannot reach it (INVARIANT 6).
pub fn with_directory_hosts_for_tests(mut self, hosts: &[&str]) -> Self {
self.hosts = hosts.iter().map(|h| (*h).to_ascii_lowercase()).collect();
self
}
/// Speak through `http` (tests).
pub fn with_http(mut self, http: HttpFactory) -> Self {
self.http = http;
self
}
/// Wait this long for an order (tests).
pub fn with_patience(mut self, patience: Duration) -> Self {
self.patience = patience;
self
}
/// Whether `url` is a directory the app may contact (INVARIANT 6): https,
/// on a listed host, with no port other than 443 and no name or
/// password in front. It is read with the parser the ACME library
/// reads it with, so the two agree on what the host is.
fn directory_allowed(&self, url: &str) -> Result<(), String> {
let refused = |why: &str| {
format!(
"The directory {} is {why}, so this version of Wanderbooks does not use it.",
detail(url)
)
};
if url
.chars()
.any(|c| c.is_control() || c.is_whitespace() || c == '\\')
{
return Err(refused("not a plain address"));
}
let uri: http::Uri = url.parse().map_err(|_| refused("not an address"))?;
if uri.scheme_str() != Some("https") {
return Err(refused("not an https address"));
}
let authority = uri.authority().ok_or_else(|| refused("not an address"))?;
if authority.as_str().contains('@') {
return Err(refused("an address with a name in front"));
}
if authority.port_u16().is_some_and(|p| p != 443) {
return Err(refused("on an unusual port"));
}
let host = authority.host().to_ascii_lowercase();
if self.hosts.contains(&host) {
Ok(())
} else {
Err(refused("on a host it does not know"))
}
}
fn builder(&self) -> Result<instant_acme::AccountBuilder, String> {
match (self.http)() {
Some(http) => Ok(Account::builder_with_http(http)),
None => Account::builder().map_err(|e| words(Kind::Start, &e)),
}
}
fn file(&self, authority: &Authority) -> PathBuf {
// The id is the relay's own short word; keep only what is safe in
// a file name.
let safe: String = authority
.id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'_'
}
})
.collect();
self.dir.join(format!("{safe}.json"))
}
/// The account at this authority: the kept one, or a new one
/// (INVARIANTS 1 and 4).
async fn account(&self, authority: &Authority) -> Result<Account, String> {
self.directory_allowed(&authority.directory)?;
let file = self.file(authority);
if let Ok(bytes) = std::fs::read(&file) {
let bytes = Zeroizing::new(bytes);
// A kept account is used only for a directory on the list: what
// is in the file is what the library will contact.
let kept_at_a_listed_host = serde_json::from_slice::<serde_json::Value>(&bytes)
.ok()
.is_some_and(|v| {
v.get("urls").is_none_or(serde_json::Value::is_null)
&& v.get("directory")
.and_then(serde_json::Value::as_str)
.is_some_and(|d| self.directory_allowed(d).is_ok())
});
if kept_at_a_listed_host
&& let Ok(credentials) = serde_json::from_slice::<AccountCredentials>(&bytes)
{
match self.builder()?.from_credentials(credentials).await {
Ok(account) => return Ok(account),
// The authority forgot it, or cannot be reached: a new
// account is made below only for the first; a network
// failure is reported as it is.
Err(e) if is_network(&e) => return Err(words(Kind::Unreachable, &e)),
Err(_) => {}
}
}
}
let eab = match (&authority.binding, authority.needs_binding) {
(Some(b), _) => {
let key = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(b.hmac_key.trim_end_matches('='))
.map_err(|_| {
"the account binding for this authority is not valid.".to_string()
})?;
Some(ExternalAccountKey::new(b.kid.clone(), &key))
}
(None, true) => {
return Err(
"this authority needs an account binding the relay has not given yet.".into(),
);
}
(None, false) => None,
};
let (account, credentials) = self
.builder()?
.create(
&NewAccount {
contact: &[],
terms_of_service_agreed: true,
only_return_existing: false,
},
authority.directory.clone(),
eab.as_ref(),
)
.await
.map_err(|e| words(Kind::NewAccount, &e))?;
private::make_dir(&self.dir)
.map_err(|e| format!("can't keep the account ({})", e.kind()))?;
let text = Zeroizing::new(
serde_json::to_vec(&credentials).map_err(|_| "can't keep the account".to_string())?,
);
private::write(&file, &text)
.map_err(|e| format!("can't keep the account ({})", e.kind()))?;
Ok(account)
}
}
fn is_network(e: &instant_acme::Error) -> bool {
matches!(
e,
instant_acme::Error::Other(_) | instant_acme::Error::Http(_)
)
}
/// What kind of thing went wrong: the app's words are chosen from this,
/// never from what the authority said (INVARIANT 5).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Start,
Unreachable,
NewAccount,
Order,
Proof,
Finish,
Issue,
Download,
}
impl Kind {
fn words(self) -> &'static str {
match self {
Kind::Start => "the app could not start talking to the authority",
Kind::Unreachable => "the authority could not be reached",
Kind::NewAccount => "the authority would not open an account",
Kind::Order => "the authority refused the order",
Kind::Proof => "the authority could not check the proof of the name",
Kind::Finish => "the authority did not finish the order",
Kind::Issue => "the authority refused to issue the certificate",
Kind::Download => "the authority did not hand over the certificate",
}
}
}
/// A failure as the app says it (INVARIANT 5): its own words for the kind
/// of failure, and what the authority said only as a short quoted detail.
fn words(kind: Kind, e: &instant_acme::Error) -> String {
match e {
instant_acme::Error::Api(p) => {
let said = detail(p.detail.as_deref().unwrap_or(""));
let what = match p.r#type.as_deref().unwrap_or("").rsplit(':').next() {
Some("rateLimited") => {
"the authority says too many certificates were asked for lately"
}
_ => kind.words(),
};
if said.is_empty() {
format!("{what}.")
} else {
format!("{what}. It said {said}.")
}
}
other => {
let said = detail(&other.to_string());
if said.is_empty() {
format!("{}.", kind.words())
} else {
format!("{}. The detail was {said}.", kind.words())
}
}
}
}
impl Issuer for AcmeIssuer {
fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result<Issued, String>> {
Box::pin(async move {
let account = self.account(req.authority).await?;
let identifiers = [Identifier::Dns(req.identifier.clone())];
let replaces = req
.replaces
.as_deref()
.and_then(|der| CertificateIdentifier::try_from(&CertificateDer::from(der)).ok());
let mut new = NewOrder::new(&identifiers);
if let Some(r) = replaces {
new = new.replaces(r);
}
let mut order = match account.new_order(&new).await {
Ok(o) => o,
// An authority without renewal information refuses the
// `replaces` hint: ordering again without it is how the
// certificate is renewed there.
Err(instant_acme::Error::Unsupported(_)) => account
.new_order(&NewOrder::new(&identifiers))
.await
.map_err(|e| words(Kind::Order, &e))?,
Err(e) => return Err(words(Kind::Order, &e)),
};
let mut authorizations = order.authorizations();
let mut published = false;
while let Some(result) = authorizations.next().await {
let mut authz = result.map_err(|e| words(Kind::Proof, &e))?;
match authz.status {
AuthorizationStatus::Pending => {}
AuthorizationStatus::Valid => continue,
_ => return Err("the authority will not accept this name.".into()),
}
let mut challenge = authz
.challenge(ChallengeType::Dns01)
.ok_or("the authority offers no DNS proof for this name.")?;
let value = challenge.key_authorization().dns_value();
req.dns.publish(&value).await.map_err(|why| {
format!(
"the relay would not publish the proof of the name. It said {}.",
detail(&why)
)
})?;
published = true;
challenge
.set_ready()
.await
.map_err(|e| words(Kind::Proof, &e))?;
}
let result = async {
let policy = RetryPolicy::new().timeout(self.patience);
let status = order
.poll_ready(&policy)
.await
.map_err(|e| words(Kind::Finish, &e))?;
if status != OrderStatus::Ready {
return Err("the authority could not check the name's proof.".to_string());
}
let key_pem =
Zeroizing::new(order.finalize().await.map_err(|e| words(Kind::Issue, &e))?);
let chain_pem = order
.poll_certificate(&policy)
.await
.map_err(|e| words(Kind::Download, &e))?;
Ok(Issued { chain_pem, key_pem })
}
.await;
if published {
req.dns.clear().await;
}
result
})
}
fn renewal_window<'a>(
&'a self,
authority: &'a Authority,
chain_pem: &'a str,
) -> BoxFuture<'a, Option<(i64, i64)>> {
Box::pin(async move {
let der = leaf_der(chain_pem)?;
let id = CertificateIdentifier::try_from(&CertificateDer::from(der)).ok()?;
let account = self.account(authority).await.ok()?;
let (info, _retry) = account.renewal_info(&id).await.ok()?;
Some((
info.suggested_window.start.unix_timestamp(),
info.suggested_window.end.unix_timestamp(),
))
})
}
}
// Silence the unused-import lint when no trait object use needs it.
#[allow(dead_code)]
fn _uses(_: &dyn DnsProof) {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_listed_host_is_accepted_at_its_directory_and_no_other_is() {
let dir = std::env::temp_dir();
let issuer = AcmeIssuer::new(&dir);
for (host, _) in DIRECTORY_HOSTS {
assert!(
issuer
.directory_allowed(&format!("https://{host}/directory"))
.is_ok(),
"{host}"
);
assert!(
issuer
.directory_allowed(&format!("https://{host}:443/directory"))
.is_ok(),
"{host} on 443"
);
assert!(
issuer
.directory_allowed(&format!("https://x.{host}/directory"))
.is_err(),
"a host under {host}"
);
assert!(
issuer
.directory_allowed(&format!("http://{host}/directory"))
.is_err(),
"{host} over http"
);
}
// The hosts' own documentation names these; a brand-new one is a
// release of the app.
let hosts: Vec<&str> = DIRECTORY_HOSTS.iter().map(|(h, _)| *h).collect();
for want in [
"acme-v02.api.letsencrypt.org",
"acme-staging-v02.api.letsencrypt.org",
"dv.acme-v02.api.pki.goog",
"acme.zerossl.com",
"acme.ssl.com",
] {
assert!(hosts.contains(&want), "{want}");
}
}
#[test]
fn an_authoritys_problem_is_the_apps_words_and_a_short_quoted_detail() {
let hostile = format!("a\u{7}\n\u{202e}b {}", "x".repeat(5000));
let problem: instant_acme::Problem = serde_json::from_value(serde_json::json!({
"type": "urn:made:up:evil",
"detail": hostile,
}))
.unwrap();
let said = words(Kind::Order, &instant_acme::Error::Api(problem));
assert!(said.starts_with("the authority refused the order. It said \u{201c}a b "));
assert!(said.chars().count() < 200, "{}", said.chars().count());
assert!(!said.chars().any(|c| c.is_control() || c == '\u{202e}'));
}
}
+652
View File
@@ -0,0 +1,652 @@
//! The app's own certificate: kept on disk, served by rustls, ordered
//! from whichever authority the relay lists, renewed ahead of expiry.
//!
//! ```text
//! GOAL: the app terminates the web caller's TLS with a certificate whose
//! key was made here and never left; the certificate survives a
//! restart without a new order; it is renewed ahead of expiry (at
//! the time the authority's renewal information suggests, else two
//! thirds of the way through its life); and the authority is data:
//! the relay's list, in order, so a swap needs no release.
//! SOURCE: WB-link-3 (TLS at the app), WB-link-4 (certificates and their
//! renewal), D-80, D-87, plan p15-app-and-relay.md section 5
//! ("Authorities are data, not code"); RFC 8555 (ACME), RFC 9773
//! (renewal information).
//! INVARIANTS:
//! 1. The private key is made by the app's side of the order and is
//! written only to the app's own private file (private.rs): it is
//! never in a request to the relay, a status, a log or an error.
//! 2. The certificate stored is for exactly the wildcard under this
//! name; one for another name, or one that does not parse, is
//! ignored and ordered again.
//! 3. A stored certificate is read at start: a restart before its
//! renewal time orders nothing.
//! 4. The authorities are tried in the relay's order; one marked not
//! usable is skipped; a failure of one falls to the next; all failing
//! is a state in words that is retried with a growing, jittered wait.
//! 5. The certificate that is serving keeps serving while a renewal
//! fails, until it ends.
//! 6. The server name must be this app's host (`<secret>.<name>.<domain>`):
//! a hello for any other name gets no certificate, so a stranger who
//! knows the four words but not the label learns nothing and reaches
//! nothing.
//! 7. A certificate is believed only if its chain ends at one of the
//! public roots the program ships ([`CertTrust::public`]), for the
//! app's wildcard, at the moment it is issued and at every load: the
//! relay names the authorities, so a certificate from one it made up
//! (a self-signed one valid for centuries) is refused, and one kept
//! on disk that fails is ignored and ordered again. Only a test makes
//! a [`CertTrust`] of its own roots; nothing at run time can.
//! 8. A lifetime over [`MAX_LIFETIME_DAYS`] days is refused, and the
//! renewal is never later than two thirds of the life or
//! [`MAX_RENEW_DAYS`] days into it, whichever is sooner.
//! 9. A certificate is never served at or after its `not_after`, even
//! when a renewal is failing or the next look is hours away.
//! SCENARIOS:
//! 1. An order with no stored certificate stores one and serves it; a
//! second start reads it and orders nothing.
//! 2. The renewal time passes: a second order is made and replaces the
//! first, naming the first as the one it replaces.
//! 3. The first authority fails and the second issues.
//! 4. A hello for another host name gets no certificate.
//! 5. A certificate from an authority that is not in the trusted roots,
//! one that lives over the cap, and one past its end are refused or
//! not served (unit tests here, `tests/link.rs`).
//! ```
use crate::private;
use futures::future::BoxFuture;
use relay::proto::Authority;
use rustls::RootCertStore;
use rustls::client::WebPkiServerVerifier;
use rustls::client::danger::ServerCertVerifier;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::CertifiedKey;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use zeroize::Zeroizing;
/// The relay publishes and clears the proof record of the app's name.
pub trait DnsProof: Send + Sync {
/// Publish the DNS-01 proof value (the 43 characters) at
/// `_acme-challenge.<name>`.
fn publish<'a>(&'a self, value: &'a str) -> BoxFuture<'a, Result<(), String>>;
/// Remove the app's proof records.
fn clear(&self) -> BoxFuture<'_, ()>;
}
/// One order.
pub struct OrderRequest<'a> {
/// The authority to order from.
pub authority: &'a Authority,
/// The one name asked for: `*.<four-words>.<domain>`.
pub identifier: String,
/// The certificate this one replaces (DER), if there is one still
/// valid from this authority: renewal information names it.
pub replaces: Option<Vec<u8>>,
/// Where the proof goes.
pub dns: &'a dyn DnsProof,
}
/// A certificate got from an authority.
pub struct Issued {
/// The certificate and its chain, PEM, leaf first.
pub chain_pem: String,
/// The private key made for it, PEM. Never leaves the app.
pub key_pem: Zeroizing<String>,
}
/// An authority's protocol, behind one small trait: everything that
/// differs between authorities beyond ACME itself (renewal information,
/// lifetimes, limits) is behind it, and the tests give it an in-process
/// authority.
pub trait Issuer: Send + Sync {
/// Order a certificate (the whole of RFC 8555: account, order,
/// DNS-01 proof through `req.dns`, finalize, download). An error is
/// in words.
fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result<Issued, String>>;
/// The renewal window the authority suggests for this certificate
/// (unix seconds, start and end), if it offers one.
fn renewal_window<'a>(
&'a self,
authority: &'a Authority,
chain_pem: &'a str,
) -> BoxFuture<'a, Option<(i64, i64)>>;
}
/// Seconds since the epoch.
pub fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
.unwrap_or(0)
}
/// The longest a certificate may live (INVARIANT 8): public authorities
/// issue for 90 days or fewer, so a longer one is not from one.
pub const MAX_LIFETIME_DAYS: i64 = 100;
/// The latest, in days from the start of its life, a renewal is planned
/// (INVARIANT 8).
pub const MAX_RENEW_DAYS: i64 = 60;
const DAY: i64 = 86_400;
/// Which certificate authorities this app believes (INVARIANT 7): the
/// public roots the program ships. Not data, not the relay's to change.
#[derive(Clone)]
pub struct CertTrust {
verifier: Arc<WebPkiServerVerifier>,
}
impl std::fmt::Debug for CertTrust {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CertTrust").finish_non_exhaustive()
}
}
impl CertTrust {
/// The public roots the program ships (Mozilla's, as
/// `webpki-root-certs`).
pub fn public() -> Result<Self, String> {
let mut roots = RootCertStore::empty();
for der in webpki_root_certs::TLS_SERVER_ROOT_CERTS {
// A root the parser can't read is skipped, not fatal.
let _ = roots.add(der.clone());
}
Self::from_roots(roots)
}
/// Trust exactly these roots: for a test's own authority. Nothing in
/// the program calls this; the relay cannot reach it (INVARIANT 7).
pub fn for_tests(roots: RootCertStore) -> Self {
Self::from_roots(roots)
.unwrap_or_else(|why| panic!("a test's roots must make a verifier: {why}"))
}
fn from_roots(roots: RootCertStore) -> Result<Self, String> {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let verifier = WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider)
.build()
.map_err(|_| "no trusted certificate authorities".to_string())?;
Ok(CertTrust { verifier })
}
/// Whether `chain_pem` (leaf first) is a good chain, at time `t`, for
/// the wildcard `identifier` (`*.<name>.<domain>`).
pub fn check(&self, chain_pem: &str, identifier: &str, t: i64) -> Result<(), String> {
let chain: Vec<CertificateDer<'static>> =
CertificateDer::pem_slice_iter(chain_pem.as_bytes())
.collect::<Result<_, _>>()
.map_err(|_| "the certificate can't be read".to_string())?;
let (leaf, rest) = chain
.split_first()
.ok_or("the authority sent no certificate")?;
// A host the wildcard covers: the chain is checked for a name a
// caller will really use.
let host = identifier.replacen('*', "check", 1);
let name = ServerName::try_from(host)
.map_err(|_| "the certificate's name is not a host name".to_string())?;
let at = UnixTime::since_unix_epoch(Duration::from_secs(u64::try_from(t).unwrap_or(0)));
self.verifier
.verify_server_cert(leaf, rest, &name, &[], at)
.map(|_| ())
.map_err(|_| {
"the certificate does not come from a public certificate authority this program trusts"
.to_string()
})
}
}
/// The certificate and its key, as kept (one file, so one atomic write).
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StoredCert {
v: u8,
/// The four-word name it is for.
pub name: String,
/// The authority that issued it.
pub authority: String,
/// The chain, PEM.
pub chain_pem: String,
key_pem: String,
/// Valid from (unix seconds).
pub not_before: i64,
/// Valid until (unix seconds).
pub not_after: i64,
/// When to order the next one (unix seconds).
pub renew_at: i64,
}
impl std::fmt::Debug for StoredCert {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Never the key (INVARIANT 1).
f.debug_struct("StoredCert")
.field("name", &self.name)
.field("authority", &self.authority)
.field("not_after", &self.not_after)
.field("renew_at", &self.renew_at)
.finish_non_exhaustive()
}
}
const FILE: &str = "cert.json";
/// The first certificate of a chain, DER.
pub fn leaf_der(chain_pem: &str) -> Option<Vec<u8>> {
CertificateDer::pem_slice_iter(chain_pem.as_bytes())
.next()?
.ok()
.map(|c| c.as_ref().to_vec())
}
/// A certificate's validity (unix seconds) and its names.
pub fn inspect(der: &[u8]) -> Option<(i64, i64, Vec<String>)> {
let (_, cert) = x509_parser::parse_x509_certificate(der).ok()?;
let v = cert.validity();
let names = cert
.subject_alternative_name()
.ok()
.flatten()
.map(|san| {
san.value
.general_names
.iter()
.filter_map(|n| match n {
x509_parser::extensions::GeneralName::DNSName(d) => Some((*d).to_string()),
_ => None,
})
.collect()
})
.unwrap_or_default();
Some((v.not_before.timestamp(), v.not_after.timestamp(), names))
}
impl StoredCert {
/// A certificate just issued, checked: it must be for `identifier`,
/// valid now, chain to a trusted root, live no longer than the cap and
/// have a key that matches (INVARIANTS 2, 7 and 8).
pub fn new(
name: &str,
authority: &str,
issued: &Issued,
identifier: &str,
renew_at: Option<i64>,
trust: &CertTrust,
) -> Result<Self, String> {
let der = leaf_der(&issued.chain_pem)
.ok_or("the authority sent something that is not a certificate")?;
let (not_before, not_after, names) =
inspect(&der).ok_or("the authority sent a certificate that can't be read")?;
if !names.iter().any(|n| n.eq_ignore_ascii_case(identifier)) {
return Err("the authority sent a certificate for another name".into());
}
let t = now();
if not_after <= t {
return Err("the authority sent a certificate that has already ended".into());
}
let cap = renewal_cap(not_before, not_after);
check_life(not_before, not_after)?;
trust.check(&issued.chain_pem, identifier, t)?;
certified(&issued.chain_pem, &issued.key_pem)
.ok_or("the certificate and its key do not go together")?;
let renew_at = renew_at.unwrap_or(cap).min(cap);
Ok(StoredCert {
v: 1,
name: name.to_owned(),
authority: authority.to_owned(),
chain_pem: issued.chain_pem.clone(),
key_pem: issued.key_pem.to_string(),
not_before,
not_after,
renew_at,
})
}
/// A stored certificate, checked again as it is read (INVARIANTS 2, 7,
/// 8): the same tests as when it was issued, against the file's own
/// words and the clock now. A renewal time set too late is brought in.
fn vetted(mut self, name: &str, identifier: &str, trust: &CertTrust) -> Option<Self> {
if self.v != 1 || self.name != name || self.certified().is_none() {
return None;
}
let der = self.der()?;
let (not_before, not_after, names) = inspect(&der)?;
if !names.iter().any(|n| n.eq_ignore_ascii_case(identifier)) {
return None;
}
check_life(not_before, not_after).ok()?;
trust.check(&self.chain_pem, identifier, now()).ok()?;
// What is in the certificate is what counts, not what the file says
// about it.
self.not_before = not_before;
self.not_after = not_after;
self.renew_at = self.renew_at.min(renewal_cap(not_before, not_after));
Some(self)
}
/// The key and chain, ready for rustls.
pub fn certified(&self) -> Option<Arc<CertifiedKey>> {
certified(&self.chain_pem, &self.key_pem)
}
/// The certificate's DER (for renewal information).
pub fn der(&self) -> Option<Vec<u8>> {
leaf_der(&self.chain_pem)
}
/// Whether it still serves.
pub fn valid_at(&self, t: i64) -> bool {
self.not_after > t
}
}
/// Two thirds of the way through its life: a third is left to renew in.
pub fn default_renewal(not_before: i64, not_after: i64) -> i64 {
not_before + (not_after - not_before) * 2 / 3
}
/// The latest a renewal may be planned (INVARIANT 8): two thirds of the
/// life or [`MAX_RENEW_DAYS`] days in, whichever is sooner.
pub fn renewal_cap(not_before: i64, not_after: i64) -> i64 {
default_renewal(not_before, not_after).min(not_before.saturating_add(MAX_RENEW_DAYS * DAY))
}
fn check_life(not_before: i64, not_after: i64) -> Result<(), String> {
if not_after.saturating_sub(not_before) > MAX_LIFETIME_DAYS * DAY {
return Err(format!(
"the certificate would live longer than {MAX_LIFETIME_DAYS} days, which no public authority issues"
));
}
Ok(())
}
fn certified(chain_pem: &str, key_pem: &str) -> Option<Arc<CertifiedKey>> {
let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(chain_pem.as_bytes())
.collect::<Result<_, _>>()
.ok()?;
if chain.is_empty() {
return None;
}
let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes()).ok()?;
let provider = rustls::crypto::ring::default_provider();
let signing = provider.key_provider.load_private_key(key).ok()?;
let ck = CertifiedKey::new(chain, signing);
ck.keys_match().ok()?;
Some(Arc::new(ck))
}
/// The certificate on disk.
pub struct CertStore {
path: PathBuf,
}
impl CertStore {
/// The store in the link folder `dir`.
pub fn new(dir: &Path) -> Self {
CertStore {
path: dir.join(FILE),
}
}
/// The stored certificate for `name`, if there is a good one
/// (INVARIANTS 2, 7, 8): one that fails any check is as if there were
/// none, and is ordered again. A file that does not read is the same.
pub fn load(&self, name: &str, identifier: &str, trust: &CertTrust) -> Option<StoredCert> {
let bytes = std::fs::read(&self.path).ok()?;
let c: StoredCert = serde_json::from_slice(&bytes).ok()?;
c.vetted(name, identifier, trust)
}
/// Keep a certificate, privately and atomically.
pub fn save(&self, c: &StoredCert) -> std::io::Result<()> {
let text = serde_json::to_vec(c).map_err(std::io::Error::other)?;
private::write(&self.path, &text)
}
/// Forget the certificate (a new identity).
pub fn forget(&self) {
let _ = std::fs::remove_file(&self.path);
}
}
/// What rustls serves: the current certificate, to the app's own host
/// name and no other (INVARIANT 6), and never at or after its end
/// (INVARIANT 9).
pub struct Resolver {
host: RwLock<String>,
key: RwLock<Option<(Arc<CertifiedKey>, i64)>>,
}
impl std::fmt::Debug for Resolver {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Resolver").finish_non_exhaustive()
}
}
impl Resolver {
/// A resolver with no certificate and no host.
pub fn new() -> Arc<Self> {
Arc::new(Resolver {
host: RwLock::new(String::new()),
key: RwLock::new(None),
})
}
/// The one host name served.
pub fn set_host(&self, host: &str) {
*self.host.write().unwrap_or_else(|e| e.into_inner()) = host.to_ascii_lowercase();
}
/// The certificate to serve, with when it ends (unix seconds), or none.
pub fn set_cert(&self, cert: Option<(Arc<CertifiedKey>, i64)>) {
*self.key.write().unwrap_or_else(|e| e.into_inner()) = cert;
}
/// Whether a certificate is being served.
pub fn has_key(&self) -> bool {
self.key.read().unwrap_or_else(|e| e.into_inner()).is_some()
}
/// The certificate for a hello naming `sni` at time `t`: only for the
/// app's own host, and only while it lasts.
pub fn pick(&self, sni: &str, t: i64) -> Option<Arc<CertifiedKey>> {
let host = self.host.read().unwrap_or_else(|e| e.into_inner());
if host.is_empty() || !sni.eq_ignore_ascii_case(&host) {
return None;
}
drop(host);
let held = self.key.read().unwrap_or_else(|e| e.into_inner());
held.as_ref()
.filter(|(_, not_after)| t < *not_after)
.map(|(key, _)| key.clone())
}
}
impl ResolvesServerCert for Resolver {
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
self.pick(hello.server_name()?, now())
}
}
/// The server settings the app terminates TLS with: TLS 1.3 and 1.2, the
/// resolver, and HTTP/2 or HTTP/1.1 by ALPN.
pub fn server_config(resolver: Arc<Resolver>) -> Arc<rustls::ServerConfig> {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let mut cfg = rustls::ServerConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap_or_else(|_| unreachable!("the ring provider has the default versions"))
.with_no_client_auth()
.with_cert_resolver(resolver);
cfg.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
// The line is the relay's; a ticket resumed there is one more thing
// to hold for nothing.
cfg.send_tls13_tickets = 0;
Arc::new(cfg)
}
#[cfg(test)]
mod tests {
use super::*;
use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair};
const IDENT: &str = "*.a-b-c-d.wanderbooks.link";
fn ca() -> CertifiedIssuer<'static, KeyPair> {
let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
params.key_usages = vec![
rcgen::KeyUsagePurpose::KeyCertSign,
rcgen::KeyUsagePurpose::CrlSign,
];
CertifiedIssuer::self_signed(params, KeyPair::generate().unwrap()).unwrap()
}
/// A certificate for `IDENT` from `ca`, living `days` days from an hour
/// ago.
fn issue(ca: &CertifiedIssuer<'static, KeyPair>, days: i64) -> Issued {
let mut params = CertificateParams::new(vec![IDENT.to_string()]).unwrap();
let t = time::OffsetDateTime::now_utc();
params.not_before = t - time::Duration::hours(1);
params.not_after = t + time::Duration::days(days);
let key = KeyPair::generate().unwrap();
let cert = params.signed_by(&key, ca).unwrap();
Issued {
chain_pem: format!("{}{}", cert.pem(), ca.pem()),
key_pem: Zeroizing::new(key.serialize_pem()),
}
}
fn trusting(ca: &CertifiedIssuer<'static, KeyPair>) -> CertTrust {
let mut roots = RootCertStore::empty();
roots.add(ca.der().clone()).unwrap();
CertTrust::for_tests(roots)
}
#[test]
fn two_thirds_of_a_life() {
assert_eq!(default_renewal(0, 90), 60);
assert_eq!(default_renewal(100, 106), 104);
}
#[test]
fn a_certificate_from_an_authority_the_program_trusts_is_kept() {
let ca = ca();
let c = StoredCert::new("a-b-c-d", "x", &issue(&ca, 60), IDENT, None, &trusting(&ca))
.expect("a good certificate");
assert!(c.valid_at(now()));
}
#[test]
fn a_certificate_from_an_authority_the_relay_made_up_is_refused() {
// The authority the relay listed signs for any name, for 8000 days
// (and, separately, for 60): neither chains to a public root.
let fake = ca();
let public = CertTrust::public().unwrap();
let why =
StoredCert::new("a-b-c-d", "x", &issue(&fake, 60), IDENT, None, &public).unwrap_err();
assert!(why.contains("public certificate authority"), "{why}");
// Valid until the year 9999, as a hostile relay's would be.
assert!(
StoredCert::new("a-b-c-d", "x", &issue(&fake, 8000), IDENT, None, &public).is_err()
);
// A self-signed leaf with nothing above it is no better.
let key = KeyPair::generate().unwrap();
let mut params = CertificateParams::new(vec![IDENT.to_string()]).unwrap();
params.not_after = time::OffsetDateTime::now_utc() + time::Duration::days(60);
let own = params.self_signed(&key).unwrap();
let issued = Issued {
chain_pem: own.pem(),
key_pem: Zeroizing::new(key.serialize_pem()),
};
assert!(StoredCert::new("a-b-c-d", "x", &issued, IDENT, None, &public).is_err());
}
#[test]
fn a_lifetime_over_the_cap_is_refused() {
let ca = ca();
let trust = trusting(&ca);
let why =
StoredCert::new("a-b-c-d", "x", &issue(&ca, 101), IDENT, None, &trust).unwrap_err();
assert!(why.contains("100 days"), "{why}");
assert!(StoredCert::new("a-b-c-d", "x", &issue(&ca, 99), IDENT, None, &trust).is_ok());
}
#[test]
fn renewal_is_never_later_than_two_thirds_or_sixty_days() {
let ca = ca();
let trust = trusting(&ca);
// 99 days: two thirds is 66 days in, so sixty days is sooner.
let c = StoredCert::new(
"a-b-c-d",
"x",
&issue(&ca, 99),
IDENT,
Some(i64::MAX),
&trust,
)
.unwrap();
assert_eq!(c.renew_at, c.not_before + 60 * DAY);
// 30 days: two thirds (20 days) is sooner.
let c = StoredCert::new("a-b-c-d", "x", &issue(&ca, 30), IDENT, None, &trust).unwrap();
assert_eq!(c.renew_at, default_renewal(c.not_before, c.not_after));
// An earlier time the authority suggests is kept.
let early = now() + 100;
let c =
StoredCert::new("a-b-c-d", "x", &issue(&ca, 30), IDENT, Some(early), &trust).unwrap();
assert_eq!(c.renew_at, early);
}
#[test]
fn a_stored_certificate_that_fails_is_ignored_when_read() {
let ca = ca();
let trust = trusting(&ca);
let dir = tempfile::tempdir().unwrap();
let store = CertStore::new(dir.path());
let good = StoredCert::new("a-b-c-d", "x", &issue(&ca, 60), IDENT, None, &trust).unwrap();
store.save(&good).unwrap();
assert!(store.load("a-b-c-d", IDENT, &trust).is_some());
// The same file, read by a program that does not trust that
// authority (the relay's made-up one): ignored.
let public = CertTrust::public().unwrap();
assert!(store.load("a-b-c-d", IDENT, &public).is_none());
// Another name: ignored.
assert!(store.load("e-f-g-h", IDENT, &trust).is_none());
// A file whose renewal time was set far out is brought in.
let mut late = good.clone();
late.renew_at = i64::MAX / 2;
store.save(&late).unwrap();
let read = store.load("a-b-c-d", IDENT, &trust).unwrap();
assert!(read.renew_at <= read.not_before + 60 * DAY);
// A certificate that lives over the cap, put on disk by hand.
let long = issue(&ca, 400);
let mut f = good;
f.chain_pem = long.chain_pem;
f.key_pem = long.key_pem.to_string();
store.save(&f).unwrap();
assert!(store.load("a-b-c-d", IDENT, &trust).is_none());
}
#[test]
fn the_resolver_serves_only_its_host_and_only_until_the_certificate_ends() {
let ca = ca();
let c =
StoredCert::new("a-b-c-d", "x", &issue(&ca, 30), IDENT, None, &trusting(&ca)).unwrap();
let r = Resolver::new();
r.set_host("Secret.a-b-c-d.wanderbooks.link");
r.set_cert(c.certified().map(|k| (k, c.not_after)));
let host = "secret.a-b-c-d.wanderbooks.link";
assert!(r.pick(host, c.not_after - 1).is_some());
assert!(r.pick(host, c.not_after).is_none(), "at its end");
assert!(
r.pick(host, c.not_after + 3600 * 6).is_none(),
"hours after"
);
assert!(r.pick("other.a-b-c-d.wanderbooks.link", 0).is_none());
}
}
+329
View File
@@ -0,0 +1,329 @@
//! The app's identity at the relay: its key, its four-word name and the
//! secret label of its address.
//!
//! ```text
//! GOAL: an installation has one durable public address,
//! `https://<secret>.<four-words>.wanderbooks.link`; its key never
//! leaves the machine; and a person can have a new address, after
//! which the old one stops working.
//! SOURCE: WB-link-1 (the identity), plan/p15-app-and-relay.md section 5
//! ("Names": one name per installation, each company a path under
//! it; the secret label stops listing and guessing), D-82, D-85,
//! D-87; relay `names.rs` (a secret label is 25 to 63 characters
//! of a-z and 0-9; the app makes it from at least 128 random bits).
//! INVARIANTS:
//! 1. The name is four words from the relay's list, picked here at
//! random and kept: the same installation has the same name until it
//! is asked for a new address after the relay lost it.
//! 2. The secret label is 32 random characters of a-z and 0-9 (about
//! 165 bits; the relay needs 128 at least), made by rejection
//! sampling with no modulo bias, never from the name, a time or a
//! counter.
//! 3. The key (Ed25519, PKCS#8) and the label are in the data root's
//! private `link/` folder, owner-only files (private.rs); neither is
//! ever sent to the relay (the relay is sent the public key) or
//! written to a log, an error or a status.
//! 4. A new label replaces the old one in one atomic write: the old
//! address stops being served the moment this returns.
//! 5. A file that is damaged is not guessed at: it is an error in
//! words, and nothing is overwritten.
//! SCENARIOS:
//! 1. The first call makes a name, a label and a key; the second
//! reads the same ones.
//! 2. A new label differs and is persisted; the name and key stay.
//! 3. A reset makes a new key and a new name too.
//! ```
use crate::private;
use relay::names::{Name, SECRET_LEN};
use relay::proto::AppKey;
use ring::rand::{SecureRandom, SystemRandom};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use zeroize::Zeroizing;
/// The length of the secret label this app makes.
pub const LABEL_LEN: usize = 32;
const FILE: &str = "identity.json";
const KEY_FILE: &str = "line.key";
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Stored {
v: u8,
name: String,
label: String,
/// True once the relay said the name is ours.
claimed: bool,
}
/// Why the identity could not be read or kept.
#[derive(Debug, thiserror::Error)]
pub enum IdentityError {
/// The folder could not be read or written.
#[error("Wanderbooks can't keep its web address on this computer ({0})")]
Io(std::io::ErrorKind),
/// A file is not what it should be.
#[error("the file that keeps the web address is damaged")]
Damaged,
}
/// One installation's identity.
pub struct Identity {
dir: PathBuf,
name: Name,
label: String,
claimed: bool,
key: AppKey,
pkcs8: Zeroizing<Vec<u8>>,
}
fn base36(n: usize) -> String {
let rng = SystemRandom::new();
let mut out = String::with_capacity(n);
while out.len() < n {
let mut b = [0u8; 64];
if rng.fill(&mut b).is_err() {
// The system generator failing is not recoverable.
panic!("the system random number generator failed");
}
for byte in b {
// 252 is the largest multiple of 36 that fits in a byte:
// anything above is dropped, so no character is likelier.
if byte < 252 && out.len() < n {
let v = byte % 36;
out.push(char::from(if v < 10 { b'0' + v } else { b'a' + v - 10 }));
}
}
}
out
}
/// A new secret label.
pub fn new_label() -> String {
base36(LABEL_LEN)
}
fn label_ok(label: &str) -> bool {
SECRET_LEN.contains(&label.len())
&& label
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
}
impl Identity {
/// Read the identity kept in `dir`, or make one (INVARIANT 1).
pub fn load_or_create(dir: &Path) -> Result<Self, IdentityError> {
private::make_dir(dir).map_err(|e| IdentityError::Io(e.kind()))?;
match std::fs::read(dir.join(FILE)) {
Ok(bytes) => Self::read(dir, &bytes),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::make(dir),
Err(e) => Err(IdentityError::Io(e.kind())),
}
}
/// The identity kept in `dir`, if there is one.
pub fn load(dir: &Path) -> Result<Option<Self>, IdentityError> {
match std::fs::read(dir.join(FILE)) {
Ok(bytes) => Self::read(dir, &bytes).map(Some),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(IdentityError::Io(e.kind())),
}
}
fn read(dir: &Path, bytes: &[u8]) -> Result<Self, IdentityError> {
let stored: Stored = serde_json::from_slice(bytes).map_err(|_| IdentityError::Damaged)?;
let name = Name::parse(&stored.name).map_err(|_| IdentityError::Damaged)?;
if stored.v != 1 || !label_ok(&stored.label) {
return Err(IdentityError::Damaged);
}
let pkcs8 = Zeroizing::new(
std::fs::read(dir.join(KEY_FILE)).map_err(|e| IdentityError::Io(e.kind()))?,
);
let key = AppKey::from_pkcs8(&pkcs8).ok_or(IdentityError::Damaged)?;
Ok(Identity {
dir: dir.to_path_buf(),
name,
label: stored.label,
claimed: stored.claimed,
key,
pkcs8,
})
}
fn make(dir: &Path) -> Result<Self, IdentityError> {
let (key, pkcs8) = AppKey::generate();
let me = Identity {
dir: dir.to_path_buf(),
name: Name::random(),
label: new_label(),
claimed: false,
key,
pkcs8: Zeroizing::new(pkcs8),
};
// The key first: a name with no key is damaged; a key with no
// name is just unused.
private::write(&dir.join(KEY_FILE), &me.pkcs8).map_err(|e| IdentityError::Io(e.kind()))?;
me.save()?;
Ok(me)
}
fn save(&self) -> Result<(), IdentityError> {
let stored = Stored {
v: 1,
name: self.name.to_string(),
label: self.label.clone(),
claimed: self.claimed,
};
let text = serde_json::to_vec_pretty(&stored).map_err(|_| IdentityError::Damaged)?;
private::write(&self.dir.join(FILE), &text).map_err(|e| IdentityError::Io(e.kind()))
}
/// The four-word name.
pub fn name(&self) -> Name {
self.name
}
/// The address: `https://<secret>.<four-words>.<domain>`.
pub fn address(&self, domain: &str) -> String {
format!("https://{}", self.host(domain))
}
/// The host name of the address.
pub fn host(&self, domain: &str) -> String {
format!("{}.{}.{domain}", self.label, self.name)
}
/// The key, to prove the name to the relay.
pub fn key(&self) -> &AppKey {
&self.key
}
/// A second handle on the same key (the line signs with it while the
/// identity stays behind its lock).
pub fn key_copy(&self) -> AppKey {
AppKey::from_pkcs8(&self.pkcs8)
.unwrap_or_else(|| unreachable!("a key that parsed parses again"))
}
/// Whether the relay has said the name is ours.
pub fn claimed(&self) -> bool {
self.claimed
}
/// Keep that the relay said the name is ours.
pub fn set_claimed(&mut self) -> Result<(), IdentityError> {
if !self.claimed {
self.claimed = true;
self.save()?;
}
Ok(())
}
/// Another name, for a name somebody else holds (only while this one
/// is not claimed).
pub fn retry_name(&mut self) -> Result<(), IdentityError> {
self.name = Name::random();
self.save()
}
/// A new secret label: the old address stops being served
/// (INVARIANT 4).
pub fn new_label(&mut self) -> Result<(), IdentityError> {
self.label = new_label();
self.save()
}
/// A whole new identity: key, name and label (the relay no longer
/// knows this one).
pub fn reset(dir: &Path) -> Result<Self, IdentityError> {
Self::make(dir)
}
}
impl std::fmt::Debug for Identity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Never the key, never the label (INVARIANT 3).
f.debug_struct("Identity")
.field("name", &self.name.to_string())
.field("claimed", &self.claimed)
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_first_call_makes_and_the_second_reads_the_same() {
let dir = tempfile::tempdir().unwrap();
let a = Identity::load_or_create(dir.path()).unwrap();
let b = Identity::load_or_create(dir.path()).unwrap();
assert_eq!(a.name(), b.name());
assert_eq!(a.host("wanderbooks.link"), b.host("wanderbooks.link"));
assert_eq!(a.key().public_key(), b.key().public_key());
assert!(!a.claimed());
assert!(a.address("wanderbooks.link").starts_with("https://"));
}
#[test]
fn labels_are_long_enough_and_use_only_the_relays_characters() {
for _ in 0..200 {
let l = new_label();
assert_eq!(l.len(), LABEL_LEN);
assert!(label_ok(&l));
}
// 32 characters of base 36 are far over 128 bits.
assert!(32.0 * 36f64.log2() > 128.0);
// Every character is reached: no modulo bias hides one.
let mut seen = std::collections::BTreeSet::new();
for _ in 0..400 {
seen.extend(new_label().chars());
}
assert_eq!(seen.len(), 36);
assert_ne!(new_label(), new_label());
}
#[test]
fn a_new_label_replaces_the_old_and_a_reset_replaces_everything() {
let dir = tempfile::tempdir().unwrap();
let mut a = Identity::load_or_create(dir.path()).unwrap();
let (name, host, key) = (a.name(), a.host("x.link"), a.key().public_key());
a.set_claimed().unwrap();
a.new_label().unwrap();
assert_ne!(a.host("x.link"), host);
let b = Identity::load_or_create(dir.path()).unwrap();
assert_eq!(b.host("x.link"), a.host("x.link"));
assert_eq!(b.name(), name);
assert_eq!(b.key().public_key(), key);
assert!(b.claimed());
let c = Identity::reset(dir.path()).unwrap();
assert_ne!(c.key().public_key(), key);
assert!(!c.claimed());
}
#[test]
fn a_damaged_file_is_an_error_not_a_new_identity() {
let dir = tempfile::tempdir().unwrap();
Identity::load_or_create(dir.path()).unwrap();
std::fs::write(dir.path().join(FILE), b"{ not json").unwrap();
assert!(matches!(
Identity::load_or_create(dir.path()),
Err(IdentityError::Damaged)
));
// Nothing was overwritten.
assert_eq!(std::fs::read(dir.path().join(FILE)).unwrap(), b"{ not json");
}
#[test]
fn debug_shows_neither_key_nor_label() {
let dir = tempfile::tempdir().unwrap();
let a = Identity::load_or_create(dir.path()).unwrap();
let shown = format!("{a:?}");
let label = a.host("x.link");
let label = label.split('.').next().unwrap();
assert!(!shown.contains(label));
}
}
+60
View File
@@ -0,0 +1,60 @@
//! The app's side of the relay (plan P15 unit B3).
//!
//! A person turns on "Allow web assistants" for a company. This crate then
//! gives the app a durable public address, `https://<secret>.<four-words>.wanderbooks.link`,
//! holds its own private key and its own certificate, keeps one outbound
//! line to the relay, and serves the sign-in and the books to Claude or
//! ChatGPT on the web through it. The relay forwards encrypted bytes and
//! can read nothing (D-80): TLS ends here.
//!
//! The crate depends on the relay crate for the wire (`proto`, `names`,
//! the client's line) and on no other `ledger-*` crate except, on Windows
//! only, `ledger-store` for the owner-only file helper.
//!
//! ```text
//! GOAL: the app's side of D-80: an address that is durable and secret, a
//! line that comes back by itself, TLS ended with a key that never
//! left the machine, a certificate that is ordered, kept and
//! renewed with the authority as data, and every failure in words.
//! SOURCE: WB-link-1 (the identity and name), WB-link-2 (the line),
//! WB-link-3 (TLS at the app and the hand to the door), WB-link-4
//! (certificates), WB-link-5 (the states in words); D-80, D-82,
//! D-85, D-87.
//! INVARIANTS:
//! 1. No key, secret label or token is in a log, an error, a status
//! Debug or a test's output; the files that hold them are owner-only.
//! 2. Nothing the relay could use to read traffic leaves the machine:
//! the relay is sent a public key, a proof and a DNS value.
//! 3. The relay protocol is not changed here; this crate only uses it.
//! SCENARIOS:
//! 1. See `tests/link.rs` and `tests/acme.rs`.
//! ```
#![forbid(unsafe_code)]
pub mod acme;
pub mod certs;
pub mod identity;
pub mod line;
pub mod link;
pub mod private;
pub mod status;
pub mod text;
pub use acme::AcmeIssuer;
pub use certs::{CertTrust, DnsProof, Issued, Issuer, OrderRequest};
pub use line::{Dial, Timing};
pub use link::{DoorTarget, Link, LinkConfig, LinkError};
pub use status::{LinkStatus, Step, Trouble};
/// The relay trust roots for the line, from the roots the program ships
/// (Mozilla's, as `webpki-root-certs`), for a relay with a public
/// certificate.
pub fn public_relay_tls() -> Result<std::sync::Arc<rustls::ClientConfig>, rustls::Error> {
let mut roots = rustls::RootCertStore::empty();
for der in webpki_root_certs::TLS_SERVER_ROOT_CERTS {
// A root the parser can't read is skipped, not fatal.
let _ = roots.add(der.clone());
}
relay::tls::client_config(roots)
}
+451
View File
@@ -0,0 +1,451 @@
//! The line to the relay, as the app holds it: dialling, the words for
//! what goes wrong, backoff, and keeping watch for a computer that slept.
//!
//! ```text
//! GOAL: one outbound connection to the relay that comes back by itself
//! after anything (no network, the relay down, a laptop that slept
//! and woke on another network), never spins hot against a relay
//! that is down, and never keeps a door open once it is told to
//! close.
//! SOURCE: WB-link-2 (the line), plan p15-app-and-relay.md 6a ("Unit
//! B3's duties: ping at least every 60 s (a line silent for 180 s
//! is dropped) ... a yamux stream limit at least the relay's"),
//! D-80; relay `client.rs` (the line), `config.rs` (limits).
//! INVARIANTS:
//! 1. A dial that fails waits a growing, jittered time (full jitter, at
//! most `backoff_max`, at least `backoff_min` after a failure) and
//! starts again. A line that held for `line_stable` (60 s) resets the
//! backoff and is redialled after a wait spread over `redial_spread`
//! (0 to 30 s, jittered), so a relay that restarts is not met by
//! every app in the same second; a line that ended sooner (a relay
//! that accepts and then drops) does not reset it and waits as a
//! failed dial does. A nudge (the network changed) resets it and
//! dials now.
//! 2. The line is pinged at most every `ping_every` (30 s, under the
//! relay's 60 s duty and 180 s silence limit); a ping that is not
//! answered in `ping_timeout` ends the line and a new one is made.
//! 3. A step of wall-clock time much longer than the monotonic time
//! that passed (the computer slept) ends the line and dials again at
//! once: a connection held across a sleep is not trusted.
//! 4. A relay certificate that is expired or not yet valid is a wrong
//! clock, said so in words, not "the relay is down".
//! 5. The stream limit offered the relay is more than the relay's own
//! (callers, control streams and slack).
//! SCENARIOS:
//! 1. The backoff grows from its minimum to its maximum and no further,
//! never exceeds the maximum with jitter, and resets; a line that
//! ended young does not reset it, one that held does, and its
//! redial is spread over `redial_spread`.
//! 2. A wall-clock jump with no monotonic jump is a wake; a small one is
//! not.
//! 3. Errors read as the right trouble: a refused connection is the
//! relay down, a name that does not resolve is no internet, an
//! expired relay certificate is a wrong clock.
//! ```
use crate::status::Trouble;
use relay::client::ClientError;
use relay::proto::Refusal;
use ring::rand::{SecureRandom, SystemRandom};
use std::io;
use std::net::SocketAddr;
use std::time::{Duration, Instant, SystemTime};
/// Where the relay is.
#[derive(Clone, Debug)]
pub enum Dial {
/// A host name and port, resolved at every dial (so a new network
/// finds the relay again).
Host(String, u16),
/// A fixed address (tests).
Addr(SocketAddr),
}
/// Every time the link waits, in one place (tests make them short).
#[derive(Clone, Copy, Debug)]
pub struct Timing {
/// A ping at least this often.
pub ping_every: Duration,
/// A ping not answered in this long ends the line.
pub ping_timeout: Duration,
/// How often the line looks for a sleep and for a ping due.
pub tick: Duration,
/// A dial that takes longer than this has failed.
pub connect_timeout: Duration,
/// The shortest wait after a failed dial.
pub backoff_min: Duration,
/// The longest wait after a failed dial.
pub backoff_max: Duration,
/// A caller's TLS handshake must finish in this long.
pub handshake: Duration,
/// The shortest wait after a failed certificate order.
pub cert_retry_min: Duration,
/// The longest wait after a failed certificate order.
pub cert_retry_max: Duration,
/// An order is given up on after this long.
pub order_timeout: Duration,
/// Renewal information is asked again this often.
pub ari_recheck: Duration,
/// A wall-clock step this much longer than the monotonic one is a
/// sleep.
pub wake_gap: Duration,
/// A line must have held this long for the backoff to start again from
/// its minimum.
pub line_stable: Duration,
/// A line that held and then ended is redialled after a wait spread
/// over this long.
pub redial_spread: Duration,
}
impl Default for Timing {
fn default() -> Self {
Timing {
ping_every: Duration::from_secs(30),
ping_timeout: Duration::from_secs(15),
tick: Duration::from_secs(5),
connect_timeout: Duration::from_secs(20),
backoff_min: Duration::from_secs(1),
backoff_max: Duration::from_secs(300),
handshake: Duration::from_secs(10),
cert_retry_min: Duration::from_secs(60),
cert_retry_max: Duration::from_secs(6 * 3600),
order_timeout: Duration::from_secs(300),
ari_recheck: Duration::from_secs(6 * 3600),
wake_gap: Duration::from_secs(30),
line_stable: Duration::from_secs(60),
redial_spread: Duration::from_secs(30),
}
}
}
/// Streams the app lets the line carry at once: the relay's own limits
/// (8 callers, 2 control, plus slack, relay `config.rs`) with room to
/// spare (INVARIANT 5).
pub const MAX_STREAMS: usize = 64;
/// A random duration in `0..=max`.
pub fn jitter(max: Duration) -> Duration {
let mut b = [0u8; 4];
if SystemRandom::new().fill(&mut b).is_err() {
return max / 2;
}
let frac = f64::from(u32::from_be_bytes(b)) / f64::from(u32::MAX);
max.mul_f64(frac)
}
/// The wait between tries: doubling, with full jitter (INVARIANT 1).
#[derive(Debug)]
pub struct Backoff {
min: Duration,
max: Duration,
failures: u32,
}
impl Backoff {
/// A backoff from `min` to `max`.
pub fn new(min: Duration, max: Duration) -> Self {
Backoff {
min,
max,
failures: 0,
}
}
/// A line held: start from the minimum again.
pub fn reset(&mut self) {
self.failures = 0;
}
/// The ceiling of the next wait, before jitter.
pub fn ceiling(&self) -> Duration {
let doubled = self
.min
.saturating_mul(1u32.checked_shl(self.failures.min(20)).unwrap_or(u32::MAX));
doubled.min(self.max)
}
/// The next wait: between the minimum (or the ceiling, if lower) and
/// the ceiling.
pub fn wait(&mut self) -> Duration {
let ceiling = self.ceiling();
self.failures = self.failures.saturating_add(1);
let floor = self.min.min(ceiling);
floor + jitter(ceiling - floor)
}
}
/// When to dial again, after a dial that failed or a line that ended
/// (INVARIANT 1).
#[derive(Debug)]
pub struct Redial {
backoff: Backoff,
stable: Duration,
spread: Duration,
}
impl Redial {
/// The waits `t` sets.
pub fn new(t: &Timing) -> Self {
Redial {
backoff: Backoff::new(t.backoff_min, t.backoff_max),
stable: t.line_stable,
spread: t.redial_spread,
}
}
/// A dial failed: the next wait.
pub fn failed(&mut self) -> Duration {
self.backoff.wait()
}
/// A line that was up for `held` has ended: the wait before the next
/// dial. Only a line that held `line_stable` starts the backoff over.
pub fn ended(&mut self, held: Duration) -> Duration {
if held >= self.stable {
self.backoff.reset();
jitter(self.spread)
} else {
self.backoff.wait()
}
}
/// The network changed: start over.
pub fn reset(&mut self) {
self.backoff.reset();
}
/// The ceiling of the next failed wait (tests).
pub fn ceiling(&self) -> Duration {
self.backoff.ceiling()
}
}
/// Notices a computer that slept (INVARIANT 3).
pub struct WakeDetector {
mono: Instant,
wall: SystemTime,
gap: Duration,
}
impl WakeDetector {
/// Start watching.
pub fn new(gap: Duration) -> Self {
WakeDetector {
mono: Instant::now(),
wall: SystemTime::now(),
gap,
}
}
/// Whether more wall-clock time than monotonic time has passed since
/// the last look (and now look again from here).
pub fn woke(&mut self) -> bool {
self.woke_with(Instant::now(), SystemTime::now())
}
/// [`WakeDetector::woke`] with the two clocks given.
pub fn woke_with(&mut self, mono: Instant, wall: SystemTime) -> bool {
let m = mono.saturating_duration_since(self.mono);
// The wall clock may go backwards (set by hand, or by the network):
// that is not a sleep.
let w = wall.duration_since(self.wall).unwrap_or_default();
self.mono = mono;
self.wall = wall;
w > m + self.gap
}
}
fn is_clock_error(e: &io::Error) -> bool {
use rustls::CertificateError as C;
let mut inner: Option<&(dyn std::error::Error + 'static)> =
e.get_ref().map(|e| e as &(dyn std::error::Error + 'static));
while let Some(err) = inner {
if let Some(rustls::Error::InvalidCertificate(c)) = err.downcast_ref::<rustls::Error>() {
return matches!(
c,
C::Expired
| C::NotValidYet
| C::ExpiredContext { .. }
| C::NotValidYetContext { .. }
);
}
inner = err.source();
}
false
}
/// An i/o error from dialling, as the trouble a person is told.
pub fn trouble_of_io(e: &io::Error) -> Trouble {
use io::ErrorKind as K;
if is_clock_error(e) {
return Trouble::ClockWrong;
}
match e.kind() {
K::NetworkUnreachable | K::HostUnreachable | K::NetworkDown | K::NotFound => {
Trouble::NoInternet
}
// A name that does not resolve comes back as `Uncategorized` or
// `Other` from the resolver; the callers say so with `NotFound`.
_ => Trouble::RelayDown,
}
}
/// What a line's failure means.
pub enum Failure {
/// Nothing wrong with this app: say it and try again.
Trouble(Trouble),
/// The relay refused.
Refused(Refusal),
}
/// A client error, as what to do about it.
pub fn failure_of(e: &ClientError) -> Failure {
match e {
ClientError::Io(e) => Failure::Trouble(trouble_of_io(e)),
ClientError::Timeout | ClientError::Closed => Failure::Trouble(Trouble::RelayDown),
ClientError::Frame(_) => Failure::Trouble(Trouble::Protocol),
ClientError::Refused(r) => Failure::Refused(*r),
}
}
/// A refusal, as the trouble a person is told (a name taken is handled by
/// the caller before this).
pub fn trouble_of_refusal(r: Refusal, claimed: bool) -> Trouble {
match r {
Refusal::Busy => Trouble::RelayBusy,
Refusal::RateLimited => Trouble::RateLimited,
Refusal::Blocked => Trouble::Blocked,
Refusal::BadRequest => Trouble::Protocol,
// A claimed name the relay turns away as unknown is one it lost
// (the relay answers a wrong key and an unknown name alike).
Refusal::BadProof | Refusal::UnknownName | Refusal::Taken => {
if claimed {
Trouble::NameLost
} else {
Trouble::RelayBusy
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_backoff_grows_stays_under_its_ceiling_and_resets() {
let mut b = Backoff::new(Duration::from_secs(1), Duration::from_secs(300));
let mut ceilings = vec![];
for _ in 0..14 {
ceilings.push(b.ceiling());
let w = b.wait();
assert!(w >= Duration::from_secs(1), "{w:?}");
assert!(w <= Duration::from_secs(300), "{w:?}");
}
assert_eq!(ceilings[0], Duration::from_secs(1));
assert_eq!(ceilings[1], Duration::from_secs(2));
assert_eq!(ceilings[3], Duration::from_secs(8));
assert_eq!(*ceilings.last().unwrap(), Duration::from_secs(300));
assert!(ceilings.windows(2).all(|w| w[0] <= w[1]));
b.reset();
assert_eq!(b.ceiling(), Duration::from_secs(1));
// Jitter really varies.
let mut b = Backoff::new(Duration::from_secs(1), Duration::from_secs(1000));
for _ in 0..8 {
b.wait();
}
let spread: std::collections::BTreeSet<u128> = (0..20)
.map(|_| {
let mut c = Backoff::new(Duration::from_secs(1), Duration::from_secs(1000));
c.failures = 8;
c.wait().as_millis()
})
.collect();
assert!(spread.len() > 5);
}
#[test]
fn a_line_that_ends_young_keeps_the_backoff_and_one_that_held_is_spread() {
let t = Timing::default();
let mut r = Redial::new(&t);
// A relay that accepts and then drops, again and again: the waits
// grow to the ceiling and stay there, never the old 1 to 2 s.
let mut last = Duration::ZERO;
for _ in 0..12 {
let c = r.ceiling();
let w = r.ended(Duration::from_secs(2));
assert!(
w >= t.backoff_min && w <= c.max(t.backoff_min),
"{w:?} {c:?}"
);
last = last.max(c);
}
assert_eq!(last, t.backoff_max);
assert_eq!(r.ceiling(), t.backoff_max);
// A line that held 60 s resets it, and the redial is spread over 0
// to 30 s: many apps do not come back in the same second.
let waits: Vec<Duration> = (0..200)
.map(|_| {
let mut r = Redial::new(&t);
r.ended(Duration::from_secs(61))
})
.collect();
assert!(waits.iter().all(|w| *w <= t.redial_spread));
assert!(waits.iter().any(|w| *w > Duration::from_secs(20)));
assert!(waits.iter().any(|w| *w < Duration::from_secs(10)));
r.ended(Duration::from_secs(61));
assert_eq!(r.ceiling(), t.backoff_min, "held: the backoff starts over");
// A line that held 59 s does not.
let mut r = Redial::new(&t);
r.failed();
r.failed();
r.ended(Duration::from_secs(59));
assert!(r.ceiling() > t.backoff_min * 4);
}
#[test]
fn a_wall_clock_jump_with_no_monotonic_jump_is_a_sleep() {
let mut w = WakeDetector::new(Duration::from_secs(30));
let (m0, s0) = (w.mono, w.wall);
// Five seconds of both: not a sleep.
assert!(!w.woke_with(m0 + Duration::from_secs(5), s0 + Duration::from_secs(5)));
// Ten minutes of wall time in five seconds of monotonic time.
let (m1, s1) = (w.mono, w.wall);
assert!(w.woke_with(m1 + Duration::from_secs(5), s1 + Duration::from_secs(605)));
// The clock set backwards is not a sleep.
let (m2, s2) = (w.mono, w.wall);
assert!(!w.woke_with(m2 + Duration::from_secs(5), s2 - Duration::from_secs(3600)));
}
#[test]
fn errors_read_as_the_right_trouble() {
let refused = io::Error::from(io::ErrorKind::ConnectionRefused);
assert_eq!(trouble_of_io(&refused), Trouble::RelayDown);
let down = io::Error::from(io::ErrorKind::NetworkUnreachable);
assert_eq!(trouble_of_io(&down), Trouble::NoInternet);
let expired = io::Error::new(
io::ErrorKind::InvalidData,
rustls::Error::InvalidCertificate(rustls::CertificateError::Expired),
);
assert_eq!(trouble_of_io(&expired), Trouble::ClockWrong);
let early = io::Error::new(
io::ErrorKind::InvalidData,
rustls::Error::InvalidCertificate(rustls::CertificateError::NotValidYet),
);
assert_eq!(trouble_of_io(&early), Trouble::ClockWrong);
let unknown_ca = io::Error::new(
io::ErrorKind::InvalidData,
rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer),
);
assert_eq!(trouble_of_io(&unknown_ca), Trouble::RelayDown);
assert_eq!(
trouble_of_refusal(Refusal::BadProof, true),
Trouble::NameLost
);
assert_eq!(
trouble_of_refusal(Refusal::RateLimited, false),
Trouble::RateLimited
);
assert_eq!(trouble_of_refusal(Refusal::Blocked, true), Trouble::Blocked);
}
}
File diff suppressed because it is too large. Load diff
+127
View File
@@ -0,0 +1,127 @@
//! Files only this account can read: the app's key, its certificate's key,
//! the secret in its address.
//!
//! ```text
//! GOAL: nothing the relay could use to read traffic, and nothing that
//! makes the address guessable, is ever readable by another account
//! on this computer, nor half-written after a crash.
//! SOURCE: WB-link-1 (the app's identity), D-80, D-87; the token files'
//! own rule (ledger-host tokens.rs: 0600, the owner-only DACL on
//! Windows).
//! INVARIANTS:
//! 1. A file is made with mode 0600 (Unix) before a byte of it is
//! written, or made owner-only before a byte is written (Windows,
//! `ledger_store::winsec::set_owner_only`, the helper the token
//! files use), and its folder 0700 or owner-only.
//! 2. A write is a temporary file, synced, then renamed over the old
//! one, and the folder is synced after the rename (Unix; Windows has
//! no such call and the rename is made durable by the file system):
//! a reader sees the old file or the new one, never a part, and a
//! crash right after cannot lose the rename.
//! SCENARIOS:
//! 1. A file written here reads back, has mode 0600, and its folder
//! 0700, on Unix; on Windows the file and its folder are owner-only
//! (`ledger_store::winsec::is_private`).
//! ```
use std::io::{self, Write};
use std::path::Path;
/// Make `dir` (and its parents) private to this account.
pub fn make_dir(dir: &Path) -> io::Result<()> {
std::fs::create_dir_all(dir)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
}
#[cfg(windows)]
ledger_store::winsec::set_owner_only(dir)?;
Ok(())
}
/// Write `bytes` to `path`, privately and atomically (INVARIANTS 1, 2).
pub fn write(path: &Path, bytes: &[u8]) -> io::Result<()> {
let tmp = path.with_extension(format!("tmp{}", std::process::id()));
let _ = std::fs::remove_file(&tmp);
let result = (|| {
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(&tmp)?;
#[cfg(windows)]
ledger_store::winsec::set_owner_only(&tmp)?;
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
std::fs::rename(&tmp, path)?;
sync_folder(path)
})();
if result.is_err() {
let _ = std::fs::remove_file(&tmp);
}
result
}
/// Make the rename durable: the folder that holds the file is synced
/// (INVARIANT 2). Windows cannot open a folder to sync it; there the
/// rename is the file system's own.
fn sync_folder(path: &Path) -> io::Result<()> {
#[cfg(unix)]
{
let dir = match path.parent() {
Some(p) if !p.as_os_str().is_empty() => p,
_ => Path::new("."),
};
std::fs::File::open(dir)?.sync_all()?;
}
#[cfg(not(unix))]
let _ = path;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_private_file_reads_back_and_is_mode_0600() {
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("link");
make_dir(&sub).unwrap();
let f = sub.join("k");
write(&f, b"one").unwrap();
write(&f, b"two").unwrap();
assert_eq!(std::fs::read(&f).unwrap(), b"two");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&f), 0o600);
assert_eq!(mode(&sub), 0o700);
}
// No temporary file is left behind.
assert_eq!(std::fs::read_dir(&sub).unwrap().count(), 1);
}
/// Windows: the file and its folder are owner-only, as the token files
/// are (the helper is `ledger_store::winsec`). Compiled for Windows
/// only; it runs on the Windows jobs of the full test run.
#[cfg(windows)]
#[test]
fn a_private_file_and_its_folder_are_owner_only_on_windows() {
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("link");
make_dir(&sub).unwrap();
let f = sub.join("k");
write(&f, b"one").unwrap();
write(&f, b"two").unwrap();
assert_eq!(std::fs::read(&f).unwrap(), b"two");
assert!(ledger_store::winsec::is_private(&sub).unwrap());
assert!(ledger_store::winsec::is_private(&f).unwrap());
}
}
+248
View File
@@ -0,0 +1,248 @@
//! What the link says about itself, in words a person can use.
//!
//! ```text
//! GOAL: every state the link can be in ends in plain words and in a
//! state that recovers by itself: no spinner forever, no jargon, and
//! never a claim that the local assistants or the window are
//! affected by the network.
//! SOURCE: WB-link-5 (the states the Connect page can show), plan
//! p15-app-and-relay.md 3.3 ("progress in plain words ... the
//! state when the relay cannot be reached, in words, with nothing
//! lost locally").
//! INVARIANTS:
//! 1. A status is data; the words come from [`LinkStatus::words`] and
//! [`Trouble::words`], one place, so a test can read what a person
//! reads.
//! 2. A trouble that ends by itself (no internet, the relay down, a
//! busy relay) says it is trying again; one that needs the person
//! (a wrong clock, the address lost) says what to do.
//! 3. No status holds a key, a secret label or a token: the address in
//! it is only there while the link is on, and a status prints
//! without it.
//! SCENARIOS:
//! 1. A status with no line and no trouble reads "Connecting to the
//! relay"; with a line and no certificate, "Getting a certificate";
//! with both, "Connected".
//! 2. Every trouble has words, and the words of one that mend
//! themselves say so.
//! ```
/// Where the link has got to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
/// Off: no line, no address served.
Off,
/// Getting the address: making the name and having the relay accept it.
GettingAddress,
/// The line to the relay is being made again.
Connecting,
/// The line is up and the certificate is being got.
GettingCertificate,
/// The line is up and the certificate is in place.
Connected,
}
/// Why the link is not further along.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Trouble {
/// The computer cannot reach the internet (no network, or no way to
/// find the relay).
NoInternet,
/// The internet is there; the relay does not answer.
RelayDown,
/// The relay is busy.
RelayBusy,
/// Too many new addresses lately, here or everywhere.
RateLimited,
/// The relay has turned this address off.
Blocked,
/// The relay no longer knows this address.
NameLost,
/// The computer's clock is wrong: the relay's certificate looks
/// expired or not yet valid.
ClockWrong,
/// The relay answered in a way this version does not understand.
Protocol,
/// The files that keep the address could not be read or written.
Files(String),
}
impl Trouble {
/// What a person reads, and what happens next (INVARIANT 2).
pub fn words(&self) -> String {
match self {
Trouble::NoInternet => "This computer can't reach the internet. Your assistants on this computer still work. Web assistants will connect again as soon as the internet is back.".into(),
Trouble::RelayDown => "Wanderbooks can't reach its relay right now. Nothing is lost, and your assistants on this computer still work. It keeps trying.".into(),
Trouble::RelayBusy => "The relay is busy. It keeps trying.".into(),
Trouble::RateLimited => "Many people are setting up web assistants right now, so the relay asked Wanderbooks to wait. It keeps trying, a little later each time.".into(),
Trouble::Blocked => "The relay has turned this address off. Get a new address, or write to us if you think this is a mistake.".into(),
Trouble::NameLost => "The relay doesn't know this address any more. Get a new address to carry on; web assistants will need the new one.".into(),
Trouble::ClockWrong => "This computer's clock looks wrong, so the relay can't be trusted yet. Set the date and time (turn on \"set automatically\"), and Wanderbooks will connect by itself.".into(),
Trouble::Protocol => "The relay speaks a newer version than this Wanderbooks. Update Wanderbooks to connect.".into(),
Trouble::Files(why) => format!("Wanderbooks can't keep its web address on this computer: {why}."),
}
}
/// Whether this ends without the person doing anything.
pub fn mends_itself(&self) -> bool {
matches!(
self,
Trouble::NoInternet
| Trouble::RelayDown
| Trouble::RelayBusy
| Trouble::RateLimited
| Trouble::ClockWrong
)
}
}
/// The link, as it stands.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct LinkStatus {
/// On or off (the person's switch).
pub on: bool,
/// The address, once there is one and while the link is on.
pub address: Option<String>,
/// The relay has accepted the name.
pub claimed: bool,
/// The line is up.
pub line_up: bool,
/// A certificate is in place and valid: when it ends (unix seconds).
pub cert_expires: Option<i64>,
/// Why the line is not up.
pub trouble: Option<Trouble>,
/// Why the certificate is not in place (or not renewed), in words.
pub cert_trouble: Option<String>,
/// Callers served so far.
pub served: u64,
}
impl std::fmt::Debug for LinkStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// The address holds the secret label: it is not printed (3).
f.debug_struct("LinkStatus")
.field("on", &self.on)
.field("has_address", &self.address.is_some())
.field("claimed", &self.claimed)
.field("line_up", &self.line_up)
.field("cert_expires", &self.cert_expires)
.field("trouble", &self.trouble)
.field("cert_trouble", &self.cert_trouble)
.field("served", &self.served)
.finish()
}
}
impl LinkStatus {
/// Where the link has got to.
pub fn step(&self) -> Step {
if !self.on {
Step::Off
} else if !self.line_up && !self.claimed {
Step::GettingAddress
} else if !self.line_up {
Step::Connecting
} else if self.cert_expires.is_none() {
Step::GettingCertificate
} else {
Step::Connected
}
}
/// True when a web assistant can reach the books now.
pub fn reachable(&self) -> bool {
self.step() == Step::Connected
}
/// The one line a person reads about progress.
pub fn words(&self) -> String {
match self.step() {
Step::Off => "Web assistants are off.".into(),
Step::GettingAddress => "Getting an address…".into(),
Step::Connecting => "Connecting to the relay…".into(),
Step::GettingCertificate => "Getting a certificate…".into(),
Step::Connected => "Connected. Web assistants can reach these books.".into(),
}
}
/// What is wrong, in words, if anything: the line's trouble, else the
/// certificate's.
pub fn problem(&self) -> Option<String> {
if let Some(t) = &self.trouble {
return Some(t.words());
}
self.cert_trouble.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_steps_read_in_order() {
let mut s = LinkStatus::default();
assert_eq!(s.step(), Step::Off);
s.on = true;
assert_eq!(s.step(), Step::GettingAddress);
assert_eq!(s.words(), "Getting an address…");
s.claimed = true;
assert_eq!(s.step(), Step::Connecting);
s.line_up = true;
assert_eq!(s.step(), Step::GettingCertificate);
s.cert_expires = Some(1);
assert_eq!(s.step(), Step::Connected);
assert!(s.reachable());
}
#[test]
fn every_trouble_has_words_and_the_mending_ones_say_so() {
let all = [
Trouble::NoInternet,
Trouble::RelayDown,
Trouble::RelayBusy,
Trouble::RateLimited,
Trouble::Blocked,
Trouble::NameLost,
Trouble::ClockWrong,
Trouble::Protocol,
Trouble::Files("the disk is full".into()),
];
for t in all {
let w = t.words();
assert!(w.ends_with('.'), "{w}");
assert!(!w.to_lowercase().contains("mcp"));
if matches!(
t,
Trouble::NoInternet
| Trouble::RelayDown
| Trouble::RelayBusy
| Trouble::RateLimited
) {
assert!(
w.contains("keeps trying") || w.contains("as soon as"),
"{w}"
);
}
}
// The ones that need the person say what to do.
assert!(Trouble::ClockWrong.words().contains("Set the date"));
assert!(Trouble::NameLost.words().contains("Get a new address"));
// Only local assistants are said to keep working, never anything
// about the window.
assert!(
Trouble::NoInternet
.words()
.contains("on this computer still work")
);
}
#[test]
fn a_status_prints_without_its_address() {
let s = LinkStatus {
address: Some("https://secretlabel.a-b-c-d.wanderbooks.link".into()),
..LinkStatus::default()
};
assert!(!format!("{s:?}").contains("secretlabel"));
}
}
+128
View File
@@ -0,0 +1,128 @@
//! Words that come from outside, made safe to show.
//!
//! ```text
//! GOAL: the relay and a certificate authority are strangers: anything
//! they send that reaches the window is short, plain and visibly
//! quoted, so it can neither fill the window, nor hide behind
//! invisible characters, nor pass for the app's own words.
//! SOURCE: WB-link-5 (the states in words); plan p15-app-and-relay.md 5
//! (the relay and the authorities are not trusted).
//! INVARIANTS:
//! 1. The window's words are the app's own, chosen from the kind of
//! failure; outside text is only ever a quoted detail at the end.
//! 2. A detail has no control character and no invisible one (the
//! zero-width, direction-changing and tag characters, the line and
//! paragraph separators), runs of white space are one space, and it
//! is at most [`DETAIL_CHARS`] characters, cut with an ellipsis.
//! 3. Cleaning twice is the same as cleaning once.
//! SCENARIOS:
//! 1. A long text with a newline, a bell and a right-to-left override
//! comes out short, on one line and with none of them.
//! 2. Text that is already clean and short comes out as it went in.
//! ```
/// The most characters of outside text shown (INVARIANT 2).
pub const DETAIL_CHARS: usize = 120;
/// Whether a character is one that must never be shown: a control
/// character, or one that draws nothing or changes how the text around it
/// reads.
fn hidden(c: char) -> bool {
c.is_control()
|| matches!(
c,
'\u{00AD}'
| '\u{034F}'
| '\u{061C}'
| '\u{115F}'
| '\u{1160}'
| '\u{17B4}'
| '\u{17B5}'
| '\u{180B}'..='\u{180F}'
| '\u{200B}'..='\u{200F}'
| '\u{2028}'..='\u{202E}'
| '\u{2060}'..='\u{206F}'
| '\u{3164}'
| '\u{FE00}'..='\u{FE0F}'
| '\u{FEFF}'
| '\u{FFA0}'
| '\u{FFF0}'..='\u{FFFB}'
| '\u{1BCA0}'..='\u{1BCA3}'
| '\u{1D173}'..='\u{1D17A}'
| '\u{E0000}'..='\u{E0FFF}'
)
}
/// `text` with the hidden characters gone, white space made single spaces,
/// and at most `max` characters (INVARIANT 2).
pub fn clean(text: &str, max: usize) -> String {
let mut out = String::new();
let mut count = 0usize;
let mut space = false;
for c in text.chars() {
// A line break or tab is white space, not a character to drop: the
// words either side of it stay apart.
if c.is_whitespace() || matches!(c, '\n' | '\r' | '\t') {
space = !out.is_empty();
continue;
}
if hidden(c) {
continue;
}
if count >= max {
out.push('\u{2026}');
return out;
}
if space {
out.push(' ');
count += 1;
space = false;
}
out.push(c);
count += 1;
}
out
}
/// Outside text as a short quoted detail (INVARIANT 1): empty when there is
/// nothing left to show.
pub fn detail(text: &str) -> String {
let c = clean(text, DETAIL_CHARS);
if c.is_empty() {
String::new()
} else {
format!("\u{201c}{c}\u{201d}")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn long_text_with_tricks_comes_out_short_and_plain() {
let nasty = format!(
"bad\u{7}\nnews\u{202e}gnp.exe\u{200b} {}",
"word ".repeat(2000)
);
let d = detail(&nasty);
assert!(d.chars().count() <= DETAIL_CHARS + 3, "{}", d.len());
assert!(d.starts_with("\u{201c}bad news"), "{d}");
assert!(d.ends_with("\u{2026}\u{201d}"), "{d}");
assert!(
!d.chars()
.any(|c| hidden(c) || (c.is_whitespace() && c != ' '))
);
assert_eq!(clean(&clean(&nasty, 50), 50), clean(&nasty, 50));
}
#[test]
fn short_clean_text_is_unchanged_and_nothing_is_nothing() {
assert_eq!(
detail("too many requests"),
"\u{201c}too many requests\u{201d}"
);
assert_eq!(detail("\u{200b}\u{202e} \n"), "");
assert_eq!(clean(" a b ", 10), "a b");
}
}
+694
View File
@@ -0,0 +1,694 @@
//! The ACME client against an in-process authority: the real
//! `instant-acme` client speaks RFC 8555 to a small authority written
//! here (it checks the proof in the relay's own DNS, signs the CSR it is
//! given with a CA of its own, and offers renewal information). No
//! network beyond 127.0.0.1: the "HTTP" is a function call.
#![allow(missing_docs)]
mod support;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use bytes::Bytes;
use futures::future::BoxFuture;
use http_body_util::BodyExt;
use instant_acme::{BodyWrapper, BytesResponse, Error, HttpClient};
use ledger_link::certs::{DnsProof, Issuer, OrderRequest, inspect, leaf_der};
use ledger_link::{AcmeIssuer, certs};
use rcgen::{CertificateSigningRequestParams, CertifiedIssuer, KeyPair};
use relay::proto::{Authority, Binding};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use support::common::{self, DOMAIN, n};
const BASE: &str = "https://acme.test";
#[derive(Default)]
struct Server {
nonce: u64,
accounts: HashMap<String, String>, // kid -> thumbprint
new_accounts: Vec<serde_json::Value>,
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>,
}
struct Order {
identifier: String,
replaces: Option<String>,
thumbprint: String,
token: String,
authz_valid: bool,
done: bool,
}
struct FakeAcme {
ca: CertifiedIssuer<'static, KeyPair>,
dns: std::net::SocketAddr,
state: Mutex<Server>,
window: (i64, i64),
}
fn jws(body: &[u8]) -> (serde_json::Value, serde_json::Value) {
let v: serde_json::Value = serde_json::from_slice(body).unwrap();
let protected: serde_json::Value =
serde_json::from_slice(&B64.decode(v["protected"].as_str().unwrap()).unwrap()).unwrap();
let payload = match v["payload"].as_str().unwrap() {
"" => serde_json::Value::Null,
p => serde_json::from_slice(&B64.decode(p).unwrap()).unwrap(),
};
(protected, payload)
}
fn thumbprint(jwk: &serde_json::Value) -> String {
let canon = format!(
r#"{{"crv":{},"kty":{},"x":{},"y":{}}}"#,
jwk["crv"], jwk["kty"], jwk["x"], jwk["y"]
);
B64.encode(Sha256::digest(canon.as_bytes()))
}
type Reply = (u16, Vec<(&'static str, String)>, Bytes);
fn json(status: u16, extra: Vec<(&'static str, String)>, v: serde_json::Value) -> Reply {
let mut h = vec![("content-type", "application/json".to_string())];
h.extend(extra);
(status, h, Bytes::from(v.to_string()))
}
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();
s.nonce += 1;
format!("nonce-{}", s.nonce)
};
let with_nonce = |mut r: Reply| {
r.1.push(("replay-nonce", nonce.clone()));
r
};
match (method, path) {
("GET", "/dir") => with_nonce(json(
200,
vec![],
serde_json::json!({
"newNonce": format!("{BASE}/nonce"),
"newAccount": format!("{BASE}/acct"),
"newOrder": format!("{BASE}/order"),
"renewalInfo": format!("{BASE}/ari"),
"meta": {}
}),
)),
(_, "/nonce") => with_nonce((200, vec![], Bytes::new())),
("POST", "/acct") => {
let (protected, payload) = jws(body);
let kid = format!("{BASE}/acct/1");
let mut s = self.state.lock().unwrap();
s.accounts
.insert(kid.clone(), thumbprint(&protected["jwk"]));
s.new_accounts.push(payload);
with_nonce(json(
201,
vec![("location", kid)],
serde_json::json!({"status":"valid"}),
))
}
("POST", "/order") => {
let (protected, payload) = jws(body);
let mut s = self.state.lock().unwrap();
if s.refuse_orders {
return with_nonce(json(
429,
vec![],
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();
let identifier = payload["identifiers"][0]["value"]
.as_str()
.unwrap()
.to_owned();
let replaces = payload["replaces"].as_str().map(str::to_owned);
let id = s.orders.len() + 1;
s.orders.push(Order {
identifier,
replaces: replaces.clone(),
thumbprint: thumb,
token: format!("token-{id}"),
authz_valid: false,
done: false,
});
let mut order = serde_json::json!({
"status":"pending",
"identifiers": payload["identifiers"],
"authorizations":[format!("{BASE}/authz/{id}")],
"finalize": format!("{BASE}/finalize/{id}"),
});
if let Some(r) = replaces {
order["replaces"] = r.into();
}
with_nonce(json(
201,
vec![("location", format!("{BASE}/order/{id}"))],
order,
))
}
("POST", p) if p.starts_with("/authz/") => {
let id: usize = p[7..].parse().unwrap();
let s = self.state.lock().unwrap();
let o = &s.orders[id - 1];
let ident = o.identifier.trim_start_matches("*.");
with_nonce(json(
200,
vec![],
serde_json::json!({
"status": if o.authz_valid {"valid"} else {"pending"},
"identifier": {"type":"dns","value": ident},
"wildcard": o.identifier.starts_with("*."),
"challenges":[{"type":"dns-01","url":format!("{BASE}/chall/{id}"),
"token":o.token,"status":"pending"}]
}),
))
}
("POST", p) if p.starts_with("/chall/") => {
let id: usize = p[7..].parse().unwrap();
let (ident, expected) = {
let s = self.state.lock().unwrap();
let o = &s.orders[id - 1];
let ka = format!("{}.{}", o.token, o.thumbprint);
(
o.identifier.trim_start_matches("*.").to_owned(),
B64.encode(Sha256::digest(ka.as_bytes())),
)
};
let seen = support::dns_txt(self.dns, &format!("_acme-challenge.{ident}.")).await;
let ok = seen.contains(&expected);
self.state.lock().unwrap().orders[id - 1].authz_valid = ok;
with_nonce(json(
200,
vec![],
serde_json::json!({"type":"dns-01","url":format!("{BASE}/chall/{id}"),
"token":format!("token-{id}"),"status": if ok {"valid"} else {"invalid"}}),
))
}
("POST", p) if p.starts_with("/order/") => {
let id: usize = p[7..].parse().unwrap();
let s = self.state.lock().unwrap();
let o = &s.orders[id - 1];
let mut order = serde_json::json!({
"status": if o.done {"valid"} else if o.authz_valid {"ready"} else {"pending"},
"identifiers":[{"type":"dns","value":o.identifier}],
"authorizations":[format!("{BASE}/authz/{id}")],
"finalize": format!("{BASE}/finalize/{id}"),
});
if o.done {
order["certificate"] = format!("{BASE}/cert/{id}").into();
}
if let Some(r) = &o.replaces {
order["replaces"] = r.clone().into();
}
with_nonce(json(200, vec![], order))
}
("POST", p) if p.starts_with("/finalize/") => {
let id: usize = p[10..].parse().unwrap();
let (_, payload) = jws(body);
let csr = B64.decode(payload["csr"].as_str().unwrap()).unwrap();
let der = rustls::pki_types::CertificateSigningRequestDer::from(csr);
let mut params = CertificateSigningRequestParams::from_der(&der).unwrap();
let now = time::OffsetDateTime::now_utc();
params.params.not_before = now - time::Duration::hours(1);
params.params.not_after = now + time::Duration::days(60);
params.params.use_authority_key_identifier_extension = true;
let cert = params.signed_by(&self.ca).unwrap();
let mut s = self.state.lock().unwrap();
s.orders[id - 1].done = true;
s.certs
.insert(id, format!("{}{}", cert.pem(), self.ca.pem()));
let o = &s.orders[id - 1];
with_nonce(json(
200,
vec![],
serde_json::json!({
"status":"valid",
"identifiers":[{"type":"dns","value":o.identifier}],
"authorizations":[format!("{BASE}/authz/{id}")],
"finalize": format!("{BASE}/finalize/{id}"),
"certificate": format!("{BASE}/cert/{id}"),
"replaces": o.replaces,
}),
))
}
("POST", p) if p.starts_with("/cert/") => {
let id: usize = p[6..].parse().unwrap();
let pem = self.state.lock().unwrap().certs[&id].clone();
with_nonce((
200,
vec![("content-type", "application/pem-certificate-chain".into())],
Bytes::from(pem),
))
}
("GET", p) if p.starts_with("/ari/") => {
self.state.lock().unwrap().ari_gets += 1;
let now = time::OffsetDateTime::now_utc();
let at = |secs: i64| {
(now + time::Duration::seconds(secs))
.format(&time::format_description::well_known::Rfc3339)
.unwrap()
};
json(
200,
vec![("retry-after", "3600".into())],
serde_json::json!({"suggestedWindow":{"start":at(self.window.0),"end":at(self.window.1)}}),
)
}
_ => json(
404,
vec![],
serde_json::json!({"type":"urn:ietf:params:acme:error:malformed","detail":"no such path"}),
),
}
}
}
struct Http(Arc<FakeAcme>);
impl HttpClient for Http {
fn request(
&self,
req: http::Request<BodyWrapper<Bytes>>,
) -> Pin<Box<dyn Future<Output = Result<BytesResponse, Error>> + Send>> {
let fake = self.0.clone();
Box::pin(async move {
let (parts, body) = req.into_parts();
let bytes = body
.collect()
.await
.map_err(|e| Error::Other(e.into()))?
.to_bytes();
let path = parts.uri.path().to_owned();
assert_eq!(parts.uri.host(), Some("acme.test"));
let (status, headers, out) = fake.handle(parts.method.as_str(), &path, &bytes).await;
let mut b = http::Response::builder().status(status);
for (k, v) in headers {
b = b.header(k, v);
}
let (parts, _) = b.body(()).unwrap().into_parts();
Ok(BytesResponse {
parts,
body: Box::new(out),
})
})
}
}
struct Proof(relay::client::LineHandle);
impl DnsProof for Proof {
fn publish<'a>(&'a self, value: &'a str) -> BoxFuture<'a, Result<(), String>> {
Box::pin(async move {
let r = self.0.publish_txt(value).await.map_err(|e| e.to_string())?;
if r.ok {
Ok(())
} else {
Err(r.error.unwrap_or_default())
}
})
}
fn clear(&self) -> BoxFuture<'_, ()> {
Box::pin(async move {
let _ = self.0.request(relay::proto::Request::ClearTxt).await;
})
}
}
struct Rig {
env: common::Env,
acme: Arc<FakeAcme>,
issuer: AcmeIssuer,
line: relay::client::Line,
dir: tempfile::TempDir,
name: relay::names::Name,
}
async fn rig(window: (i64, i64)) -> Rig {
let env = common::start(common::quick_limits()).await;
let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
let ca = CertifiedIssuer::self_signed(params, KeyPair::generate().unwrap()).unwrap();
let acme = Arc::new(FakeAcme {
ca,
dns: env.relay.dns_udp_addr(),
state: Mutex::new(Server::default()),
window,
});
let dir = tempfile::tempdir().unwrap();
let a2 = acme.clone();
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();
Rig {
env,
acme,
issuer,
line,
dir,
name,
}
}
fn authority(binding: bool) -> Authority {
Authority {
id: "fake".into(),
directory: format!("{BASE}/dir"),
needs_binding: binding,
usable: true,
binding: binding.then(|| Binding {
kid: "kid-1".into(),
hmac_key: B64.encode(b"0123456789abcdef0123456789abcdef"),
}),
}
}
/// WB-link-4: account, order, the DNS proof through the relay, finalize
/// and download, in the real client; the key is made here; the account is
/// kept privately; the relay's DNS is left clean.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_order_goes_through_account_proof_finalize_and_download() {
let r = rig((60, 120)).await;
let proof = Proof(r.line.handle());
let a = authority(false);
let ident = format!("*.{}.{DOMAIN}", r.name);
let issued = r
.issuer
.issue(OrderRequest {
authority: &a,
identifier: ident.clone(),
replaces: None,
dns: &proof,
})
.await
.unwrap();
let der = leaf_der(&issued.chain_pem).unwrap();
let (nb, na, names) = inspect(&der).unwrap();
assert_eq!(names, std::slice::from_ref(&ident));
assert!(nb < certs::now() && na > certs::now());
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,
&certs::CertTrust::for_tests(r.acme.roots())
)
.is_ok()
);
// The account is kept in a private file, with no contact in it.
let file = r.dir.path().join("acme/fake.json");
assert!(file.exists());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
0o600
);
}
{
let st = r.acme.state.lock().unwrap();
assert_eq!(st.new_accounts.len(), 1);
assert!(
st.new_accounts[0]["contact"]
.as_array()
.is_none_or(|c| c.is_empty())
);
assert_eq!(st.new_accounts[0]["termsOfServiceAgreed"], true);
}
// The relay holds no proof once the order is done.
let left = support::dns_txt(
r.env.relay.dns_udp_addr(),
&format!("_acme-challenge.{}.{DOMAIN}.", r.name),
)
.await;
assert!(left.is_empty(), "{left:?}");
}
/// WB-link-4: a second order reuses the account, a renewal names the
/// certificate it replaces, and the authority's renewal window is read.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_renewal_reuses_the_account_names_what_it_replaces_and_reads_the_window() {
let r = rig((600, 900)).await;
let proof = Proof(r.line.handle());
let a = authority(false);
let ident = format!("*.{}.{DOMAIN}", r.name);
let first = r
.issuer
.issue(OrderRequest {
authority: &a,
identifier: ident.clone(),
replaces: None,
dns: &proof,
})
.await
.unwrap();
let second = r
.issuer
.issue(OrderRequest {
authority: &a,
identifier: ident.clone(),
replaces: leaf_der(&first.chain_pem),
dns: &proof,
})
.await
.unwrap();
assert_ne!(first.chain_pem, second.chain_pem);
assert_ne!(
*first.key_pem, *second.key_pem,
"a fresh key for each certificate"
);
{
let st = r.acme.state.lock().unwrap();
assert_eq!(st.new_accounts.len(), 1, "the account was reused");
assert!(st.orders[0].replaces.is_none());
let id = st.orders[1].replaces.clone().unwrap();
assert!(id.contains('.'), "an ARI certificate id: {id}");
}
let (s, e) = r
.issuer
.renewal_window(&a, &first.chain_pem)
.await
.expect("the authority offers a window");
let now = certs::now();
assert!(
(now + 590..=now + 610).contains(&s) && (now + 890..=now + 910).contains(&e),
"{s} {e} {now}"
);
assert_eq!(r.acme.state.lock().unwrap().ari_gets, 1);
}
/// WB-link-4: an authority that needs an account binding gets the one the
/// relay gave, and without one nothing is asked of it.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_binding_is_sent_when_there_is_one_and_never_invented() {
let r = rig((60, 120)).await;
let proof = Proof(r.line.handle());
let ident = format!("*.{}.{DOMAIN}", r.name);
let mut no = authority(true);
no.binding = None;
no.usable = false;
let err = r
.issuer
.issue(OrderRequest {
authority: &no,
identifier: ident.clone(),
replaces: None,
dns: &proof,
})
.await
.err()
.unwrap();
assert!(err.contains("needs an account binding"), "{err}");
assert!(r.acme.state.lock().unwrap().new_accounts.is_empty());
let yes = authority(true);
r.issuer
.issue(OrderRequest {
authority: &yes,
identifier: ident,
replaces: None,
dns: &proof,
})
.await
.unwrap();
let st = r.acme.state.lock().unwrap();
let eab = &st.new_accounts[0]["externalAccountBinding"];
assert!(eab.is_object(), "{:?}", st.new_accounts);
let protected: serde_json::Value =
serde_json::from_slice(&B64.decode(eab["protected"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(protected["kid"], "kid-1");
}
/// WB-link-4: an authority's refusal comes back in its own words.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_refusal_comes_back_in_the_authoritys_words() {
let r = rig((60, 120)).await;
r.acme.state.lock().unwrap().refuse_orders = true;
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.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}");
}
+787
View File
@@ -0,0 +1,787 @@
//! The link, end to end on localhost: an in-process relay (the relay
//! crate's own), an in-process certificate authority that checks the proof
//! in the relay's DNS, a stand-in for the remote door, and an assistant.
//! Nothing here touches a network beyond 127.0.0.1.
#![allow(missing_docs)]
mod support;
use ledger_link::{CertTrust, Dial, Step, Trouble};
use std::sync::atomic::Ordering;
use std::time::Duration;
use support::*;
fn contains(hay: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
/// WB-link-1 to WB-link-3: claim, prove, line up, certificate; then a web
/// caller's TLS connection through the relay is ended at the app and the
/// door is given the secret, the caller's address and plain HTTP; and
/// what crossed the relay was ciphertext.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_caller_through_the_relay_reaches_the_door_and_the_relay_sees_only_ciphertext() {
let w = world(LIST, |_| {}).await;
assert_eq!(w.link.status().step(), Step::Off);
w.link.turn_on().unwrap();
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
assert!(s.claimed && s.line_up && s.cert_expires.is_some());
assert_eq!(w.env.relay.shared().lines.len(), 1);
assert_eq!(
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
let host = w.host();
// The address is `<secret>.<four words>.<domain>`, the secret 25 or
// more characters of a-z and 0-9.
let parts: Vec<&str> = host.split('.').collect();
assert_eq!(parts.len(), 4, "{host}");
assert!(
parts[0].len() >= 25
&& parts[0]
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
);
assert_eq!(format!("{}.{}", parts[2], parts[3]), DOMAIN);
let reply = w
.assistant(&host)
.await
.expect("TLS completes with the app");
assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
assert!(reply.ends_with(BODY));
// The door was given the secret first, then the caller's address as
// the relay saw it, then plain HTTP with no TLS in it.
let seen = w.door.seen.lock().unwrap().clone();
assert_eq!(seen.len(), 1);
assert!(seen[0].secret_ok);
let from_relay = w.caller_tap.source_ports.lock().unwrap().clone();
assert_eq!(seen[0].caller, from_relay.first().copied());
assert!(seen[0].request.starts_with("GET /ping HTTP/1.1\r\n"));
// What crossed the relay, both ways, is TLS: the request and the reply
// are not in it in the clear.
for crossed in [
w.caller_tap.seen_up(),
w.caller_tap.seen_down(),
w.tap.seen_up(),
w.tap.seen_down(),
] {
assert!(!crossed.is_empty());
assert!(!contains(&crossed, b"GET /ping"));
assert!(!contains(&crossed, BODY.as_bytes()));
assert!(!contains(&crossed, SECRET.as_bytes()));
}
// The caller's own bytes carried the name in the clear (the relay
// routes on it) and the app's certificate only inside TLS 1.3.
assert!(contains(&w.caller_tap.seen_up(), host.as_bytes()));
// Nothing private was sent to the relay: not the line's key, not the
// certificate's key, not the account.
let key = std::fs::read(w.dir.path().join("link/line.key")).unwrap();
let cert: serde_json::Value =
serde_json::from_slice(&std::fs::read(w.dir.path().join("link/cert.json")).unwrap())
.unwrap();
let cert_key = cert["key_pem"].as_str().unwrap().to_owned();
for crossed in [w.tap.seen_up(), w.tap.seen_down(), w.caller_tap.seen_up()] {
assert!(!contains(&crossed, &key));
assert!(!contains(&crossed, cert_key.as_bytes()));
assert!(!contains(&crossed, b"PRIVATE KEY"));
}
}
/// WB-link-1: the key and certificate files are private, and the secret
/// label is in no status text.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_key_the_certificate_and_the_label_are_private() {
let w = world(LIST, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let dir = w.dir.path().join("link");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode =
|p: std::path::PathBuf| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(dir.clone()), 0o700);
for f in ["identity.json", "line.key", "cert.json"] {
assert_eq!(mode(dir.join(f)), 0o600, "{f}");
}
}
let host = w.host();
let label = host.split('.').next().unwrap();
let status = format!("{:?} {}", w.link.status(), w.link.status().words());
assert!(!status.contains(label));
// The label is not the name's, nor guessable from the files' times.
assert!(!host.split('.').nth(1).unwrap().contains(label));
}
/// WB-link-1, 4: off means off (the line ends, the certificate stops being
/// served), the name is kept, on again is the same address, and a restart
/// of the app reuses the stored certificate: one order in all.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn off_closes_the_line_and_the_address_is_the_same_on_again_and_after_a_restart() {
let mut w = world(LIST, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let host = w.host();
assert_eq!(w.fake.orders(), 1);
w.link.turn_off();
let s = w.link.status();
assert_eq!(s.step(), Step::Off);
assert!(s.address.is_none());
// The relay lost the line, and a caller is turned away.
eventually("the relay lost the line", || {
w.env.relay.shared().lines.is_empty()
})
.await;
assert!(w.assistant(&host).await.is_err());
// The name is kept.
assert_eq!(
w.link
.kept_address()
.unwrap()
.trim_start_matches("https://"),
host
);
w.link.turn_on().unwrap();
until(&w.link, "connected again", |s| s.step() == Step::Connected).await;
assert_eq!(w.host(), host);
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
assert_eq!(
w.fake.orders(),
1,
"a certificate already held is not ordered again"
);
// The name was claimed once.
assert_eq!(
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
// The app is closed and started again.
w.link.turn_off();
w.restart(|_| {});
w.link.turn_on().unwrap();
until(&w.link, "connected after a restart", |s| {
s.step() == Step::Connected
})
.await;
assert_eq!(w.host(), host);
assert_eq!(w.fake.orders(), 1, "a restart orders nothing");
assert_eq!(
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
}
/// WB-link-1: a new address replaces the secret label and the old one
/// stops working at once; the name, the key and the certificate stay.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_new_address_stops_the_old_one() {
let w = world(LIST, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let old = w.host();
assert!(w.assistant(&old).await.is_ok());
let new = w.link.new_address().unwrap();
let new = new.trim_start_matches("https://").to_owned();
assert_ne!(new, old);
// Same name, a different label.
assert_eq!(
old.split_once('.').unwrap().1,
new.split_once('.').unwrap().1
);
until(&w.link, "connected again", |s| s.step() == Step::Connected).await;
assert_eq!(w.host(), new);
assert!(
w.assistant(&old).await.is_err(),
"the old address no longer gets a certificate"
);
assert!(w.assistant(&new).await.unwrap().ends_with(BODY));
assert_eq!(w.fake.orders(), 1, "the wildcard certificate still serves");
// The apex and a made-up label get nothing either.
let name = new.split_once('.').unwrap().1.to_owned();
assert!(w.assistant(&name).await.is_err());
assert!(
w.assistant(&format!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.{name}"))
.await
.is_err()
);
}
/// WB-link-2: the relay drops the line, and the app dials again by itself.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_line_comes_back_after_the_relay_drops_it() {
let w = world(LIST, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let before = w.tap.accepted.load(Ordering::SeqCst);
let host = w.host();
w.tap.sever();
eventually("the app dialled again", || {
w.tap.accepted.load(Ordering::SeqCst) > before
})
.await;
until(&w.link, "connected again", |s| {
s.line_up && s.step() == Step::Connected
})
.await;
eventually("the relay has the line", || {
w.env.relay.shared().lines.len() == 1
})
.await;
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
// The name was not claimed again; the proof is the key.
assert_eq!(
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
}
/// WB-link-2: pings keep an idle line. The relay drops a line silent for
/// its idle limit; this one outlives several of them.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn pings_keep_an_idle_line_and_silence_loses_it() {
let mut limits = relay_limits();
limits.line_idle_ms = 700;
let w = world_with(limits, LIST, |t| {
t.ping_every = Duration::from_millis(150);
})
.await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let dialled = w.tap.accepted.load(Ordering::SeqCst);
tokio::time::sleep(Duration::from_millis(2500)).await;
assert_eq!(
w.tap.accepted.load(Ordering::SeqCst),
dialled,
"an idle but pinged line is never dropped and redialled"
);
assert!(w.link.status().line_up);
// Without pings the same relay drops it.
let silent = world_with(
{
let mut l = relay_limits();
l.line_idle_ms = 500;
l
},
LIST,
|t| t.ping_every = Duration::from_secs(3600),
)
.await;
silent.link.turn_on().unwrap();
until(&silent.link, "connected", |s| s.step() == Step::Connected).await;
let first = silent.tap.accepted.load(Ordering::SeqCst);
eventually("the silent line was dropped and dialled again", || {
silent.tap.accepted.load(Ordering::SeqCst) > first
})
.await;
}
fn relay_limits() -> relay::Limits {
support::common::quick_limits()
}
/// WB-link-5: with the relay unreachable the state says so in words and
/// mends itself; the people at the window lose nothing.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_unreachable_relay_says_so_in_words_and_recovers_by_itself() {
let w = world(LIST, |_| {}).await;
w.tap.refuse.store(true, Ordering::SeqCst);
w.link.turn_on().unwrap();
let s = until(&w.link, "a trouble", |s| s.trouble.is_some()).await;
assert_eq!(s.trouble, Some(Trouble::RelayDown));
assert_eq!(s.step(), Step::GettingAddress);
assert!(s.problem().unwrap().contains("keeps trying"));
assert!(s.problem().unwrap().contains("on this computer still work"));
// Several failed dials, spaced by backoff: not a hot loop.
tokio::time::sleep(Duration::from_millis(800)).await;
assert!(w.tap.accepted.load(Ordering::SeqCst) < 25);
// The network comes back.
w.tap.refuse.store(false, Ordering::SeqCst);
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
assert!(s.trouble.is_none() && s.cert_trouble.is_none());
}
/// WB-link-5: no internet at all (the relay's name does not resolve) is
/// said as that.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn no_internet_is_said_as_that() {
let w = world(LIST, |_| {}).await;
// Rebuild the link with a dial that cannot resolve.
let mut cfg = config(&w);
cfg.dial = Dial::Host("relay.nonexistent.invalid".into(), 443);
cfg.dir = w.dir.path().join("link2");
let link = ledger_link::Link::start_on(tokio::runtime::Handle::current(), cfg);
link.turn_on().unwrap();
let s = until(&link, "a trouble", |s| s.trouble.is_some()).await;
assert_eq!(s.trouble, Some(Trouble::NoInternet));
assert!(s.problem().unwrap().contains("can't reach the internet"));
link.turn_off();
}
/// WB-link-5: a relay whose certificate is not valid yet or has ended
/// means this clock is wrong; it is said so, and the state keeps trying.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_wrong_clock_is_said_as_that() {
use rcgen::{CertificateParams, KeyPair};
let w = world(LIST, |_| {}).await;
// A TLS server with a certificate that ended yesterday.
let mut params = CertificateParams::new(vec![RELAY_HOST.to_string()]).unwrap();
let now = time::OffsetDateTime::now_utc();
params.not_before = now - time::Duration::days(30);
params.not_after = now - time::Duration::days(1);
let key = KeyPair::generate().unwrap();
let cert = params.self_signed(&key).unwrap();
let chain = vec![cert.der().clone()];
let pk = rustls::pki_types::PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
key.serialize_der(),
));
let server = relay::tls::server_config(chain, pk).unwrap();
let acceptor = tokio_rustls::TlsAcceptor::from(server);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
loop {
let Ok((s, _)) = listener.accept().await else {
return;
};
let a = acceptor.clone();
tokio::spawn(async move {
let _ = a.accept(s).await;
});
}
});
let mut roots = rustls::RootCertStore::empty();
roots.add(cert.der().clone()).unwrap();
let mut cfg = config(&w);
cfg.dial = Dial::Addr(addr);
cfg.relay_tls = relay::tls::client_config(roots).unwrap();
cfg.dir = w.dir.path().join("link3");
let link = ledger_link::Link::start_on(tokio::runtime::Handle::current(), cfg);
link.turn_on().unwrap();
let s = until(&link, "a trouble", |s| s.trouble.is_some()).await;
assert_eq!(s.trouble, Some(Trouble::ClockWrong));
assert!(s.problem().unwrap().contains("clock"));
assert!(Trouble::ClockWrong.mends_itself());
link.turn_off();
}
/// WB-link-1, 5: a relay that no longer knows the name says so in words,
/// and a new address (a whole new identity) claims a new name and carries on.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_relay_that_lost_the_name_says_so_and_a_new_address_carries_on() {
let mut w = world(LIST, |_| {}).await;
// A second relay, with an empty registry, whose certificate this app
// trusts too.
let fresh = support::common::start_with(
support::common::quick_limits(),
relay::authorities::AuthorityList::from_toml(LIST).unwrap(),
)
.await;
let mut roots = fresh.relay_ca.roots();
roots
.roots
.extend(w.env.relay_ca.roots().roots.iter().cloned());
let mut cfg = config(&w);
cfg.relay_tls = relay::tls::client_config(roots).unwrap();
w.link = ledger_link::Link::start_on(tokio::runtime::Handle::current(), cfg);
w.link.set_door(Some(w.door.target.clone()));
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let old = w.host();
*w.tap.upstream.lock().unwrap() = fresh.router();
w.tap.sever();
let s = until(&w.link, "the name is lost", |s| {
s.trouble == Some(Trouble::NameLost)
})
.await;
assert!(s.problem().unwrap().contains("Get a new address"));
let new = w.link.new_address().unwrap();
assert_ne!(new.trim_start_matches("https://"), old);
until(&w.link, "claimed a new name", |s| s.claimed && s.line_up).await;
assert_eq!(
fresh.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
}
/// WB-link-4: the authorities are the relay's list, in its order; one
/// marked not usable is skipped; the first failing falls to the second;
/// the certificate is kept 0600 and reused; and the wildcard is for this
/// name and none other.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_first_authority_fails_and_the_second_issues() {
let w = world(LIST, |_| {}).await;
w.fake.state.lock().unwrap().fail.insert("first".into());
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let orders: Vec<String> = w
.fake
.state
.lock()
.unwrap()
.orders
.iter()
.map(|o| o.authority.clone())
.collect();
assert_eq!(orders, ["first", "second"]);
let host = w.host();
let name = host.split_once('.').unwrap().1;
let id = w.fake.state.lock().unwrap().orders[1].identifier.clone();
assert_eq!(id, format!("*.{name}"));
// The relay's DNS holds no proof once the order is done.
let proofs = dns_txt(
w.env.relay.dns_udp_addr(),
&format!("_acme-challenge.{name}."),
)
.await;
assert!(proofs.is_empty(), "{proofs:?}");
}
/// WB-link-4: an authority that needs a binding the relay has none for is
/// listed and not usable: it is skipped, and the next is used.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_authority_that_is_not_usable_is_skipped() {
const LIST_BINDING: &str = r#"
[[authority]]
id = "needs-binding"
directory = "https://fake.example/b"
caa_domain = "b.example"
needs_binding = true
[[authority]]
id = "plain"
directory = "https://fake.example/p"
caa_domain = "p.example"
"#;
let w = world(LIST_BINDING, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let orders: Vec<String> = w
.fake
.state
.lock()
.unwrap()
.orders
.iter()
.map(|o| o.authority.clone())
.collect();
assert_eq!(
orders,
["plain"],
"the one that is not usable was never asked"
);
}
/// WB-link-4: every authority failing is a state in words that is retried
/// and mends itself; the line stays up meanwhile.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn every_authority_failing_is_said_and_retried_until_one_works() {
let w = world(LIST, |_| {}).await;
{
let mut st = w.fake.state.lock().unwrap();
st.fail.insert("first".into());
st.fail.insert("second".into());
}
w.link.turn_on().unwrap();
let s = until(&w.link, "a certificate trouble", |s| {
s.cert_trouble.is_some()
})
.await;
assert_eq!(s.step(), Step::GettingCertificate);
assert!(s.line_up);
let words = s.problem().unwrap();
assert!(
words.contains("could not get a certificate") && words.contains("keeps trying"),
"{words}"
);
// Retried, with a wait.
eventually("several tries", || w.fake.orders() >= 4).await;
// The authority comes back.
w.fake.state.lock().unwrap().fail.clear();
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
assert!(s.cert_trouble.is_none());
}
/// WB-link-4: renewal ahead of expiry, at the time the authority's
/// renewal information suggests, naming the certificate it replaces; the
/// certificate that serves keeps serving while a renewal fails.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_certificate_is_renewed_at_the_authoritys_suggested_time() {
let w = world(LIST, |_| {}).await;
w.fake.state.lock().unwrap().window = Some((1, 2));
w.link.turn_on().unwrap();
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let first_end = s.cert_expires.unwrap();
assert_eq!(w.fake.orders(), 1);
eventually("a renewal", || w.fake.orders() >= 2).await;
{
let st = w.fake.state.lock().unwrap();
assert!(!st.orders[0].replaces);
assert!(
st.orders[1].replaces,
"a renewal names the certificate it replaces"
);
assert_eq!(st.orders[0].authority, st.orders[1].authority);
}
until(&w.link, "the new certificate serves", |s| {
s.cert_expires.is_some_and(|e| e >= first_end) && s.cert_trouble.is_none()
})
.await;
assert!(w.assistant(&w.host()).await.unwrap().ends_with(BODY));
// A renewal that fails leaves the one in use serving.
{
let mut st = w.fake.state.lock().unwrap();
st.fail.insert("first".into());
st.fail.insert("second".into());
st.window = Some((1, 2));
}
let n = w.fake.orders();
eventually("a failed renewal try", || w.fake.orders() > n + 1).await;
let s = until(&w.link, "the renewal trouble", |s| s.cert_trouble.is_some()).await;
assert!(s.cert_expires.is_some());
assert!(
s.cert_trouble
.unwrap()
.contains("the one in use still works")
);
assert!(w.assistant(&w.host()).await.unwrap().ends_with(BODY));
}
/// WB-link-4: with no renewal information a certificate is renewed two
/// thirds of the way through its life.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn without_renewal_information_it_renews_two_thirds_through() {
let w = world(LIST, |_| {}).await;
// The authority's certificates are good for an hour from now and began
// an hour ago: two thirds of two hours is 20 minutes from now.
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let cert: serde_json::Value =
serde_json::from_slice(&std::fs::read(w.dir.path().join("link/cert.json")).unwrap())
.unwrap();
let (b, e, r) = (
cert["not_before"].as_i64().unwrap(),
cert["not_after"].as_i64().unwrap(),
cert["renew_at"].as_i64().unwrap(),
);
assert_eq!(r, b + (e - b) * 2 / 3);
assert_eq!(w.fake.orders(), 1);
}
/// WB-link-3: a caller that never finishes its handshake is dropped, and
/// a connection while the door is gone is closed, not held.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_stalled_handshake_is_dropped_and_no_door_means_no_service() {
let w = world(LIST, |t| t.handshake = Duration::from_millis(500)).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let host = w.host();
// No door: the caller's connection ends.
w.link.set_door(None);
let r = w.assistant(&host).await;
assert!(r.is_err() || r.unwrap().is_empty());
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()));
}
+551
View File
@@ -0,0 +1,551 @@
//! Shared setup for the link's tests: an in-process relay (the relay
//! crate's own test setup), an in-process certificate authority, a stand-in
//! for the remote door, a tap between the app and the relay, and an
//! assistant. Everything stays on 127.0.0.1.
#![allow(dead_code, missing_docs)]
#[path = "../../../relay/tests/common/mod.rs"]
pub mod common;
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::{CertTrust, Dial, DoorTarget, Link, LinkConfig, LinkStatus, Timing};
use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose};
use relay::proto::{Authority, Caller};
use rustls::RootCertStore;
use rustls::pki_types::ServerName;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::watch;
use tokio_rustls::TlsConnector;
use zeroize::Zeroizing;
pub use common::{DOMAIN, RELAY_HOST};
/// The words the fake authority speaks through.
pub struct Order {
pub authority: String,
pub identifier: String,
pub replaces: bool,
pub had_binding: bool,
}
pub struct FakeState {
pub orders: Vec<Order>,
/// Authority ids that refuse.
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)>,
}
/// An in-process certificate authority: it asks the relay's own DNS for
/// the proof, as a real one would, and signs with a CA of its own.
pub struct Fake {
ca: CertifiedIssuer<'static, KeyPair>,
dns: SocketAddr,
pub state: Mutex<FakeState>,
}
pub fn txt_at(m: &Message) -> Vec<String> {
m.answers
.iter()
.filter_map(|r| match &r.data {
RData::TXT(t) => Some(t.to_string()),
_ => None,
})
.collect()
}
pub async fn dns_txt(addr: SocketAddr, name: &str) -> Vec<String> {
let mut q = Message::query();
q.queries.push(Query::query(
DnsName::from_ascii(name).unwrap(),
RecordType::TXT,
));
let sock = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
sock.send_to(&q.to_vec().unwrap(), addr).await.unwrap();
let mut buf = [0u8; 2048];
let (len, _) = tokio::time::timeout(Duration::from_secs(5), sock.recv_from(&mut buf))
.await
.expect("an answer")
.unwrap();
txt_at(&Message::from_vec(&buf[..len]).unwrap())
}
impl Fake {
pub fn new(dns: SocketAddr) -> Arc<Self> {
let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
params
.distinguished_name
.push(rcgen::DnType::CommonName, "fake authority");
let ca = CertifiedIssuer::self_signed(params, KeyPair::generate().unwrap()).unwrap();
Arc::new(Fake {
ca,
dns,
state: Mutex::new(FakeState {
orders: vec![],
fail: Default::default(),
lifetime: 3600,
say: None,
window: None,
}),
})
}
pub fn roots(&self) -> RootCertStore {
let mut roots = RootCertStore::empty();
roots.add(self.ca.der().clone()).unwrap();
roots
}
pub fn orders(&self) -> usize {
self.state.lock().unwrap().orders.len()
}
}
fn proof_value() -> String {
// 43 base64url characters, as a DNS-01 value is.
let alphabet = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let r = relay::proto::random32();
(0..43)
.map(|i| char::from(alphabet[usize::from(r[i % 32] % 64)]))
.collect()
}
impl Issuer for Fake {
fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result<Issued, String>> {
Box::pin(async move {
let (fails, lifetime, say) = {
let mut st = self.state.lock().unwrap();
st.orders.push(Order {
authority: req.authority.id.clone(),
identifier: req.identifier.clone(),
replaces: req.replaces.is_some(),
had_binding: req.authority.binding.is_some(),
});
(
st.fail.contains(&req.authority.id),
st.lifetime,
st.say.clone(),
)
};
if fails {
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.
let value = proof_value();
req.dns.publish(&value).await?;
let name = req.identifier.trim_start_matches("*.");
let seen = dns_txt(self.dns, &format!("_acme-challenge.{name}.")).await;
req.dns.clear().await;
if !seen.contains(&value) {
return Err("the proof of the name was not in the DNS".into());
}
let mut params = CertificateParams::new(vec![req.identifier.clone()]).unwrap();
let now = time::OffsetDateTime::now_utc();
params.not_before = now - time::Duration::hours(1);
params.not_after = now + time::Duration::seconds(lifetime);
let key = KeyPair::generate().unwrap();
let cert = params.signed_by(&key, &self.ca).unwrap();
Ok(Issued {
chain_pem: format!("{}{}", cert.pem(), self.ca.pem()),
key_pem: Zeroizing::new(key.serialize_pem()),
})
})
}
fn renewal_window<'a>(
&'a self,
_authority: &'a Authority,
_chain_pem: &'a str,
) -> BoxFuture<'a, Option<(i64, i64)>> {
Box::pin(async move {
let w = self.state.lock().unwrap().window;
let now = ledger_link::certs::now();
w.map(|(a, b)| (now + a, now + b))
})
}
}
/// What crosses between two ends, recorded, and cut on request.
pub struct Tap {
pub addr: SocketAddr,
pub upstream: Arc<Mutex<SocketAddr>>,
pub accepted: Arc<AtomicUsize>,
pub refuse: Arc<AtomicBool>,
pub to_upstream: Arc<Mutex<Vec<u8>>>,
pub from_upstream: Arc<Mutex<Vec<u8>>>,
cut: watch::Sender<u64>,
/// The address the relay sees connections from.
pub source_ports: Arc<Mutex<Vec<SocketAddr>>>,
}
impl Tap {
pub async fn new(upstream: SocketAddr) -> Tap {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let tap = Tap {
addr,
upstream: Arc::new(Mutex::new(upstream)),
accepted: Arc::new(AtomicUsize::new(0)),
refuse: Arc::new(AtomicBool::new(false)),
to_upstream: Arc::new(Mutex::new(vec![])),
from_upstream: Arc::new(Mutex::new(vec![])),
cut: watch::channel(0).0,
source_ports: Arc::new(Mutex::new(vec![])),
};
let (up, accepted, refuse, to, from, cut, ports) = (
tap.upstream.clone(),
tap.accepted.clone(),
tap.refuse.clone(),
tap.to_upstream.clone(),
tap.from_upstream.clone(),
tap.cut.clone(),
tap.source_ports.clone(),
);
tokio::spawn(async move {
loop {
let Ok((client, _)) = listener.accept().await else {
return;
};
accepted.fetch_add(1, Ordering::SeqCst);
if refuse.load(Ordering::SeqCst) {
continue; // dropped at once
}
let target = *up.lock().unwrap();
let (to, from, ports) = (to.clone(), from.clone(), ports.clone());
let mut watcher = cut.subscribe();
tokio::spawn(async move {
let Ok(server) = TcpStream::connect(target).await else {
return;
};
if let Ok(local) = server.local_addr() {
ports.lock().unwrap().push(local);
}
let (mut cr, mut cw) = client.into_split();
let (mut sr, mut sw) = server.into_split();
let a = async {
let mut buf = [0u8; 8192];
loop {
let n = cr.read(&mut buf).await.unwrap_or(0);
if n == 0 {
break;
}
to.lock().unwrap().extend_from_slice(&buf[..n]);
if sw.write_all(&buf[..n]).await.is_err() {
break;
}
}
let _ = sw.shutdown().await;
};
let b = async {
let mut buf = [0u8; 8192];
loop {
let n = sr.read(&mut buf).await.unwrap_or(0);
if n == 0 {
break;
}
from.lock().unwrap().extend_from_slice(&buf[..n]);
if cw.write_all(&buf[..n]).await.is_err() {
break;
}
}
let _ = cw.shutdown().await;
};
tokio::select! {
() = async { tokio::join!(a, b); } => {}
_ = watcher.changed() => {}
}
});
}
});
tap
}
/// Cut every connection now (the network dropped them).
pub fn sever(&self) {
self.cut.send_modify(|n| *n += 1);
}
pub fn seen_up(&self) -> Vec<u8> {
self.to_upstream.lock().unwrap().clone()
}
pub fn seen_down(&self) -> Vec<u8> {
self.from_upstream.lock().unwrap().clone()
}
}
/// What the stand-in door was given.
#[derive(Clone, Debug)]
pub struct Seen {
pub secret_ok: bool,
pub caller: Option<SocketAddr>,
pub request: String,
}
/// A stand-in for the remote door: it wants the secret, then the PROXY
/// header, then plain HTTP, and answers a fixed body.
pub struct Door {
pub target: DoorTarget,
pub seen: Arc<Mutex<Vec<Seen>>>,
}
pub const SECRET: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
pub const BODY: &str = "the door says hello";
impl Door {
pub async fn new() -> Door {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let seen = Arc::new(Mutex::new(vec![]));
let record = seen.clone();
tokio::spawn(async move {
loop {
let Ok((mut s, _)) = listener.accept().await else {
return;
};
let record = record.clone();
tokio::spawn(async move {
let mut given = [0u8; 64];
if s.read_exact(&mut given).await.is_err() {
return;
}
let secret_ok = given.as_slice() == SECRET.as_bytes();
let caller = Caller::read(&mut s).await.ok().map(|c| c.source);
let mut req = Vec::new();
let mut buf = [0u8; 1024];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
let n = s.read(&mut buf).await.unwrap_or(0);
if n == 0 {
break;
}
req.extend_from_slice(&buf[..n]);
}
record.lock().unwrap().push(Seen {
secret_ok,
caller,
request: String::from_utf8_lossy(&req).into_owned(),
});
if secret_ok {
let _ = s
.write_all(
format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{BODY}",
BODY.len()
)
.as_bytes(),
)
.await;
}
});
}
});
Door {
target: DoorTarget::new(addr, SECRET).unwrap(),
seen,
}
}
}
/// The timings the tests run at.
pub fn fast() -> Timing {
Timing {
ping_every: Duration::from_millis(200),
ping_timeout: Duration::from_secs(2),
tick: Duration::from_millis(100),
connect_timeout: Duration::from_secs(3),
backoff_min: Duration::from_millis(50),
backoff_max: Duration::from_millis(400),
handshake: Duration::from_secs(3),
cert_retry_min: Duration::from_millis(100),
cert_retry_max: Duration::from_millis(500),
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),
}
}
pub const LIST: &str = r#"
[[authority]]
id = "first"
directory = "https://fake.example/first"
caa_domain = "first.example"
[[authority]]
id = "second"
directory = "https://fake.example/second"
caa_domain = "second.example"
"#;
pub struct World {
pub env: common::Env,
pub tap: Tap,
pub caller_tap: Tap,
pub door: Door,
pub fake: Arc<Fake>,
pub dir: tempfile::TempDir,
pub link: Link,
}
pub fn config(w: &World) -> LinkConfig {
LinkConfig {
dir: w.dir.path().join("link"),
domain: DOMAIN.into(),
relay_host: RELAY_HOST.into(),
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(),
}
}
pub async fn world(list: &str, timing: impl FnOnce(&mut Timing)) -> World {
world_with(common::quick_limits(), list, timing).await
}
pub async fn world_with(
limits: relay::Limits,
list: &str,
timing: impl FnOnce(&mut Timing),
) -> World {
let authorities = relay::authorities::AuthorityList::from_toml(list).unwrap();
let env = common::start_with(limits, authorities).await;
let tap = Tap::new(env.router()).await;
let caller_tap = Tap::new(env.router()).await;
let door = Door::new().await;
let fake = Fake::new(env.relay.dns_udp_addr());
let dir = tempfile::tempdir().unwrap();
let mut cfg = LinkConfig {
dir: dir.path().join("link"),
domain: DOMAIN.into(),
relay_host: RELAY_HOST.into(),
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);
let link = Link::start_on(tokio::runtime::Handle::current(), cfg);
link.set_door(Some(door.target.clone()));
World {
env,
tap,
caller_tap,
door,
fake,
dir,
link,
}
}
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);
timing(&mut cfg.timing);
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()));
}
/// An assistant: TLS to `host` through the tap, one GET, the whole
/// reply.
pub async fn assistant(&self, host: &str) -> std::io::Result<String> {
let tcp = TcpStream::connect(self.tap_for_callers()).await?;
let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(self.fake.roots())
.with_no_client_auth();
let mut tls = tokio::time::timeout(
Duration::from_secs(5),
TlsConnector::from(Arc::new(cfg))
.connect(ServerName::try_from(host.to_owned()).unwrap(), tcp),
)
.await
.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::TimedOut, "the handshake never finished")
})??;
tls.write_all(
format!("GET /ping HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n").as_bytes(),
)
.await?;
let mut out = Vec::new();
let _ = tokio::time::timeout(Duration::from_secs(10), tls.read_to_end(&mut out)).await;
Ok(String::from_utf8_lossy(&out).into_owned())
}
fn tap_for_callers(&self) -> SocketAddr {
// Callers reach the relay's router the way the internet does: not
// through the app's tap, but through one of their own, which is
// also where what crosses is recorded.
self.caller_tap.addr
}
pub fn host(&self) -> String {
self.link
.status()
.address
.or_else(|| self.link.kept_address())
.unwrap()
.trim_start_matches("https://")
.to_owned()
}
}
pub async fn until(link: &Link, what: &str, mut ok: impl FnMut(&LinkStatus) -> bool) -> LinkStatus {
for _ in 0..400 {
let s = link.status();
if ok(&s) {
return s;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!("never: {what}; last status {:?}", link.status());
}
pub async fn eventually(what: &str, mut ok: impl FnMut() -> bool) {
for _ in 0..400 {
if ok() {
return;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!("never: {what}");
}