[relay] Wake-up: a push endpoint per mailbox, and a constant wake to it when a blob arrives
ci / check (pull_request) Has been cancelled

This commit is contained in:
2026-11-20 12:04:55 +01:00
parent f075fae0e3
commit f852b1a6d1
21 changed files with 1606 additions and 40 deletions
+31 -2
View File
@@ -32,8 +32,8 @@ use sha2::Sha256;
use snapshot::Bytes;
use std::fmt;
use tabellarius_protocol::{
blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, Sha256Hash,
Token, MAX_BLOB_BYTES,
blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, PushEndpoint,
Sha256Hash, Token, MAX_BLOB_BYTES,
};
pub use transport::{MemoryTransport, Transport, TransportError};
@@ -523,6 +523,35 @@ impl<T: Transport> Client<T> {
out.clone()
}
/// The mailboxes this client fetches: each contact's inbox (a blocked contact's too, which
/// nothing reaches) and each open invite's welcome mailbox. For wake-ups (`PROTOCOL.md` §6): an
/// app registers one push endpoint per mailbox, so the relay cannot link them by endpoint.
pub fn inboxes(&self) -> Vec<MailboxId> {
self.contacts
.iter()
.filter_map(|c| c.inbox.map(|m| m.id))
.chain(self.welcome_boxes.iter().map(|w| w.mailbox.id))
.collect()
}
/// Where the relay wakes us when this mailbox receives (`Some`), or nowhere (`None`). Only a
/// mailbox from [`Client::inboxes`]; another is [`ClientError::UnknownContact`].
pub fn set_push(
&self,
mailbox: &MailboxId,
endpoint: Option<&PushEndpoint>,
) -> Result<(), ClientError> {
let fetch = self
.contacts
.iter()
.filter_map(|c| c.inbox)
.chain(self.welcome_boxes.iter().map(|w| w.mailbox))
.find(|m| m.id == *mailbox)
.ok_or(ClientError::UnknownContact)?
.fetch;
Ok(self.transport.set_push(mailbox, &fetch, endpoint)?)
}
/// Blocks a contact, staged: they are marked, and their way into our mailbox is closed by a
/// rotate to the hash of a fresh token that nobody gets. Nothing is sent to them. Save the
/// snapshot, then deliver the result.
+38 -2
View File
@@ -5,7 +5,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tabellarius_protocol::{
blob_hash, CreateInvite, CreateMailbox, InviteId, MailboxId, Sha256Hash, Token,
blob_hash, CreateInvite, CreateMailbox, InviteId, MailboxId, PushEndpoint, Sha256Hash, Token,
};
/// Why the relay said no. Carries nothing of the request.
@@ -41,12 +41,21 @@ pub trait Transport {
) -> Result<(), TransportError>;
/// The KeyPackage, once.
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError>;
/// Where the relay wakes the mailbox's owner when a blob arrives (`Some`), or nowhere (`None`).
/// `PROTOCOL.md` §6, `.agents/features/wake-up.md`.
fn set_push(
&self,
id: &MailboxId,
fetch: &Token,
endpoint: Option<&PushEndpoint>,
) -> Result<(), TransportError>;
}
#[derive(Default)]
struct Boxes {
mailboxes: HashMap<MailboxId, (Sha256Hash, Sha256Hash, Vec<Vec<u8>>)>,
invites: HashMap<InviteId, (Sha256Hash, Vec<u8>)>,
push: HashMap<MailboxId, PushEndpoint>,
}
/// An in-memory relay with the same rules as the real one (no expiry: there is no clock here).
@@ -68,7 +77,12 @@ impl MemoryTransport {
.sum()
}
/// Every byte the relay holds, for privacy tests: ids, hashes, blobs and KeyPackages.
/// The push endpoint a mailbox holds, if any.
pub fn push_endpoint(&self, id: &MailboxId) -> Option<String> {
self.boxes().push.get(id).map(|e| e.as_str().to_string())
}
/// Every byte the relay holds, for privacy tests: ids, hashes, blobs, KeyPackages, endpoints.
pub fn everything_stored(&self) -> Vec<u8> {
let b = self.boxes();
let mut out = Vec::new();
@@ -83,6 +97,10 @@ impl MemoryTransport {
out.extend_from_slice(hash.as_bytes());
out.extend_from_slice(kp);
}
for (id, endpoint) in &b.push {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(endpoint.as_str().as_bytes());
}
out
}
}
@@ -172,4 +190,22 @@ impl Transport for MemoryTransport {
_ => Err(TransportError::NotFound),
}
}
fn set_push(
&self,
id: &MailboxId,
fetch: &Token,
endpoint: Option<&PushEndpoint>,
) -> Result<(), TransportError> {
let mut b = self.boxes();
match b.mailboxes.get(id) {
Some((_, f, _)) if *f == fetch.hash() => {}
_ => return Err(TransportError::NotFound),
}
match endpoint {
Some(e) => b.push.insert(*id, e.clone()),
None => b.push.remove(id),
};
Ok(())
}
}
+83
View File
@@ -0,0 +1,83 @@
//! Wake-up (`.agents/features/wake-up.md` §2.4) on the in-memory relay: which mailboxes a client
//! fetches, and an endpoint per mailbox, set only with that mailbox's fetch token.
use tabellarius_client::*;
use tabellarius_protocol::PushEndpoint;
fn endpoint(path: &str) -> PushEndpoint {
PushEndpoint::parse(&format!("https://push.invalid/{path}")).expect("endpoint")
}
#[test]
fn inboxes_are_the_open_welcome_mailboxes_then_each_contacts_inbox() {
let relay = MemoryTransport::default();
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
assert!(eva.inboxes().is_empty());
let invite = eva.create_invite().expect("invite");
let welcome = eva.inboxes();
assert_eq!(
welcome.len(),
1,
"the welcome mailbox, while the invite is open"
);
// Someone who joins wakes the inviter through it.
eva.set_push(&welcome[0], Some(&endpoint("upWelcome")))
.expect("set");
assert_eq!(
relay.push_endpoint(&welcome[0]).as_deref(),
Some("https://push.invalid/upWelcome")
);
jan.accept_invite(&invite).expect("accept");
assert_eq!(jan.inboxes().len(), 1);
eva.poll().expect("poll");
// Joined: the welcome mailbox is dropped, Jan's inbox at Eva's is there.
let after = eva.inboxes();
assert_eq!(after.len(), 1);
assert_ne!(after[0], welcome[0]);
// Every mailbox is different: one endpoint each never links them.
let mut all = eva.inboxes();
all.extend(jan.inboxes());
all.sort_by_key(|m| m.to_wire());
all.dedup();
assert_eq!(all.len(), 2);
}
#[test]
fn only_a_mailbox_of_ones_own_takes_an_endpoint_and_clearing_removes_it() {
let relay = MemoryTransport::default();
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
let invite = eva.create_invite().expect("invite");
jan.accept_invite(&invite).expect("accept");
eva.poll().expect("poll");
let (mine, his) = (eva.inboxes()[0], jan.inboxes()[0]);
assert_eq!(
eva.set_push(&his, Some(&endpoint("upX"))),
Err(ClientError::UnknownContact)
);
assert_eq!(relay.push_endpoint(&his), None);
eva.set_push(&mine, Some(&endpoint("upEva"))).expect("set");
eva.set_push(&mine, Some(&endpoint("upEva2")))
.expect("replace");
assert_eq!(
relay.push_endpoint(&mine).as_deref(),
Some("https://push.invalid/upEva2")
);
eva.set_push(&mine, None).expect("clear");
assert_eq!(relay.push_endpoint(&mine), None);
}
#[test]
fn a_blocked_contacts_inbox_is_still_listed() {
let relay = MemoryTransport::default();
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
let invite = eva.create_invite().expect("invite");
let jan_side = jan.accept_invite(&invite).expect("accept");
eva.poll().expect("poll");
let out = jan.block(jan_side).expect("block");
jan.deliver(&out).expect("deliver");
// Listed, so turning wake-ups off clears it too; nothing reaches it to wake anyone.
assert_eq!(jan.inboxes().len(), 1);
}
+54 -1
View File
@@ -129,13 +129,32 @@ impl Transport for Http {
serde_json::from_slice(&body).map_err(|_| TransportError::Failed)?;
Ok(claimed.key_package.bytes().to_vec())
}
fn set_push(
&self,
id: &MailboxId,
fetch: &Token,
endpoint: Option<&PushEndpoint>,
) -> Result<(), TransportError> {
let path = format!("/v0/mailboxes/{}/push", id.to_wire());
match endpoint {
Some(e) => {
let body = serde_json::to_vec(&SetPush {
endpoint: e.clone(),
})
.map_err(|_| TransportError::Failed)?;
self.call("PUT", &path, Some(fetch), &body, true)
}
None => self.call("DELETE", &path, Some(fetch), &[], false),
}
.map(|_| ())
}
}
/// Starts the real relay on 127.0.0.1:<free port> with its database in `db`.
fn start_relay(db: &std::path::Path) -> SocketAddr {
let store = Arc::new(Store::open(db).expect("store"));
let clock: Clock = Arc::new(|| 1_794_000_000);
let app = router(AppState { store, clock });
let app = router(AppState::new(store, clock));
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
@@ -222,3 +241,37 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
// The messages were there, as ciphertext: the database grew while they waited.
assert!(waiting.len() >= 4096, "the relay stored something");
}
// Wake-up (`.agents/features/wake-up.md` §2.4): an endpoint per mailbox, set and cleared through the
// real relay with the mailbox's fetch token.
#[test]
fn each_inbox_takes_its_own_push_endpoint_through_the_real_relay() {
let dir = tempfile::tempdir().expect("tempdir");
let db = dir.path().join("relay.db");
let relay = Http(start_relay(&db));
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
let invite = eva.create_invite().expect("invite");
jan.accept_invite(&invite).expect("accept");
eva.poll().expect("poll");
let (eva_boxes, jan_boxes) = (eva.inboxes(), jan.inboxes());
assert_eq!((eva_boxes.len(), jan_boxes.len()), (1, 1));
let endpoint = |path: &str| PushEndpoint::parse(&format!("https://push.invalid/{path}"));
let a = endpoint("upEvaOnly1").expect("endpoint");
eva.set_push(&eva_boxes[0], Some(&a)).expect("set");
jan.set_push(
&jan_boxes[0],
Some(&endpoint("upJanOnly2").expect("endpoint")),
)
.expect("set");
let stored = std::fs::read(&db).expect("db");
assert!(contains(&stored, b"upEvaOnly1") && contains(&stored, b"upJanOnly2"));
// Not Jan's mailbox: Eva cannot set it.
assert_eq!(
eva.set_push(&jan_boxes[0], Some(&a)),
Err(ClientError::UnknownContact)
);
eva.set_push(&eva_boxes[0], None).expect("clear");
// Nothing is posted after this: a post would make the relay try to wake `push.invalid`, and no
// test reaches for the network.
}
+8
View File
@@ -323,6 +323,14 @@ impl Transport for Flaky {
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
self.inner.create_invite(r)
}
fn set_push(
&self,
id: &tabellarius_protocol::MailboxId,
fetch: &tabellarius_protocol::Token,
endpoint: Option<&tabellarius_protocol::PushEndpoint>,
) -> Result<(), TransportError> {
self.inner.set_push(id, fetch, endpoint)
}
fn rotate_post_token(
&self,
id: &tabellarius_protocol::MailboxId,
+114
View File
@@ -23,6 +23,12 @@ pub const MAX_BLOBS_PER_FETCH: usize = 100;
pub const BLOB_TTL_SECS: i64 = 30 * 24 * 3600;
/// An unclaimed invite expires after this many seconds (7 days, `PROTOCOL.md` §4).
pub const INVITE_TTL_SECS: i64 = 7 * 24 * 3600;
/// The longest push endpoint a mailbox may hold (UnifiedPush's own limit, `wake-up.md` §2.1).
pub const MAX_PUSH_ENDPOINT_BYTES: usize = 1000;
/// The body of every wake: a constant, so it carries nothing (`PROTOCOL.md` §6).
pub const WAKE_BODY: &[u8] = b"wake";
/// A mailbox is woken at most once in this many seconds.
pub const WAKE_EVERY_SECS: i64 = 60;
/// Why a value from the wire was refused. Carries no part of the input.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -35,6 +41,8 @@ pub enum ParseError {
Scheme,
/// More bytes than the protocol allows.
TooLarge { max: usize },
/// Not a push endpoint the protocol accepts (`wake-up.md` §2.1).
Endpoint,
}
impl fmt::Display for ParseError {
@@ -46,6 +54,7 @@ impl fmt::Display for ParseError {
}
ParseError::Scheme => write!(f, "expected 'Bearer <token>'"),
ParseError::TooLarge { max } => write!(f, "more than {max} bytes"),
ParseError::Endpoint => write!(f, "not an https push endpoint"),
}
}
}
@@ -327,3 +336,108 @@ pub fn hour_of(unix_secs: i64) -> i64 {
pub fn day_of(unix_secs: i64) -> i64 {
unix_secs.div_euclid(86_400)
}
/// A push endpoint (`PROTOCOL.md` §6, `.agents/features/wake-up.md` §2.1): a capability URL at the
/// push server the mailbox's owner chose. `https://` with a host, no user info, no fragment, printable
/// ASCII, at most [`MAX_PUSH_ENDPOINT_BYTES`]; `http://` only to a loopback host, which a relay
/// accepts only when its operator allows it (tests).
#[derive(Clone, PartialEq, Eq)]
pub struct PushEndpoint {
url: String,
host: String,
https: bool,
}
impl PushEndpoint {
pub fn parse(text: &str) -> Result<Self, ParseError> {
let bad = || ParseError::Endpoint;
if text.len() > MAX_PUSH_ENDPOINT_BYTES {
return Err(ParseError::TooLarge {
max: MAX_PUSH_ENDPOINT_BYTES,
});
}
if !text.bytes().all(|b| (0x21..=0x7e).contains(&b)) || text.contains('#') {
return Err(bad());
}
let (https, rest) = if let Some(r) = text.strip_prefix("https://") {
(true, r)
} else if let Some(r) = text.strip_prefix("http://") {
(false, r)
} else {
return Err(bad());
};
let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())];
if authority.contains('@') {
return Err(bad());
}
let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
let end = v6.find(']').ok_or_else(bad)?;
(&v6[..end], &v6[end + 1..])
} else {
match authority.find(':') {
Some(i) => (&authority[..i], &authority[i..]),
None => (authority, ""),
}
};
if host.is_empty() || host.contains(['[', ']']) && !authority.starts_with('[') {
return Err(bad());
}
if !port.is_empty() {
let digits = port.strip_prefix(':').ok_or_else(bad)?;
match digits.parse::<u16>() {
Ok(p) if p > 0 && !digits.starts_with('0') => {}
_ => return Err(bad()),
}
}
let host = host.to_ascii_lowercase();
if !https && !matches!(host.as_str(), "127.0.0.1" | "::1" | "localhost") {
return Err(bad());
}
Ok(Self {
url: text.to_string(),
host,
https,
})
}
pub fn as_str(&self) -> &str {
&self.url
}
/// The host, lower case, without brackets or port.
pub fn host(&self) -> &str {
&self.host
}
/// `http://` to a loopback host: only for a relay whose operator allows it.
pub fn is_loopback_http(&self) -> bool {
!self.https
}
}
/// The endpoint is a capability: `Debug` shows its host only.
impl fmt::Debug for PushEndpoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PushEndpoint({})", self.host)
}
}
impl Serialize for PushEndpoint {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.url)
}
}
impl<'de> Deserialize<'de> for PushEndpoint {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let text = Cow::<'de, str>::deserialize(d)?;
PushEndpoint::parse(&text).map_err(serde::de::Error::custom)
}
}
/// `PUT /v0/mailboxes/{id}/push`: where to wake the mailbox's owner (`PROTOCOL.md` §6).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SetPush {
pub endpoint: PushEndpoint,
}
+80
View File
@@ -184,3 +184,83 @@ proptest! {
prop_assert_eq!(back.bytes(), &bytes[..]);
}
}
// Wake-up (`.agents/features/wake-up.md` §2.1): the push endpoint a mailbox may hold.
#[test]
fn a_push_endpoint_is_https_or_loopback_http_and_nothing_else() {
for good in [
"https://ntfy.sh/upAbCdEf0123456789?up=1",
"https://push.example.cz:8443/x",
"https://[2001:db8::1]/up",
"https://ntfy.sh",
] {
let e = PushEndpoint::parse(good).unwrap_or_else(|_| panic!("{good}"));
assert_eq!(e.as_str(), good);
assert!(!e.is_loopback_http());
}
assert_eq!(
PushEndpoint::parse("https://NTFY.sh/a").map(|e| e.host().to_string()),
Ok("ntfy.sh".into())
);
for loopback in [
"http://127.0.0.1:9000/up",
"http://[::1]:9000/up",
"http://localhost/up",
] {
assert!(PushEndpoint::parse(loopback)
.expect("loopback")
.is_loopback_http());
}
for bad in [
"",
"ntfy.sh/up",
"ftp://ntfy.sh/up",
"http://ntfy.sh/up",
"http://10.0.0.1/up",
"https:///up",
"https://user:pw@ntfy.sh/up",
"https://user@ntfy.sh/up",
"https://ntfy.sh/up#frag",
"https://ntfy.sh/a b",
"https://ntfy.sh/\u{e9}",
"https://ntfy.sh:0/up",
"https://ntfy.sh:65536/up",
"https://ntfy.sh:08/up",
"https://ntfy.sh:/up",
"https://[::1/up",
"https://ntfy]sh/up",
] {
assert!(PushEndpoint::parse(bad).is_err(), "{bad}");
}
let long = format!("https://ntfy.sh/{}", "a".repeat(MAX_PUSH_ENDPOINT_BYTES));
assert_eq!(
PushEndpoint::parse(&long),
Err(ParseError::TooLarge {
max: MAX_PUSH_ENDPOINT_BYTES
})
);
}
#[test]
fn set_push_refuses_unknown_fields_and_bad_endpoints_and_debug_hides_the_path() {
let ok: SetPush =
serde_json::from_str(r#"{"endpoint":"https://ntfy.sh/upSecret"}"#).expect("json");
assert_eq!(ok.endpoint.as_str(), "https://ntfy.sh/upSecret");
assert!(!format!("{ok:?}").contains("upSecret"));
assert!(serde_json::from_str::<SetPush>(r#"{"endpoint":"http://ntfy.sh/x"}"#).is_err());
assert!(
serde_json::from_str::<SetPush>(r#"{"endpoint":"https://ntfy.sh/x","extra":1}"#).is_err()
);
assert_eq!(
serde_json::to_string(&ok).expect("json"),
r#"{"endpoint":"https://ntfy.sh/upSecret"}"#
);
}
proptest! {
#[test]
fn a_push_endpoint_parser_never_panics(text in "\\PC{0,64}") {
let _ = PushEndpoint::parse(&text);
let _ = PushEndpoint::parse(&format!("https://{text}"));
}
}
+3
View File
@@ -18,6 +18,9 @@ subtle = "2"
# The join page's Content-Security-Policy names its inline script and style by SHA-256 (base64).
sha2 = "0.10"
base64 = "0.22"
# The wake (`.agents/features/wake-up.md` §2.2): the relay's only outgoing request. rustls with
# Mozilla's roots built in; the resolver is the relay's own, which drops every non-global address.
ureq = { version = "3", default-features = false, features = ["rustls"] }
[dev-dependencies]
getrandom = "0.3"
+54 -3
View File
@@ -2,6 +2,7 @@
//! address, and nothing here writes a request anywhere.
use crate::store::{Refused, Store};
use crate::wake::Waker;
use axum::body::Bytes;
use axum::extract::{DefaultBodyLimit, Path, State};
use axum::http::{header, HeaderMap, StatusCode};
@@ -11,8 +12,8 @@ use axum::{Json, Router};
use serde::de::DeserializeOwned;
use std::sync::Arc;
use tabellarius_protocol::{
CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, Sha256Hash,
Token, VersionInfo, MAX_BLOB_BYTES, VERSION,
CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, SetPush,
Sha256Hash, Token, VersionInfo, MAX_BLOB_BYTES, VERSION,
};
/// Unix seconds. The server passes the system clock; tests pass their own.
@@ -22,6 +23,23 @@ pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
pub struct AppState {
pub store: Arc<Store>,
pub clock: Clock,
/// Wakes a mailbox's owner when a blob arrives (`PROTOCOL.md` §6).
pub waker: Arc<Waker>,
}
impl AppState {
/// A relay that wakes only global `https://` endpoints: what a relay facing the internet runs.
pub fn new(store: Arc<Store>, clock: Clock) -> Self {
Self::with_waker(store, clock, Waker::new(false))
}
pub fn with_waker(store: Arc<Store>, clock: Clock, waker: Waker) -> Self {
Self {
store,
clock,
waker: Arc::new(waker),
}
}
}
/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url.
@@ -35,6 +53,7 @@ pub fn router(state: AppState) -> Router {
.route("/v0/mailboxes", post(create_mailbox))
.route("/v0/mailboxes/{id}/blobs/{hash}", delete(acknowledge))
.route("/v0/mailboxes/{id}/post-token", put(rotate_post_token))
.route("/v0/mailboxes/{id}/push", put(set_push).delete(clear_push))
.route("/v0/invites", post(create_invite))
.route("/v0/invites/{id}", get(claim_invite))
.route("/version", get(version))
@@ -98,7 +117,12 @@ async fn post_blob(
) -> Result<StatusCode, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
s.store.post(&id, &token, &body, (s.clock)())?;
let now = (s.clock)();
s.store.post(&id, &token, &body, now)?;
// Only after the blob is stored under a valid post token; the 201 does not wait for the wake.
if let Ok(Some(endpoint)) = s.store.push_endpoint(&id) {
s.waker.wake(Arc::clone(&s.store), id, endpoint, now);
}
Ok(StatusCode::CREATED)
}
@@ -139,6 +163,33 @@ async fn rotate_post_token(
Ok(StatusCode::NO_CONTENT)
}
async fn set_push(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> Result<StatusCode, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
let req: SetPush = json(&body)?;
if !s.waker.accepts(&req.endpoint) {
return Err(Status(StatusCode::BAD_REQUEST));
}
s.store.set_push(&id, &token, Some(&req.endpoint))?;
Ok(StatusCode::NO_CONTENT)
}
async fn clear_push(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
) -> Result<StatusCode, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
s.store.set_push(&id, &token, None)?;
Ok(StatusCode::NO_CONTENT)
}
async fn create_invite(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
let req: CreateInvite = json(&body)?;
s.store.create_invite(&req, (s.clock)())?;
+13 -3
View File
@@ -4,6 +4,7 @@
pub mod http;
pub mod join;
pub mod store;
pub mod wake;
use std::net::SocketAddr;
use std::path::PathBuf;
@@ -17,17 +18,20 @@ pub struct Args {
pub listen: SocketAddr,
pub db: PathBuf,
pub limits: store::Limits,
/// `--push-loopback`: accept and wake `http://` loopback push endpoints. Tests only.
pub push_loopback: bool,
}
/// `--listen <addr:port>`, `--db <path>`, and the relay-wide quotas `--max-bytes`,
/// `--max-mailboxes`, `--max-invites` (positive integers). Anything else is refused with a usage
/// `--max-mailboxes`, `--max-invites` (positive integers), and `--push-loopback` (tests). Anything else is refused with a usage
/// line.
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] \
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000]";
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000] \n [--push-loopback]";
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
let mut db = PathBuf::from(DEFAULT_DB);
let mut limits = store::Limits::default();
let mut push_loopback = false;
let mut it = args.into_iter();
let positive = |v: Option<String>| -> Result<i64, String> {
v.and_then(|v| v.parse::<i64>().ok())
@@ -39,6 +43,7 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
"--max-bytes" => limits.total_bytes = positive(it.next())?,
"--max-mailboxes" => limits.mailboxes = positive(it.next())?,
"--max-invites" => limits.invites = positive(it.next())?,
"--push-loopback" => push_loopback = true,
"--listen" => {
listen = it
.next()
@@ -54,5 +59,10 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
_ => return Err(usage.to_string()),
}
}
Ok(Args { listen, db, limits })
Ok(Args {
listen,
db,
limits,
push_loopback,
})
}
+7 -2
View File
@@ -1,5 +1,5 @@
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] [--max-bytes N]
//! [--max-mailboxes N] [--max-invites N]`
//! [--max-mailboxes N] [--max-invites N] [--push-loopback]`
//!
//! Prints one line at start (version and address) and nothing per request.
@@ -8,6 +8,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tabellarius_relay::http::{router, AppState, Clock};
use tabellarius_relay::parse_args;
use tabellarius_relay::store::Store;
use tabellarius_relay::wake::Waker;
fn now() -> i64 {
SystemTime::now()
@@ -63,7 +64,11 @@ async fn main() {
});
let clock: Clock = Arc::new(now);
let app = router(AppState { store, clock });
let app = router(AppState::with_waker(
store,
clock,
Waker::new(args.push_loopback),
));
let shutdown = async {
let _ = tokio::signal::ctrl_c().await;
};
+51 -3
View File
@@ -1,6 +1,6 @@
//! Every rule of the relay, over SQLite, with the clock passed in.
//!
//! The database holds exactly `docs/PROTOCOL.md` §5: three tables, and nothing about who connected.
//! The database holds exactly `docs/PROTOCOL.md` §5: four tables, and nothing about who connected.
//! A wrong token and an unknown id give the same [`Refused::NotFound`], so nobody can probe which
//! mailboxes or invites exist.
@@ -10,8 +10,8 @@ use std::sync::Mutex;
use subtle::ConstantTimeEq;
use tabellarius_protocol::{
blob_hash, day_of, hour_of, BlobBytes, ClaimedInvite, CreateInvite, CreateMailbox, FetchedBlob,
InviteId, KeyPackageBytes, MailboxId, Sha256Hash, Token, BLOB_TTL_SECS, INVITE_TTL_SECS,
MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES,
InviteId, KeyPackageBytes, MailboxId, PushEndpoint, Sha256Hash, Token, BLOB_TTL_SECS,
INVITE_TTL_SECS, MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES,
};
/// The schema, and nothing else (`PROTOCOL.md` §5). A column added here is a protocol change.
@@ -35,6 +35,10 @@ CREATE TABLE IF NOT EXISTS invites (
key_package BLOB NOT NULL,
expiry INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS push (
mailbox_id BLOB PRIMARY KEY NOT NULL,
endpoint TEXT NOT NULL
);
";
/// Why a request was refused. Deliberately coarse: it says nothing about which part was wrong.
@@ -351,6 +355,50 @@ impl Store {
})
}
/// Sets (`Some`) or removes (`None`) the mailbox's push endpoint. Needs the fetch token: only the
/// owner says where to be woken (`PROTOCOL.md` §6).
pub fn set_push(
&self,
id: &MailboxId,
token: &Token,
endpoint: Option<&PushEndpoint>,
) -> Result<(), Refused> {
let conn = self.conn();
Self::authorize(&conn, id, token, Column::Fetch)?;
match endpoint {
Some(e) => conn.execute(
"INSERT OR REPLACE INTO push (mailbox_id, endpoint) VALUES (?1, ?2)",
params![&id.as_bytes()[..], e.as_str()],
)?,
None => conn.execute(
"DELETE FROM push WHERE mailbox_id = ?1",
[&id.as_bytes()[..]],
)?,
};
Ok(())
}
/// The endpoint to wake after a blob was stored for this mailbox, if its owner gave one.
pub fn push_endpoint(&self, id: &MailboxId) -> Result<Option<String>, Refused> {
Ok(self
.conn()
.query_row(
"SELECT endpoint FROM push WHERE mailbox_id = ?1",
[&id.as_bytes()[..]],
|r| r.get(0),
)
.optional()?)
}
/// The push server said the endpoint is gone: removes it, unless the owner has set another since.
pub fn drop_push_if(&self, id: &MailboxId, endpoint: &str) -> Result<(), Refused> {
self.conn().execute(
"DELETE FROM push WHERE mailbox_id = ?1 AND endpoint = ?2",
params![&id.as_bytes()[..], endpoint],
)?;
Ok(())
}
/// Deletes blobs older than 30 days and invites past their expiry.
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
let conn = self.conn();
+257
View File
@@ -0,0 +1,257 @@
//! The relay's only outgoing request: a wake to a mailbox owner's push endpoint when a blob arrived
//! (`docs/PROTOCOL.md` §6, `.agents/features/wake-up.md` §2.2).
//!
//! The body is a constant; nothing of the mailbox, the blob or its sender goes out. A mailbox is
//! woken at most once a minute, remembered in memory only. The endpoint's host is resolved here and
//! every address that is not global is dropped before connecting, so a mailbox owner cannot point
//! the relay at its own network. Nothing about a wake is printed.
use crate::store::Store;
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tabellarius_protocol::{MailboxId, PushEndpoint, WAKE_BODY, WAKE_EVERY_SECS};
use tokio::sync::Semaphore;
use ureq::config::Config;
use ureq::http::Uri;
use ureq::unversioned::resolver::{DefaultResolver, ResolvedSocketAddrs, Resolver};
use ureq::unversioned::transport::{DefaultConnector, NextTimeout};
/// At most this many wakes are on their way at once; beyond that a wake is dropped.
pub const MAX_IN_FLIGHT: usize = 16;
/// A wake gives up after this long.
pub const WAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// The in-memory "woken lately" map is pruned when it reaches this size.
const MAX_REMEMBERED: usize = 100_000;
pub struct Waker {
allow_loopback: bool,
/// Mailbox → the second it was last woken. Memory only: `PROTOCOL.md` §5 does not change.
woken: Mutex<HashMap<MailboxId, i64>>,
slots: Arc<Semaphore>,
agent: ureq::Agent,
}
/// What a wake came to; the tests read it, the relay only acts on `Gone`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
Delivered,
/// 404 or 410: the endpoint no longer exists, so it is removed.
Gone,
/// Anything else: the network, a refused address, a timeout, another status.
Failed,
}
impl Waker {
/// `allow_loopback`: `http://` to a loopback host, and loopback addresses, for tests only
/// (`--push-loopback`). A relay facing the internet never sets it.
pub fn new(allow_loopback: bool) -> Self {
let config = Config::builder()
.timeout_global(Some(WAKE_TIMEOUT))
.max_redirects(0)
.http_status_as_error(false)
.proxy(None)
.build();
let agent = ureq::Agent::with_parts(
config,
DefaultConnector::default(),
GlobalOnly { allow_loopback },
);
Self {
allow_loopback,
woken: Mutex::new(HashMap::new()),
slots: Arc::new(Semaphore::new(MAX_IN_FLIGHT)),
agent,
}
}
/// Whether this relay accepts the endpoint at all.
pub fn accepts(&self, endpoint: &PushEndpoint) -> bool {
!endpoint.is_loopback_http() || self.allow_loopback
}
/// After a blob was stored: wakes the mailbox's owner, unless it was woken in the last minute or
/// too many wakes are on their way. Returns at once; the request runs in the background.
pub fn wake(&self, store: Arc<Store>, id: MailboxId, endpoint: String, now: i64) -> bool {
if !self.due(id, now) {
return false;
}
let Ok(slot) = Arc::clone(&self.slots).try_acquire_owned() else {
return false;
};
let agent = self.agent.clone();
tokio::task::spawn_blocking(move || {
let _slot = slot;
if send(&agent, &endpoint) == Outcome::Gone {
let _ = store.drop_push_if(&id, &endpoint);
}
});
true
}
/// Once a minute per mailbox. A clock that went back counts as due.
fn due(&self, id: MailboxId, now: i64) -> bool {
let mut woken = self.woken.lock().unwrap_or_else(|e| e.into_inner());
if let Some(&last) = woken.get(&id) {
if (0..WAKE_EVERY_SECS).contains(&(now - last)) {
return false;
}
}
if woken.len() >= MAX_REMEMBERED {
woken.retain(|_, last| now - *last < WAKE_EVERY_SECS);
}
woken.insert(id, now);
true
}
}
/// One wake: the constant body and nothing else of the relay's.
pub fn send(agent: &ureq::Agent, endpoint: &str) -> Outcome {
let sent = agent
.post(endpoint)
.header("TTL", "86400")
.header("Urgency", "normal")
.header("Content-Type", "application/octet-stream")
.send(WAKE_BODY);
match sent.map(|r| r.status().as_u16()) {
Ok(200..=299) => Outcome::Delivered,
Ok(404 | 410) => Outcome::Gone,
_ => Outcome::Failed,
}
}
/// The system's resolver, with every address that is not global dropped.
#[derive(Debug)]
struct GlobalOnly {
allow_loopback: bool,
}
impl Resolver for GlobalOnly {
fn resolve(
&self,
uri: &Uri,
config: &Config,
timeout: NextTimeout,
) -> Result<ResolvedSocketAddrs, ureq::Error> {
let all = DefaultResolver::default().resolve(uri, config, timeout)?;
let mut kept = self.empty();
for addr in &all {
if reachable(addr.ip(), self.allow_loopback) {
kept.push(*addr);
}
}
if kept.is_empty() {
Err(ureq::Error::HostNotFound)
} else {
Ok(kept)
}
}
}
/// Whether the relay may connect to this address: global unicast only (loopback when allowed).
pub fn reachable(ip: IpAddr, allow_loopback: bool) -> bool {
match ip {
IpAddr::V4(v4) => v4_reachable(v4, allow_loopback),
IpAddr::V6(v6) => {
// An IPv4 address in IPv6 clothing is judged as the IPv4 address.
if let Some(v4) = v6.to_ipv4_mapped() {
return v4_reachable(v4, allow_loopback);
}
let s = v6.segments();
// NAT64 (64:ff9b::/96) reaches the IPv4 address in its last 32 bits.
if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
let v4 =
Ipv4Addr::new((s[6] >> 8) as u8, s[6] as u8, (s[7] >> 8) as u8, s[7] as u8);
return v4_reachable(v4, allow_loopback);
}
v6_reachable(v6, allow_loopback)
}
}
}
fn v4_reachable(ip: Ipv4Addr, allow_loopback: bool) -> bool {
if ip.is_loopback() {
return allow_loopback;
}
let o = ip.octets();
!(o[0] == 0 // "this network"
|| ip.is_private() // 10/8, 172.16/12, 192.168/16
|| ip.is_link_local() // 169.254/16
|| (o[0] == 100 && (o[1] & 0xc0) == 64) // CGNAT 100.64/10
|| (o[0] == 192 && o[1] == 0 && o[2] == 0) // IETF 192.0.0/24
|| ip.is_documentation()
|| (o[0] == 198 && (o[1] & 0xfe) == 18) // benchmarking 198.18/15
|| ip.is_multicast()
|| o[0] >= 240) // reserved and broadcast
}
fn v6_reachable(ip: Ipv6Addr, allow_loopback: bool) -> bool {
if ip.is_loopback() {
return allow_loopback;
}
let s = ip.segments();
!(ip.is_unspecified()
|| ip.is_multicast()
|| s[..6] == [0; 6] // IPv4-compatible ::/96
|| (s[0] & 0xfe00) == 0xfc00 // unique local fc00::/7
|| (s[0] & 0xffc0) == 0xfe80 // link-local fe80::/10
|| (s[0] & 0xffc0) == 0xfec0 // site-local fec0::/10
|| (s[0] == 0x2001 && s[1] == 0x0db8) // documentation
|| s[0] == 0x2002 // 6to4: an IPv4 address inside
|| (s[0] == 0x2001 && s[1] == 0) // Teredo
|| (s[0] == 0x0100 && s[1..4] == [0; 3])) // discard-only 100::/64
}
#[cfg(test)]
mod tests {
use super::*;
fn ok(text: &str) -> bool {
reachable(text.parse().expect("an address"), false)
}
#[test]
fn only_global_addresses_are_reachable() {
for global in ["1.1.1.1", "159.69.10.20", "2a01:4f8::1", "64:ff9b::808:808"] {
assert!(ok(global), "{global}");
}
for not in [
"127.0.0.1",
"10.1.2.3",
"172.16.0.1",
"192.168.1.1",
"169.254.169.254",
"100.64.0.1",
"0.0.0.0",
"192.0.0.8",
"192.0.2.1",
"198.18.0.1",
"224.0.0.1",
"255.255.255.255",
"::1",
"::",
"fc00::1",
"fd12::1",
"fe80::1",
"ff02::1",
"2001:db8::1",
"::ffff:10.0.0.1",
"::ffff:127.0.0.1",
"::10.0.0.1",
"64:ff9b::a00:1",
"2002:a00:1::",
"2001:0:4136:e378::1",
"100::1",
] {
assert!(!ok(not), "{not}");
}
}
#[test]
fn loopback_only_when_allowed() {
assert!(reachable("127.0.0.1".parse().expect("v4"), true));
assert!(reachable("::1".parse().expect("v6"), true));
assert!(!reachable("10.0.0.1".parse().expect("v4"), true));
}
}
+1 -1
View File
@@ -44,7 +44,7 @@ impl Relay {
fn with(limits: Limits) -> Self {
let store = Arc::new(Store::open_in_memory_with(limits).expect("store"));
let clock: Clock = Arc::new(|| T0);
Relay(router(AppState { store, clock }))
Relay(router(AppState::new(store, clock)))
}
async fn call(
&self,
+12 -4
View File
@@ -63,10 +63,7 @@ impl Relay {
let now = Arc::new(AtomicI64::new(T0));
let n = Arc::clone(&now);
let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst));
let app = router(AppState {
store: Arc::clone(&store),
clock,
});
let app = router(AppState::new(Arc::clone(&store), clock));
Self { app, store, now }
}
fn advance(&self, secs: i64) {
@@ -168,6 +165,8 @@ fn schema_is_exactly_protocol_section_5() {
"created_day".into(),
],
),
// Wake-up (`.agents/features/wake-up.md` §2.3), only for a mailbox whose owner opted in.
("push".into(), vec!["mailbox_id".into(), "endpoint".into()]),
];
assert_eq!(
live, expected,
@@ -628,6 +627,15 @@ fn the_relay_listens_on_loopback_unless_told_otherwise() {
let args = parse_args(Vec::<String>::new()).expect("defaults");
assert_eq!(args.listen.to_string(), DEFAULT_LISTEN);
assert!(args.listen.ip().is_loopback());
assert!(
!args.push_loopback,
"loopback push endpoints only when asked for"
);
assert!(
parse_args(["--push-loopback".to_string()])
.expect("flag")
.push_loopback
);
assert!(parse_args(["--listen".to_string()]).is_err());
assert!(parse_args(["--verbose".to_string()]).is_err());
}
+448
View File
@@ -0,0 +1,448 @@
//! Wake-up (`docs/PROTOCOL.md` §6, `.agents/features/wake-up.md`): the push routes and the one
//! request the relay sends, against a push server on loopback. Tokens and ids are generated per test.
use axum::body::{Body, Bytes};
use axum::http::{header, HeaderMap, Method, Request, StatusCode};
use http_body_util::BodyExt;
use std::sync::atomic::{AtomicI64, AtomicU16, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tabellarius_protocol::*;
use tabellarius_relay::http::{router, AppState, Clock};
use tabellarius_relay::store::Store;
use tabellarius_relay::wake::Waker;
use tower::ServiceExt;
const T0: i64 = 1_794_000_000;
fn random<const N: usize>() -> [u8; N] {
let mut b = [0u8; N];
getrandom::fill(&mut b).expect("system randomness");
b
}
struct Mailbox {
id: MailboxId,
post: Token,
fetch: Token,
}
impl Mailbox {
fn new() -> Self {
Self {
id: MailboxId::from_bytes(random()),
post: Token::from_bytes(random()),
fetch: Token::from_bytes(random()),
}
}
fn path(&self, rest: &str) -> String {
format!("/v0/mailboxes/{}/{rest}", self.id.to_wire())
}
}
/// What reached the push server: path, headers, body.
#[derive(Clone)]
struct Seen {
path: String,
headers: HeaderMap,
body: Vec<u8>,
}
/// A push server on loopback that records every request and answers with `status`.
struct PushServer {
port: u16,
seen: Arc<Mutex<Vec<Seen>>>,
status: Arc<AtomicU16>,
}
impl PushServer {
async fn start() -> Self {
let seen = Arc::new(Mutex::new(Vec::new()));
let status = Arc::new(AtomicU16::new(201));
let (s, st) = (Arc::clone(&seen), Arc::clone(&status));
let app = axum::Router::new().fallback(
move |uri: axum::http::Uri, headers: HeaderMap, body: Bytes| {
let (s, st) = (Arc::clone(&s), Arc::clone(&st));
async move {
s.lock().expect("seen").push(Seen {
path: uri.to_string(),
headers,
body: body.to_vec(),
});
StatusCode::from_u16(st.load(Ordering::SeqCst)).expect("status")
}
},
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let port = listener.local_addr().expect("addr").port();
tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
Self { port, seen, status }
}
fn endpoint(&self, path: &str) -> String {
format!("http://127.0.0.1:{}{path}", self.port)
}
fn seen(&self) -> Vec<Seen> {
self.seen.lock().expect("seen").clone()
}
/// Waits up to 5 s for `n` requests.
async fn wait_for(&self, n: usize) -> Vec<Seen> {
for _ in 0..100 {
if self.seen().len() >= n {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
self.seen()
}
/// Gives a wake that should not happen a second to show up anyway.
async fn quiet(&self) -> Vec<Seen> {
tokio::time::sleep(Duration::from_secs(1)).await;
self.seen()
}
}
struct Relay {
app: axum::Router,
store: Arc<Store>,
now: Arc<AtomicI64>,
}
impl Relay {
/// `loopback`: the relay was started with `--push-loopback`, as tests must be to reach a local
/// push server.
fn new(loopback: bool) -> Self {
let store = Arc::new(Store::open_in_memory().expect("store"));
let now = Arc::new(AtomicI64::new(T0));
let n = Arc::clone(&now);
let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst));
let app = router(AppState::with_waker(
Arc::clone(&store),
clock,
Waker::new(loopback),
));
Self { app, store, now }
}
async fn call(
&self,
method: Method,
path: &str,
auth: Option<&Token>,
body: Vec<u8>,
) -> StatusCode {
let mut req = Request::builder().method(method).uri(path);
if let Some(t) = auth {
req = req.header(header::AUTHORIZATION, t.to_bearer());
}
let resp = self
.app
.clone()
.oneshot(req.body(Body::from(body)).expect("request"))
.await
.expect("infallible");
let status = resp.status();
let body = resp.into_body().collect().await.expect("body").to_bytes();
assert!(
status != StatusCode::NOT_FOUND || body.is_empty(),
"a 404 has no body"
);
status
}
async fn mailbox(&self) -> Mailbox {
let m = Mailbox::new();
let body = serde_json::to_vec(&CreateMailbox {
id: m.id,
post_token_hash: m.post.hash(),
fetch_token_hash: m.fetch.hash(),
})
.expect("json");
assert_eq!(
self.call(Method::POST, "/v0/mailboxes", None, body).await,
StatusCode::CREATED
);
m
}
async fn set_push(&self, m: &Mailbox, token: &Token, endpoint: &str) -> StatusCode {
let body = format!(r#"{{"endpoint":"{endpoint}"}}"#).into_bytes();
self.call(Method::PUT, &m.path("push"), Some(token), body)
.await
}
async fn clear_push(&self, m: &Mailbox, token: &Token) -> StatusCode {
self.call(Method::DELETE, &m.path("push"), Some(token), vec![])
.await
}
async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode {
self.call(Method::POST, &m.path("blobs"), Some(token), blob.to_vec())
.await
}
fn advance(&self, secs: i64) {
self.now.fetch_add(secs, Ordering::SeqCst);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn only_the_owner_sets_or_clears_where_to_be_woken() {
let relay = Relay::new(true);
let push = PushServer::start().await;
let m = relay.mailbox().await;
let endpoint = push.endpoint("/up/a");
// The post token is the contact's: it cannot say where the owner is woken.
assert_eq!(
relay.set_push(&m, &m.post, &endpoint).await,
StatusCode::NOT_FOUND
);
assert_eq!(
relay.set_push(&Mailbox::new(), &m.fetch, &endpoint).await,
StatusCode::NOT_FOUND
);
assert_eq!(
relay
.call(Method::PUT, &m.path("push"), Some(&m.fetch), b"{}".to_vec())
.await,
StatusCode::BAD_REQUEST
);
assert_eq!(
relay
.set_push(&m, &m.fetch, "http://push.example.cz/up")
.await,
StatusCode::BAD_REQUEST
);
assert_eq!(
relay.set_push(&m, &m.fetch, &endpoint).await,
StatusCode::NO_CONTENT
);
assert_eq!(
relay.store.push_endpoint(&m.id).expect("read"),
Some(endpoint)
);
assert_eq!(relay.clear_push(&m, &m.post).await, StatusCode::NOT_FOUND);
assert_eq!(relay.clear_push(&m, &m.fetch).await, StatusCode::NO_CONTENT);
assert_eq!(relay.store.push_endpoint(&m.id).expect("read"), None);
// Clearing what is not there is not an error.
assert_eq!(relay.clear_push(&m, &m.fetch).await, StatusCode::NO_CONTENT);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_relay_facing_the_internet_refuses_loopback_endpoints() {
let relay = Relay::new(false);
let m = relay.mailbox().await;
assert_eq!(
relay.set_push(&m, &m.fetch, "http://127.0.0.1:9/up").await,
StatusCode::BAD_REQUEST
);
assert_eq!(relay.store.push_endpoint(&m.id).expect("read"), None);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_post_wakes_with_a_constant_and_nothing_of_the_mailbox_or_the_blob() {
let relay = Relay::new(true);
let push = PushServer::start().await;
let m = relay.mailbox().await;
assert_eq!(
relay
.set_push(&m, &m.fetch, &push.endpoint("/upToken123?up=1"))
.await,
StatusCode::NO_CONTENT
);
let canary = b"CANARY-wake-7f3a9c";
assert_eq!(relay.post(&m, &m.post, canary).await, StatusCode::CREATED);
let seen = push.wait_for(1).await;
assert_eq!(seen.len(), 1, "one wake");
let wake = &seen[0];
assert_eq!(wake.path, "/upToken123?up=1");
assert_eq!(wake.body, WAKE_BODY);
assert_eq!(wake.headers.get("ttl").expect("TTL"), "86400");
assert_eq!(wake.headers.get("urgency").expect("Urgency"), "normal");
// Nothing of the mailbox, its tokens or the blob, anywhere in the request.
let mut everything = wake.path.clone().into_bytes();
for (name, value) in &wake.headers {
everything.extend_from_slice(name.as_str().as_bytes());
everything.extend_from_slice(value.as_bytes());
}
everything.extend_from_slice(&wake.body);
let text = String::from_utf8_lossy(&everything);
for secret in [
m.id.to_wire(),
m.post.to_wire(),
m.fetch.to_wire(),
blob_hash(canary).to_wire(),
] {
assert!(!text.contains(&secret), "the wake carries {secret}");
}
assert!(!text.contains("CANARY"), "the wake carries the blob");
assert!(!text.contains("authorization"), "no token goes out");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_mailbox_is_woken_at_most_once_a_minute() {
let relay = Relay::new(true);
let push = PushServer::start().await;
let m = relay.mailbox().await;
relay.set_push(&m, &m.fetch, &push.endpoint("/up/a")).await;
for _ in 0..3 {
assert_eq!(relay.post(&m, &m.post, b"x").await, StatusCode::CREATED);
}
assert_eq!(push.wait_for(1).await.len(), 1);
relay.advance(WAKE_EVERY_SECS - 1);
relay.post(&m, &m.post, b"y").await;
assert_eq!(push.quiet().await.len(), 1, "within the minute");
relay.advance(1);
relay.post(&m, &m.post, b"z").await;
assert_eq!(push.wait_for(2).await.len(), 2, "after the minute");
// Another mailbox has its own minute.
let other = relay.mailbox().await;
relay
.set_push(&other, &other.fetch, &push.endpoint("/up/b"))
.await;
relay.post(&other, &other.post, b"w").await;
let seen = push.wait_for(3).await;
assert_eq!(seen.len(), 3);
assert_eq!(seen[2].path, "/up/b");
}
#[tokio::test(flavor = "multi_thread")]
async fn nothing_wakes_without_a_stored_post_or_without_an_endpoint() {
let relay = Relay::new(true);
let push = PushServer::start().await;
let m = relay.mailbox().await;
// No endpoint: a post wakes nobody.
relay.post(&m, &m.post, b"before").await;
relay.set_push(&m, &m.fetch, &push.endpoint("/up/a")).await;
// A refused post wakes nobody: a stranger, or the owner's fetch token.
assert_eq!(
relay.post(&m, &Token::from_bytes(random()), b"x").await,
StatusCode::NOT_FOUND
);
assert_eq!(relay.post(&m, &m.fetch, b"x").await, StatusCode::NOT_FOUND);
let too_big = vec![0u8; MAX_BLOB_BYTES + 1];
assert_ne!(relay.post(&m, &m.post, &too_big).await, StatusCode::CREATED);
assert!(push.quiet().await.is_empty());
// Cleared: nothing either.
relay.clear_push(&m, &m.fetch).await;
relay.post(&m, &m.post, b"after").await;
assert!(push.quiet().await.is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn an_endpoint_the_push_server_says_is_gone_is_removed() {
let relay = Relay::new(true);
let push = PushServer::start().await;
let m = relay.mailbox().await;
let endpoint = push.endpoint("/up/a");
relay.set_push(&m, &m.fetch, &endpoint).await;
// A failure that is not "gone" keeps it.
push.status.store(500, Ordering::SeqCst);
relay.post(&m, &m.post, b"x").await;
push.wait_for(1).await;
tokio::time::sleep(Duration::from_millis(300)).await;
assert_eq!(
relay.store.push_endpoint(&m.id).expect("read"),
Some(endpoint)
);
push.status.store(410, Ordering::SeqCst);
relay.advance(WAKE_EVERY_SECS);
relay.post(&m, &m.post, b"y").await;
push.wait_for(2).await;
let mut gone = false;
for _ in 0..50 {
gone = relay.store.push_endpoint(&m.id).expect("read").is_none();
if gone {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
assert!(gone, "410: the endpoint is removed");
}
/// A raw listener that only counts connections: proves whether the relay connected at all.
async fn counting_listener() -> (u16, Arc<AtomicUsize>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let port = listener.local_addr().expect("addr").port();
let count = Arc::new(AtomicUsize::new(0));
let c = Arc::clone(&count);
tokio::spawn(async move {
while let Ok((conn, _)) = listener.accept().await {
c.fetch_add(1, Ordering::SeqCst);
drop(conn);
}
});
(port, count)
}
#[tokio::test(flavor = "multi_thread")]
async fn an_https_endpoint_on_a_local_address_is_never_connected_to() {
// `https://127.0.0.1` passes the endpoint's syntax, so only the resolver stands in the way.
for (loopback, expected) in [(false, 0), (true, 1)] {
let relay = Relay::new(loopback);
let (port, count) = counting_listener().await;
let m = relay.mailbox().await;
assert_eq!(
relay
.set_push(&m, &m.fetch, &format!("https://127.0.0.1:{port}/up"))
.await,
StatusCode::NO_CONTENT
);
relay.post(&m, &m.post, b"x").await;
tokio::time::sleep(Duration::from_secs(1)).await;
assert_eq!(
count.load(Ordering::SeqCst),
expected,
"with --push-loopback {loopback}"
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_redirect_from_the_push_server_is_not_followed() {
let relay = Relay::new(true);
let push = PushServer::start().await;
let m = relay.mailbox().await;
// The push server answers 303 to a second path on itself: following it would show up there.
let target = push.endpoint("/second");
let redirecting = axum::Router::new().fallback(move || {
let target = target.clone();
async move { (StatusCode::SEE_OTHER, [(header::LOCATION, target)]) }
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let port = listener.local_addr().expect("addr").port();
tokio::spawn(async move {
let _ = axum::serve(listener, redirecting).await;
});
relay
.set_push(&m, &m.fetch, &format!("http://127.0.0.1:{port}/first"))
.await;
relay.post(&m, &m.post, b"x").await;
assert!(push.quiet().await.is_empty(), "the redirect was followed");
}
#[test]
fn a_gone_endpoint_does_not_remove_the_one_set_since() {
let store = Store::open_in_memory().expect("store");
let m = Mailbox::new();
store
.create_mailbox(
&CreateMailbox {
id: m.id,
post_token_hash: m.post.hash(),
fetch_token_hash: m.fetch.hash(),
},
T0,
)
.expect("mailbox");
let newer = PushEndpoint::parse("https://push.invalid/newer").expect("endpoint");
store.set_push(&m.id, &m.fetch, Some(&newer)).expect("set");
store
.drop_push_if(&m.id, "https://push.invalid/older")
.expect("drop");
assert_eq!(
store.push_endpoint(&m.id).expect("read").as_deref(),
Some("https://push.invalid/newer")
);
}