feat(relay): the relay service for wanderbooks.link (P15 unit B2)

A new crate, crates/relay (lib `relay`, binary wanderbooks-relay), with no
ledger-* dependency. Routes an assistant's TLS connection by the server name
in its ClientHello down the line an app holds open, forwarding encrypted
bytes only; the line is yamux over TLS 1.3 on 443, the app proving its key
with an Ed25519 signature bound to the session's TLS exporter and a fresh
nonce. One durable table (SQLite: name, key, created, blocked), four-word
names from a curated list of 1454 words (42.0 bits), a PROXY v2 header with
the caller's address, an authoritative DNS server that publishes an app's
ACME DNS-01 value for its own name only, and a list of certificate
authorities served as data. Every table, queue, buffer and time is bounded.

New dependencies, each permissive and passing cargo deny: yamux 0.14
(Apache-2.0 OR MIT; the multiplexer), hickory-proto 0.26 (MIT OR Apache-2.0;
DNS wire format, std only), rusqlite (already in the tree), rustls and
tokio-rustls (already in the tree, ring provider), ring (Ed25519, already in
the tree); dev only: rcgen 0.14 (MIT OR Apache-2.0), proptest, tempfile.
Added to the kernel-only lint list (no Decimal in the crate).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 09:33:03 -07:00
1 parent 5682258f8d
commit 31f706bd7e
22 files changed
+7010 -6

No files matched your search

+342
View File
@@ -0,0 +1,342 @@
//! The certificate authorities: a list the relay serves, not code.
//!
//! Every authority an app may use speaks the same protocol (ACME,
//! RFC 8555). The app's certificate code knows the protocol and nothing
//! about any one authority; at each issuance it asks the relay for the
//! list to try, in order. Swapping Let's Encrypt for Google Trust Services
//! or ZeroSSL, or adding one, is an edit to the list the relay reads, with
//! no release of the app.
//!
//! ```toml
//! [[authority]]
//! id = "letsencrypt"
//! directory = "https://acme-v02.api.letsencrypt.org/directory"
//!
//! [[authority]]
//! id = "zerossl"
//! directory = "https://acme.zerossl.com/v2/DV90"
//! needs_binding = true
//! binding_kid = "…"
//! binding_hmac_key = "…"
//! ```
//!
//! ```text
//! GOAL: the authority an app asks is chosen by the relay's list at the
//! moment of the request, in the list's order, so an operator can
//! change authorities without a release of the app.
//! SOURCE: WB-relay-5 (the list of authorities), D-87, RFC 8555 section
//! 7.3.4 (external account binding).
//! INVARIANTS:
//! 1. The list is served in the order written, with each authority's
//! directory address and whether it needs a binding.
//! 2. An authority that needs a binding is served only with one: a
//! list that names one without a credential is refused when read,
//! and the previous list stays in force.
//! 3. A bad file never replaces a good list.
//! 4. The list is bounded: at most 16 authorities.
//! SCENARIOS:
//! 1. Two authorities, the first plain and the second with a binding,
//! are served in that order, the second with its credential.
//! 2. The file is edited to put the second first: the next read serves
//! that order.
//! 3. The file is edited to garbage: the old list is still served.
//! ```
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::time::SystemTime;
use serde::Deserialize;
use crate::names::Name;
use crate::proto::{Authority, Binding};
const MAX_AUTHORITIES: usize = 16;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct File {
#[serde(default)]
authority: Vec<Entry>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct Entry {
id: String,
directory: String,
#[serde(default)]
needs_binding: bool,
binding_kid: Option<String>,
binding_hmac_key: Option<String>,
}
/// Why a list was refused.
#[derive(Debug, thiserror::Error)]
pub enum ListError {
/// The file is not valid TOML of this shape.
#[error("authority list: {0}")]
Toml(#[from] toml::de::Error),
/// The file could not be read.
#[error("authority list: {0}")]
Io(#[from] std::io::Error),
/// The list is empty, too long, or an entry is wrong.
#[error("authority list: {0}")]
Invalid(String),
}
/// Where an app's binding credential comes from. The static list gives
/// every app the credential written in the file; a deployment that
/// obtains one per app from the authority's API implements this instead.
pub trait BindingSource: Send + Sync {
/// The credential for this app at this authority, if one is needed.
fn binding_for(&self, authority_id: &str, name: &Name) -> Option<Binding>;
}
#[derive(Debug, Clone)]
struct Listed {
id: String,
directory: String,
needs_binding: bool,
binding: Option<Binding>,
}
/// The list the relay serves.
pub struct AuthorityList {
current: RwLock<Arc<Vec<Listed>>>,
source: Option<PathBuf>,
seen: std::sync::Mutex<Option<SystemTime>>,
bindings: Option<Arc<dyn BindingSource>>,
}
fn is_loopback_http(url: &str) -> bool {
["http://127.0.0.1", "http://localhost", "http://[::1]"]
.iter()
.any(|p| url.starts_with(p))
}
fn parse(text: &str) -> Result<Vec<Listed>, ListError> {
let file: File = toml::from_str(text)?;
if file.authority.is_empty() || file.authority.len() > MAX_AUTHORITIES {
return Err(ListError::Invalid(format!(
"1 to {MAX_AUTHORITIES} authorities, not {}",
file.authority.len()
)));
}
let mut out: Vec<Listed> = Vec::new();
for e in file.authority {
if e.id.is_empty() || e.id.len() > 64 || out.iter().any(|o| o.id == e.id) {
return Err(ListError::Invalid(format!("authority id {:?}", e.id)));
}
if e.directory.len() > 512
|| !(e.directory.starts_with("https://") || is_loopback_http(&e.directory))
{
return Err(ListError::Invalid(format!(
"{}: the directory must be https",
e.id
)));
}
let binding = match (e.binding_kid, e.binding_hmac_key) {
(Some(kid), Some(hmac_key)) => Some(Binding { kid, hmac_key }),
(None, None) => None,
_ => {
return Err(ListError::Invalid(format!(
"{}: a binding needs both its kid and its key",
e.id
)));
}
};
if e.needs_binding && binding.is_none() {
return Err(ListError::Invalid(format!(
"{} needs a binding and has none",
e.id
)));
}
out.push(Listed {
id: e.id,
directory: e.directory,
needs_binding: e.needs_binding,
binding,
});
}
Ok(out)
}
impl AuthorityList {
/// A list from TOML text.
pub fn from_toml(text: &str) -> Result<Self, ListError> {
Ok(AuthorityList {
current: RwLock::new(Arc::new(parse(text)?)),
source: None,
seen: std::sync::Mutex::new(None),
bindings: None,
})
}
/// A list read from a file, and read again by [`AuthorityList::reload`].
pub fn from_file(path: PathBuf) -> Result<Self, ListError> {
let text = std::fs::read_to_string(&path)?;
let list = parse(&text)?;
let seen = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
Ok(AuthorityList {
current: RwLock::new(Arc::new(list)),
source: Some(path),
seen: std::sync::Mutex::new(seen),
bindings: None,
})
}
/// An empty list: no authority is offered until one is configured.
pub fn empty() -> Self {
AuthorityList {
current: RwLock::new(Arc::new(Vec::new())),
source: None,
seen: std::sync::Mutex::new(None),
bindings: None,
}
}
/// Take bindings from `source` instead of the file's.
pub fn with_binding_source(mut self, source: Arc<dyn BindingSource>) -> Self {
self.bindings = Some(source);
self
}
/// Read the file again if it changed. A bad file changes nothing.
/// Returns whether the list was replaced.
pub fn reload(&self) -> Result<bool, ListError> {
let Some(path) = &self.source else {
return Ok(false);
};
let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok();
{
let mut seen = self.seen.lock().unwrap_or_else(|p| p.into_inner());
if *seen == modified && modified.is_some() {
return Ok(false);
}
*seen = modified;
}
let list = parse(&std::fs::read_to_string(path)?)?;
*self.current.write().unwrap_or_else(|p| p.into_inner()) = Arc::new(list);
Ok(true)
}
/// The list for this app, in order.
pub fn for_app(&self, name: &Name) -> Vec<Authority> {
let list = Arc::clone(&self.current.read().unwrap_or_else(|p| p.into_inner()));
list.iter()
.map(|a| Authority {
id: a.id.clone(),
directory: a.directory.clone(),
needs_binding: a.needs_binding,
binding: if a.needs_binding {
self.bindings
.as_ref()
.and_then(|b| b.binding_for(&a.id, name))
.or_else(|| a.binding.clone())
} else {
None
},
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
const TWO: &str = r#"
[[authority]]
id = "letsencrypt"
directory = "https://acme-v02.api.letsencrypt.org/directory"
[[authority]]
id = "zerossl"
directory = "https://acme.zerossl.com/v2/DV90"
needs_binding = true
binding_kid = "kid-1"
binding_hmac_key = "a2V5"
"#;
fn name() -> Name {
Name::parse("ledger-accrual-tally-mint").unwrap()
}
#[test]
fn the_list_is_served_in_order_with_its_binding() {
let l = AuthorityList::from_toml(TWO).unwrap();
let got = l.for_app(&name());
assert_eq!(got.len(), 2);
assert_eq!(got[0].id, "letsencrypt");
assert!(!got[0].needs_binding && got[0].binding.is_none());
assert_eq!(got[1].id, "zerossl");
assert!(got[1].needs_binding);
assert_eq!(
got[1].binding,
Some(Binding {
kid: "kid-1".into(),
hmac_key: "a2V5".into()
})
);
}
#[test]
fn a_bad_list_is_refused() {
for bad in [
"",
"[[authority]]\nid='a'\ndirectory='http://example.com/dir'\n",
"[[authority]]\nid='a'\ndirectory='https://x/d'\nneeds_binding=true\n",
"[[authority]]\nid='a'\ndirectory='https://x/d'\nbinding_kid='k'\n",
"[[authority]]\nid='a'\ndirectory='https://x/d'\n[[authority]]\nid='a'\ndirectory='https://y/d'\n",
"[[authority]]\nid='a'\ndirectory='https://x/d'\nsurprise=1\n",
] {
assert!(AuthorityList::from_toml(bad).is_err(), "{bad:?}");
}
let many: String = (0..17)
.map(|i| format!("[[authority]]\nid='a{i}'\ndirectory='https://x/d'\n"))
.collect();
assert!(AuthorityList::from_toml(&many).is_err());
}
#[test]
fn an_edit_changes_what_is_served_and_a_bad_edit_does_not() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorities.toml");
std::fs::write(&path, TWO).unwrap();
let l = AuthorityList::from_file(path.clone()).unwrap();
assert_eq!(l.for_app(&name())[0].id, "letsencrypt");
let flipped = "[[authority]]\nid='zerossl'\ndirectory='https://acme.zerossl.com/v2/DV90'\nneeds_binding=true\nbinding_kid='k'\nbinding_hmac_key='a2V5'\n[[authority]]\nid='letsencrypt'\ndirectory='https://acme-v02.api.letsencrypt.org/directory'\n";
std::fs::write(&path, flipped).unwrap();
// Same-second edits may not move the mtime: force it to look new.
*l.seen.lock().unwrap() = None;
assert!(l.reload().unwrap());
assert_eq!(l.for_app(&name())[0].id, "zerossl");
std::fs::write(&path, "not toml {{{").unwrap();
*l.seen.lock().unwrap() = None;
assert!(l.reload().is_err());
assert_eq!(l.for_app(&name())[0].id, "zerossl", "the good list stands");
}
#[test]
fn a_binding_source_overrides_the_file() {
struct PerApp;
impl BindingSource for PerApp {
fn binding_for(&self, id: &str, name: &Name) -> Option<Binding> {
Some(Binding {
kid: format!("{id}-{name}"),
hmac_key: "x".into(),
})
}
}
let l = AuthorityList::from_toml(TWO)
.unwrap()
.with_binding_source(Arc::new(PerApp));
let got = l.for_app(&name());
assert_eq!(
got[1].binding.as_ref().unwrap().kid,
"zerossl-ledger-accrual-tally-mint"
);
assert!(got[0].binding.is_none());
}
}
+290
View File
@@ -0,0 +1,290 @@
//! The app's side of the line: dial out, prove the name, hold the line.
//!
//! This is the client the tests use, and the part of the protocol the
//! desktop app (unit B3) builds on. It does not do the app's policy:
//! when to dial, when to renew, what to do with a caller.
//!
//! ```text
//! GOAL: connect to the relay, prove the key for a name for this session
//! only, and hand the app each caller with the caller's address.
//! SOURCE: WB-relay-2 (the line and its proof), WB-relay-6 (the caller's
//! address).
//! INVARIANTS:
//! 1. The proof signs this session's TLS exporter and the relay's fresh
//! nonce: it cannot be reused in another session.
//! 2. A caller stream is handed on only after its address header
//! parsed; a stream with a bad header is dropped.
//! 3. Pending headers are bounded in number and in time.
//! SCENARIOS:
//! 1. `connect` with a new name and `claim = true` gives a line with
//! `verdict.claimed`; a second connect with `claim = false` and the
//! same key gives a line, and with another key is refused.
//! ```
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use rustls::ClientConfig;
use rustls::pki_types::ServerName;
use tokio::net::TcpStream;
use tokio::sync::{Semaphore, mpsc};
use tokio::task::JoinHandle;
use tokio::time::timeout;
use tokio_rustls::TlsConnector;
use tokio_util::compat::TokioAsyncReadCompatExt;
use crate::mux::{self, Mux, MuxLimits, Stream};
use crate::names::Name;
use crate::proto::{
self, AppKey, Authority, Caller, Challenge, EXPORTER_LABEL, Hello, Refusal, Request, Response,
VERSION, Verdict, read_frame, write_frame,
};
/// Why a line could not be made, or a request failed.
#[derive(Debug, thiserror::Error)]
pub enum ClientError {
/// The network or TLS failed.
#[error("i/o: {0}")]
Io(#[from] io::Error),
/// A message was malformed or too long.
#[error("protocol: {0}")]
Frame(#[from] proto::FrameError),
/// The relay said no.
#[error("the relay refused the line: {0:?}")]
Refused(Refusal),
/// The relay did not answer in time.
#[error("timed out")]
Timeout,
/// The line is closed.
#[error("the line is closed")]
Closed,
}
/// A caller handed to the app.
pub struct Incoming {
/// Who the caller is, as the relay saw them.
pub caller: Caller,
/// The caller's bytes: their TLS ClientHello first.
pub stream: Stream,
}
/// Options for a line.
#[derive(Debug, Clone, Copy)]
pub struct LineOptions {
/// Streams at once on the line. At least the relay's `streams_per_app`
/// plus `control_streams_per_app` plus 16, or the relay's opens are
/// refused.
pub max_streams: usize,
/// How long a caller stream may take to send its address header.
pub header_timeout: Duration,
/// How long a request waits for its answer.
pub request_timeout: Duration,
}
impl Default for LineOptions {
fn default() -> Self {
LineOptions {
max_streams: 64,
header_timeout: Duration::from_secs(5),
request_timeout: Duration::from_secs(10),
}
}
}
/// An app's open line.
pub struct Line {
/// The relay's verdict: claimed or not, and the stream limit.
pub verdict: Verdict,
handle: LineHandle,
incoming: mpsc::Receiver<Incoming>,
task: JoinHandle<()>,
}
/// TLS to the relay, as `server_name` (the relay's host).
pub async fn tls_connect(
addr: SocketAddr,
tls: Arc<ClientConfig>,
server_name: &str,
) -> io::Result<tokio_rustls::client::TlsStream<TcpStream>> {
let tcp = TcpStream::connect(addr).await?;
tcp.set_nodelay(true)?;
let name = ServerName::try_from(server_name.to_owned())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
TlsConnector::from(tls).connect(name, tcp).await
}
/// This TLS session's exporter value, the thing a proof is bound to.
pub fn session_exporter(tls: &tokio_rustls::client::TlsStream<TcpStream>) -> io::Result<[u8; 32]> {
let mut out = [0u8; 32];
tls.get_ref()
.1
.export_keying_material(&mut out[..], EXPORTER_LABEL, None)
.map_err(|e| io::Error::other(e.to_string()))?;
Ok(out)
}
/// The hello for a session: the name, the key, and the signature.
pub fn make_hello(
key: &AppKey,
name: &Name,
claim: bool,
exporter: &[u8; 32],
nonce: &[u8; 32],
) -> Hello {
Hello {
v: VERSION,
name: name.to_string(),
public_key: proto::hex(&key.public_key()),
claim,
signature: proto::hex(&key.sign(&proto::proof_message(exporter, nonce, name, claim))),
}
}
/// Dial the relay and bring up the line for `name`. `claim` is true only
/// the first time, to take the name.
pub async fn connect(
addr: SocketAddr,
tls: Arc<ClientConfig>,
server_name: &str,
name: Name,
key: &AppKey,
claim: bool,
opts: LineOptions,
) -> Result<Line, ClientError> {
let mut stream = timeout(opts.request_timeout, tls_connect(addr, tls, server_name))
.await
.map_err(|_| ClientError::Timeout)??;
let exporter = session_exporter(&stream)?;
let challenge: Challenge = timeout(opts.request_timeout, read_frame(&mut stream))
.await
.map_err(|_| ClientError::Timeout)??;
let nonce = proto::unhex::<32>(&challenge.nonce)
.ok_or_else(|| ClientError::Io(io::Error::new(io::ErrorKind::InvalidData, "bad nonce")))?;
let hello = make_hello(key, &name, claim, &exporter, &nonce);
write_frame(&mut stream, &hello).await?;
let verdict: Verdict = timeout(opts.request_timeout, read_frame(&mut stream))
.await
.map_err(|_| ClientError::Timeout)??;
if !verdict.ok {
return Err(ClientError::Refused(
verdict.refusal.unwrap_or(Refusal::BadRequest),
));
}
Ok(Line::up(stream, verdict, opts))
}
impl Line {
/// Start the multiplexer over a TLS stream that has passed the
/// handshake.
pub fn up(
stream: tokio_rustls::client::TlsStream<TcpStream>,
verdict: Verdict,
opts: LineOptions,
) -> Line {
let (tx, incoming) = mpsc::channel::<Incoming>(16);
let pending = Arc::new(Semaphore::new(64));
let header_timeout = opts.header_timeout;
let (mux, task) = mux::spawn(
stream.compat(),
yamux::Mode::Client,
MuxLimits {
max_streams: opts.max_streams,
idle: Duration::from_secs(3600 * 24 * 365),
},
None,
move |mut stream| {
let Ok(permit) = Arc::clone(&pending).try_acquire_owned() else {
return; // too many callers waiting to be read: drop
};
let tx = tx.clone();
tokio::spawn(async move {
let header = timeout(header_timeout, Caller::read(&mut stream)).await;
drop(permit);
if let Ok(Ok(caller)) = header {
let _ = tx.try_send(Incoming { caller, stream });
}
});
},
);
Line {
verdict,
handle: LineHandle { mux, opts },
incoming,
task,
}
}
/// The next caller, or `None` when the line has ended.
pub async fn accept(&mut self) -> Option<Incoming> {
self.incoming.recv().await
}
/// A clonable handle for requests and closing, for use beside
/// [`Line::accept`].
pub fn handle(&self) -> LineHandle {
self.handle.clone()
}
/// Close the line and wait for it.
pub async fn close(self) {
self.handle.mux.close();
let _ = self.task.await;
}
}
/// What can be done with a line besides taking callers: requests, and
/// closing. Clones share the line.
#[derive(Clone)]
pub struct LineHandle {
mux: Mux,
opts: LineOptions,
}
impl LineHandle {
/// One request on a stream of its own.
pub async fn request(&self, request: Request) -> Result<Response, ClientError> {
let wait = self.opts.request_timeout;
let mut stream = self.mux.open(wait).await.map_err(|_| ClientError::Closed)?;
timeout(wait, async {
write_frame(&mut stream, &request).await?;
let r: Response = read_frame(&mut stream).await?;
Ok::<_, ClientError>(r)
})
.await
.map_err(|_| ClientError::Timeout)?
}
/// Ask the relay to publish an ACME DNS-01 proof value for this
/// app's name.
pub async fn publish_txt(&self, value: &str) -> Result<Response, ClientError> {
self.request(Request::PublishTxt {
value: value.to_owned(),
})
.await
}
/// The certificate authorities to try, in order.
pub async fn authorities(&self) -> Result<Vec<Authority>, ClientError> {
let r = self.request(Request::Authorities).await?;
Ok(r.authorities.unwrap_or_default())
}
/// True once the line has ended.
pub fn is_closed(&self) -> bool {
self.mux.is_closed()
}
/// Ask the line to close.
pub fn close(&self) {
self.mux.close();
}
}
impl std::ops::Deref for Line {
type Target = LineHandle;
fn deref(&self) -> &LineHandle {
&self.handle
}
}
+234
View File
@@ -0,0 +1,234 @@
//! The relay's settings, and every limit it enforces.
//!
//! Every limit is a number here with a default and a reason; nothing in
//! the relay is unbounded. The defaults are sized for hundreds of
//! thousands of idle apps on one modest host.
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use std::path::PathBuf;
use std::time::Duration;
use serde::Deserialize;
/// A name server of the domain, and where it is.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NameServer {
/// Its host name (`ns1.wanderbooks.link`).
pub name: String,
/// Its IPv4 addresses.
#[serde(default)]
pub v4: Vec<Ipv4Addr>,
/// Its IPv6 addresses.
#[serde(default)]
pub v6: Vec<Ipv6Addr>,
}
/// Every limit and timeout. Times are in milliseconds.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Limits {
/// Apps connected at once. Admission stops here.
pub max_lines: usize,
/// Connections open at once, all kinds (hello stage, line handshake,
/// callers being spliced, apps' lines).
pub max_connections: usize,
/// Connections that have not yet sent a whole ClientHello.
pub max_pending_hellos: usize,
/// Of those, from one address. Strict: this is the slow-loris limit.
pub max_pending_per_ip: u32,
/// Connections from one address, all stages. Generous: the AI vendors'
/// callers share a few addresses between all their users.
pub max_connections_per_ip: u32,
/// How long a peer has to send a whole ClientHello, from connecting.
pub hello_timeout_ms: u64,
/// Line handshakes (TLS and proof) in progress at once.
pub max_handshakes: usize,
/// How long a line's TLS handshake and proof may take in all.
pub handshake_timeout_ms: u64,
/// How long to wait for the app to open a stream for a caller.
pub open_stream_timeout_ms: u64,
/// Caller streams open on one app's line at once.
pub streams_per_app: u32,
/// Control streams (requests from the app) in progress at once, per line.
pub control_streams_per_app: u32,
/// The copy buffer, per direction, per spliced connection, in bytes.
pub copy_buffer: usize,
/// A spliced connection with no byte either way this long is closed.
pub stream_idle_ms: u64,
/// A spliced connection's longest life.
pub stream_max_age_ms: u64,
/// A write that makes no progress this long ends the connection: a
/// slow reader is closed, not buffered for.
pub write_stall_ms: u64,
/// A line from which nothing has been read this long is dropped. The
/// app sends a keep-alive well inside this.
pub line_idle_ms: u64,
/// A control request, read to reply, must finish in this long.
pub control_timeout_ms: u64,
/// How long a published proof record lives.
pub txt_ttl_ms: u64,
/// Proof records held at most, over all apps.
pub txt_max_entries: usize,
/// Values one name may hold at once (the wildcard and the apex).
pub txt_per_name: usize,
/// Publishes one name may make in an hour.
pub txt_publishes_per_hour: u32,
/// New names that may be claimed in one window, over all apps.
pub claims_per_window: u32,
/// The window for `claims_per_window`: a week, the certificate
/// authority's new-certificate limit.
pub claim_window_ms: u64,
/// New names one address may claim in `claim_ip_window_ms`.
pub claims_per_ip: u32,
/// The window for `claims_per_ip`.
pub claim_ip_window_ms: u64,
/// Registry requests queued at most; past this the relay says busy.
pub registry_queue: usize,
/// Slots in each fixed per-address table (a power of two).
pub ip_slots: usize,
/// DNS queries per second one address may send, sustained.
pub dns_qps_per_ip: u32,
/// TCP DNS connections open at once.
pub dns_tcp_max: usize,
/// TCP DNS connections from one address.
pub dns_tcp_per_ip: u32,
/// A TCP DNS connection's wait for its next query.
pub dns_tcp_timeout_ms: u64,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_lines: 500_000,
max_connections: 1_000_000,
max_pending_hellos: 4_096,
max_pending_per_ip: 32,
max_connections_per_ip: 20_000,
hello_timeout_ms: 8_000,
max_handshakes: 1_024,
handshake_timeout_ms: 10_000,
open_stream_timeout_ms: 5_000,
streams_per_app: 32,
control_streams_per_app: 4,
copy_buffer: 8 * 1024,
stream_idle_ms: 10 * 60_000,
stream_max_age_ms: 6 * 3_600_000,
write_stall_ms: 30_000,
line_idle_ms: 180_000,
control_timeout_ms: 10_000,
txt_ttl_ms: 10 * 60_000,
txt_max_entries: 100_000,
txt_per_name: 4,
txt_publishes_per_hour: 12,
claims_per_window: 50,
claim_window_ms: 7 * 24 * 3_600_000,
claims_per_ip: 5,
claim_ip_window_ms: 24 * 3_600_000,
registry_queue: 256,
ip_slots: 1 << 16,
dns_qps_per_ip: 20,
dns_tcp_max: 512,
dns_tcp_per_ip: 8,
dns_tcp_timeout_ms: 5_000,
}
}
}
macro_rules! durations {
($($name:ident => $field:ident),* $(,)?) => {
impl Limits {
$(
#[doc = concat!("`", stringify!($field), "` as a duration.")]
pub fn $name(&self) -> Duration { Duration::from_millis(self.$field) }
)*
}
};
}
durations! {
hello_timeout => hello_timeout_ms,
handshake_timeout => handshake_timeout_ms,
open_stream_timeout => open_stream_timeout_ms,
stream_idle => stream_idle_ms,
stream_max_age => stream_max_age_ms,
write_stall => write_stall_ms,
line_idle => line_idle_ms,
control_timeout => control_timeout_ms,
txt_ttl => txt_ttl_ms,
claim_window => claim_window_ms,
claim_ip_window => claim_ip_window_ms,
dns_tcp_timeout => dns_tcp_timeout_ms,
}
/// The relay's configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
/// The domain the relay serves (`wanderbooks.link`).
pub domain: String,
/// The host an app's line dials (`relay.wanderbooks.link`).
pub relay_host: String,
/// Where the router listens (443 in production).
pub router_addr: SocketAddr,
/// Where DNS listens, UDP and TCP (53 in production).
pub dns_addr: SocketAddr,
/// The registry's file: the one durable table (D-85).
pub registry_path: PathBuf,
/// The relay's own certificate chain, PEM, for `relay_host`.
pub tls_cert: PathBuf,
/// Its private key, PEM.
pub tls_key: PathBuf,
/// The certificate authorities, served to apps; read again when it
/// changes. See [`crate::authorities`].
pub authorities_path: Option<PathBuf>,
/// IPv4 addresses every name under the domain points at.
pub address_v4: Vec<Ipv4Addr>,
/// IPv6 addresses every name under the domain points at.
pub address_v6: Vec<Ipv6Addr>,
/// The domain's name servers, at least two in production.
pub nameservers: Vec<NameServer>,
/// Limits and timeouts.
pub limits: Limits,
}
impl Default for Config {
fn default() -> Self {
Config {
domain: "wanderbooks.link".into(),
relay_host: "relay.wanderbooks.link".into(),
router_addr: SocketAddr::from(([0, 0, 0, 0], 443)),
dns_addr: SocketAddr::from(([0, 0, 0, 0], 53)),
registry_path: PathBuf::from("registry.sqlite3"),
tls_cert: PathBuf::from("relay-cert.pem"),
tls_key: PathBuf::from("relay-key.pem"),
authorities_path: None,
address_v4: Vec::new(),
address_v6: Vec::new(),
nameservers: Vec::new(),
limits: Limits::default(),
}
}
}
impl Config {
/// Read a TOML configuration.
pub fn from_toml(text: &str) -> Result<Self, toml::de::Error> {
toml::from_str(text)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_load_and_unknown_keys_are_refused() {
let c = Config::from_toml("").expect("empty is the defaults");
assert_eq!(c.limits.streams_per_app, 32);
let c = Config::from_toml("[limits]\nstreams_per_app = 4\n").unwrap();
assert_eq!(c.limits.streams_per_app, 4);
assert!(Config::from_toml("bogus = 1").is_err());
assert!(Config::from_toml("[limits]\nbogus = 1").is_err());
}
}
+623
View File
@@ -0,0 +1,623 @@
//! The domain's authoritative DNS server.
//!
//! The relay answers for `wanderbooks.link` itself, over UDP and TCP.
//! It answers two questions and refuses the rest:
//!
//! - any name under the domain is at the relay's address (A, AAAA), the
//! name servers at their own;
//! - `TXT _acme-challenge.<four-words>.<domain>` is the proof value that
//! app just handed in, held in memory for minutes.
//!
//! Nothing is stored per user: the answers are made, not looked up, so a
//! catch-all that stops covering names under a label of its own (RFC 4592)
//! is not a risk here: every name below the zone is answered the same way
//! whatever else exists beneath it.
//!
//! ```text
//! GOAL: be the domain's DNS: point every name at the relay, publish an
//! app's proof record and nobody else's, and be no use to someone
//! who wants a resolver, an amplifier, or a way to make the relay
//! hold memory.
//! SOURCE: WB-relay-5 (the proof records and the domain's DNS), RFC 1035,
//! RFC 4592 (wildcards), RFC 6891 (EDNS), RFC 8482 (ANY).
//! INVARIANTS:
//! 1. A query outside the zone is refused; recursion is never offered.
//! 2. Every name under the zone has A and AAAA answers at the relay's
//! addresses, including names beneath a label that has a TXT record.
//! 3. A TXT answer exists only at `_acme-challenge.<name>` for a name
//! with a live published value, and holds only those values.
//! 4. A UDP answer never exceeds the client's stated size (512 without
//! EDNS, at most 1 232 with it); an oversized one is truncated
//! (TC) and the client retries over TCP.
//! 5. The server holds no per-query state: the UDP loop answers inline
//! from fixed tables, and TCP is capped in connections, in queries
//! per connection and in time.
//! 6. Per address, UDP queries are rate limited from a fixed table.
//! SCENARIOS:
//! 1. A for `x.<secret>.<name>.<domain>` is the relay's address, with
//! and without a TXT record published for that name.
//! 2. TXT for `_acme-challenge.<name>` returns the published value, and
//! returns nothing after the value expires.
//! 3. A for `example.com` is REFUSED; ANY is answered with no data.
//! 4. A hundred queries in a burst from one address: the excess is
//! dropped.
//! ```
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use std::time::Instant;
use hickory_proto::op::{Edns, Message, MessageType, OpCode, ResponseCode};
use hickory_proto::rr::rdata::{A, AAAA, NS, SOA, TXT};
use hickory_proto::rr::{DNSClass, Name as DnsName, RData, Record, RecordType};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, UdpSocket};
use tokio::sync::Semaphore;
use tokio_util::sync::CancellationToken;
use crate::config::Config;
use crate::gate::{IpGate, RateTable};
use crate::names::{Name, Zone};
use crate::txt::TxtStore;
const TTL_ADDR: u32 = 300;
const TTL_APEX: u32 = 3600;
const TTL_TXT: u32 = 5;
const TTL_NEGATIVE: u32 = 60;
/// The biggest UDP answer ever sent, whatever the client asks for.
const UDP_MAX: usize = 1232;
/// The biggest query read, over either transport.
const QUERY_MAX: usize = 1232;
/// The DNS service: pure, no sockets. Feed it a query, get the answer.
pub struct DnsService {
zone: Zone,
domain: DnsName,
v4: Vec<Ipv4Addr>,
v6: Vec<Ipv6Addr>,
nameservers: Vec<(String, DnsName, Vec<IpAddr>)>,
txt: Arc<TxtStore>,
}
impl DnsService {
/// A service for the configured domain.
pub fn new(zone: Zone, cfg: &Config, txt: Arc<TxtStore>) -> Result<Self, String> {
let domain =
DnsName::from_ascii(format!("{}.", zone.domain())).map_err(|e| e.to_string())?;
let mut nameservers = Vec::new();
for ns in &cfg.nameservers {
let name = DnsName::from_ascii(format!("{}.", ns.name.trim_end_matches('.')))
.map_err(|e| e.to_string())?;
let ips = ns
.v4
.iter()
.map(|a| IpAddr::V4(*a))
.chain(ns.v6.iter().map(|a| IpAddr::V6(*a)))
.collect();
nameservers.push((
ns.name.trim_end_matches('.').to_ascii_lowercase(),
name,
ips,
));
}
Ok(DnsService {
zone,
domain,
v4: cfg.address_v4.clone(),
v6: cfg.address_v6.clone(),
nameservers,
txt,
})
}
fn soa(&self) -> Record {
let mname = self
.nameservers
.first()
.map(|(_, n, _)| n.clone())
.unwrap_or_else(|| {
DnsName::from_ascii(format!("ns1.{}", self.domain))
.unwrap_or_else(|_| self.domain.clone())
});
let rname = DnsName::from_ascii(format!("hostmaster.{}", self.domain))
.unwrap_or_else(|_| self.domain.clone());
Record::from_rdata(
self.domain.clone(),
TTL_APEX,
RData::SOA(SOA::new(mname, rname, 1, 3600, 600, 86_400, TTL_NEGATIVE)),
)
}
fn addresses(&self, owner: &DnsName, text: &str, want_v6: bool) -> Vec<Record> {
if let Some((_, _, ips)) = self.nameservers.iter().find(|(n, _, _)| n == text) {
return ips
.iter()
.filter_map(|ip| match (ip, want_v6) {
(IpAddr::V4(a), false) => Some(RData::A(A::from(*a))),
(IpAddr::V6(a), true) => Some(RData::AAAA(AAAA::from(*a))),
_ => None,
})
.map(|d| Record::from_rdata(owner.clone(), TTL_ADDR, d))
.collect();
}
if want_v6 {
self.v6
.iter()
.map(|a| Record::from_rdata(owner.clone(), TTL_ADDR, RData::AAAA(AAAA::from(*a))))
.collect()
} else {
self.v4
.iter()
.map(|a| Record::from_rdata(owner.clone(), TTL_ADDR, RData::A(A::from(*a))))
.collect()
}
}
/// The answer to a query message, or `None` to say nothing at all (a
/// response, or too little to answer). `udp` limits the size.
pub fn answer(&self, wire: &[u8], udp: bool, now: Instant) -> Option<Vec<u8>> {
if wire.len() > QUERY_MAX {
return None;
}
let query = match Message::from_vec(wire) {
Ok(m) => m,
Err(_) => {
// Too short to have an id: nothing to answer. A response
// (QR set) is never answered, so no two servers can loop.
let id = wire.get(..2).map(|b| u16::from_be_bytes([b[0], b[1]]))?;
if wire.get(2).is_none_or(|b| b & 0x80 != 0) {
return None;
}
return Message::error_msg(id, OpCode::Query, ResponseCode::FormErr)
.to_vec()
.ok();
}
};
if query.metadata.message_type == MessageType::Response {
return None;
}
let id = query.metadata.id;
let reply = |code| {
Message::error_msg(id, query.metadata.op_code, code)
.to_vec()
.ok()
};
if query.metadata.op_code != OpCode::Query {
return reply(ResponseCode::NotImp);
}
let [q] = query.queries.as_slice() else {
return reply(ResponseCode::FormErr);
};
if q.query_class() != DNSClass::IN {
return reply(ResponseCode::Refused);
}
let qname = q.name().to_ascii();
let lower = qname.trim_end_matches('.').to_ascii_lowercase();
let Some(labels) = self.zone.below(&lower) else {
return reply(ResponseCode::Refused);
};
let mut resp = Message::response(id, OpCode::Query);
resp.metadata.authoritative = true;
resp.metadata.recursion_desired = query.metadata.recursion_desired;
resp.queries.push(q.clone());
if let Some(e) = &query.edns {
let mut edns = Edns::new();
edns.set_max_payload(u16::try_from(UDP_MAX).unwrap_or(1232));
edns.set_version(0);
resp.edns = Some(edns);
let _ = e;
}
let owner = q.name().clone();
let apex = labels.is_empty();
match q.query_type() {
RecordType::A => resp.answers = self.addresses(&owner, &lower, false),
RecordType::AAAA => resp.answers = self.addresses(&owner, &lower, true),
RecordType::SOA if apex => resp.answers.push(self.soa()),
RecordType::NS if apex => {
for (_, ns, ips) in &self.nameservers {
resp.answers.push(Record::from_rdata(
owner.clone(),
TTL_APEX,
RData::NS(NS(ns.clone())),
));
for ip in ips {
let data = match ip {
IpAddr::V4(a) => RData::A(A::from(*a)),
IpAddr::V6(a) => RData::AAAA(AAAA::from(*a)),
};
resp.additionals
.push(Record::from_rdata(ns.clone(), TTL_ADDR, data));
}
}
}
RecordType::TXT => {
if let ["_acme-challenge", name] = labels.as_slice()
&& let Ok(name) = Name::parse(&name.to_ascii_lowercase())
{
for v in self.txt.get(&name, now) {
resp.answers.push(Record::from_rdata(
owner.clone(),
TTL_TXT,
RData::TXT(TXT::new(vec![v])),
));
}
}
}
// ANY (RFC 8482), and every type the relay has nothing of: no
// data, which is not a refusal and not a missing name.
_ => {}
}
if resp.answers.is_empty() {
resp.authorities.push(self.soa());
}
let mut bytes = resp.to_vec().ok()?;
if udp {
let limit = query
.edns
.as_ref()
.map_or(512, |e| usize::from(e.max_payload()).clamp(512, UDP_MAX));
if bytes.len() > limit {
resp.metadata.truncation = true;
resp.answers.clear();
resp.authorities.clear();
resp.additionals.clear();
bytes = resp.to_vec().ok()?;
}
}
Some(bytes)
}
}
/// Serve UDP until cancelled. Answers are made inline, with no task per
/// query, and a sender over its rate gets no answer.
pub async fn serve_udp(
socket: Arc<UdpSocket>,
svc: Arc<DnsService>,
qps: u32,
slots: usize,
cancel: CancellationToken,
) {
let mut rate = RateTable::new(slots, qps, qps.saturating_mul(2).max(1));
let mut buf = vec![0u8; QUERY_MAX + 1];
loop {
let (n, from) = tokio::select! {
() = cancel.cancelled() => return,
r = socket.recv_from(&mut buf) => match r {
Ok(x) => x,
Err(_) => {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
continue;
}
},
};
let now = Instant::now();
if !rate.allow(from.ip(), now) {
continue;
}
if let Some(out) = svc.answer(&buf[..n], true, now) {
// A full send buffer drops the answer: a client retries.
let _ = socket.try_send_to(&out, from);
}
}
}
/// The limits of the TCP side.
#[derive(Debug, Clone, Copy)]
pub struct TcpLimits {
/// Connections at once.
pub max: usize,
/// Connections at once from one address.
pub per_ip: u32,
/// The wait for each query, and for the rest of one that began.
pub timeout: std::time::Duration,
/// Queries answered on one connection.
pub queries: u32,
}
/// Serve TCP until cancelled.
pub async fn serve_tcp(
listener: TcpListener,
svc: Arc<DnsService>,
limits: TcpLimits,
slots: usize,
cancel: CancellationToken,
) {
let permits = Arc::new(Semaphore::new(limits.max));
let gate = IpGate::new(slots, limits.per_ip);
loop {
let (mut stream, from) = tokio::select! {
() = cancel.cancelled() => return,
r = listener.accept() => match r {
Ok(x) => x,
Err(_) => {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
continue;
}
},
};
let (Ok(permit), Some(ip_permit)) = (
Arc::clone(&permits).try_acquire_owned(),
gate.acquire(from.ip()),
) else {
continue; // over the limit: close it
};
let svc = Arc::clone(&svc);
tokio::spawn(async move {
let _held = (permit, ip_permit);
for _ in 0..limits.queries {
let mut len = [0u8; 2];
let read = async {
stream.read_exact(&mut len).await?;
let n = usize::from(u16::from_be_bytes(len));
if n == 0 || n > QUERY_MAX {
return Err(std::io::ErrorKind::InvalidData.into());
}
let mut body = vec![0u8; n];
stream.read_exact(&mut body).await?;
Ok::<_, std::io::Error>(body)
};
let Ok(Ok(body)) = tokio::time::timeout(limits.timeout, read).await else {
return;
};
let Some(out) = svc.answer(&body, false, Instant::now()) else {
return;
};
let Ok(n) = u16::try_from(out.len()) else {
return;
};
let mut framed = n.to_be_bytes().to_vec();
framed.extend(out);
if tokio::time::timeout(limits.timeout, stream.write_all(&framed))
.await
.is_err()
{
return;
}
}
});
}
}
/// A socket address for tests and the binary: where DNS is listening.
pub fn bound(addr: SocketAddr) -> SocketAddr {
addr
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use hickory_proto::op::Query;
use super::*;
fn svc() -> (DnsService, Arc<TxtStore>) {
let cfg = Config {
address_v4: vec!["198.51.100.7".parse().unwrap()],
address_v6: vec!["2001:db8::7".parse().unwrap()],
nameservers: vec![
crate::config::NameServer {
name: "ns1.wanderbooks.link".into(),
v4: vec!["198.51.100.53".parse().unwrap()],
v6: vec![],
},
crate::config::NameServer {
name: "ns2.wanderbooks.link".into(),
v4: vec!["203.0.113.53".parse().unwrap()],
v6: vec![],
},
],
..Config::default()
};
let txt = Arc::new(TxtStore::new(Duration::from_secs(60), 100, 4, 100));
let zone = Zone::new(&cfg.domain, &cfg.relay_host);
(DnsService::new(zone, &cfg, Arc::clone(&txt)).unwrap(), txt)
}
fn ask(svc: &DnsService, name: &str, ty: RecordType, udp: bool) -> Message {
let mut m = Message::query();
m.queries
.push(Query::query(DnsName::from_ascii(name).unwrap(), ty));
let out = svc
.answer(&m.to_vec().unwrap(), udp, Instant::now())
.expect("an answer");
Message::from_vec(&out).unwrap()
}
const APP: &str = "ledger-accrual-tally-mint.wanderbooks.link.";
const SECRET: &str = "k3j9x0q7m2z8c5v1b4n6a9s2d";
const PROOF: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ";
#[test]
fn every_name_under_the_zone_is_at_the_relay_even_beneath_a_label_with_a_record() {
let (svc, txt) = svc();
let deep = format!("{SECRET}.{APP}");
for publish in [false, true] {
if publish {
txt.publish(
Name::parse("ledger-accrual-tally-mint").unwrap(),
PROOF,
Instant::now(),
)
.unwrap();
}
for name in [
APP,
deep.as_str(),
"relay.wanderbooks.link.",
"wanderbooks.link.",
"A.B.C.D.wanderbooks.link.",
] {
let m = ask(&svc, name, RecordType::A, true);
assert_eq!(m.metadata.response_code, ResponseCode::NoError, "{name}");
assert!(m.metadata.authoritative);
assert!(
matches!(m.answers.as_slice(), [r] if r.data == RData::A(A::from(Ipv4Addr::new(198, 51, 100, 7)))),
"{name}: {:?}",
m.answers
);
let m6 = ask(&svc, name, RecordType::AAAA, true);
assert_eq!(m6.answers.len(), 1, "{name}");
}
}
}
#[test]
fn the_name_servers_are_at_their_own_addresses() {
let (svc, _) = svc();
let m = ask(&svc, "ns2.wanderbooks.link.", RecordType::A, true);
assert!(
matches!(m.answers.as_slice(), [r] if r.data == RData::A(A::from(Ipv4Addr::new(203, 0, 113, 53))))
);
let ns = ask(&svc, "wanderbooks.link.", RecordType::NS, true);
assert_eq!(ns.answers.len(), 2);
assert_eq!(ns.additionals.len(), 2);
let soa = ask(&svc, "wanderbooks.link.", RecordType::SOA, true);
assert_eq!(soa.answers.len(), 1);
}
#[test]
fn the_proof_record_is_answered_for_its_own_name_until_it_expires() {
let (svc, txt) = svc();
let mint = Name::parse("ledger-accrual-tally-mint").unwrap();
let t0 = Instant::now();
txt.publish(mint, PROOF, t0).unwrap();
let q = format!("_acme-challenge.{APP}");
let m = ask(&svc, &q, RecordType::TXT, true);
assert_eq!(m.answers.len(), 1);
let RData::TXT(t) = &m.answers[0].data else {
panic!("a TXT")
};
assert_eq!(t.to_string(), PROOF);
// Another app's challenge name has nothing; so does a made-up one.
for other in [
"_acme-challenge.ledger-accrual-tally-vault.wanderbooks.link.",
"_acme-challenge.not-a-name.wanderbooks.link.",
&format!("_acme-challenge.{SECRET}.{APP}"),
APP,
] {
let m = ask(&svc, other, RecordType::TXT, true);
assert_eq!(m.metadata.response_code, ResponseCode::NoError, "{other}");
assert!(m.answers.is_empty(), "{other}");
assert_eq!(m.authorities.len(), 1, "a no-data answer carries the SOA");
}
// After the value's life it is gone.
txt.sweep(t0 + Duration::from_secs(61));
let gone = svc
.answer(
&{
let mut m = Message::query();
m.queries.push(Query::query(
DnsName::from_ascii(&q).unwrap(),
RecordType::TXT,
));
m.to_vec().unwrap()
},
true,
t0 + Duration::from_secs(61),
)
.unwrap();
assert!(Message::from_vec(&gone).unwrap().answers.is_empty());
}
#[test]
fn outside_the_zone_is_refused_and_odd_queries_are_answered_plainly() {
let (svc, _) = svc();
for name in [
"example.com.",
"link.",
"xwanderbooks.link.",
"wanderbooks.link.example.com.",
] {
let m = ask(&svc, name, RecordType::A, true);
assert_eq!(m.metadata.response_code, ResponseCode::Refused, "{name}");
assert!(m.answers.is_empty());
}
let any = ask(&svc, APP, RecordType::ANY, true);
assert_eq!(any.metadata.response_code, ResponseCode::NoError);
assert!(any.answers.is_empty());
let mx = ask(&svc, APP, RecordType::MX, true);
assert!(mx.answers.is_empty() && mx.metadata.response_code == ResponseCode::NoError);
// Not a query, and a response: refused to be answered.
let mut upd = Message::query();
upd.metadata.op_code = OpCode::Update;
upd.queries.push(Query::query(
DnsName::from_ascii(APP).unwrap(),
RecordType::A,
));
let out = svc
.answer(&upd.to_vec().unwrap(), true, Instant::now())
.unwrap();
assert_eq!(
Message::from_vec(&out).unwrap().metadata.response_code,
ResponseCode::NotImp
);
let mut resp = Message::response(7, OpCode::Query);
resp.queries.push(Query::query(
DnsName::from_ascii(APP).unwrap(),
RecordType::A,
));
assert!(
svc.answer(&resp.to_vec().unwrap(), true, Instant::now())
.is_none()
);
// Two questions, no questions.
let mut two = Message::query();
two.queries.push(Query::query(
DnsName::from_ascii(APP).unwrap(),
RecordType::A,
));
two.queries.push(Query::query(
DnsName::from_ascii(APP).unwrap(),
RecordType::AAAA,
));
let out = svc
.answer(&two.to_vec().unwrap(), true, Instant::now())
.unwrap();
assert_eq!(
Message::from_vec(&out).unwrap().metadata.response_code,
ResponseCode::FormErr
);
let none = Message::query().to_vec().unwrap();
let out = svc.answer(&none, true, Instant::now()).unwrap();
assert_eq!(
Message::from_vec(&out).unwrap().metadata.response_code,
ResponseCode::FormErr
);
}
#[test]
fn garbage_never_panics_and_is_mostly_ignored() {
let (svc, _) = svc();
assert!(svc.answer(b"", true, Instant::now()).is_none());
assert!(svc.answer(b"x", true, Instant::now()).is_none());
assert!(
svc.answer(&vec![0u8; QUERY_MAX + 1], true, Instant::now())
.is_none()
);
let mut seed = 0x9e37_79b9u32;
for len in 0..300usize {
let bytes: Vec<u8> = (0..len)
.map(|_| {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(seed >> 24) as u8
})
.collect();
let _ = svc.answer(&bytes, true, Instant::now());
let _ = svc.answer(&bytes, false, Instant::now());
}
}
#[test]
fn a_udp_answer_never_exceeds_the_clients_size() {
let (svc, _) = svc();
// A query with no EDNS gets at most 512 bytes; ours are far less,
// so check the cap by forcing a tiny limit through truncation of
// a big NS set.
let m = ask(&svc, "wanderbooks.link.", RecordType::NS, true);
let bytes = m.to_vec().unwrap();
assert!(bytes.len() <= 512);
assert!(!m.metadata.truncation);
}
}
+131
View File
@@ -0,0 +1,131 @@
//! A connection with its first bytes put back, and a clock on its reads.
//!
//! The router reads the ClientHello itself to find the server name. For
//! the relay's own host the same bytes must then go to TLS, so the stream
//! is wrapped to give them back first. The wrapper also stamps the time of
//! every read, which is how a silent line is told from a quiet one.
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::Instant;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
/// The time of the last read, in milliseconds since `base`.
#[derive(Debug)]
pub struct Activity {
base: Instant,
last_ms: AtomicU64,
}
impl Activity {
/// A clock that reads "now" as its last activity.
pub fn new() -> Arc<Self> {
Arc::new(Activity {
base: Instant::now(),
last_ms: AtomicU64::new(0),
})
}
/// Record activity.
pub fn touch(&self) {
let ms = u64::try_from(self.base.elapsed().as_millis()).unwrap_or(u64::MAX);
self.last_ms.store(ms, Ordering::Relaxed);
}
/// How long since the last activity.
pub fn since(&self) -> std::time::Duration {
let now = u64::try_from(self.base.elapsed().as_millis()).unwrap_or(u64::MAX);
std::time::Duration::from_millis(now.saturating_sub(self.last_ms.load(Ordering::Relaxed)))
}
}
/// `inner`, with `prefix` read first, and every read stamped on `activity`.
pub struct Front<S> {
prefix: Vec<u8>,
at: usize,
inner: S,
activity: Option<Arc<Activity>>,
}
impl<S> Front<S> {
/// Give `prefix` back before anything from `inner`.
pub fn new(prefix: Vec<u8>, inner: S, activity: Option<Arc<Activity>>) -> Self {
Front {
prefix,
at: 0,
inner,
activity,
}
}
}
impl<S: AsyncRead + Unpin> AsyncRead for Front<S> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let this = &mut *self;
if this.at < this.prefix.len() {
let rest = &this.prefix[this.at..];
let n = rest.len().min(buf.remaining());
buf.put_slice(&rest[..n]);
this.at += n;
if this.at == this.prefix.len() {
// Give the memory back: a line lives for days.
this.prefix = Vec::new();
this.at = 0;
}
return Poll::Ready(Ok(()));
}
let before = buf.filled().len();
let r = Pin::new(&mut this.inner).poll_read(cx, buf);
if matches!(r, Poll::Ready(Ok(())))
&& buf.filled().len() > before
&& let Some(a) = &this.activity
{
a.touch();
}
r
}
}
impl<S: AsyncWrite + Unpin> AsyncWrite for Front<S> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
#[cfg(test)]
mod tests {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use super::*;
#[tokio::test]
async fn the_prefix_comes_first_then_the_stream() {
let (mut a, b) = tokio::io::duplex(64);
a.write_all(b"world").await.unwrap();
drop(a);
let act = Activity::new();
let mut f = Front::new(b"hello ".to_vec(), b, Some(act.clone()));
let mut out = String::new();
f.read_to_string(&mut out).await.unwrap();
assert_eq!(out, "hello world");
assert!(act.since() < std::time::Duration::from_secs(5));
}
}
+206
View File
@@ -0,0 +1,206 @@
//! Fixed-size per-address tables.
//!
//! A hash map keyed by address grows with the number of strangers. These
//! tables do not: an address hashes (with a key picked at start) to one of
//! a fixed number of slots, and the slot holds a counter. Two addresses
//! may share a slot, which makes the limit slightly stricter for both,
//! never looser. The memory is the same however many addresses call.
//!
//! ```text
//! GOAL: limit what one address can hold open or ask for, in memory that
//! does not depend on how many addresses there are.
//! SOURCE: WB-relay-7 (bounds).
//! INVARIANTS:
//! 1. The table never allocates after it is made.
//! 2. A permit's drop gives back exactly what it took: after every
//! permit is dropped every slot reads zero.
//! 3. An address is refused once its slot holds `limit` permits, and
//! never admitted past it.
//! SCENARIOS:
//! 1. A limit of 2: two permits for one address, the third is refused;
//! dropping one lets a new one in.
//! 2. IPv6 addresses count by /64.
//! ```
use std::hash::{BuildHasher, RandomState};
use std::net::IpAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
/// A fixed table of per-address counters.
pub struct IpGate {
slots: Box<[AtomicU32]>,
mask: usize,
state: RandomState,
limit: u32,
}
/// One held place in an [`IpGate`]; dropping it frees the place.
pub struct IpPermit {
gate: Arc<IpGate>,
slot: usize,
}
impl IpGate {
/// A table of `slots` (rounded up to a power of two), each address
/// allowed `limit` permits at once.
pub fn new(slots: usize, limit: u32) -> Arc<Self> {
let n = slots.max(2).next_power_of_two();
Arc::new(IpGate {
slots: (0..n).map(|_| AtomicU32::new(0)).collect(),
mask: n - 1,
state: RandomState::new(),
limit,
})
}
fn slot(&self, ip: IpAddr) -> usize {
let key = match ip {
IpAddr::V4(v4) => u128::from(u32::from(v4)),
// An IPv6 subscriber has a /64 at least: count them together.
IpAddr::V6(v6) => {
u128::from(u64::from_be_bytes(
v6.octets()[..8].try_into().unwrap_or([0; 8]),
)) | (1 << 100)
}
};
// Truncating a hash to a table index is the point.
(self.state.hash_one(key) as usize) & self.mask
}
/// Take a place for `ip`, or `None` when it already holds its limit.
pub fn acquire(self: &Arc<Self>, ip: IpAddr) -> Option<IpPermit> {
let slot = self.slot(ip);
let cell = &self.slots[slot];
let mut cur = cell.load(Ordering::Relaxed);
loop {
if cur >= self.limit {
return None;
}
match cell.compare_exchange_weak(cur, cur + 1, Ordering::AcqRel, Ordering::Relaxed) {
Ok(_) => {
return Some(IpPermit {
gate: Arc::clone(self),
slot,
});
}
Err(seen) => cur = seen,
}
}
}
/// Permits held now, over all slots (for tests and the stats line).
pub fn held(&self) -> u64 {
self.slots
.iter()
.map(|c| u64::from(c.load(Ordering::Relaxed)))
.fold(0, u64::saturating_add)
}
}
impl Drop for IpPermit {
fn drop(&mut self) {
self.gate.slots[self.slot].fetch_sub(1, Ordering::AcqRel);
}
}
/// A fixed table of token buckets, one per address slot, for a loop that
/// owns it (the UDP DNS loop). Memory is fixed.
pub struct RateTable {
slots: Vec<(std::time::Instant, f64)>,
mask: usize,
state: RandomState,
rate: f64,
burst: f64,
}
impl RateTable {
/// `rate` queries per second sustained, `burst` at once.
pub fn new(slots: usize, rate: u32, burst: u32) -> Self {
let n = slots.max(2).next_power_of_two();
let now = std::time::Instant::now();
RateTable {
slots: vec![(now, f64::from(burst)); n],
mask: n - 1,
state: RandomState::new(),
rate: f64::from(rate),
burst: f64::from(burst),
}
}
/// Spend one token for `ip` at `now`; false when it has none.
pub fn allow(&mut self, ip: IpAddr, now: std::time::Instant) -> bool {
let key = match ip {
IpAddr::V4(v4) => u128::from(u32::from(v4)),
IpAddr::V6(v6) => {
u128::from(u64::from_be_bytes(
v6.octets()[..8].try_into().unwrap_or([0; 8]),
)) | (1 << 100)
}
};
let slot = (self.state.hash_one(key) as usize) & self.mask;
let (last, tokens) = &mut self.slots[slot];
let gained = now.saturating_duration_since(*last).as_secs_f64() * self.rate;
*tokens = (*tokens + gained).min(self.burst);
*last = now;
if *tokens >= 1.0 {
*tokens -= 1.0;
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_limit_of_two_admits_two_and_frees_on_drop() {
let gate = IpGate::new(1024, 2);
let ip: IpAddr = "203.0.113.9".parse().unwrap();
let a = gate.acquire(ip).unwrap();
let _b = gate.acquire(ip).unwrap();
assert!(gate.acquire(ip).is_none());
assert_eq!(gate.held(), 2);
drop(a);
let _c = gate.acquire(ip).expect("a place was freed");
assert!(gate.acquire(ip).is_none());
assert!(gate.acquire("198.51.100.1".parse().unwrap()).is_some());
}
#[test]
fn every_permit_gives_back_what_it_took() {
let gate = IpGate::new(64, 1000);
let mut held = Vec::new();
for i in 0..500u32 {
let ip = IpAddr::from(std::net::Ipv4Addr::from(i.wrapping_mul(2_654_435_761)));
if let Some(p) = gate.acquire(ip) {
held.push(p);
}
}
assert_eq!(gate.held(), held.len() as u64);
drop(held);
assert_eq!(gate.held(), 0);
}
#[test]
fn ipv6_counts_by_the_slash_64() {
let gate = IpGate::new(1 << 12, 1);
let a: IpAddr = "2001:db8:1:2::1".parse().unwrap();
let b: IpAddr = "2001:db8:1:2:ffff::9".parse().unwrap();
let _p = gate.acquire(a).unwrap();
assert!(gate.acquire(b).is_none(), "same /64");
}
#[test]
fn a_rate_table_allows_a_burst_then_the_rate() {
let mut t = RateTable::new(256, 10, 3);
let ip: IpAddr = "203.0.113.9".parse().unwrap();
let t0 = std::time::Instant::now();
assert!(t.allow(ip, t0) && t.allow(ip, t0) && t.allow(ip, t0));
assert!(!t.allow(ip, t0));
assert!(t.allow(ip, t0 + std::time::Duration::from_millis(150)));
}
}
+317
View File
@@ -0,0 +1,317 @@
//! Reading the server name from a TLS ClientHello, without terminating TLS.
//!
//! The first record of a TLS connection is unencrypted. The router reads
//! it, takes the server name, and forwards the bytes untouched. The
//! parser works on a byte slice, never allocates beyond the name it
//! returns, and treats every length as hostile.
//!
//! ```text
//! GOAL: find the server name in the first TLS record, or say it is not
//! there, on any bytes a stranger can send, without panicking and
//! without reading past what was given.
//! SOURCE: WB-relay-1 (the router), RFC 8446 section 4.1.2 and RFC 6066
//! section 3 (the record and the server_name extension).
//! INVARIANTS:
//! 1. `record_len` and `server_name` never panic and never read beyond
//! the slice, whatever the bytes.
//! 2. A name is returned only from a well-formed server_name extension
//! of a complete ClientHello that fits one record, and only when it
//! is a plausible host name (ASCII letters, digits, `-`, `.`, `_`,
//! at most 253 bytes, no empty label).
//! 3. The record length is read from five bytes and is at most 16 384,
//! so a caller never holds more than 16 389 bytes for the hello.
//! SCENARIOS:
//! 1. A real rustls ClientHello for `a.example` gives `a.example`.
//! 2. A hello with no server_name, a truncated hello, an SSLv2 hello
//! and random bytes give an error, not a name.
//! ```
/// The most a TLS record may carry (RFC 8446 section 5.1).
pub const MAX_RECORD: usize = 16 * 1024;
/// A record's header: type, version, length.
pub const RECORD_HEADER: usize = 5;
/// Why the first bytes are not a hello with a name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum HelloError {
/// Not a TLS handshake record, or one longer than TLS allows.
#[error("not a TLS handshake record")]
NotTls,
/// The record is well formed but has no usable server name.
#[error("no server name")]
NoName,
/// The bytes are not a well-formed ClientHello.
#[error("malformed ClientHello")]
Malformed,
}
/// From the first five bytes: how many more bytes the record has.
///
/// Refuses anything that is not a handshake record of a TLS version
/// 1.0 to 1.3, or longer than a TLS record may be.
pub fn record_len(header: &[u8]) -> Result<usize, HelloError> {
let [kind, major, minor, hi, lo] = *header
.first_chunk::<RECORD_HEADER>()
.ok_or(HelloError::NotTls)?;
if kind != 0x16 || major != 3 || minor > 4 {
return Err(HelloError::NotTls);
}
let len = usize::from(u16::from_be_bytes([hi, lo]));
if len == 0 || len > MAX_RECORD {
return Err(HelloError::NotTls);
}
Ok(len)
}
/// A cursor over a slice that refuses to read past its end.
struct Cur<'a>(&'a [u8]);
impl<'a> Cur<'a> {
fn take(&mut self, n: usize) -> Result<&'a [u8], HelloError> {
let (head, rest) = self.0.split_at_checked(n).ok_or(HelloError::Malformed)?;
self.0 = rest;
Ok(head)
}
fn u8(&mut self) -> Result<u8, HelloError> {
Ok(self.take(1)?[0])
}
fn u16(&mut self) -> Result<usize, HelloError> {
let b = self.take(2)?;
Ok(usize::from(u16::from_be_bytes([b[0], b[1]])))
}
fn u24(&mut self) -> Result<usize, HelloError> {
let b = self.take(3)?;
Ok((usize::from(b[0]) << 16) | (usize::from(b[1]) << 8) | usize::from(b[2]))
}
fn vec8(&mut self) -> Result<&'a [u8], HelloError> {
let n = usize::from(self.u8()?);
self.take(n)
}
fn vec16(&mut self) -> Result<&'a [u8], HelloError> {
let n = self.u16()?;
self.take(n)
}
}
/// The server name in a complete first record (header and body), lower
/// case and without a trailing dot.
///
/// The record must hold the whole ClientHello: a hello split over several
/// records is refused (`Malformed`), as no client sends one in practice
/// and holding several records would let a stranger make us hold more.
pub fn server_name(record: &[u8]) -> Result<String, HelloError> {
let len = record_len(record)?;
let body = record
.get(RECORD_HEADER..RECORD_HEADER + len)
.ok_or(HelloError::Malformed)?;
let mut hs = Cur(body);
if hs.u8()? != 0x01 {
return Err(HelloError::Malformed); // not a ClientHello
}
let hello_len = hs.u24()?;
let mut hello = Cur(hs.take(hello_len)?);
hello.take(2)?; // client_version
hello.take(32)?; // random
hello.vec8()?; // session_id
hello.vec16()?; // cipher_suites
hello.vec8()?; // compression_methods
if hello.0.is_empty() {
return Err(HelloError::NoName); // a hello with no extensions
}
let mut exts = Cur(hello.vec16()?);
let mut found: Option<String> = None;
while !exts.0.is_empty() {
let kind = exts.u16()?;
let data = exts.vec16()?;
if kind == 0 {
if found.is_some() {
return Err(HelloError::Malformed); // two server_name extensions
}
found = Some(parse_server_name_ext(data)?);
}
}
found.ok_or(HelloError::NoName)
}
fn parse_server_name_ext(data: &[u8]) -> Result<String, HelloError> {
let mut ext = Cur(data);
let mut list = Cur(ext.vec16()?);
if !ext.0.is_empty() {
return Err(HelloError::Malformed);
}
let mut host: Option<&[u8]> = None;
while !list.0.is_empty() {
let name_type = list.u8()?;
let name = list.vec16()?;
if name_type == 0 {
if host.is_some() {
return Err(HelloError::Malformed);
}
host = Some(name);
}
}
let host = host.ok_or(HelloError::NoName)?;
plausible_host(host)
}
/// A host name the router can look at: ASCII, at most 253 bytes, labels
/// of 1 to 63 bytes from letters, digits, `-` and `_`; lowered, and the
/// trailing dot dropped. An IP address is a host name that will not match
/// any app, which is the right answer.
fn plausible_host(raw: &[u8]) -> Result<String, HelloError> {
let text = std::str::from_utf8(raw).map_err(|_| HelloError::Malformed)?;
let text = text.strip_suffix('.').unwrap_or(text);
if text.is_empty() || text.len() > 253 {
return Err(HelloError::NoName);
}
for label in text.split('.') {
if label.is_empty()
|| label.len() > 63
|| !label
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
{
return Err(HelloError::NoName);
}
}
Ok(text.to_ascii_lowercase())
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
/// A ClientHello record built by hand, with the given extensions.
pub(crate) fn hello_record(exts: &[(u16, Vec<u8>)]) -> Vec<u8> {
let mut ext_bytes = Vec::new();
for (kind, data) in exts {
ext_bytes.extend(kind.to_be_bytes());
ext_bytes.extend(u16::try_from(data.len()).unwrap().to_be_bytes());
ext_bytes.extend(data);
}
let mut hello = vec![3, 3];
hello.extend([7u8; 32]);
hello.push(0); // session id
hello.extend([0, 2, 0x13, 0x01]); // one cipher suite
hello.extend([1, 0]); // null compression
hello.extend(u16::try_from(ext_bytes.len()).unwrap().to_be_bytes());
hello.extend(ext_bytes);
let mut hs = vec![1];
hs.extend(&u32::try_from(hello.len()).unwrap().to_be_bytes()[1..]);
hs.extend(hello);
let mut rec = vec![0x16, 3, 1];
rec.extend(u16::try_from(hs.len()).unwrap().to_be_bytes());
rec.extend(hs);
rec
}
pub(crate) fn sni_ext(host: &str) -> (u16, Vec<u8>) {
let mut entry = vec![0];
entry.extend(u16::try_from(host.len()).unwrap().to_be_bytes());
entry.extend(host.as_bytes());
let mut data = u16::try_from(entry.len()).unwrap().to_be_bytes().to_vec();
data.extend(entry);
(0, data)
}
#[test]
fn a_hand_built_hello_gives_its_name_lowered() {
let rec = hello_record(&[(43, vec![2, 3, 4]), sni_ext("A.Example.")]);
assert_eq!(server_name(&rec).as_deref(), Ok("a.example"));
}
#[test]
fn no_name_no_extensions_and_odd_names_are_refused() {
assert_eq!(server_name(&hello_record(&[])), Err(HelloError::NoName));
assert_eq!(
server_name(&hello_record(&[(43, vec![2, 3, 4])])),
Err(HelloError::NoName)
);
for bad in ["", "a..b", "a b", "ex\u{e9}.com", &"a".repeat(64)] {
assert!(
server_name(&hello_record(&[sni_ext(bad)])).is_err(),
"{bad:?}"
);
}
let long = format!(
"{}.{}.{}.{}",
"a".repeat(63),
"b".repeat(63),
"c".repeat(63),
"d".repeat(63)
);
assert!(server_name(&hello_record(&[sni_ext(&long)])).is_err());
// Two server_name extensions are ambiguous: refused.
assert_eq!(
server_name(&hello_record(&[sni_ext("a.example"), sni_ext("b.example")])),
Err(HelloError::Malformed)
);
}
#[test]
fn not_tls_and_cut_off_bytes_are_refused() {
assert_eq!(record_len(b""), Err(HelloError::NotTls));
assert_eq!(record_len(b"GET /"), Err(HelloError::NotTls));
assert_eq!(record_len(&[0x16, 3, 1, 0, 0]), Err(HelloError::NotTls));
assert_eq!(record_len(&[0x16, 3, 1, 0x40, 1]), Err(HelloError::NotTls));
assert_eq!(record_len(&[0x16, 3, 1, 0x40, 0]), Ok(16384));
// SSLv2-style hello.
assert_eq!(record_len(&[0x80, 0x2e, 1, 0, 2]), Err(HelloError::NotTls));
let rec = hello_record(&[sni_ext("a.example")]);
for cut in 0..rec.len() {
assert!(server_name(&rec[..cut]).is_err(), "cut at {cut}");
}
// A handshake that is not a ClientHello.
let mut other = rec.clone();
other[5] = 2;
assert_eq!(server_name(&other), Err(HelloError::Malformed));
}
#[test]
fn a_real_rustls_hello_gives_its_name() {
use std::io::Write;
let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider());
let config = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(rustls::RootCertStore::empty())
.with_no_client_auth();
let name = rustls::pki_types::ServerName::try_from("real.example").unwrap();
let mut conn = rustls::ClientConnection::new(std::sync::Arc::new(config), name).unwrap();
let mut out = Vec::new();
conn.write_tls(&mut out).unwrap();
out.flush().unwrap();
assert_eq!(server_name(&out).as_deref(), Ok("real.example"));
assert_eq!(record_len(&out[..5]).unwrap(), out.len() - 5);
}
proptest::proptest! {
#![proptest_config(proptest::prelude::ProptestConfig::with_cases(4000))]
/// Invariant 1: random bytes never panic.
#[test]
fn random_bytes_never_panic(bytes in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..600)) {
let _ = record_len(&bytes);
let _ = server_name(&bytes);
}
/// Invariant 1 again, on bytes that look like a hello: a valid
/// one with a few bytes flipped, or cut anywhere.
#[test]
fn a_mutated_hello_never_panics(
flips in proptest::collection::vec((0usize..400, proptest::prelude::any::<u8>()), 0..8),
cut in 0usize..400,
) {
let mut rec = hello_record(&[(43, vec![2, 3, 4]), sni_ext("a.example")]);
for (at, to) in flips {
if let Some(b) = rec.get_mut(at) { *b = to; }
}
rec.truncate(cut.max(1));
if let Ok(name) = server_name(&rec) {
// Whatever came out is a plausible host name.
proptest::prop_assert!(!name.is_empty() && name.len() <= 253);
proptest::prop_assert!(name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'.' || b == b'_'));
}
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//! The relay for `wanderbooks.link`.
//!
//! A person runs the Wanderbooks desktop app at home. Web assistants can
//! only call servers on the public internet. The app dials out to this
//! relay and holds one multiplexed line open; the relay routes an
//! assistant's incoming TLS connection, by its server name, down that
//! line to the app. The relay never holds the app's private key and
//! cannot read the traffic: it forwards encrypted bytes. It is also the
//! domain's authoritative DNS server, which lets an app prove its own
//! name to a certificate authority and no other.
//!
//! The crate depends on no `ledger-*` crate. The modules [`proto`],
//! [`names`] and [`client`] are the app's side of the protocol too.
//!
//! ```text
//! GOAL: let a web assistant reach an app behind a home network, with
//! the relay unable to read anything, unable to be made to hold
//! unbounded memory, and unable to give a stranger an app's name
//! or a certificate for it.
//! SOURCE: WB-relay-1 (the router), WB-relay-2 (the line and its proof),
//! WB-relay-3 (names), WB-relay-4 (the registry), WB-relay-5
//! (proof records, DNS and authorities), WB-relay-6 (the
//! caller's address), WB-relay-7 (bounds); D-80, D-82, D-85, D-87.
//! INVARIANTS:
//! 1. No unsafe code anywhere in the crate.
//! 2. The relay holds no key or certificate for any app and never
//! decrypts an app's traffic.
//! 3. The only durable state is the registry (name, key, created,
//! blocked); proof records live minutes, in memory.
//! SCENARIOS:
//! 1. See `tests/relay.rs`: a real TLS client reaches a real TLS
//! server through the relay, and the relay never sees plaintext.
//! ```
#![forbid(unsafe_code)]
pub mod authorities;
pub mod client;
pub mod config;
pub mod dns;
pub mod front;
pub mod gate;
pub mod hello;
pub mod mux;
pub mod names;
pub mod proto;
pub mod registry;
pub mod server;
pub mod splice;
pub mod tls;
pub mod txt;
pub use config::{Config, Limits};
pub use server::Relay;
+104
View File
@@ -0,0 +1,104 @@
//! `wanderbooks-relay`: run the relay from a configuration file.
//!
//! ```text
//! wanderbooks-relay <config.toml>
//! wanderbooks-relay <config.toml> block <four-word-name>
//! wanderbooks-relay <config.toml> unblock <four-word-name>
//! ```
use std::process::ExitCode;
use std::sync::atomic::Ordering;
use std::time::Duration;
use relay::authorities::AuthorityList;
use relay::names::Name;
use relay::registry::Registry;
use relay::{Config, Relay, tls};
fn fail(msg: &str) -> ExitCode {
eprintln!("wanderbooks-relay: {msg}");
ExitCode::FAILURE
}
#[tokio::main]
async fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let Some(path) = args.first() else {
return fail("usage: wanderbooks-relay <config.toml> [block|unblock <name>]");
};
let text = match std::fs::read_to_string(path) {
Ok(t) => t,
Err(e) => return fail(&format!("{path}: {e}")),
};
let cfg = match Config::from_toml(&text) {
Ok(c) => c,
Err(e) => return fail(&format!("{path}: {e}")),
};
let words: Vec<&str> = args.iter().map(String::as_str).collect();
if let [_, verb @ ("block" | "unblock"), name] = words.as_slice() {
let Ok(name) = Name::parse(name) else {
return fail("a name is four words from the list, joined by hyphens");
};
let registry = match Registry::open(&cfg.registry_path, 4) {
Ok(r) => r,
Err(e) => return fail(&e.to_string()),
};
return match registry.set_blocked(&name, *verb == "block").await {
Ok(true) => {
println!("{verb}ed {name}");
ExitCode::SUCCESS
}
Ok(false) => fail("no such name"),
Err(e) => fail(&e.to_string()),
};
}
if args.len() != 1 {
return fail("usage: wanderbooks-relay <config.toml> [block|unblock <name>]");
}
let tls = match tls::server_config_from_files(&cfg.tls_cert, &cfg.tls_key) {
Ok(t) => t,
Err(e) => return fail(&e),
};
let authorities = match &cfg.authorities_path {
Some(p) => match AuthorityList::from_file(p.clone()) {
Ok(l) => l,
Err(e) => return fail(&e.to_string()),
},
None => AuthorityList::empty(),
};
let relay = match Relay::start(cfg, tls, authorities).await {
Ok(r) => r,
Err(e) => return fail(&format!("could not start: {e}")),
};
eprintln!(
"wanderbooks-relay: router on {}, DNS on {} (udp) and {} (tcp)",
relay.router_addr(),
relay.dns_udp_addr(),
relay.dns_tcp_addr()
);
let shared = relay.shared().clone();
let stats = tokio::spawn(async move {
let mut tick = tokio::time::interval(Duration::from_secs(60));
loop {
tick.tick().await;
let m = &shared.metrics;
eprintln!(
"lines {} routed {} unknown_or_offline {} shed {} hello_timeouts {} bad_hello {} claims {}",
m.lines_up.load(Ordering::Relaxed),
m.routed.load(Ordering::Relaxed),
m.unknown_or_offline.load(Ordering::Relaxed),
m.shed.load(Ordering::Relaxed),
m.hello_timeouts.load(Ordering::Relaxed),
m.bad_hello.load(Ordering::Relaxed),
m.claims.load(Ordering::Relaxed),
);
}
});
let _ = tokio::signal::ctrl_c().await;
eprintln!("wanderbooks-relay: shutting down");
stats.abort();
relay.shutdown().await;
ExitCode::SUCCESS
}
+350
View File
@@ -0,0 +1,350 @@
//! One multiplexed line: streams in both directions over one connection.
//!
//! A line is a yamux connection over the app's TLS. One task drives it:
//! it answers the peer's frames, accepts the streams the peer opens, and
//! opens streams on request. Opening is by a bounded request queue, so a
//! caller who wants a stream waits its turn and cannot make the line hold
//! more than a request at a time.
//!
//! ```text
//! GOAL: many assistant connections ride one line, with the number of
//! streams, the bytes buffered per stream and the time a silent
//! line may live all capped, and a line that is closed or dropped
//! stops its task.
//! SOURCE: WB-relay-7 (bounds), the yamux specification.
//! INVARIANTS:
//! 1. At most `max_streams` streams exist on a line, in both
//! directions together. A line asked for one more, from either
//! side, is ended (that is yamux's rule), so the relay keeps its
//! own per-line permits below the limit.
//! 2. Each stream's receive window is 256 KiB and a line's windows sum
//! to at most 256 KiB times `max_streams`: no window grows.
//! 3. A line from which nothing was read for `idle` is closed.
//! 4. Dropping every handle, or `close`, ends the driver.
//! SCENARIOS:
//! 1. Streams opened on one side arrive on the other.
//! 2. With `max_streams` open, one more open does not succeed.
//! 3. A line with a silent peer is closed after `idle`.
//! ```
use std::future::poll_fn;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio::time::Instant;
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
use tokio_util::sync::CancellationToken;
use yamux::{Config, Connection, Mode};
use crate::front::Activity;
/// A stream on a line, as tokio's `AsyncRead` and `AsyncWrite`.
pub type Stream = Compat<yamux::Stream>;
/// Why a stream could not be opened.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum MuxError {
/// The line is closed.
#[error("the line is closed")]
Closed,
/// Waited too long.
#[error("timed out opening a stream")]
Timeout,
/// The line refused (too many streams, or the peer is gone).
#[error("the line refused the stream")]
Refused,
}
type Open = oneshot::Sender<Result<Stream, MuxError>>;
/// A handle for opening streams on a line. Clones share the line.
#[derive(Clone)]
pub struct Mux {
cmd: mpsc::Sender<Open>,
cancel: CancellationToken,
}
/// What a line is allowed.
#[derive(Debug, Clone, Copy)]
pub struct MuxLimits {
/// Streams at once, both directions together.
pub max_streams: usize,
/// A line from which nothing was read for this long is closed.
pub idle: Duration,
}
fn yamux_config(max_streams: usize) -> Config {
let mut cfg = Config::default();
cfg.set_max_num_streams(max_streams);
// 256 KiB is yamux's initial window per stream. Capping the sum at
// 256 KiB times the stream limit stops the auto-tuning from growing
// any window: this is the most a line can ever hold in receive
// buffers.
cfg.set_max_connection_receive_window(Some(max_streams * yamux::DEFAULT_CREDIT as usize));
cfg
}
impl Mux {
/// Open a stream, waiting at most `wait` for the line to take the
/// request and for the peer to accept it.
pub async fn open(&self, wait: Duration) -> Result<Stream, MuxError> {
let (reply, answer) = oneshot::channel();
let deadline = Instant::now() + wait;
match tokio::time::timeout_at(deadline, self.cmd.send(reply)).await {
Err(_) => return Err(MuxError::Timeout),
Ok(Err(_)) => return Err(MuxError::Closed),
Ok(Ok(())) => {}
}
match tokio::time::timeout_at(deadline, answer).await {
Err(_) => Err(MuxError::Timeout),
Ok(Err(_)) => Err(MuxError::Closed),
Ok(Ok(r)) => r,
}
}
/// Close the line.
pub fn close(&self) {
self.cancel.cancel();
}
/// True once the line is closed or its driver has ended.
pub fn is_closed(&self) -> bool {
self.cancel.is_cancelled() || self.cmd.is_closed()
}
}
enum Event {
Inbound(Stream),
Ended,
}
fn step<T>(
conn: &mut Connection<T>,
cmds: &mut mpsc::Receiver<Open>,
pending: &mut Option<Open>,
cx: &mut Context<'_>,
) -> Poll<Event>
where
T: futures::AsyncRead + futures::AsyncWrite + Unpin,
{
// The connection makes progress only when polled for inbound streams,
// so that always comes first.
match conn.poll_next_inbound(cx) {
Poll::Ready(Some(Ok(s))) => return Poll::Ready(Event::Inbound(s.compat())),
Poll::Ready(Some(Err(_)) | None) => return Poll::Ready(Event::Ended),
Poll::Pending => {}
}
loop {
if pending.is_none() {
match cmds.poll_recv(cx) {
Poll::Ready(Some(open)) => *pending = Some(open),
Poll::Ready(None) => return Poll::Ready(Event::Ended),
Poll::Pending => return Poll::Pending,
}
}
if pending.as_ref().is_some_and(|p| p.is_closed()) {
*pending = None; // the asker gave up: do not open for nobody
continue;
}
match conn.poll_new_outbound(cx) {
Poll::Ready(Ok(s)) => {
if let Some(p) = pending.take() {
let _ = p.send(Ok(s.compat()));
}
// Opening queued a frame; only polling for inbound frames
// sends it, so come round again at once.
cx.waker().wake_by_ref();
return Poll::Pending;
}
Poll::Ready(Err(yamux::ConnectionError::TooManyStreams)) => {
if let Some(p) = pending.take() {
let _ = p.send(Err(MuxError::Refused));
}
}
Poll::Ready(Err(_)) => return Poll::Ready(Event::Ended),
Poll::Pending => return Poll::Pending,
}
}
}
/// Start driving a line. `on_inbound` is called, inline and without
/// blocking, with each stream the peer opens; it must spawn or drop.
pub fn spawn<T>(
socket: T,
mode: Mode,
limits: MuxLimits,
activity: Option<Arc<Activity>>,
mut on_inbound: impl FnMut(Stream) + Send + 'static,
) -> (Mux, JoinHandle<()>)
where
T: futures::AsyncRead + futures::AsyncWrite + Unpin + Send + 'static,
{
let (cmd, mut cmds) = mpsc::channel::<Open>(4);
let cancel = CancellationToken::new();
let mux = Mux {
cmd,
cancel: cancel.clone(),
};
let mut conn = Connection::new(socket, yamux_config(limits.max_streams), mode);
let task = tokio::spawn(async move {
let mut pending: Option<Open> = None;
let idle = limits.idle;
let timer = tokio::time::sleep(idle);
tokio::pin!(timer);
loop {
tokio::select! {
() = cancel.cancelled() => break,
() = &mut timer => {
let quiet = activity.as_ref().map_or(Duration::ZERO, |a| a.since());
if quiet >= idle {
break;
}
timer.as_mut().reset(Instant::now() + (idle - quiet));
}
event = poll_fn(|cx| step(&mut conn, &mut cmds, &mut pending, cx)) => match event {
Event::Inbound(stream) => on_inbound(stream),
Event::Ended => break,
},
}
}
cancel.cancel();
// Refuse anyone still waiting, then close the connection politely
// but briefly.
if let Some(p) = pending.take() {
let _ = p.send(Err(MuxError::Closed));
}
cmds.close();
let _ =
tokio::time::timeout(Duration::from_secs(2), poll_fn(|cx| conn.poll_close(cx))).await;
});
(mux, task)
}
#[cfg(test)]
mod tests {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_util::compat::TokioAsyncReadCompatExt;
use super::*;
fn pair(
max: usize,
idle: Duration,
on_server_inbound: impl FnMut(Stream) + Send + 'static,
) -> (Mux, Mux, mpsc::UnboundedReceiver<Stream>) {
let (a, b) = tokio::io::duplex(64 * 1024);
let limits = MuxLimits {
max_streams: max,
idle,
};
let (tx, rx) = mpsc::unbounded_channel();
let (server, _) = spawn(a.compat(), Mode::Server, limits, None, on_server_inbound);
let (client, _) = spawn(b.compat(), Mode::Client, limits, None, move |s| {
let _ = tx.send(s);
});
(server, client, rx)
}
#[tokio::test]
async fn a_stream_opened_by_one_side_arrives_on_the_other() {
let (server, _client, mut rx) = pair(8, Duration::from_secs(60), |_| {});
let mut s = server.open(Duration::from_secs(2)).await.unwrap();
s.write_all(b"ping").await.unwrap();
s.flush().await.unwrap();
let mut got = rx.recv().await.unwrap();
let mut buf = [0u8; 4];
got.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"ping");
got.write_all(b"pong").await.unwrap();
got.flush().await.unwrap();
s.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"pong");
}
#[tokio::test]
async fn a_line_holds_only_its_streams() {
let (server, _client, mut rx) = pair(2, Duration::from_secs(60), |_| {});
let mut held = Vec::new();
for _ in 0..2 {
let mut s = server.open(Duration::from_secs(2)).await.unwrap();
s.write_all(b"x").await.unwrap();
s.flush().await.unwrap();
held.push(s);
held.push(rx.recv().await.unwrap()); // keep the far end open too
}
let third = server.open(Duration::from_millis(500)).await;
assert!(third.is_err(), "a third stream was opened past the limit");
}
#[tokio::test]
async fn a_silent_line_is_closed_after_its_idle_time() {
let (a, b) = tokio::io::duplex(1024);
let activity = Activity::new();
let limits = MuxLimits {
max_streams: 2,
idle: Duration::from_millis(150),
};
let (mux, task) = spawn(a.compat(), Mode::Server, limits, Some(activity), |_| {});
let _keep = b; // the peer is there and says nothing
tokio::time::timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert!(mux.is_closed());
assert_eq!(
mux.open(Duration::from_millis(100)).await.err(),
Some(MuxError::Closed)
);
}
#[tokio::test]
async fn closing_ends_the_driver() {
let (server, client, _rx) = pair(2, Duration::from_secs(60), |_| {});
server.close();
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(server.is_closed());
assert!(client.open(Duration::from_secs(2)).await.is_err() || client.is_closed());
}
#[tokio::test]
async fn a_large_transfer_both_ways_completes() {
let (server, _client, mut rx) = pair(8, Duration::from_secs(60), |_| {});
let mut near = server.open(Duration::from_secs(2)).await.unwrap();
near.write_all(b"x").await.unwrap();
near.flush().await.unwrap();
let mut far = rx.recv().await.unwrap();
let mut one = [0u8; 1];
far.read_exact(&mut one).await.unwrap();
let echo = tokio::spawn(async move {
let mut buf = [0u8; 4096];
loop {
let n = far.read(&mut buf).await.unwrap();
if n == 0 {
far.shutdown().await.unwrap();
return;
}
far.write_all(&buf[..n]).await.unwrap();
}
});
let (mut rd, mut wr) = tokio::io::split(near);
let data = vec![9u8; 2_000_000];
let send = tokio::spawn({
let data = data.clone();
async move {
wr.write_all(&data).await.unwrap();
wr.shutdown().await.unwrap();
}
});
let mut got = Vec::new();
tokio::time::timeout(Duration::from_secs(20), rd.read_to_end(&mut got))
.await
.expect("the echo completes")
.unwrap();
assert_eq!(got.len(), data.len());
send.await.unwrap();
echo.await.unwrap();
}
}
+308
View File
@@ -0,0 +1,308 @@
//! Names: four words from the curated list, and the address they make.
//!
//! An app's public name is four words from `words.txt` joined by hyphens
//! (`ledger-accrual-tally-mint`). Its endpoint is a long random label
//! beneath it (`<secret>.<four-words>.wanderbooks.link`). The relay routes
//! on the four words and checks only that the secret label has the right
//! shape; the app, which made the label, is the one that checks its value.
//!
//! ```text
//! GOAL: an app's public name is four words from a curated finance and
//! accounting list, never a word a customer would not want in an
//! address; the relay accepts no other name, so no stranger can
//! claim `relay`, `ns1`, `_acme-challenge` or anything else that
//! is not four listed words.
//! SOURCE: WB-relay-3 (names), D-82 in plan/p15-app-and-relay.md.
//! INVARIANTS:
//! 1. A `Name` is four indices into the list, so a name that exists is
//! four listed words: there is no way to hold any other.
//! 2. Parsing is exact: `Name::parse(&name.to_string()) == name`, and
//! any string that is not four listed words, hyphen-joined in
//! lower case, is refused.
//! 3. A host name is routed only as `<secret>.<name>.<domain>`; the
//! domain's apex, the relay's own host and every other shape are
//! not an app's.
//! SCENARIOS:
//! 1. `ledger-accrual-tally-mint` parses, and prints as itself.
//! 2. `ledger-accrual-tally` (three words) and `ledger-accrual-tally-zzzz`
//! (an unlisted word) are refused.
//! 3. `<secret>.ledger-accrual-tally-mint.wanderbooks.link` is that
//! app's; `relay.wanderbooks.link` is the relay's own host.
//! ```
use std::fmt;
use std::sync::OnceLock;
use ring::rand::{SecureRandom, SystemRandom};
const WORDS_TXT: &str = include_str!("../words.txt");
/// The curated list: one lower-case word per line, sorted, no duplicates.
/// The words are for recognition, so they are finance and accounting
/// terms and pleasant plain words, and none a customer would not want in
/// an address (the list's tests refuse a set of unwelcome words).
pub fn words() -> &'static [&'static str] {
static WORDS: OnceLock<Vec<&'static str>> = OnceLock::new();
WORDS.get_or_init(|| WORDS_TXT.lines().filter(|l| !l.is_empty()).collect())
}
/// How many bits of choice four words from the list make.
pub fn name_bits() -> f64 {
// The list is a few thousand words at most, far inside f64's exact range.
4.0 * (words().len() as f64).log2()
}
/// Why a name or host was refused.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum NameError {
/// Not exactly four hyphen-joined words.
#[error("a name is four words joined by hyphens")]
Shape,
/// A word that is not on the list.
#[error("a word that is not on the list")]
UnknownWord,
}
/// An app's public name: four words from the list, held as their indices.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Name([u16; 4]);
impl Name {
/// Parse `a-b-c-d`: four listed words, lower case, hyphen-joined.
pub fn parse(text: &str) -> Result<Self, NameError> {
let list = words();
let mut idx = [0u16; 4];
let mut parts = text.split('-');
for slot in &mut idx {
let word = parts.next().ok_or(NameError::Shape)?;
let at = list
.binary_search(&word)
.map_err(|_| NameError::UnknownWord)?;
*slot = u16::try_from(at).map_err(|_| NameError::Shape)?;
}
if parts.next().is_some() {
return Err(NameError::Shape);
}
Ok(Name(idx))
}
/// A uniformly random name (rejection sampling, no modulo bias).
pub fn random() -> Self {
let rng = SystemRandom::new();
// Words are fewer than 65 536, so an index fits in a `u16` and the
// largest multiple of the list's length below 2^16 is the cut.
let n = u32::try_from(words().len()).unwrap_or(u32::MAX);
let limit = (0x1_0000 / n) * n;
let mut idx = [0u16; 4];
for slot in &mut idx {
loop {
let mut b = [0u8; 2];
if rng.fill(&mut b).is_err() {
// The system generator failing is not recoverable.
panic!("the system random number generator failed");
}
let v = u32::from(u16::from_be_bytes(b));
if v < limit {
*slot = u16::try_from(v % n).unwrap_or(0);
break;
}
}
}
Name(idx)
}
/// The four words.
pub fn words(&self) -> [&'static str; 4] {
let list = words();
self.0
.map(|i| list.get(usize::from(i)).copied().unwrap_or(""))
}
}
impl fmt::Display for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let w = self.words();
write!(f, "{}-{}-{}-{}", w[0], w[1], w[2], w[3])
}
}
impl fmt::Debug for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Name({self})")
}
}
/// The shortest and longest secret label the relay will route. The app
/// makes the label; the relay checks only its shape.
pub const SECRET_LEN: std::ops::RangeInclusive<usize> = 16..=63;
/// What a host name (a TLS server name or a DNS name) is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HostKind {
/// The relay's own host: an app's line dials it.
Relay,
/// An assistant reaching the app of this name.
App(Name),
/// Anything else.
Other,
}
/// Which of the relay's own host names is the line's, and the domain.
#[derive(Debug, Clone)]
pub struct Zone {
domain: String,
relay_host: String,
}
impl Zone {
/// `domain` is `wanderbooks.link`, `relay_host` is
/// `relay.wanderbooks.link`; both are lowered and unrooted.
pub fn new(domain: &str, relay_host: &str) -> Self {
Zone {
domain: normalize(domain),
relay_host: normalize(relay_host),
}
}
/// The domain this relay serves.
pub fn domain(&self) -> &str {
&self.domain
}
/// Classify a host name from a ClientHello.
pub fn classify(&self, host: &str) -> HostKind {
let host = normalize(host);
if host == self.relay_host {
return HostKind::Relay;
}
let Some(front) = host
.strip_suffix(&self.domain)
.and_then(|f| f.strip_suffix('.'))
else {
return HostKind::Other;
};
let mut labels = front.split('.');
let (Some(secret), Some(name), None) = (labels.next(), labels.next(), labels.next()) else {
return HostKind::Other;
};
if !SECRET_LEN.contains(&secret.len())
|| !secret
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
{
return HostKind::Other;
}
match Name::parse(name) {
Ok(n) => HostKind::App(n),
Err(_) => HostKind::Other,
}
}
/// The part of a DNS name below the zone, as labels from the left, or
/// `None` when the name is outside the zone. The apex gives no labels.
pub fn below<'a>(&self, host: &'a str) -> Option<Vec<&'a str>> {
let host = host.strip_suffix('.').unwrap_or(host);
if host.eq_ignore_ascii_case(&self.domain) {
return Some(Vec::new());
}
let cut = host.len().checked_sub(self.domain.len() + 1)?;
let (front, rest) = host.split_at_checked(cut)?;
let rest = rest.strip_prefix('.')?;
if !rest.eq_ignore_ascii_case(&self.domain) {
return None;
}
Some(front.split('.').collect())
}
}
fn normalize(host: &str) -> String {
host.trim_end_matches('.').to_ascii_lowercase()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_list_is_sorted_unique_plain_and_welcome() {
let list = words();
assert!(list.len() >= 1024, "{} words", list.len());
assert!(list.windows(2).all(|w| w[0] < w[1]), "sorted, no repeats");
for w in list {
assert!(
(3..=11).contains(&w.len()) && w.bytes().all(|b| b.is_ascii_lowercase()),
"{w}"
);
}
// Words a customer would not want in an address.
for bad in [
"ass", "sex", "gay", "nig", "fuck", "shit", "damn", "hell", "death", "dead", "kill",
"war", "gun", "bomb", "poor", "debt", "fail", "bust", "scam", "fraud", "loss", "lose",
"owe", "deficit", "default", "bankrupt", "arrears", "penalty", "fine", "cancer",
"porn", "rape", "nazi", "slave", "hate", "drug", "sin",
] {
assert!(list.binary_search(&bad).is_err(), "{bad} is on the list");
}
assert!(name_bits() > 40.0, "{} bits", name_bits());
}
#[test]
fn a_name_is_four_listed_words_and_prints_as_itself() {
let n = Name::parse("ledger-accrual-tally-mint").expect("listed words");
assert_eq!(n.to_string(), "ledger-accrual-tally-mint");
assert_eq!(Name::parse(&n.to_string()), Ok(n));
assert_eq!(Name::parse("ledger-accrual-tally"), Err(NameError::Shape));
assert_eq!(
Name::parse("ledger-accrual-tally-mint-mint"),
Err(NameError::Shape)
);
assert_eq!(
Name::parse("ledger-accrual-tally-zzzz"),
Err(NameError::UnknownWord)
);
assert_eq!(
Name::parse("Ledger-accrual-tally-mint"),
Err(NameError::UnknownWord)
);
for reserved in ["relay", "ns1", "_acme-challenge", "www", "", "-", "---"] {
assert!(Name::parse(reserved).is_err(), "{reserved}");
}
let r = Name::random();
assert_eq!(Name::parse(&r.to_string()), Ok(r));
}
#[test]
fn a_host_is_routed_only_as_secret_dot_name_dot_domain() {
let zone = Zone::new("wanderbooks.link", "relay.wanderbooks.link");
let secret = "k3j9x0q7m2z8c5v1b4n6a9s2d";
let name = Name::parse("ledger-accrual-tally-mint").unwrap();
let host = format!("{secret}.ledger-accrual-tally-mint.wanderbooks.link");
assert_eq!(zone.classify(&host), HostKind::App(name));
assert_eq!(zone.classify(&format!("{host}.")), HostKind::App(name));
assert_eq!(zone.classify(&host.to_uppercase()), HostKind::App(name));
assert_eq!(zone.classify("relay.wanderbooks.link"), HostKind::Relay);
for other in [
"ledger-accrual-tally-mint.wanderbooks.link",
"wanderbooks.link",
"short.ledger-accrual-tally-mint.wanderbooks.link",
"k3j9x0q7m2z8c5v1b4n6a9s2d.ledger-accrual-tally.wanderbooks.link",
"a.k3j9x0q7m2z8c5v1b4n6a9s2d.ledger-accrual-tally-mint.wanderbooks.link",
"k3j9x0q7m2z8c5v1b4n6a9s2d.ledger-accrual-tally-mint.example.com",
"K3J9X0Q7M2Z8C5V1B4N6A9S2D_.ledger-accrual-tally-mint.wanderbooks.link",
"xwanderbooks.link",
"",
] {
assert_eq!(zone.classify(other), HostKind::Other, "{other}");
}
}
#[test]
fn below_names_the_labels_under_the_zone() {
let zone = Zone::new("wanderbooks.link", "relay.wanderbooks.link");
assert_eq!(zone.below("wanderbooks.link."), Some(vec![]));
assert_eq!(zone.below("A.b.Wanderbooks.Link"), Some(vec!["A", "b"]));
assert_eq!(zone.below("xwanderbooks.link"), None);
assert_eq!(zone.below("example.com"), None);
assert_eq!(zone.below("link"), None);
}
}
+536
View File
@@ -0,0 +1,536 @@
//! The wire protocol between an app and the relay.
//!
//! Three things travel the app's line, all small and bounded:
//!
//! 1. The **handshake**, once, right after the line's TLS: the relay sends
//! a challenge; the app answers with its name, its public key and a
//! signature; the relay says yes, or why not.
//! 2. **Caller streams**, opened by the relay: the caller's address in a
//! PROXY protocol version 2 header, then the caller's own encrypted
//! bytes.
//! 3. **Control streams**, opened by the app: one request, one reply.
//!
//! ```text
//! GOAL: an app proves it holds the key for its name on every connection,
//! so that neither a stranger nor a replayed recording of an old
//! proof can take the name's line; and the app is told the caller's
//! real address in a form no caller can forge.
//! SOURCE: WB-relay-2 (the line and its proof), WB-relay-6 (the caller's
//! address); RFC 8032 (Ed25519), RFC 5705 and RFC 8446 section 7.5
//! (TLS exporters), the PROXY protocol specification version 2.
//! INVARIANTS:
//! 1. The proof signs the line's own TLS exporter value, a fresh 32-byte
//! nonce, the name and the claim flag: it is good for one TLS
//! session and no other, and no relay or stranger who sat in the
//! middle of another session can use it.
//! 2. Every frame is at most 2 048 bytes and every field has a length:
//! a stranger cannot make the relay read or hold more.
//! 3. The caller-address header is written by the relay before any
//! byte of the caller's, and parses only in its exact form.
//! SCENARIOS:
//! 1. A proof made for one session fails on another session's exporter,
//! on another nonce, with another name, and with the claim flag
//! flipped.
//! 2. A PROXY header for IPv4 and for IPv6 round-trips; a header with
//! trailing bytes, a wrong signature, or a wrong length is refused.
//! ```
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use ring::rand::SecureRandom;
use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey};
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use crate::names::Name;
/// The protocol version in every handshake message.
pub const VERSION: u8 = 1;
/// The most a handshake or control frame may carry.
pub const MAX_FRAME: usize = 2048;
/// The TLS exporter label the proof binds to.
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-wanderbooks-relay-line-v1";
const PROOF_CONTEXT: &[u8] = b"wanderbooks-relay/line/v1\0";
/// The relay's opening message on a new line.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Challenge {
/// Protocol version.
pub v: u8,
/// 32 fresh random bytes, hex.
pub nonce: String,
}
/// The app's answer: who it is, and the proof.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Hello {
/// Protocol version.
pub v: u8,
/// The four-word name.
pub name: String,
/// The Ed25519 public key (32 bytes), hex.
pub public_key: String,
/// True to claim the name if nobody has it. False to reconnect.
pub claim: bool,
/// The signature (64 bytes), hex, over [`proof_message`].
pub signature: String,
}
/// Why the relay turned a line away.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Refusal {
/// The name is already held by another key.
Taken,
/// A reconnect for a name nobody has claimed.
UnknownName,
/// The proof did not verify, or the key is not the name's.
BadProof,
/// The name is blocked by the operator.
Blocked,
/// The relay is busy; try again later.
Busy,
/// Too many new names, or too many tries, from here or in total.
RateLimited,
/// The message was malformed or of another version.
BadRequest,
}
/// The relay's verdict on a [`Hello`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Verdict {
/// True: the line is up.
pub ok: bool,
/// Why not, when not.
pub refusal: Option<Refusal>,
/// True when this connection claimed the name for the first time.
pub claimed: bool,
/// The most caller streams the relay will open on this line at once.
pub max_streams: u32,
}
/// What an app asks of the relay on a control stream. The name is never
/// in a request: it is the line's, proven at the handshake.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum Request {
/// A keep-alive; the reply shows the relay is there.
Ping,
/// Publish this ACME DNS-01 proof value at `_acme-challenge.<name>`.
PublishTxt {
/// The 43-character base64url value.
value: String,
},
/// Remove this app's proof records.
ClearTxt,
/// The certificate authorities to try, in order.
Authorities,
}
/// A certificate authority the app may try, and how to reach it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Authority {
/// A short stable id (`letsencrypt`).
pub id: String,
/// The ACME directory address (RFC 8555).
pub directory: String,
/// True when the authority requires an external account binding.
pub needs_binding: bool,
/// The binding credential for this app, when one is needed.
pub binding: Option<Binding>,
}
/// An external account binding credential (RFC 8555 section 7.3.4).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
/// The key identifier.
pub kid: String,
/// The HMAC key, base64url.
pub hmac_key: String,
}
/// The reply to a [`Request`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Response {
/// True when the request was done.
pub ok: bool,
/// A short reason when not.
pub error: Option<String>,
/// The list, for [`Request::Authorities`].
pub authorities: Option<Vec<Authority>>,
}
/// A frame could not be read or written.
#[derive(Debug, thiserror::Error)]
pub enum FrameError {
/// The peer closed, or the stream failed.
#[error("i/o: {0}")]
Io(#[from] std::io::Error),
/// The frame is longer than [`MAX_FRAME`].
#[error("frame too long")]
TooLong,
/// The frame is not the message it should be.
#[error("bad message: {0}")]
Bad(#[from] serde_json::Error),
}
/// Read one frame: a two-byte length (at most [`MAX_FRAME`]), then that
/// many bytes of JSON.
pub async fn read_frame<R, T>(r: &mut R) -> Result<T, FrameError>
where
R: AsyncRead + Unpin,
T: for<'de> Deserialize<'de>,
{
let mut len = [0u8; 2];
r.read_exact(&mut len).await?;
let len = usize::from(u16::from_be_bytes(len));
if len > MAX_FRAME {
return Err(FrameError::TooLong);
}
let mut buf = vec![0u8; len];
r.read_exact(&mut buf).await?;
Ok(serde_json::from_slice(&buf)?)
}
/// Write one frame.
pub async fn write_frame<W, T>(w: &mut W, msg: &T) -> Result<(), FrameError>
where
W: AsyncWrite + Unpin,
T: Serialize,
{
let body = serde_json::to_vec(msg)?;
if body.len() > MAX_FRAME {
return Err(FrameError::TooLong);
}
let mut out = Vec::with_capacity(2 + body.len());
out.extend(
u16::try_from(body.len())
.map_err(|_| FrameError::TooLong)?
.to_be_bytes(),
);
out.extend(body);
w.write_all(&out).await?;
w.flush().await?;
Ok(())
}
/// Lower-case hex.
pub fn hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for b in bytes {
out.push(char::from(DIGITS[usize::from(b >> 4)]));
out.push(char::from(DIGITS[usize::from(b & 15)]));
}
out
}
/// Decode exactly `N` bytes of hex, or `None`.
pub fn unhex<const N: usize>(text: &str) -> Option<[u8; N]> {
let bytes = text.as_bytes();
if bytes.len() != N * 2 {
return None;
}
let mut out = [0u8; N];
let (pairs, _) = bytes.as_chunks::<2>();
for (slot, [h, l]) in out.iter_mut().zip(pairs) {
let hi = char::from(*h).to_digit(16)?;
let lo = char::from(*l).to_digit(16)?;
*slot = u8::try_from(hi * 16 + lo).ok()?;
}
Some(out)
}
/// 32 random bytes.
pub fn random32() -> [u8; 32] {
let mut b = [0u8; 32];
if ring::rand::SystemRandom::new().fill(&mut b).is_err() {
// The system generator failing is not recoverable.
panic!("the system random number generator failed");
}
b
}
/// What the app signs: the context, this TLS session's exporter value,
/// the relay's nonce, the name and the claim flag.
pub fn proof_message(exporter: &[u8; 32], nonce: &[u8; 32], name: &Name, claim: bool) -> Vec<u8> {
let text = name.to_string();
let mut m = Vec::with_capacity(PROOF_CONTEXT.len() + 32 + 32 + 2 + text.len());
m.extend(PROOF_CONTEXT);
m.extend(exporter);
m.extend(nonce);
m.push(u8::from(claim));
// A name is under 255 bytes by construction (four words of at most 11).
m.push(u8::try_from(text.len()).unwrap_or(u8::MAX));
m.extend(text.as_bytes());
m
}
/// Verify an Ed25519 signature.
pub fn verify(public_key: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
UnparsedPublicKey::new(&ED25519, public_key)
.verify(message, signature)
.is_ok()
}
/// An app's own key: it owns the name.
pub struct AppKey(Ed25519KeyPair);
impl AppKey {
/// A new key, and its PKCS#8 encoding to keep.
pub fn generate() -> (Self, Vec<u8>) {
let rng = ring::rand::SystemRandom::new();
let Ok(doc) = Ed25519KeyPair::generate_pkcs8(&rng) else {
// The system generator failing is not recoverable.
panic!("the system random number generator failed");
};
let bytes = doc.as_ref().to_vec();
let key = Self::from_pkcs8(&bytes).unwrap_or_else(|| unreachable!("a fresh key parses"));
(key, bytes)
}
/// A key from its PKCS#8 encoding.
pub fn from_pkcs8(bytes: &[u8]) -> Option<Self> {
Ed25519KeyPair::from_pkcs8(bytes).ok().map(AppKey)
}
/// The public key, 32 bytes.
pub fn public_key(&self) -> [u8; 32] {
let mut out = [0u8; 32];
out.copy_from_slice(self.0.public_key().as_ref());
out
}
/// Sign.
pub fn sign(&self, message: &[u8]) -> [u8; 64] {
let mut out = [0u8; 64];
out.copy_from_slice(self.0.sign(message).as_ref());
out
}
}
const PP2_SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
/// The caller's address and the one it reached, as the relay saw them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Caller {
/// Who connected to the relay.
pub source: SocketAddr,
/// The relay address they connected to.
pub destination: SocketAddr,
}
/// An IPv4-mapped IPv6 address is the IPv4 address.
fn unmap(addr: SocketAddr) -> SocketAddr {
match addr {
SocketAddr::V6(v6) => match v6.ip().to_ipv4_mapped() {
Some(v4) => SocketAddr::new(IpAddr::V4(v4), v6.port()),
None => addr,
},
v4 => v4,
}
}
impl Caller {
/// The PROXY protocol version 2 header for this caller (28 bytes for
/// IPv4, 52 for IPv6), with no extensions.
pub fn encode(&self) -> Vec<u8> {
let (src, dst) = (unmap(self.source), unmap(self.destination));
let mut out = Vec::with_capacity(52);
out.extend(PP2_SIGNATURE);
out.push(0x21); // version 2, PROXY
match (src, dst) {
(SocketAddr::V4(s), SocketAddr::V4(d)) => {
out.push(0x11); // TCP over IPv4
out.extend(12u16.to_be_bytes());
out.extend(s.ip().octets());
out.extend(d.ip().octets());
out.extend(s.port().to_be_bytes());
out.extend(d.port().to_be_bytes());
}
(s, d) => {
let (s6, d6) = (to_v6(s), to_v6(d));
out.push(0x21); // TCP over IPv6
out.extend(36u16.to_be_bytes());
out.extend(s6.0.octets());
out.extend(d6.0.octets());
out.extend(s6.1.to_be_bytes());
out.extend(d6.1.to_be_bytes());
}
}
out
}
/// Read a header from the front of a stream. Exactly the forms
/// [`Caller::encode`] writes are accepted.
pub async fn read<R: AsyncRead + Unpin>(r: &mut R) -> Result<Caller, FrameError> {
let mut head = [0u8; 16];
r.read_exact(&mut head).await?;
let bad = || FrameError::Io(std::io::ErrorKind::InvalidData.into());
if head[..12] != PP2_SIGNATURE || head[12] != 0x21 {
return Err(bad());
}
let len = usize::from(u16::from_be_bytes([head[14], head[15]]));
match (head[13], len) {
(0x11, 12) => {
let mut b = [0u8; 12];
r.read_exact(&mut b).await?;
Ok(Caller {
source: SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(b[0], b[1], b[2], b[3])),
u16::from_be_bytes([b[8], b[9]]),
),
destination: SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(b[4], b[5], b[6], b[7])),
u16::from_be_bytes([b[10], b[11]]),
),
})
}
(0x21, 36) => {
let mut b = [0u8; 36];
r.read_exact(&mut b).await?;
let ip = |at: usize| {
let mut o = [0u8; 16];
o.copy_from_slice(&b[at..at + 16]);
IpAddr::V6(Ipv6Addr::from(o))
};
Ok(Caller {
source: SocketAddr::new(ip(0), u16::from_be_bytes([b[32], b[33]])),
destination: SocketAddr::new(ip(16), u16::from_be_bytes([b[34], b[35]])),
})
}
_ => Err(bad()),
}
}
}
fn to_v6(addr: SocketAddr) -> (Ipv6Addr, u16) {
match addr {
SocketAddr::V4(v4) => (v4.ip().to_ipv6_mapped(), v4.port()),
SocketAddr::V6(v6) => (*v6.ip(), v6.port()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_round_trips_and_refuses_the_wrong_length() {
let b = random32();
assert_eq!(unhex::<32>(&hex(&b)), Some(b));
assert_eq!(unhex::<32>("00"), None);
assert_eq!(unhex::<2>("zz00"), None);
assert_eq!(unhex::<2>("+f00"), None);
}
#[test]
fn a_proof_holds_for_one_session_and_nothing_else() {
let (key, _) = AppKey::generate();
let name = Name::parse("ledger-accrual-tally-mint").unwrap();
let other = Name::parse("ledger-accrual-tally-vault").unwrap();
let (exporter, nonce) = (random32(), random32());
let sig = key.sign(&proof_message(&exporter, &nonce, &name, true));
let pk = key.public_key();
assert!(verify(
&pk,
&proof_message(&exporter, &nonce, &name, true),
&sig
));
assert!(!verify(
&pk,
&proof_message(&random32(), &nonce, &name, true),
&sig
));
assert!(!verify(
&pk,
&proof_message(&exporter, &random32(), &name, true),
&sig
));
assert!(!verify(
&pk,
&proof_message(&exporter, &nonce, &other, true),
&sig
));
assert!(!verify(
&pk,
&proof_message(&exporter, &nonce, &name, false),
&sig
));
let (stranger, _) = AppKey::generate();
assert!(!verify(
&stranger.public_key(),
&proof_message(&exporter, &nonce, &name, true),
&sig
));
}
#[tokio::test]
async fn a_caller_header_round_trips_for_v4_and_v6_and_nothing_else_parses() {
let v4 = Caller {
source: "203.0.113.9:51000".parse().unwrap(),
destination: "198.51.100.1:443".parse().unwrap(),
};
let v6 = Caller {
source: "[2001:db8::7]:51000".parse().unwrap(),
destination: "[2001:db8::1]:443".parse().unwrap(),
};
assert_eq!(v4.encode().len(), 28);
assert_eq!(v6.encode().len(), 52);
for c in [v4, v6] {
let bytes = c.encode();
assert_eq!(Caller::read(&mut &bytes[..]).await.unwrap(), c);
}
// A mapped IPv4 caller is written as IPv4.
let mapped = Caller {
source: "[::ffff:203.0.113.9]:51000".parse().unwrap(),
destination: "198.51.100.1:443".parse().unwrap(),
};
assert_eq!(mapped.encode(), v4.encode());
let good = v4.encode();
for at in 0..good.len() {
let mut cut = good.clone();
cut.truncate(at);
assert!(Caller::read(&mut &cut[..]).await.is_err(), "cut at {at}");
}
let mut wrong = good.clone();
wrong[0] = b'G';
assert!(Caller::read(&mut &wrong[..]).await.is_err());
let mut wrong_len = good.clone();
wrong_len[15] = 13;
assert!(Caller::read(&mut &wrong_len[..]).await.is_err());
assert!(
Caller::read(&mut &b"GET / HTTP/1.1\r\n\r\n"[..])
.await
.is_err()
);
}
#[tokio::test]
async fn frames_are_bounded() {
let mut buf = Vec::new();
write_frame(&mut buf, &Request::Ping).await.unwrap();
let back: Request = read_frame(&mut &buf[..]).await.unwrap();
assert!(matches!(back, Request::Ping));
let long = [0xffu8, 0xff];
assert!(matches!(
read_frame::<_, Request>(&mut &long[..]).await,
Err(FrameError::TooLong)
));
let junk = [0u8, 3, b'n', b'o', b'!'];
assert!(matches!(
read_frame::<_, Request>(&mut &junk[..]).await,
Err(FrameError::Bad(_))
));
let unknown = br#"{"op":"publish_txt","value":"x","extra":1}"#;
let mut framed = u16::try_from(unknown.len()).unwrap().to_be_bytes().to_vec();
framed.extend(unknown);
assert!(read_frame::<_, Request>(&mut &framed[..]).await.is_err());
}
}
+395
View File
@@ -0,0 +1,395 @@
//! The registry: the one small durable table (D-85).
//!
//! It holds, per name, the app's public key, when the name was claimed
//! and whether the operator has blocked it. Nothing else about an app is
//! kept anywhere: not an address, not a label, not a log of connections.
//! A claim, and the limit on new names, are one transaction.
//!
//! SQLite is driven from one thread of its own, through a bounded queue,
//! so a slow disk makes the relay say "busy" and never makes it hold more.
//!
//! ```text
//! GOAL: a name belongs to the first key that claims it and to no other,
//! for as long as the registry file lives, however many connections
//! race for it and however often the relay restarts.
//! SOURCE: WB-relay-4 (the registry), D-85 in plan/p15-app-and-relay.md.
//! INVARIANTS:
//! 1. A name has at most one key: a second claim, with the same key or
//! another, never changes the row.
//! 2. A claim is durable before it is acknowledged (synchronous = FULL).
//! 3. At most `max_new` names are claimed in any `window`, counted from
//! the rows' own creation times, so a restart does not reset it.
//! 4. The queue to the database thread is bounded: past it a request
//! is refused as busy, not held.
//! SCENARIOS:
//! 1. Two claims of one name with different keys: one wins, the other
//! sees `Exists`.
//! 2. A claim, a restart (reopen), a lookup: the key is still there.
//! 3. The window limit counts rows made before a reopen.
//! ```
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use rusqlite::{Connection, OptionalExtension, params};
use tokio::sync::{mpsc, oneshot};
use crate::names::Name;
/// What the registry holds for a name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Entry {
/// The app's Ed25519 public key.
pub public_key: [u8; 32],
/// True when the operator has blocked the name.
pub blocked: bool,
}
/// How a claim ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Claimed {
/// This claim made the row.
New,
/// The name was already held, by this entry.
Exists(Entry),
/// Too many names were claimed in the window.
LimitReached,
}
/// Why the registry could not answer.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RegistryError {
/// The queue to the database is full.
#[error("the registry is busy")]
Busy,
/// The database thread is gone.
#[error("the registry is closed")]
Closed,
/// The database refused.
#[error("registry database: {0}")]
Db(String),
}
type Reply<T> = oneshot::Sender<Result<T, RegistryError>>;
enum Cmd {
Lookup(String, Reply<Option<Entry>>),
Claim {
name: String,
key: [u8; 32],
now: i64,
window_secs: i64,
max_new: u32,
reply: Reply<Claimed>,
},
SetBlocked(String, bool, Reply<bool>),
Count(Reply<u64>),
}
/// A handle to the registry. Clones share one database thread.
#[derive(Clone)]
pub struct Registry {
tx: mpsc::Sender<Cmd>,
}
fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
}
fn db(e: rusqlite::Error) -> RegistryError {
RegistryError::Db(e.to_string())
}
impl Registry {
/// Open (or create) the registry file, and start its thread. `queue`
/// is how many requests may wait.
pub fn open(path: &Path, queue: usize) -> Result<Self, RegistryError> {
let conn = Connection::open(path).map_err(db)?;
conn.execute_batch(
"PRAGMA journal_mode = WAL;
PRAGMA synchronous = FULL;
PRAGMA busy_timeout = 5000;
CREATE TABLE IF NOT EXISTS apps (
name TEXT PRIMARY KEY,
public_key BLOB NOT NULL CHECK (length(public_key) = 32),
created INTEGER NOT NULL,
blocked INTEGER NOT NULL DEFAULT 0
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS apps_created ON apps (created);",
)
.map_err(db)?;
let (tx, mut rx) = mpsc::channel::<Cmd>(queue.max(1));
std::thread::Builder::new()
.name("relay-registry".into())
.spawn(move || {
while let Some(cmd) = rx.blocking_recv() {
serve(&conn, cmd);
}
})
.map_err(|e| RegistryError::Db(e.to_string()))?;
Ok(Registry { tx })
}
async fn ask<T>(&self, make: impl FnOnce(Reply<T>) -> Cmd) -> Result<T, RegistryError> {
let (reply, answer) = oneshot::channel();
self.tx.try_send(make(reply)).map_err(|e| match e {
mpsc::error::TrySendError::Full(_) => RegistryError::Busy,
mpsc::error::TrySendError::Closed(_) => RegistryError::Closed,
})?;
answer.await.map_err(|_| RegistryError::Closed)?
}
/// The entry for a name, if claimed.
pub async fn lookup(&self, name: &Name) -> Result<Option<Entry>, RegistryError> {
self.ask(|r| Cmd::Lookup(name.to_string(), r)).await
}
/// Claim a name for a key, unless more than `max_new` names were
/// claimed within `window` already.
pub async fn claim(
&self,
name: &Name,
key: [u8; 32],
window: std::time::Duration,
max_new: u32,
) -> Result<Claimed, RegistryError> {
self.ask(|reply| Cmd::Claim {
name: name.to_string(),
key,
now: unix_now(),
window_secs: i64::try_from(window.as_secs()).unwrap_or(i64::MAX),
max_new,
reply,
})
.await
}
/// Block or unblock a name; false when there is no such name.
pub async fn set_blocked(&self, name: &Name, blocked: bool) -> Result<bool, RegistryError> {
self.ask(|r| Cmd::SetBlocked(name.to_string(), blocked, r))
.await
}
/// How many names are claimed.
pub async fn count(&self) -> Result<u64, RegistryError> {
self.ask(Cmd::Count).await
}
}
fn entry_of(key: Vec<u8>, blocked: i64) -> Option<Entry> {
Some(Entry {
public_key: key.try_into().ok()?,
blocked: blocked != 0,
})
}
fn lookup(conn: &Connection, name: &str) -> Result<Option<Entry>, RegistryError> {
let row: Option<(Vec<u8>, i64)> = conn
.query_row(
"SELECT public_key, blocked FROM apps WHERE name = ?1",
params![name],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()
.map_err(db)?;
match row {
None => Ok(None),
Some((key, blocked)) => entry_of(key, blocked)
.map(Some)
.ok_or_else(|| RegistryError::Db("a stored key is not 32 bytes".into())),
}
}
fn serve(conn: &Connection, cmd: Cmd) {
match cmd {
Cmd::Lookup(name, reply) => {
let _ = reply.send(lookup(conn, &name));
}
Cmd::Count(reply) => {
let n = conn
.query_row("SELECT count(*) FROM apps", [], |r| r.get::<_, i64>(0))
.map(|n| u64::try_from(n).unwrap_or(0))
.map_err(db);
let _ = reply.send(n);
}
Cmd::SetBlocked(name, blocked, reply) => {
let r = conn
.execute(
"UPDATE apps SET blocked = ?2 WHERE name = ?1",
params![name, i64::from(blocked)],
)
.map(|n| n > 0)
.map_err(db);
let _ = reply.send(r);
}
Cmd::Claim {
name,
key,
now,
window_secs,
max_new,
reply,
} => {
let _ = reply.send(claim(conn, &name, key, now, window_secs, max_new));
}
}
}
fn claim(
conn: &Connection,
name: &str,
key: [u8; 32],
now: i64,
window_secs: i64,
max_new: u32,
) -> Result<Claimed, RegistryError> {
// One immediate transaction: the count and the insert are one step.
conn.execute_batch("BEGIN IMMEDIATE").map_err(db)?;
let result = (|| {
if let Some(e) = lookup(conn, name)? {
return Ok(Claimed::Exists(e));
}
let recent: i64 = conn
.query_row(
"SELECT count(*) FROM apps WHERE created > ?1",
params![now.saturating_sub(window_secs)],
|r| r.get(0),
)
.map_err(db)?;
if recent >= i64::from(max_new) {
return Ok(Claimed::LimitReached);
}
conn.execute(
"INSERT INTO apps (name, public_key, created, blocked) VALUES (?1, ?2, ?3, 0)",
params![name, key.as_slice(), now],
)
.map_err(db)?;
Ok(Claimed::New)
})();
match result {
Ok(c) => {
conn.execute_batch("COMMIT").map_err(db)?;
Ok(c)
}
Err(e) => {
let _ = conn.execute_batch("ROLLBACK");
Err(e)
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
const DAY: Duration = Duration::from_secs(86_400);
fn name(s: &str) -> Name {
Name::parse(s).unwrap()
}
#[tokio::test]
async fn the_first_claim_wins_and_the_row_never_changes() {
let dir = tempfile::tempdir().unwrap();
let reg = Registry::open(&dir.path().join("r.db"), 16).unwrap();
let n = name("ledger-accrual-tally-mint");
assert_eq!(reg.lookup(&n).await.unwrap(), None);
assert_eq!(reg.claim(&n, [1; 32], DAY, 10).await.unwrap(), Claimed::New);
let held = Entry {
public_key: [1; 32],
blocked: false,
};
assert_eq!(
reg.claim(&n, [2; 32], DAY, 10).await.unwrap(),
Claimed::Exists(held)
);
assert_eq!(
reg.claim(&n, [1; 32], DAY, 10).await.unwrap(),
Claimed::Exists(held)
);
assert_eq!(reg.lookup(&n).await.unwrap(), Some(held));
assert_eq!(reg.count().await.unwrap(), 1);
}
#[tokio::test]
async fn racing_claims_have_one_winner() {
let dir = tempfile::tempdir().unwrap();
let reg = Registry::open(&dir.path().join("r.db"), 64).unwrap();
let n = name("ledger-accrual-tally-mint");
let mut tasks = Vec::new();
for i in 0..20u8 {
let reg = reg.clone();
tasks.push(tokio::spawn(async move {
reg.claim(&n, [i; 32], DAY, 100).await.unwrap()
}));
}
let mut wins = 0;
for t in tasks {
if t.await.unwrap() == Claimed::New {
wins += 1;
}
}
assert_eq!(wins, 1);
}
#[tokio::test]
async fn a_claim_outlives_a_restart_and_the_window_counts_old_rows() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("r.db");
{
let reg = Registry::open(&path, 16).unwrap();
for w in ["ledger-accrual-tally-mint", "ledger-accrual-tally-vault"] {
assert_eq!(
reg.claim(&name(w), [7; 32], DAY, 2).await.unwrap(),
Claimed::New
);
}
}
let reg = Registry::open(&path, 16).unwrap();
let held = reg
.lookup(&name("ledger-accrual-tally-mint"))
.await
.unwrap();
assert_eq!(held.map(|e| e.public_key), Some([7; 32]));
assert_eq!(
reg.claim(&name("ledger-accrual-tally-audit"), [8; 32], DAY, 2)
.await
.unwrap(),
Claimed::LimitReached
);
// The limit is for new names only: an existing one still answers.
assert!(matches!(
reg.claim(&name("ledger-accrual-tally-mint"), [8; 32], DAY, 2)
.await
.unwrap(),
Claimed::Exists(_)
));
// A window that has passed counts nothing.
assert_eq!(
reg.claim(
&name("ledger-accrual-tally-audit"),
[8; 32],
Duration::from_secs(0),
2
)
.await
.unwrap(),
Claimed::New
);
}
#[tokio::test]
async fn blocking_a_name_is_kept() {
let dir = tempfile::tempdir().unwrap();
let reg = Registry::open(&dir.path().join("r.db"), 16).unwrap();
let n = name("ledger-accrual-tally-mint");
assert!(!reg.set_blocked(&n, true).await.unwrap(), "no such name");
reg.claim(&n, [1; 32], DAY, 10).await.unwrap();
assert!(reg.set_blocked(&n, true).await.unwrap());
assert!(reg.lookup(&n).await.unwrap().unwrap().blocked);
}
}
+810
View File
@@ -0,0 +1,810 @@
//! The relay itself: the router, the lines, the control streams, DNS.
//!
//! ```text
//! GOAL: route an assistant's TLS connection, by the server name in its
//! first message, down the line of the app that owns the name, and
//! forward the encrypted bytes both ways, holding no certificate
//! for any app and reading nothing; and keep every table, buffer
//! and queue bounded whoever connects.
//! SOURCE: WB-relay-1 (the router), WB-relay-2 (the line and its proof),
//! WB-relay-6 (the caller's address), WB-relay-7 (bounds), D-80.
//! INVARIANTS:
//! 1. The router never terminates TLS for an app's name: for a name
//! under the domain it reads only the ClientHello's server name and
//! then copies bytes. The only TLS the relay ends is the line's, for
//! its own host.
//! 2. An unknown name, an app that is not connected, an app over its
//! stream limit, and every malformed first message are closed in the
//! same way (a TLS alert, then close): a stranger cannot tell which.
//! 3. The caller's address is written by the relay, as the first bytes
//! on the stream, before any byte of the caller's; it is the socket's
//! peer address, never a value the caller sent.
//! 4. A name's line is replaced when its owner reconnects with a good
//! proof, and removed when it ends; the table holds one entry per
//! connected app and no more than `max_lines`.
//! 5. Every connection is counted against a global limit and a
//! per-address limit before any work is done for it, and a hello
//! that is not complete in `hello_timeout` is closed.
//! 6. Per app: at most `streams_per_app` caller streams and
//! `control_streams_per_app` control streams, each with its own
//! timeouts; nothing queues without a bound.
//! SCENARIOS:
//! 1. An assistant connects with the app's name as server name; the app
//! sees the caller's address, then the assistant's ClientHello, and
//! TLS completes between them with the app's own certificate.
//! 2. An unknown name, and an offline app, are closed with the same
//! alert.
//! 3. A peer that connects and sends nothing, or one byte a second, is
//! closed at the hello timeout.
//! 4. A client holding the right key but a recorded old proof is
//! refused.
//! ```
use std::collections::HashMap;
use std::hash::{BuildHasher, RandomState};
use std::io;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream, UdpSocket};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinHandle;
use tokio::time::timeout;
use tokio_rustls::TlsAcceptor;
use tokio_util::compat::TokioAsyncReadCompatExt;
use tokio_util::sync::CancellationToken;
use crate::authorities::AuthorityList;
use crate::config::Config;
use crate::dns::{DnsService, TcpLimits};
use crate::front::{Activity, Front};
use crate::gate::IpGate;
use crate::hello::{self, HelloError};
use crate::mux::{self, Mux, MuxLimits};
use crate::names::{HostKind, Name, Zone};
use crate::proto::{
self, Caller, Challenge, EXPORTER_LABEL, Hello, Refusal, Request, Response, VERSION, Verdict,
read_frame, write_frame,
};
use crate::registry::{Claimed, Registry};
use crate::splice::{self, SpliceLimits};
use crate::txt::{PublishError, TxtStore};
/// What happened, counted. Read by tests and printed by the binary.
#[derive(Default, Debug)]
pub struct Metrics {
/// Connections accepted by the router.
pub accepted: AtomicU64,
/// Connections dropped at once because a limit was reached.
pub shed: AtomicU64,
/// Hellos not finished in time.
pub hello_timeouts: AtomicU64,
/// First bytes that were not a ClientHello with a name.
pub bad_hello: AtomicU64,
/// Names that are not an app's, or apps that are not connected.
pub unknown_or_offline: AtomicU64,
/// Callers whose app was over its stream limit.
pub app_busy: AtomicU64,
/// Streams the app did not open in time, or refused.
pub open_failed: AtomicU64,
/// Callers spliced to an app.
pub routed: AtomicU64,
/// Line handshakes begun.
pub line_attempts: AtomicU64,
/// Lines refused for a bad or replayed proof.
pub refused_proof: AtomicU64,
/// Lines refused for any other reason.
pub refused_other: AtomicU64,
/// Names claimed for the first time.
pub claims: AtomicU64,
/// Control requests served.
pub control: AtomicU64,
/// Lines up now.
pub lines_up: AtomicUsize,
}
impl Metrics {
/// Add one to a counter.
pub fn bump(counter: &AtomicU64) {
counter.fetch_add(1, Ordering::Relaxed);
}
}
/// An app's open line, as the router uses it.
#[derive(Clone)]
pub struct LineHandle {
id: u64,
mux: Mux,
streams: Arc<Semaphore>,
}
/// The routing table: name to open line, in memory, rebuilt as apps
/// reconnect. Sharded so no lock is held by many.
pub struct LineMap {
shards: Vec<Mutex<HashMap<Name, LineHandle>>>,
state: RandomState,
count: AtomicUsize,
next: AtomicU64,
max: usize,
}
impl LineMap {
fn new(max: usize) -> Self {
LineMap {
shards: (0..256).map(|_| Mutex::new(HashMap::new())).collect(),
state: RandomState::new(),
count: AtomicUsize::new(0),
next: AtomicU64::new(1),
max,
}
}
fn shard(&self, name: &Name) -> &Mutex<HashMap<Name, LineHandle>> {
// Truncating the hash to a shard index is the point.
&self.shards[(self.state.hash_one(name) as usize) % self.shards.len()]
}
fn lock<'a>(
m: &'a Mutex<HashMap<Name, LineHandle>>,
) -> std::sync::MutexGuard<'a, HashMap<Name, LineHandle>> {
m.lock().unwrap_or_else(|p| p.into_inner())
}
/// The line of `name`, if connected.
pub fn get(&self, name: &Name) -> Option<LineHandle> {
Self::lock(self.shard(name)).get(name).cloned()
}
/// Lines up.
pub fn len(&self) -> usize {
self.count.load(Ordering::Relaxed)
}
/// True when no line is up.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Whether a line for `name` could be taken now.
fn has_room(&self, name: &Name) -> bool {
self.len() < self.max || Self::lock(self.shard(name)).contains_key(name)
}
fn insert(&self, name: Name, handle: LineHandle) -> Result<(), ()> {
let mut shard = Self::lock(self.shard(&name));
let replaced = shard.contains_key(&name);
if !replaced && self.count.load(Ordering::Relaxed) >= self.max {
return Err(());
}
if let Some(old) = shard.insert(name, handle) {
old.mux.close(); // the owner reconnected: the old line is done
} else {
self.count.fetch_add(1, Ordering::Relaxed);
}
Ok(())
}
fn remove_if(&self, name: &Name, id: u64) {
let mut shard = Self::lock(self.shard(name));
if shard.get(name).is_some_and(|h| h.id == id) {
shard.remove(name);
self.count.fetch_sub(1, Ordering::Relaxed);
}
}
fn close_all(&self) {
for s in &self.shards {
for h in Self::lock(s).values() {
h.mux.close();
}
}
}
}
/// Per-address claim limit: a fixed table of (window start, count).
struct ClaimIps {
slots: Mutex<Vec<(Instant, u32)>>,
mask: usize,
state: RandomState,
limit: u32,
window: Duration,
}
impl ClaimIps {
fn new(slots: usize, limit: u32, window: Duration) -> Self {
let n = slots.max(2).next_power_of_two();
ClaimIps {
slots: Mutex::new(vec![(Instant::now(), 0); n]),
mask: n - 1,
state: RandomState::new(),
limit,
window,
}
}
fn allow(&self, ip: std::net::IpAddr, now: Instant) -> bool {
// Truncating the hash to a slot index is the point.
let slot = (self.state.hash_one(ip) as usize) & self.mask;
let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
let (start, count) = &mut slots[slot];
if now.saturating_duration_since(*start) >= self.window {
*start = now;
*count = 0;
}
if *count >= self.limit {
return false;
}
*count += 1;
true
}
}
/// Everything the tasks share.
pub struct Shared {
/// The configuration.
pub cfg: Config,
zone: Zone,
/// Who is connected.
pub lines: LineMap,
/// The durable table.
pub registry: Registry,
/// Proof records.
pub txt: Arc<TxtStore>,
/// The certificate authorities offered.
pub authorities: Arc<AuthorityList>,
acceptor: TlsAcceptor,
/// What happened.
pub metrics: Metrics,
conn_permits: Arc<Semaphore>,
hello_permits: Arc<Semaphore>,
handshake_permits: Arc<Semaphore>,
conn_gate: Arc<IpGate>,
pending_gate: Arc<IpGate>,
claim_ips: ClaimIps,
}
/// A TLS fatal alert, `unrecognized_name`: the same for every refusal.
const ALERT: [u8; 7] = [0x15, 3, 3, 0, 2, 2, 112];
async fn refuse(tcp: &mut TcpStream) {
let _ = timeout(Duration::from_secs(1), async {
tcp.write_all(&ALERT).await?;
tcp.shutdown().await
})
.await;
}
/// Read the first TLS record. Memory grows only as bytes arrive.
async fn read_hello(tcp: &mut TcpStream) -> Result<(Vec<u8>, String), HelloError> {
let eof = || HelloError::Malformed;
let mut head = [0u8; hello::RECORD_HEADER];
tcp.read_exact(&mut head).await.map_err(|_| eof())?;
let len = hello::record_len(&head)?;
let total = hello::RECORD_HEADER + len;
let mut rec = Vec::with_capacity(hello::RECORD_HEADER + 1024);
rec.extend_from_slice(&head);
while rec.len() < total {
let at = rec.len();
let want = (total - at).min(4096);
rec.resize(at + want, 0);
let n = tcp.read(&mut rec[at..]).await.map_err(|_| eof())?;
rec.truncate(at + n);
if n == 0 {
return Err(eof());
}
}
let host = hello::server_name(&rec)?;
Ok((rec, host))
}
async fn handle(
ctx: Arc<Shared>,
mut tcp: TcpStream,
peer: SocketAddr,
conn: OwnedSemaphorePermit,
conn_ip: crate::gate::IpPermit,
pending_ip: crate::gate::IpPermit,
hello_permit: OwnedSemaphorePermit,
) {
let _held = (conn, conn_ip);
let _ = tcp.set_nodelay(true);
let first = timeout(ctx.cfg.limits.hello_timeout(), read_hello(&mut tcp)).await;
drop((pending_ip, hello_permit));
let (record, host) = match first {
Err(_) => {
Metrics::bump(&ctx.metrics.hello_timeouts);
return;
}
Ok(Err(_)) => {
Metrics::bump(&ctx.metrics.bad_hello);
return;
}
Ok(Ok(x)) => x,
};
match ctx.zone.classify(&host) {
HostKind::Relay => serve_line(ctx, tcp, record, peer).await,
HostKind::App(name) => route(ctx, tcp, record, peer, name).await,
HostKind::Other => {
Metrics::bump(&ctx.metrics.unknown_or_offline);
refuse(&mut tcp).await;
}
}
}
async fn route(
ctx: Arc<Shared>,
mut tcp: TcpStream,
record: Vec<u8>,
peer: SocketAddr,
name: Name,
) {
let l = &ctx.cfg.limits;
let Some(line) = ctx.lines.get(&name) else {
Metrics::bump(&ctx.metrics.unknown_or_offline);
return refuse(&mut tcp).await;
};
let Ok(_stream_permit) = Arc::clone(&line.streams).try_acquire_owned() else {
Metrics::bump(&ctx.metrics.app_busy);
return refuse(&mut tcp).await;
};
let Ok(mut stream) = line.mux.open(l.open_stream_timeout()).await else {
Metrics::bump(&ctx.metrics.open_failed);
return refuse(&mut tcp).await;
};
let Ok(local) = tcp.local_addr() else {
return;
};
// The caller's address first, written by us from the socket, then the
// caller's own first bytes: nothing the caller sends can come before.
let mut first = Caller {
source: peer,
destination: local,
}
.encode();
first.extend_from_slice(&record);
drop(record);
let sent = timeout(l.write_stall(), async {
stream.write_all(&first).await?;
stream.flush().await
})
.await;
if !matches!(sent, Ok(Ok(()))) {
Metrics::bump(&ctx.metrics.open_failed);
return;
}
drop(first);
Metrics::bump(&ctx.metrics.routed);
let _ = splice::splice(
tcp,
stream,
SpliceLimits {
buffer: l.copy_buffer,
idle: l.stream_idle(),
stall: l.write_stall(),
max_age: l.stream_max_age(),
},
)
.await;
}
type LineTls = tokio_rustls::server::TlsStream<Front<TcpStream>>;
async fn serve_line(ctx: Arc<Shared>, tcp: TcpStream, record: Vec<u8>, peer: SocketAddr) {
let l = &ctx.cfg.limits;
let Ok(handshake_permit) = Arc::clone(&ctx.handshake_permits).try_acquire_owned() else {
Metrics::bump(&ctx.metrics.shed);
return;
};
Metrics::bump(&ctx.metrics.line_attempts);
let activity = Activity::new();
let front = Front::new(record, tcp, Some(Arc::clone(&activity)));
let up = timeout(l.handshake_timeout(), handshake(&ctx, front, peer)).await;
drop(handshake_permit);
let Ok(Ok((tls, name))) = up else { return };
let streams = Arc::new(Semaphore::new(l.streams_per_app as usize));
let control = Arc::new(Semaphore::new(l.control_streams_per_app as usize));
let limits = MuxLimits {
// The permits, and sixteen over: a stream the app has closed may
// still be counted on its side for a moment after our permit is
// back, and yamux ends a line that is asked for a stream over its
// count.
max_streams: (l.streams_per_app + l.control_streams_per_app + 16) as usize,
idle: l.line_idle(),
};
let ctx2 = Arc::clone(&ctx);
let (mux, task) = mux::spawn(
tls.compat(),
yamux::Mode::Server,
limits,
Some(activity),
move |stream| {
if let Ok(permit) = Arc::clone(&control).try_acquire_owned() {
let ctx = Arc::clone(&ctx2);
tokio::spawn(async move {
serve_control(ctx, name, stream).await;
drop(permit);
});
}
},
);
let id = ctx.lines.next.fetch_add(1, Ordering::Relaxed);
let handle = LineHandle {
id,
mux: mux.clone(),
streams,
};
if ctx.lines.insert(name, handle).is_err() {
mux.close();
let _ = task.await;
return;
}
ctx.metrics.lines_up.fetch_add(1, Ordering::Relaxed);
let _ = task.await;
ctx.lines.remove_if(&name, id);
ctx.metrics.lines_up.fetch_sub(1, Ordering::Relaxed);
}
/// TLS, the challenge, the proof, the verdict.
async fn handshake(
ctx: &Arc<Shared>,
front: Front<TcpStream>,
peer: SocketAddr,
) -> Result<(LineTls, Name), ()> {
let mut tls = ctx.acceptor.accept(front).await.map_err(|_| ())?;
let mut exporter = [0u8; 32];
tls.get_ref()
.1
.export_keying_material(&mut exporter[..], EXPORTER_LABEL, None)
.map_err(|_| ())?;
let nonce = proto::random32();
write_frame(
&mut tls,
&Challenge {
v: VERSION,
nonce: proto::hex(&nonce),
},
)
.await
.map_err(|_| ())?;
let hello: Hello = read_frame(&mut tls).await.map_err(|_| ())?;
let (verdict, name) = decide(ctx, &hello, &exporter, &nonce, peer.ip()).await;
write_frame(&mut tls, &verdict).await.map_err(|_| ())?;
match name {
Some(n) if verdict.ok => Ok((tls, n)),
_ => {
let _ = timeout(Duration::from_secs(1), tls.shutdown()).await;
Err(())
}
}
}
fn refused(why: Refusal) -> (Verdict, Option<Name>) {
(
Verdict {
ok: false,
refusal: Some(why),
claimed: false,
max_streams: 0,
},
None,
)
}
/// Is this hello a proof, for a name and key the registry will take?
async fn decide(
ctx: &Arc<Shared>,
hello: &Hello,
exporter: &[u8; 32],
nonce: &[u8; 32],
ip: std::net::IpAddr,
) -> (Verdict, Option<Name>) {
let l = &ctx.cfg.limits;
let (Ok(name), Some(key), Some(sig), true) = (
Name::parse(&hello.name),
proto::unhex::<32>(&hello.public_key),
proto::unhex::<64>(&hello.signature),
hello.v == VERSION,
) else {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::BadRequest);
};
// The proof first, before any database work: a stranger without a
// key never reaches the registry.
if !proto::verify(
&key,
&proto::proof_message(exporter, nonce, &name, hello.claim),
&sig,
) {
Metrics::bump(&ctx.metrics.refused_proof);
return refused(Refusal::BadProof);
}
let mut claimed = false;
match ctx.registry.lookup(&name).await {
Err(_) => {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::Busy);
}
Ok(Some(e)) => {
if e.blocked {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::Blocked);
}
if e.public_key != key {
Metrics::bump(&ctx.metrics.refused_proof);
return refused(if hello.claim {
Refusal::Taken
} else {
Refusal::BadProof
});
}
}
Ok(None) => {
if !hello.claim {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::UnknownName);
}
if !ctx.claim_ips.allow(ip, Instant::now()) {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::RateLimited);
}
match ctx
.registry
.claim(&name, key, l.claim_window(), l.claims_per_window)
.await
{
Ok(Claimed::New) => {
claimed = true;
Metrics::bump(&ctx.metrics.claims);
}
Ok(Claimed::Exists(e)) if e.public_key == key && !e.blocked => {}
Ok(Claimed::Exists(_)) => {
Metrics::bump(&ctx.metrics.refused_proof);
return refused(Refusal::Taken);
}
Ok(Claimed::LimitReached) => {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::RateLimited);
}
Err(_) => {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::Busy);
}
}
}
}
if !ctx.lines.has_room(&name) {
Metrics::bump(&ctx.metrics.refused_other);
return refused(Refusal::Busy);
}
(
Verdict {
ok: true,
refusal: None,
claimed,
max_streams: l.streams_per_app,
},
Some(name),
)
}
/// One request from an app on its own line. The name is the line's.
async fn serve_control(ctx: Arc<Shared>, name: Name, mut stream: mux::Stream) {
let _ = timeout(ctx.cfg.limits.control_timeout(), async {
let request: Request = read_frame(&mut stream).await.ok()?;
Metrics::bump(&ctx.metrics.control);
let response = match request {
Request::Ping => Response {
ok: true,
..Response::default()
},
Request::PublishTxt { value } => match ctx.txt.publish(name, &value, Instant::now()) {
Ok(()) => Response {
ok: true,
..Response::default()
},
Err(PublishError::BadValue) => Response {
ok: false,
error: Some("bad_value".into()),
..Response::default()
},
Err(PublishError::Limit) => Response {
ok: false,
error: Some("limit".into()),
..Response::default()
},
},
Request::ClearTxt => {
ctx.txt.clear(&name);
Response {
ok: true,
..Response::default()
}
}
Request::Authorities => Response {
ok: true,
authorities: Some(ctx.authorities.for_app(&name)),
..Response::default()
},
};
write_frame(&mut stream, &response).await.ok()?;
let _ = stream.shutdown().await;
Some(())
})
.await;
}
async fn accept_loop(ctx: Arc<Shared>, listener: TcpListener, cancel: CancellationToken) {
loop {
let (tcp, peer) = tokio::select! {
() = cancel.cancelled() => return,
r = listener.accept() => match r {
Ok(x) => x,
Err(_) => {
// Out of descriptors, or a reset: do not spin.
tokio::time::sleep(Duration::from_millis(50)).await;
continue;
}
},
};
let ip = peer.ip();
let (Ok(conn), Some(conn_ip), Some(pending_ip), Ok(hello)) = (
Arc::clone(&ctx.conn_permits).try_acquire_owned(),
ctx.conn_gate.acquire(ip),
ctx.pending_gate.acquire(ip),
Arc::clone(&ctx.hello_permits).try_acquire_owned(),
) else {
Metrics::bump(&ctx.metrics.shed);
continue; // closed by drop, before any work
};
Metrics::bump(&ctx.metrics.accepted);
tokio::spawn(handle(
Arc::clone(&ctx),
tcp,
peer,
conn,
conn_ip,
pending_ip,
hello,
));
}
}
/// A running relay.
pub struct Relay {
shared: Arc<Shared>,
router: SocketAddr,
dns_udp: SocketAddr,
dns_tcp: SocketAddr,
cancel: CancellationToken,
tasks: Vec<JoinHandle<()>>,
}
impl Relay {
/// Bind and start the router and DNS. Port 0 picks a free port.
pub async fn start(
cfg: Config,
tls: Arc<rustls::ServerConfig>,
authorities: AuthorityList,
) -> io::Result<Relay> {
let l = cfg.limits.clone();
let zone = Zone::new(&cfg.domain, &cfg.relay_host);
let registry = Registry::open(&cfg.registry_path, l.registry_queue)
.map_err(|e| io::Error::other(e.to_string()))?;
let txt = Arc::new(TxtStore::new(
l.txt_ttl(),
l.txt_max_entries,
l.txt_per_name,
l.txt_publishes_per_hour,
));
let dns = Arc::new(
DnsService::new(zone.clone(), &cfg, Arc::clone(&txt)).map_err(io::Error::other)?,
);
let router_listener = TcpListener::bind(cfg.router_addr).await?;
let router = router_listener.local_addr()?;
let udp = UdpSocket::bind(cfg.dns_addr).await?;
let dns_udp = udp.local_addr()?;
// TCP DNS on the same port number when it was asked for 0.
let tcp_addr = SocketAddr::new(cfg.dns_addr.ip(), dns_udp.port());
let dns_tcp_listener = TcpListener::bind(tcp_addr).await?;
let dns_tcp = dns_tcp_listener.local_addr()?;
let shared = Arc::new(Shared {
zone,
lines: LineMap::new(l.max_lines),
registry,
txt: Arc::clone(&txt),
authorities: Arc::new(authorities),
acceptor: TlsAcceptor::from(tls),
metrics: Metrics::default(),
conn_permits: Arc::new(Semaphore::new(l.max_connections)),
hello_permits: Arc::new(Semaphore::new(l.max_pending_hellos)),
handshake_permits: Arc::new(Semaphore::new(l.max_handshakes)),
conn_gate: IpGate::new(l.ip_slots, l.max_connections_per_ip),
pending_gate: IpGate::new(l.ip_slots, l.max_pending_per_ip),
claim_ips: ClaimIps::new(4096, l.claims_per_ip, l.claim_ip_window()),
cfg,
});
let cancel = CancellationToken::new();
let mut tasks = vec![
tokio::spawn(accept_loop(
Arc::clone(&shared),
router_listener,
cancel.clone(),
)),
tokio::spawn(crate::dns::serve_udp(
Arc::new(udp),
Arc::clone(&dns),
l.dns_qps_per_ip,
l.ip_slots,
cancel.clone(),
)),
tokio::spawn(crate::dns::serve_tcp(
dns_tcp_listener,
dns,
TcpLimits {
max: l.dns_tcp_max,
per_ip: l.dns_tcp_per_ip,
timeout: l.dns_tcp_timeout(),
queries: 16,
},
l.ip_slots,
cancel.clone(),
)),
];
// Housekeeping: expired proof records, a changed authority list.
let (sweep_shared, sweep_cancel) = (Arc::clone(&shared), cancel.clone());
tasks.push(tokio::spawn(async move {
let mut tick = tokio::time::interval(Duration::from_secs(30));
loop {
tokio::select! {
() = sweep_cancel.cancelled() => return,
_ = tick.tick() => {
sweep_shared.txt.sweep(Instant::now());
let _ = sweep_shared.authorities.reload();
}
}
}
}));
Ok(Relay {
shared,
router,
dns_udp,
dns_tcp,
cancel,
tasks,
})
}
/// Where the router listens.
pub fn router_addr(&self) -> SocketAddr {
self.router
}
/// Where DNS listens over UDP.
pub fn dns_udp_addr(&self) -> SocketAddr {
self.dns_udp
}
/// Where DNS listens over TCP.
pub fn dns_tcp_addr(&self) -> SocketAddr {
self.dns_tcp
}
/// The shared state: tables and counters.
pub fn shared(&self) -> &Arc<Shared> {
&self.shared
}
/// Stop accepting, close every line, and wait for the listeners.
pub async fn shutdown(self) {
self.cancel.cancel();
self.shared.lines.close_all();
for t in self.tasks {
let _ = t.await;
}
}
}
+267
View File
@@ -0,0 +1,267 @@
//! Piping bytes both ways between a caller and a stream, with nothing
//! held back.
//!
//! Each direction has one buffer. It reads only when the buffer is empty
//! and writes it out before reading again, so a reader that is slow on
//! one side slows the writer on the other, and no more than one buffer
//! per direction ever sits in the relay. The relay reads none of it: the
//! bytes are TLS between the assistant and the app.
//!
//! ```text
//! GOAL: forward encrypted bytes both ways, with a slow, silent or
//! hostile end unable to make the relay hold more than two small
//! buffers or hold the connection past its limits.
//! SOURCE: WB-relay-1 (the router and its splice), WB-relay-7 (bounds).
//! INVARIANTS:
//! 1. At most `buffer` bytes are held per direction.
//! 2. A write that makes no progress for `stall` ends the connection:
//! a slow reader is closed, never buffered for.
//! 3. A connection with no byte either way for `idle`, or alive for
//! `max_age`, is closed.
//! 4. A close in one direction (EOF) is passed on as a close of the
//! other side's write half; the other direction carries on until it
//! ends too.
//! SCENARIOS:
//! 1. Bytes written at either end arrive at the other, in order, and a
//! close at one end reaches the other.
//! 2. A peer that never reads: the splice ends after `stall`.
//! 3. A peer that says nothing: the splice ends after `idle`.
//! ```
use std::io;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::time::{Instant, sleep, timeout};
/// The limits of one splice.
#[derive(Debug, Clone, Copy)]
pub struct SpliceLimits {
/// Buffer bytes per direction.
pub buffer: usize,
/// No byte either way for this long ends it.
pub idle: Duration,
/// A write stuck this long ends it.
pub stall: Duration,
/// Its longest life.
pub max_age: Duration,
}
/// How a splice ended.
#[derive(Debug, PartialEq, Eq)]
pub enum End {
/// Both directions closed.
Done,
/// No traffic for the idle time.
Idle,
/// Lived to its maximum age.
MaxAge,
/// A write made no progress for the stall time.
Stalled,
/// An end failed.
Error(io::ErrorKind),
}
/// When bytes last moved, on tokio's clock (so tests can pause it).
struct Stamp {
base: Instant,
ms: AtomicU64,
}
impl Stamp {
fn new() -> Self {
Stamp {
base: Instant::now(),
ms: AtomicU64::new(0),
}
}
fn touch(&self) {
let ms = u64::try_from(self.base.elapsed().as_millis()).unwrap_or(u64::MAX);
self.ms.store(ms, Ordering::Relaxed);
}
fn quiet(&self) -> Duration {
let now = u64::try_from(self.base.elapsed().as_millis()).unwrap_or(u64::MAX);
Duration::from_millis(now.saturating_sub(self.ms.load(Ordering::Relaxed)))
}
}
async fn pump<R, W>(
from: &mut R,
to: &mut W,
buffer: usize,
stall: Duration,
last: &Stamp,
) -> Result<(), End>
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
let mut buf = vec![0u8; buffer.max(1)];
loop {
let n = from
.read(&mut buf)
.await
.map_err(|e| End::Error(e.kind()))?;
if n == 0 {
// Pass the close on. A failure here only means the far end
// has already gone.
let _ = timeout(stall, to.shutdown()).await;
return Ok(());
}
last.touch();
match timeout(stall, async {
to.write_all(&buf[..n]).await?;
to.flush().await
})
.await
{
Err(_) => return Err(End::Stalled),
Ok(Err(e)) => return Err(End::Error(e.kind())),
Ok(Ok(())) => last.touch(),
}
}
}
/// Splice `a` and `b` until both close or a limit is hit.
pub async fn splice<A, B>(a: A, b: B, limits: SpliceLimits) -> End
where
A: AsyncRead + AsyncWrite + Unpin,
B: AsyncRead + AsyncWrite + Unpin,
{
let (mut ar, mut aw) = tokio::io::split(a);
let (mut br, mut bw) = tokio::io::split(b);
let last = Stamp::new();
let both = async {
// The first failure ends both; a clean close in one direction
// lets the other carry on.
match tokio::try_join!(
pump(&mut ar, &mut bw, limits.buffer, limits.stall, &last),
pump(&mut br, &mut aw, limits.buffer, limits.stall, &last),
) {
Ok(((), ())) => End::Done,
Err(e) => e,
}
};
let idle = async {
loop {
let quiet = last.quiet();
if quiet >= limits.idle {
return End::Idle;
}
sleep(limits.idle - quiet).await;
}
};
tokio::select! {
end = both => end,
end = idle => end,
() = sleep(limits.max_age) => End::MaxAge,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn limits() -> SpliceLimits {
SpliceLimits {
buffer: 1024,
idle: Duration::from_secs(30),
stall: Duration::from_secs(30),
max_age: Duration::from_secs(60),
}
}
#[tokio::test]
async fn bytes_cross_both_ways_and_closes_are_passed_on() {
let (mut left, a) = tokio::io::duplex(256);
let (mut right, b) = tokio::io::duplex(256);
let task = tokio::spawn(splice(a, b, limits()));
left.write_all(b"to the right").await.unwrap();
left.shutdown().await.unwrap();
let mut got = Vec::new();
right.read_to_end(&mut got).await.unwrap();
assert_eq!(got, b"to the right");
right.write_all(b"and back").await.unwrap();
right.shutdown().await.unwrap();
let mut back = Vec::new();
left.read_to_end(&mut back).await.unwrap();
assert_eq!(back, b"and back");
assert_eq!(task.await.unwrap(), End::Done);
}
#[tokio::test]
async fn a_large_transfer_arrives_whole_in_small_buffers() {
let (mut left, a) = tokio::io::duplex(512);
let (mut right, b) = tokio::io::duplex(512);
let task = tokio::spawn(splice(a, b, limits()));
let data: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();
let send = data.clone();
let writer = tokio::spawn(async move {
left.write_all(&send).await.unwrap();
left.shutdown().await.unwrap();
left
});
let mut got = Vec::new();
right.read_to_end(&mut got).await.unwrap();
assert_eq!(got, data);
right.shutdown().await.unwrap();
let _left = writer.await.unwrap();
assert_eq!(task.await.unwrap(), End::Done);
}
#[tokio::test(start_paused = true)]
async fn a_peer_that_never_reads_stalls_the_splice_and_buffers_little() {
let (mut left, a) = tokio::io::duplex(1024);
let (_right, b) = tokio::io::duplex(1024); // never read
let l = SpliceLimits {
stall: Duration::from_secs(5),
..limits()
};
let task = tokio::spawn(splice(a, b, l));
// Keep writing; the relay must stop reading once its buffer and
// the pipes are full, so this write cannot complete in full.
let flood = tokio::spawn(async move {
let chunk = vec![1u8; 4096];
let mut sent = 0usize;
while left.write_all(&chunk).await.is_ok() {
sent += chunk.len();
if sent > 1_000_000 {
break;
}
}
sent
});
assert_eq!(task.await.unwrap(), End::Stalled);
let sent = flood.await.unwrap();
assert!(sent < 20_000, "{sent} bytes were taken from a stalled pipe");
}
#[tokio::test(start_paused = true)]
async fn a_silent_connection_is_closed_after_its_idle_time() {
let (_left, a) = tokio::io::duplex(64);
let (_right, b) = tokio::io::duplex(64);
let l = SpliceLimits {
idle: Duration::from_secs(10),
..limits()
};
assert_eq!(splice(a, b, l).await, End::Idle);
}
#[tokio::test(start_paused = true)]
async fn a_busy_connection_still_ends_at_its_maximum_age() {
let (mut left, a) = tokio::io::duplex(64);
let (_right, b) = tokio::io::duplex(64);
let l = SpliceLimits {
idle: Duration::from_secs(10),
max_age: Duration::from_secs(25),
..limits()
};
let task = tokio::spawn(splice(a, b, l));
for _ in 0..5 {
tokio::time::sleep(Duration::from_secs(6)).await;
let _ = left.write_all(b"x").await;
}
assert_eq!(task.await.unwrap(), End::MaxAge);
}
}
+51
View File
@@ -0,0 +1,51 @@
//! TLS settings for the line, both ends.
//!
//! The line is TLS 1.3 only. The relay presents its own certificate for
//! its own host; the app checks it against the roots it is given. The app
//! proves itself not with a certificate but with the signature of
//! [`crate::proto`], bound to this session's exporter.
use std::path::Path;
use std::sync::Arc;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::{ClientConfig, RootCertStore, ServerConfig};
fn provider() -> Arc<rustls::crypto::CryptoProvider> {
Arc::new(rustls::crypto::ring::default_provider())
}
/// The relay's server settings from a chain and key.
pub fn server_config(
chain: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
) -> Result<Arc<ServerConfig>, rustls::Error> {
let mut cfg = ServerConfig::builder_with_provider(provider())
.with_protocol_versions(&[&rustls::version::TLS13])?
.with_no_client_auth()
.with_single_cert(chain, key)?;
// A line is long-lived and proven by signature: no tickets to hold.
cfg.send_tls13_tickets = 0;
Ok(Arc::new(cfg))
}
/// The relay's server settings from PEM files.
pub fn server_config_from_files(cert: &Path, key: &Path) -> Result<Arc<ServerConfig>, String> {
let chain = CertificateDer::pem_file_iter(cert)
.map_err(|e| format!("{}: {e}", cert.display()))?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("{}: {e}", cert.display()))?;
let key = PrivateKeyDer::from_pem_file(key).map_err(|e| format!("{}: {e}", key.display()))?;
server_config(chain, key).map_err(|e| e.to_string())
}
/// An app's client settings: TLS 1.3, checking the relay against `roots`.
pub fn client_config(roots: RootCertStore) -> Result<Arc<ClientConfig>, rustls::Error> {
Ok(Arc::new(
ClientConfig::builder_with_provider(provider())
.with_protocol_versions(&[&rustls::version::TLS13])?
.with_root_certificates(roots)
.with_no_client_auth(),
))
}
+271
View File
@@ -0,0 +1,271 @@
//! The proof records: what the relay's DNS says at `_acme-challenge.<name>`.
//!
//! An app that wants a certificate for its name asks the relay, over its
//! own proven line, to publish the ACME DNS-01 value at
//! `_acme-challenge.<its name>.<domain>`. The record is held in memory for
//! minutes and answered by the DNS server; nothing is stored per user.
//!
//! The request carries no name. The name is the line's, proven at the
//! handshake, so an app can publish for its own name and for no other.
//!
//! ```text
//! GOAL: a certificate for a name can be proven by the app that holds the
//! name's key and by nobody else, and the relay never proves a name
//! on its own account.
//! SOURCE: WB-relay-5 (the proof records and the domain's DNS), RFC 8555
//! section 8.4 (the DNS-01 challenge), D-87.
//! INVARIANTS:
//! 1. `publish` takes the name from the caller's authenticated line;
//! no value can be placed under any other name.
//! 2. A value is exactly the 43 base64url characters of a SHA-256
//! digest; any other text is refused.
//! 3. Records expire: after `ttl` they are not answered and the sweep
//! frees them.
//! 4. Memory is bounded: at most `max_entries` names, `per_name` values
//! each, and a name's publishes are counted per hour.
//! SCENARIOS:
//! 1. A published value is answered until its ttl, then not.
//! 2. A fifth value for one name (limit 4) is refused; the first four
//! stand.
//! 3. A store at its entry limit refuses a new name and still serves
//! the old ones.
//! 4. A thirteenth publish within the hour is refused.
//! ```
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use crate::names::Name;
/// Why a publish was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PublishError {
/// The value is not a DNS-01 proof value.
#[error("not a proof value")]
BadValue,
/// The store is full, or this name publishes too often.
#[error("too many proof records")]
Limit,
}
struct Slot {
values: Vec<(String, Instant)>,
window_start: Instant,
publishes: u32,
}
/// The proof records, in memory.
pub struct TxtStore {
inner: Mutex<HashMap<Name, Slot>>,
ttl: Duration,
max_entries: usize,
per_name: usize,
per_hour: u32,
}
const HOUR: Duration = Duration::from_secs(3600);
/// Is this an ACME DNS-01 value: base64url of a SHA-256 digest, no padding?
pub fn is_proof_value(text: &str) -> bool {
text.len() == 43
&& text
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
impl TxtStore {
/// A store with these limits.
pub fn new(ttl: Duration, max_entries: usize, per_name: usize, per_hour: u32) -> Self {
TxtStore {
inner: Mutex::new(HashMap::new()),
ttl,
max_entries,
per_name: per_name.max(1),
per_hour,
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<Name, Slot>> {
// A panic while holding the lock cannot leave the map half-edited
// in a way that matters more than refusing to serve.
self.inner.lock().unwrap_or_else(|p| p.into_inner())
}
/// Publish `value` for `name` at `now`.
pub fn publish(&self, name: Name, value: &str, now: Instant) -> Result<(), PublishError> {
if !is_proof_value(value) {
return Err(PublishError::BadValue);
}
let mut map = self.lock();
if !map.contains_key(&name) && map.len() >= self.max_entries {
sweep_locked(&mut map, self.ttl, now);
if map.len() >= self.max_entries {
return Err(PublishError::Limit);
}
}
let slot = map.entry(name).or_insert_with(|| Slot {
values: Vec::new(),
window_start: now,
publishes: 0,
});
if now.saturating_duration_since(slot.window_start) >= HOUR {
slot.window_start = now;
slot.publishes = 0;
}
if slot.publishes >= self.per_hour {
return Err(PublishError::Limit);
}
slot.values
.retain(|(_, at)| now.saturating_duration_since(*at) < self.ttl);
if let Some(held) = slot.values.iter_mut().find(|(v, _)| v == value) {
held.1 = now; // the same value again only renews it
} else if slot.values.len() >= self.per_name {
return Err(PublishError::Limit);
} else {
slot.values.push((value.to_owned(), now));
}
slot.publishes += 1;
Ok(())
}
/// The live values for `name` at `now`.
pub fn get(&self, name: &Name, now: Instant) -> Vec<String> {
self.lock()
.get(name)
.map(|s| {
s.values
.iter()
.filter(|(_, at)| now.saturating_duration_since(*at) < self.ttl)
.map(|(v, _)| v.clone())
.collect()
})
.unwrap_or_default()
}
/// Drop every value of `name`. Its publish count stays for the hour.
pub fn clear(&self, name: &Name) {
if let Some(slot) = self.lock().get_mut(name) {
slot.values.clear();
}
}
/// Free everything expired. Called every half minute by the relay.
pub fn sweep(&self, now: Instant) {
sweep_locked(&mut self.lock(), self.ttl, now);
}
/// Names held (for tests and the stats line).
pub fn len(&self) -> usize {
self.lock().len()
}
/// True when nothing is held.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
fn sweep_locked(map: &mut HashMap<Name, Slot>, ttl: Duration, now: Instant) {
map.retain(|_, slot| {
slot.values
.retain(|(_, at)| now.saturating_duration_since(*at) < ttl);
!slot.values.is_empty() || now.saturating_duration_since(slot.window_start) < HOUR
});
}
#[cfg(test)]
mod tests {
use super::*;
fn value(c: char) -> String {
std::iter::repeat_n(c, 43).collect()
}
fn name(s: &str) -> Name {
Name::parse(s).unwrap()
}
#[test]
fn a_value_is_answered_until_its_ttl() {
let s = TxtStore::new(Duration::from_secs(60), 10, 4, 12);
let n = name("ledger-accrual-tally-mint");
let t0 = Instant::now();
s.publish(n, &value('a'), t0).unwrap();
assert_eq!(s.get(&n, t0 + Duration::from_secs(59)), vec![value('a')]);
assert!(s.get(&n, t0 + Duration::from_secs(60)).is_empty());
s.sweep(t0 + Duration::from_secs(61));
assert_eq!(s.len(), 1, "the publish count is kept for the hour");
s.sweep(t0 + HOUR + Duration::from_secs(1));
assert!(s.is_empty());
}
#[test]
fn only_proof_values_are_taken() {
let s = TxtStore::new(Duration::from_secs(60), 10, 4, 12);
let n = name("ledger-accrual-tally-mint");
let t0 = Instant::now();
for bad in [
"",
"short",
&"a".repeat(44),
&format!("{}=", "a".repeat(42)),
&format!("{}.", "a".repeat(42)),
] {
assert_eq!(
s.publish(n, bad, t0),
Err(PublishError::BadValue),
"{bad:?}"
);
}
assert!(s.get(&n, t0).is_empty());
}
#[test]
fn values_per_name_and_names_in_all_are_bounded() {
let s = TxtStore::new(Duration::from_secs(60), 2, 2, 100);
let (a, b, c) = (
name("ledger-accrual-tally-mint"),
name("ledger-accrual-tally-vault"),
name("ledger-accrual-tally-audit"),
);
let t0 = Instant::now();
s.publish(a, &value('a'), t0).unwrap();
s.publish(a, &value('b'), t0).unwrap();
assert_eq!(s.publish(a, &value('c'), t0), Err(PublishError::Limit));
s.publish(a, &value('a'), t0)
.expect("the same value renews");
s.publish(b, &value('a'), t0).unwrap();
assert_eq!(s.publish(c, &value('a'), t0), Err(PublishError::Limit));
assert_eq!(s.get(&a, t0).len(), 2);
assert_eq!(s.get(&b, t0).len(), 1);
// After a's values expire there is room again.
s.publish(c, &value('a'), t0 + Duration::from_secs(61))
.unwrap_err();
s.sweep(t0 + HOUR + Duration::from_secs(1));
s.publish(c, &value('a'), t0 + HOUR + Duration::from_secs(2))
.unwrap();
}
#[test]
fn publishes_are_counted_per_hour() {
let s = TxtStore::new(Duration::from_secs(5), 10, 4, 3);
let n = name("ledger-accrual-tally-mint");
let t0 = Instant::now();
for _ in 0..3 {
s.publish(n, &value('a'), t0).unwrap();
}
assert_eq!(s.publish(n, &value('a'), t0), Err(PublishError::Limit));
s.publish(n, &value('a'), t0 + HOUR).expect("a new hour");
}
#[test]
fn clear_removes_the_values() {
let s = TxtStore::new(Duration::from_secs(60), 10, 4, 12);
let n = name("ledger-accrual-tally-mint");
let t0 = Instant::now();
s.publish(n, &value('a'), t0).unwrap();
s.clear(&n);
assert!(s.get(&n, t0).is_empty());
}
}