[relay] F20: merge feature/relay — wire types and the relay, on loopback first
ci / check (push) Has been cancelled

This commit is contained in:
2026-11-11 21:12:00 +01:00
12 changed files with 3099 additions and 10 deletions
+122
View File
@@ -0,0 +1,122 @@
# F20 — Wire types and the relay, on loopback first
Analysis, 2026-11-11. Issues #4 (protocol crate) and #5 (relay). It builds on `docs/PROTOCOL.md` v0,
approved 2026-11-08. The home-server deploy (#8) and the client (#6) come later.
## 1. Why and what
Chat needs somewhere for a message to wait until the other person's device fetches it. The relay is
that place, and it is the part of the system most open to abuse of trust: whoever runs it sees every
connection. So it is built to `PROTOCOL.md` §5 exactly, and every claim in §7 that this feature can
prove is proved by a test.
After F20 a developer can run `tabellarius-relay` on `127.0.0.1` and:
- create a mailbox;
- post an opaque blob to it with a post token;
- fetch the mailbox's blobs with the fetch token;
- acknowledge a blob, which deletes it;
- rotate the post token (block);
- leave an invite with a KeyPackage, and fetch it once with the invite's secret.
The relay never sees a plaintext message: it receives bytes and stores them. Encryption is the
client's job (F21).
## 2. Architecture
```mermaid
flowchart LR
client[client, F21] -- HTTP/1.1 JSON + octets, /v0/... --> api[relay: axum router]
api --> core[relay::Store — every rule, clock passed in]
core --> db[(SQLite: mailboxes, blobs, invites)]
proto[protocol crate: ids, tokens, limits, request/response types, parsers] --> api
proto --> client
```
### Wire types (`tabellarius-protocol`, no I/O)
- `MailboxId`, `InviteId`: 16 random bytes. `Token` (post, fetch, invite secret): 32 random bytes.
Each travels as unpadded base64url. Parsing is strict: an exact length, the alphabet only, and the
canonical form only, so one value has exactly one spelling.
- `TokenHash`: SHA-256 of a token, 32 bytes. The client sends hashes when it creates a mailbox or an
invite. The relay therefore never sees a fetch token until it is used, and stores only what it was
given.
- Limits: a blob is at most 256 KiB, and a KeyPackage at most 16 KiB.
- Request and response bodies are `serde` structs with `deny_unknown_fields`. The version is in the
path (`/v0/`).
### Endpoints (`/v0`)
| Method and path | Auth (`Authorization: Bearer <base64url>`) | Effect |
|:--|:--|:--|
| `POST /v0/mailboxes` `{id, postTokenHash, fetchTokenHash}` | none | creates the mailbox; `created_day` = today; 409 if the id exists |
| `POST /v0/mailboxes/{id}/blobs` (octets) | post token | stores the blob with `size` and the hour it arrived |
| `GET /v0/mailboxes/{id}/blobs` | fetch token | `[{blob: base64url, receivedHour}]`, oldest first, at most 100 |
| `DELETE /v0/mailboxes/{id}/blobs/{sha256}` | fetch token | acknowledges: deletes that mailbox's blob whose SHA-256 is given |
| `PUT /v0/mailboxes/{id}/post-token` `{postTokenHash}` | fetch token | rotates the post token; the old one is refused from now on |
| `POST /v0/invites` `{id, secretHash, keyPackage}` | none | stores the invite; it expires after 7 days |
| `GET /v0/invites/{id}` | invite secret | returns the KeyPackage once, then deletes the invite |
| `GET /version` | none | crate version and build commit |
- **Acknowledging by the blob's SHA-256**, not by a relay-assigned id. §5 has no id column. A
sequential row id would also tell clients how much traffic the relay carries. The client knows the
hash of what it fetched; the relay computes it over that mailbox's blobs only.
- **A wrong token, an unknown mailbox and an unknown invite give the same 404.** Nobody can probe
which mailboxes exist. Hashes are compared in constant time (`subtle`).
- **The clock is passed in.** The store's methods take `now`. The server reads the system clock once
per request, and tests pass their own.
- **Purge:** `Store::purge(now)` deletes blobs older than 30 days and invites past their expiry. The
server runs it every hour and at start.
- **No logs of requests.** No `tracing` subscriber. The server prints one line at start: the
version and the bind address. There is no per-request log of IPs, user agents or bodies. Counts
are not built yet.
- **Bind address:** `127.0.0.1:8470` by default. Another address must be given explicitly
(`--listen`). TLS is the reverse proxy's job (F23).
### Storage — exactly §5
```sql
mailboxes(id BLOB PRIMARY KEY, post_hash BLOB, fetch_hash BLOB, created_day INTEGER)
blobs(mailbox_id BLOB, ciphertext BLOB, size INTEGER, received_hour INTEGER)
invites(id BLOB PRIMARY KEY, secret_hash BLOB, key_package BLOB, expiry INTEGER)
```
- `received_hour` is the arrival time rounded down to the hour (unix seconds / 3600), and
`created_day` the day (/ 86400). `expiry` is rounded up to the hour.
- `secure_delete` is on, so deleted blobs are overwritten in the file and not left in free pages.
WAL is off (`journal_mode=DELETE`), so there is no second copy in a `-wal` file.
- A test compares the live schema (`sqlite_master`, `PRAGMA table_info`) with this list. A column
added in passing fails it. The SQLite row id stays internal and is never sent.
## 3. Risks
- **Privacy, by the operator's own logs:** the relay keeps none. A reverse proxy might, and that is
F23's NixOS module. Timing and IP at connection time stay visible to an operator who logs at the
network layer (§1, stated).
- **Privacy, metadata in the database:** `size` and `received_hour` are in §5 on purpose, coarse by
design. Nothing links two mailboxes to one person.
- **Abuse:** creating a mailbox and an invite needs no account, so anyone who can reach the relay can
fill its disk. v0 caps sizes, not counts. On a home relay behind a private address that is
acceptable. Quotas without identity (proof of work, per-mailbox caps) are a gap, before any public
relay (§4).
- **Crypto:** none is written here. SHA-256 comes from `sha2`, the constant-time compare from
`subtle`, and randomness only in tests and the client.
- **Offline:** the relay is only the post office. The app works offline for everything else.
## 4. Gaps and designed solutions
| Gap | Solution |
|:--|:--|
| No per-mailbox or global quota | a blob count and a byte cap per mailbox, refused with 507; before any public relay |
| `cargo fuzz` needs nightly and Linux, and the CI runners are Windows | parsers are hammered with `proptest` (random and mutated input, 10,000 cases each) in `cargo test`; `cargo fuzz` targets are added with the Linux runner |
| Deleting a whole mailbox (leaving the app, erase everything) | not in §5's operations; proposed for v1 of the protocol, with the client |
| Counts for the operator (requests, blobs) | an in-memory counter at `/metrics` on loopback; later |
| The canary in a *message* (§7, first test) | needs MLS, so it is proved end to end in F21. F20 proves the canary for tokens and addresses |
## 5. Verification matrix
| Case | Kind | Test |
|:--|:--|:--|
| Ids and tokens round-trip; wrong length, alphabet, padding or non-canonical spelling refused | unit + property | `protocol` |
| Any byte string given to any parser: an error, never a panic | property (10,000 cases) | `protocol` |
| Unknown JSON field refused | unit | `protocol` |
| The live database schema is exactly §5 | integration | `relay` `schema_is_exactly_protocol_section_5` |
| Post with no, a wrong or the fetch token: 404; with the post token: 201 | integration (HTTP) | `relay` |
| After rotation the old post token is refused and the new one accepted | integration | `relay` |
| An acknowledged blob is gone; another mailbox's blob with the same bytes is not | integration | `relay` |
| A blob is purged after 30 days and kept at 29 (clock injected) | integration | `relay` |
| An invite is fetched once, with the right secret only; it is gone after 7 days | integration | `relay` |
| Tokens, invite secrets and the client address never appear in the database file (byte search) | integration | `relay` `no_token_or_address_reaches_the_database` |
| A deleted blob's bytes are not left in the file (`secure_delete`) | integration | `relay` |
| A blob over 256 KiB is refused with 413 | integration | `relay` |
| The binary binds loopback by default and serves `/version` | integration (spawned binary) | `relay` |
| `relay` does not depend on `client`; `protocol` depends on nothing here | CI | `scripts/check-deps.sh` |
+86
View File
@@ -0,0 +1,86 @@
# Review — `feature/relay` (F20: wire types and the relay, on loopback)
Adversarial self-review, 2026-11-11. Base: `main` at a19a469. Analysis: `.agents/features/relay.md`.
## Evidence
| What | Result |
|:--|:--|
| `cargo test --workspace --locked` | protocol **14** (9 unit, 5 property tests of 10,000 cases each), relay **17**, client 0 — **31 passed, 0 failed** |
| `cargo clippy --workspace --all-targets --locked -- -D warnings`, `cargo fmt --all --check` | clean |
| `scripts/check-deps.sh` | relay does not depend on client; protocol depends on nothing here |
| `scripts/test-hooks.sh` | 7 passed |
| Planted bugs (`mutate_relay.py`, one at a time, then restored) | **12/12 caught** after one test was fixed (F1) |
| Planted bug | Caught by |
|:--|:--|
| Any token accepted | 4 tests, among them *only the post token posts…* |
| `secure_delete` off | *a deleted blob is not left in the file* |
| WAL journal (a `-wal` copy) | *no token, secret or address reaches the database* |
| A `sender_ip` column slipped in | *schema is exactly protocol section 5* |
| Blob TTL a day short | *purged after 30 days, not before* (after F1) |
| Blob TTL two hours long | the same, and *a deleted blob is not left…* |
| An invite not deleted on claim | *claimed once…*, *still good just before 7 days* |
| An invite that never expires | *an invite expires after 7 days* |
| Rotation that changes nothing | *after rotation the old post token is refused* |
| Acknowledging across mailboxes | *an acknowledged blob is gone and no other is touched* |
| An unknown mailbox answered 403 instead of 404 | 5 tests, among them *an unknown mailbox looks exactly like a wrong token* |
| A request printed to stderr | *the binary serves its version and prints no request* |
## Findings
**F1 — test honesty, found by a planted bug, fixed.** The purge test first checked at 29 days and
at 31 days. A TTL one day short still passed it. The test now checks one hour before and one hour
after the 30-day boundary. A TTL that is a day short or two hours long both fail it.
**F2 — privacy, the canary in §7 is only half proved here.** *A canary string sent in a message
never appears in the relay's database* is a property of the client's encryption. The relay stores
whatever bytes it is given. F20 proves the relay's half: no token, invite secret, client address or
user agent ever reaches the database file. The file was searched byte by byte after real TCP
requests. The message canary is F21's first end-to-end test.
**F3 — privacy, what the relay does keep.**
- **Per mailbox:** the token hashes and the day it was made.
- **Per blob:** the ciphertext, its size and the hour it arrived.
- **Per invite:** the secret's hash, the KeyPackage and the expiry, rounded up to the hour.
All of it is §5's list, checked by the schema test. A KeyPackage holds the inviter's MLS public key
and credential. That is §4 by design: it is how the invitee starts the conversation. It is deleted
when claimed, or at expiry.
**F4 — correctness, acknowledging by hash.** Two identical blobs in one mailbox: one acknowledgement
deletes one of them, and the second waits for its own. MLS ciphertexts do not repeat, so this only
matters for a misbehaving client. The cost is reading the mailbox's blobs on each acknowledgement:
at most 100 are fetched at a time, which is fine for a home relay. If it ever matters, a per-blob
hash column would be a protocol change.
**F5 — abuse, open by design (relay.md §4).** Mailbox and invite creation need no account. A relay
reachable by strangers can be filled. v0 caps sizes (a blob ≤ 256 KiB, JSON ≤ 32 KiB), not counts.
The relay listens on loopback by default; quotas come before any public relay.
**F6 — the HTTP routes are not in `PROTOCOL.md` yet.** The routes, the uniform 404 and acknowledging
by hash live in `relay.md` §2 and in the protocol crate. None of it adds a stored field or loosens a
promise. They are still part of *what crosses the wire*, so adding them to `PROTOCOL.md` (a new §8)
needs Mark's approval.
**F7 — concurrency.** One SQLite connection behind a mutex, used briefly inside async handlers. On a
home relay that is fine. Under load it would block a runtime thread. `spawn_blocking` or a pool is
the fix when it matters.
**F8 — scope.**
- Fuzzing uses `proptest`: 50,000 parser cases and 3,500 random requests per run. `cargo fuzz`
waits for a Linux runner (relay.md §4).
- Not tested: the hourly purge timer in `main.rs`. The purge itself is tested, with the clock passed
in.
- Not checked: the reproducible Nix build, by hand in WSL; there is no Nix there yet.
## Privacy — every path a byte could leave
- **Off the relay:** only the responses to the token holder. A refusal is a bare status with no body.
- **Into a log:** one line at start (version and bind address). Nothing per request, tested on the
real binary.
- **Into the database:** §5 only, tested by the schema test and by a byte search of the file.
## Not verified
- TLS and a reverse proxy (F23).
- A real network beyond loopback.
- Load.
- The Nix build.
- Windows only: the CI runners are Windows, and so is this machine.
Generated
+1019
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -7,6 +7,13 @@ edition.workspace = true
publish.workspace = true
[dependencies]
base64 = "0.22"
serde = { version = "1", features = ["derive"] }
sha2 = "0.10"
[dev-dependencies]
proptest = "1.11"
serde_json = "1"
[lints]
workspace = true
+329 -2
View File
@@ -1,2 +1,329 @@
//! Wire types for the Tabellarius protocol (`docs/PROTOCOL.md`).
//! Empty until the protocol review is approved.
//! Wire types for the Tabellarius protocol v0 (`docs/PROTOCOL.md`, approved 2026-11-08).
//!
//! No I/O. Every value that crosses the wire has exactly one spelling: ids and tokens are unpadded
//! base64url of a fixed number of bytes, and parsing refuses anything else with a [`ParseError`].
//! The HTTP routes that carry these types are listed in `.agents/features/relay.md` §2.
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};
use std::borrow::Cow;
use std::fmt;
/// The protocol version, as it appears in every path (`/v0/...`).
pub const VERSION: &str = "v0";
/// The largest blob (one MLS message) the relay accepts.
pub const MAX_BLOB_BYTES: usize = 256 * 1024;
/// The largest KeyPackage an invite may carry.
pub const MAX_KEY_PACKAGE_BYTES: usize = 16 * 1024;
/// At most this many blobs come back from one fetch; the rest wait for the next.
pub const MAX_BLOBS_PER_FETCH: usize = 100;
/// A blob not acknowledged is deleted after this many seconds (30 days, `PROTOCOL.md` §5).
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;
/// Why a value from the wire was refused. Carries no part of the input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
/// Not unpadded base64url, or not its one canonical spelling.
Encoding,
/// Decoded to the wrong number of bytes.
Length { expected: usize, got: usize },
/// The bearer header is missing its `Bearer ` prefix.
Scheme,
/// More bytes than the protocol allows.
TooLarge { max: usize },
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::Encoding => write!(f, "not canonical unpadded base64url"),
ParseError::Length { expected, got } => {
write!(f, "expected {expected} bytes, got {got}")
}
ParseError::Scheme => write!(f, "expected 'Bearer <token>'"),
ParseError::TooLarge { max } => write!(f, "more than {max} bytes"),
}
}
}
impl std::error::Error for ParseError {}
fn is_base64url(text: &str) -> bool {
text.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// Decodes canonical unpadded base64url: refuses other alphabets, padding, and spellings whose
/// unused trailing bits are not zero (those would give one value a second spelling).
fn decode_canonical(text: &str) -> Result<Vec<u8>, ParseError> {
if !is_base64url(text) {
return Err(ParseError::Encoding);
}
let bytes = URL_SAFE_NO_PAD
.decode(text)
.map_err(|_| ParseError::Encoding)?;
if URL_SAFE_NO_PAD.encode(&bytes) != text {
return Err(ParseError::Encoding);
}
Ok(bytes)
}
fn decode_exact<const N: usize>(text: &str) -> Result<[u8; N], ParseError> {
// A cheap bound first: anything longer than N bytes' worth of characters is refused unread.
if text.len() > N.div_ceil(3) * 4 {
return Err(ParseError::Length {
expected: N,
got: text.len() / 4 * 3,
});
}
let bytes = decode_canonical(text)?;
let got = bytes.len();
bytes
.try_into()
.map_err(|_| ParseError::Length { expected: N, got })
}
macro_rules! fixed_bytes {
($(#[$doc:meta])* $name:ident, $len:expr) => {
$(#[$doc])*
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct $name([u8; $len]);
impl $name {
pub const LEN: usize = $len;
pub fn from_bytes(bytes: [u8; $len]) -> Self {
Self(bytes)
}
pub fn as_bytes(&self) -> &[u8; $len] {
&self.0
}
/// Parses the wire spelling: unpadded base64url of exactly `LEN` bytes.
pub fn parse(text: &str) -> Result<Self, ParseError> {
decode_exact::<$len>(text).map(Self)
}
pub fn to_wire(&self) -> String {
URL_SAFE_NO_PAD.encode(self.0)
}
}
impl Serialize for $name {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.to_wire())
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let text = Cow::<'de, str>::deserialize(d)?;
Self::parse(&text).map_err(serde::de::Error::custom)
}
}
};
}
fixed_bytes!(
/// A mailbox: 16 random bytes made by its owner. One per contact (`PROTOCOL.md` §3).
MailboxId,
16
);
fixed_bytes!(
/// An invite: 16 random bytes made by the inviter (`PROTOCOL.md` §4).
InviteId,
16
);
fixed_bytes!(
/// SHA-256 of a token, or of a blob when it is acknowledged. The relay stores token hashes only.
Sha256Hash,
32
);
fixed_bytes!(
/// A capability: a post token, a fetch token or an invite's one-time secret. 32 random bytes.
/// Never stored by the relay; only its [`Sha256Hash`] is.
Token,
32
);
impl Token {
/// The hash the relay stores and compares against.
pub fn hash(&self) -> Sha256Hash {
Sha256Hash(Sha256::digest(self.0).into())
}
/// Parses an `Authorization` header value: `Bearer <token>`.
pub fn from_bearer(header: &str) -> Result<Self, ParseError> {
let token = header.strip_prefix("Bearer ").ok_or(ParseError::Scheme)?;
Self::parse(token)
}
pub fn to_bearer(&self) -> String {
format!("Bearer {}", self.to_wire())
}
}
// Tokens are secrets: never printed, not even in a debug log.
impl fmt::Debug for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Token(..)")
}
}
macro_rules! debug_as_wire {
($($name:ident),*) => {$(
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({})", stringify!($name), self.to_wire())
}
}
)*};
}
debug_as_wire!(MailboxId, InviteId, Sha256Hash);
/// The SHA-256 of a blob: how its recipient acknowledges it.
pub fn blob_hash(blob: &[u8]) -> Sha256Hash {
Sha256Hash(Sha256::digest(blob).into())
}
/// Bytes inside JSON as unpadded base64url, with an upper bound checked before decoding.
#[derive(Clone, PartialEq, Eq)]
pub struct WireBytes(pub Vec<u8>);
impl WireBytes {
pub fn parse(text: &str, max: usize) -> Result<Self, ParseError> {
// 4 characters carry 3 bytes: anything longer cannot fit, and is refused before decoding.
if text.len() > max.div_ceil(3) * 4 {
return Err(ParseError::TooLarge { max });
}
let bytes = decode_canonical(text)?;
if bytes.len() > max {
return Err(ParseError::TooLarge { max });
}
Ok(Self(bytes))
}
}
impl fmt::Debug for WireBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "WireBytes({} bytes)", self.0.len())
}
}
impl Serialize for WireBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&URL_SAFE_NO_PAD.encode(&self.0))
}
}
macro_rules! bounded_bytes {
($(#[$doc:meta])* $name:ident, $max:expr) => {
$(#[$doc])*
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
#[serde(transparent)]
pub struct $name(pub WireBytes);
impl $name {
pub fn new(bytes: Vec<u8>) -> Result<Self, ParseError> {
if bytes.len() > $max {
return Err(ParseError::TooLarge { max: $max });
}
Ok(Self(WireBytes(bytes)))
}
pub fn bytes(&self) -> &[u8] {
&self.0 .0
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let text = Cow::<'de, str>::deserialize(d)?;
WireBytes::parse(&text, $max)
.map(Self)
.map_err(serde::de::Error::custom)
}
}
};
}
bounded_bytes!(
/// A KeyPackage inside an invite, at most [`MAX_KEY_PACKAGE_BYTES`].
KeyPackageBytes,
MAX_KEY_PACKAGE_BYTES
);
bounded_bytes!(
/// A blob inside a fetch response, at most [`MAX_BLOB_BYTES`].
BlobBytes,
MAX_BLOB_BYTES
);
/// `POST /v0/mailboxes`. The owner sends hashes, so the relay never sees the tokens themselves here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CreateMailbox {
pub id: MailboxId,
pub post_token_hash: Sha256Hash,
pub fetch_token_hash: Sha256Hash,
}
/// `PUT /v0/mailboxes/{id}/post-token`: blocking someone = giving everyone else a new post token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RotatePostToken {
pub post_token_hash: Sha256Hash,
}
/// One waiting blob in `GET /v0/mailboxes/{id}/blobs`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FetchedBlob {
pub blob: BlobBytes,
/// Unix time in hours, rounded down: all the relay keeps of when it arrived.
pub received_hour: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FetchedBlobs {
pub blobs: Vec<FetchedBlob>,
}
/// `POST /v0/invites`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CreateInvite {
pub id: InviteId,
pub secret_hash: Sha256Hash,
pub key_package: KeyPackageBytes,
}
/// `GET /v0/invites/{id}`: the inviter's KeyPackage, handed out once.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ClaimedInvite {
pub key_package: KeyPackageBytes,
}
/// `GET /version`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct VersionInfo {
pub protocol: String,
pub relay: String,
}
/// Rounds unix seconds down to the hour, as the relay stores arrival times.
pub fn hour_of(unix_secs: i64) -> i64 {
unix_secs.div_euclid(3600)
}
/// Rounds unix seconds down to the day, as the relay stores when a mailbox was made.
pub fn day_of(unix_secs: i64) -> i64 {
unix_secs.div_euclid(86_400)
}
+186
View File
@@ -0,0 +1,186 @@
//! The wire spelling: one value, one spelling, and no input that panics a parser.
use proptest::prelude::*;
use tabellarius_protocol::*;
#[test]
fn ids_and_tokens_round_trip_through_their_wire_spelling() {
let id = MailboxId::from_bytes([7; 16]);
assert_eq!(id.to_wire().len(), 22);
assert_eq!(MailboxId::parse(&id.to_wire()), Ok(id));
let token = Token::from_bytes([9; 32]);
assert_eq!(token.to_wire().len(), 43);
assert_eq!(Token::from_bearer(&token.to_bearer()), Ok(token));
}
#[test]
fn a_wrong_length_alphabet_padding_or_spelling_is_refused() {
let good = MailboxId::from_bytes([0xAB; 16]).to_wire();
// one character short, one too many
assert!(MailboxId::parse(&good[..21]).is_err());
assert!(MailboxId::parse(&format!("{good}A")).is_err());
// the standard alphabet and padding are not this protocol's
assert_eq!(
MailboxId::parse(&good.replace('-', "+").replace('_', "/").replace('q', "+")),
Err(ParseError::Encoding)
);
assert_eq!(
MailboxId::parse(&format!("{good}==")),
Err(ParseError::Encoding)
);
// a Token is not a MailboxId
assert!(matches!(
MailboxId::parse(&Token::from_bytes([1; 32]).to_wire()),
Err(ParseError::Length { expected: 16, .. })
));
assert_eq!(
MailboxId::parse(""),
Err(ParseError::Length {
expected: 16,
got: 0
})
);
}
#[test]
fn a_second_spelling_of_the_same_bytes_is_refused() {
// 16 bytes leave 4 unused bits in the last character. 'A' (000000) is canonical for a zero
// tail; 'B' (000001) decodes to the same bytes with a non-zero unused bit.
let canonical = MailboxId::from_bytes([0; 16]).to_wire();
assert!(canonical.ends_with('A'));
let other = format!("{}B", &canonical[..21]);
assert_eq!(MailboxId::parse(&other), Err(ParseError::Encoding));
}
#[test]
fn a_bearer_header_needs_its_scheme() {
let token = Token::from_bytes([3; 32]);
assert_eq!(
Token::from_bearer(&token.to_wire()),
Err(ParseError::Scheme)
);
assert_eq!(
Token::from_bearer(&format!("bearer {}", token.to_wire())),
Err(ParseError::Scheme)
);
assert!(Token::from_bearer(&format!("Bearer {}", token.to_wire())).is_err());
}
#[test]
fn a_token_is_never_printed() {
let token = Token::from_bytes([0x5A; 32]);
let shown = format!("{token:?}");
assert_eq!(shown, "Token(..)");
assert!(!shown.contains(&token.to_wire()));
}
#[test]
fn the_hash_of_a_token_is_its_sha256() {
// SHA-256 of 32 zero bytes, a published value.
let hash = Token::from_bytes([0; 32]).hash();
let hex: String = hash.as_bytes().iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(
hex,
"66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925"
);
}
#[test]
fn json_bodies_refuse_unknown_fields_and_bad_values() {
let ok = serde_json::json!({
"id": MailboxId::from_bytes([1; 16]).to_wire(),
"postTokenHash": Sha256Hash::from_bytes([2; 32]).to_wire(),
"fetchTokenHash": Sha256Hash::from_bytes([3; 32]).to_wire(),
});
let parsed: CreateMailbox = serde_json::from_value(ok.clone()).expect("valid body");
assert_eq!(parsed.id, MailboxId::from_bytes([1; 16]));
let mut extra = ok.clone();
extra["name"] = serde_json::json!("Eva");
assert!(serde_json::from_value::<CreateMailbox>(extra).is_err());
let mut short = ok;
short["id"] = serde_json::json!("AAAA");
assert!(serde_json::from_value::<CreateMailbox>(short).is_err());
}
#[test]
fn a_key_package_over_the_limit_is_refused_before_decoding() {
let at_limit = KeyPackageBytes::new(vec![0; MAX_KEY_PACKAGE_BYTES]).expect("at the limit");
let body = serde_json::json!({
"id": InviteId::from_bytes([1; 16]).to_wire(),
"secretHash": Sha256Hash::from_bytes([2; 32]).to_wire(),
"keyPackage": at_limit,
});
assert!(serde_json::from_value::<CreateInvite>(body.clone()).is_ok());
let mut over = body;
over["keyPackage"] = serde_json::json!("A".repeat(MAX_KEY_PACKAGE_BYTES / 3 * 4 + 8));
let err = serde_json::from_value::<CreateInvite>(over).expect_err("over the limit");
assert!(err.to_string().contains("more than"), "{err}");
assert!(KeyPackageBytes::new(vec![0; MAX_KEY_PACKAGE_BYTES + 1]).is_err());
}
#[test]
fn time_is_kept_only_to_the_hour_and_the_day() {
assert_eq!(hour_of(7199), 1);
assert_eq!(hour_of(-1), -1);
assert_eq!(day_of(86_399), 0);
assert_eq!(day_of(86_400), 1);
}
fn config() -> ProptestConfig {
ProptestConfig {
cases: 10_000,
..ProptestConfig::default()
}
}
proptest! {
#![proptest_config(config())]
/// Any string at all: every parser answers with a value or an error, never a panic.
#[test]
fn no_string_panics_a_parser(text in any::<String>()) {
let _ = MailboxId::parse(&text);
let _ = InviteId::parse(&text);
let _ = Sha256Hash::parse(&text);
let _ = Token::parse(&text);
let _ = Token::from_bearer(&text);
let _ = WireBytes::parse(&text, MAX_BLOB_BYTES);
}
/// Strings from the base64url alphabet (the ones that get furthest into the decoder).
#[test]
fn no_base64url_string_panics_a_parser(text in "[A-Za-z0-9_=+/-]{0,90}") {
let _ = MailboxId::parse(&text);
let _ = Token::parse(&text);
let _ = Token::from_bearer(&format!("Bearer {text}"));
let _ = WireBytes::parse(&text, 64);
}
/// Any JSON-ish bytes given to every request body: an error or a value, never a panic.
#[test]
fn no_body_panics_the_json_parsers(bytes in proptest::collection::vec(any::<u8>(), 0..300)) {
let _ = serde_json::from_slice::<CreateMailbox>(&bytes);
let _ = serde_json::from_slice::<RotatePostToken>(&bytes);
let _ = serde_json::from_slice::<CreateInvite>(&bytes);
let _ = serde_json::from_slice::<FetchedBlobs>(&bytes);
let _ = serde_json::from_slice::<ClaimedInvite>(&bytes);
}
/// Every id that parses has exactly the spelling it was given.
#[test]
fn whatever_parses_has_one_spelling(text in "[A-Za-z0-9_-]{22}") {
if let Ok(id) = MailboxId::parse(&text) {
prop_assert_eq!(id.to_wire(), text);
}
}
/// Bytes survive the wire unchanged.
#[test]
fn bytes_round_trip(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
let wire = serde_json::to_string(&BlobBytes::new(bytes.clone()).expect("small")).expect("json");
let back: BlobBytes = serde_json::from_str(&wire).expect("parses");
prop_assert_eq!(back.bytes(), &bytes[..]);
}
}
+13
View File
@@ -8,6 +8,19 @@ publish.workspace = true
[dependencies]
tabellarius-protocol = { path = "../protocol" }
axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "signal"] }
# Plain SQLite: the relay holds only ciphertext and hashes; nothing in it is readable (PROTOCOL.md §5).
rusqlite = { version = "0.41", features = ["bundled"] }
serde = "1"
serde_json = "1"
subtle = "2"
[dev-dependencies]
getrandom = "0.3"
http-body-util = "0.1"
tempfile = "3"
tower = { version = "0.5", features = ["util"] }
[lints]
workspace = true
+162
View File
@@ -0,0 +1,162 @@
//! The HTTP face of the store. No logging, no connection info: a handler never sees the client's
//! address, and nothing here writes a request anywhere.
use crate::store::{Refused, Store};
use axum::body::Bytes;
use axum::extract::{DefaultBodyLimit, Path, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post, put};
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,
};
/// Unix seconds. The server passes the system clock; tests pass their own.
pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
#[derive(Clone)]
pub struct AppState {
pub store: Arc<Store>,
pub clock: Clock,
}
/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url.
const MAX_JSON_BYTES: usize = 32 * 1024;
pub fn router(state: AppState) -> Router {
let blob_routes = Router::new()
.route("/v0/mailboxes/{id}/blobs", post(post_blob).get(fetch_blobs))
.layer(DefaultBodyLimit::max(MAX_BLOB_BYTES));
Router::new()
.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/invites", post(create_invite))
.route("/v0/invites/{id}", get(claim_invite))
.route("/version", get(version))
.layer(DefaultBodyLimit::max(MAX_JSON_BYTES))
.merge(blob_routes)
.with_state(state)
}
/// Every refusal is a bare status code: no body that could echo the request back.
struct Status(StatusCode);
impl IntoResponse for Status {
fn into_response(self) -> Response {
self.0.into_response()
}
}
impl From<Refused> for Status {
fn from(r: Refused) -> Self {
Status(match r {
Refused::NotFound => StatusCode::NOT_FOUND,
Refused::Exists => StatusCode::CONFLICT,
Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR,
})
}
}
/// Parses a JSON body with the protocol's strict types; any failure is a plain 400.
fn json<T: DeserializeOwned>(body: &Bytes) -> Result<T, Status> {
serde_json::from_slice(body).map_err(|_| Status(StatusCode::BAD_REQUEST))
}
/// A malformed id in the path is treated like an unknown one.
fn mailbox(id: &str) -> Result<MailboxId, Status> {
MailboxId::parse(id).map_err(|_| Status(StatusCode::NOT_FOUND))
}
/// A missing or malformed bearer token is treated like a wrong one.
fn bearer(headers: &HeaderMap) -> Result<Token, Status> {
headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| Token::from_bearer(v).ok())
.ok_or(Status(StatusCode::NOT_FOUND))
}
async fn create_mailbox(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
let req: CreateMailbox = json(&body)?;
s.store.create_mailbox(&req, (s.clock)())?;
Ok(StatusCode::CREATED)
}
async fn post_blob(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> Result<StatusCode, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
s.store.post(&id, &token, &body, (s.clock)())?;
Ok(StatusCode::CREATED)
}
async fn fetch_blobs(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
) -> Result<Json<FetchedBlobs>, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
let blobs = s.store.fetch(&id, &token)?;
Ok(Json(FetchedBlobs { blobs }))
}
async fn acknowledge(
State(s): State<AppState>,
Path((id, hash)): Path<(String, String)>,
headers: HeaderMap,
) -> Result<StatusCode, Status> {
let id = mailbox(&id)?;
let token = bearer(&headers)?;
let hash = Sha256Hash::parse(&hash).map_err(|_| Status(StatusCode::NOT_FOUND))?;
s.store.acknowledge(&id, &token, &hash)?;
Ok(StatusCode::NO_CONTENT)
}
async fn rotate_post_token(
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: RotatePostToken = json(&body)?;
s.store
.rotate_post_token(&id, &token, &req.post_token_hash)?;
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)())?;
Ok(StatusCode::CREATED)
}
async fn claim_invite(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
) -> Result<Response, Status> {
let id = InviteId::parse(&id).map_err(|_| Status(StatusCode::NOT_FOUND))?;
let secret = bearer(&headers)?;
let claimed = s.store.claim_invite(&id, &secret, (s.clock)())?;
Ok(Json(claimed).into_response())
}
async fn version() -> Json<VersionInfo> {
Json(VersionInfo {
protocol: VERSION.to_string(),
relay: env!("CARGO_PKG_VERSION").to_string(),
})
}
+44
View File
@@ -0,0 +1,44 @@
//! The Tabellarius relay: holds ciphertext addressed to a mailbox until its owner fetches and
//! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request.
pub mod http;
pub mod store;
use std::net::SocketAddr;
use std::path::PathBuf;
/// Loopback unless told otherwise: a relay reachable from outside is a deliberate choice (F23).
pub const DEFAULT_LISTEN: &str = "127.0.0.1:8470";
pub const DEFAULT_DB: &str = "tabellarius-relay.db";
#[derive(Debug, PartialEq, Eq)]
pub struct Args {
pub listen: SocketAddr,
pub db: PathBuf,
}
/// `--listen <addr:port>`, `--db <path>`. 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]";
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
let mut db = PathBuf::from(DEFAULT_DB);
let mut it = args.into_iter();
while let Some(arg) = it.next() {
match arg.as_str() {
"--listen" => {
listen = it
.next()
.and_then(|v| v.parse().ok())
.ok_or_else(|| usage.to_string())?;
}
"--db" => {
db = it
.next()
.map(PathBuf::from)
.ok_or_else(|| usage.to_string())?
}
_ => return Err(usage.to_string()),
}
}
Ok(Args { listen, db })
}
+75 -8
View File
@@ -1,10 +1,77 @@
//! Placeholder: prints its version and exits. Opens no socket, stores nothing.
//! It exists so the reproducible build has an artefact to hash. The relay itself is written only
//! after the protocol review is approved.
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]`
//!
//! Prints one line at start (version and address) and nothing per request.
fn main() {
println!(
"tabellarius-relay {} (no relay yet: protocol under review)",
env!("CARGO_PKG_VERSION")
);
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tabellarius_relay::http::{router, AppState, Clock};
use tabellarius_relay::parse_args;
use tabellarius_relay::store::Store;
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
#[tokio::main]
async fn main() {
let args = match parse_args(std::env::args().skip(1)) {
Ok(a) => a,
Err(usage) => {
eprintln!("{usage}");
std::process::exit(2);
}
};
let store = match Store::open(&args.db) {
Ok(s) => Arc::new(s),
Err(_) => {
eprintln!(
"tabellarius-relay: cannot open the database {}",
args.db.display()
);
std::process::exit(1);
}
};
let listener = match tokio::net::TcpListener::bind(args.listen).await {
Ok(l) => l,
Err(_) => {
eprintln!("tabellarius-relay: cannot listen on {}", args.listen);
std::process::exit(1);
}
};
let bound = listener
.local_addr()
.map(|a| a.to_string())
.unwrap_or_default();
println!(
"tabellarius-relay {} protocol {} listening on {bound}",
env!("CARGO_PKG_VERSION"),
tabellarius_protocol::VERSION
);
// Purge at start and every hour: blobs after 30 days, invites after their expiry.
let purger = Arc::clone(&store);
tokio::spawn(async move {
let mut every_hour = tokio::time::interval(Duration::from_secs(3600));
loop {
every_hour.tick().await;
let _ = purger.purge(now());
}
});
let clock: Clock = Arc::new(now);
let app = router(AppState { store, clock });
let shutdown = async {
let _ = tokio::signal::ctrl_c().await;
};
if axum::serve(listener, app)
.with_graceful_shutdown(shutdown)
.await
.is_err()
{
eprintln!("tabellarius-relay: the server stopped with an error");
std::process::exit(1);
}
}
+313
View File
@@ -0,0 +1,313 @@
//! 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.
//! A wrong token and an unknown id give the same [`Refused::NotFound`], so nobody can probe which
//! mailboxes or invites exist.
use rusqlite::{params, Connection, OptionalExtension};
use std::path::Path;
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,
};
/// The schema, and nothing else (`PROTOCOL.md` §5). A column added here is a protocol change.
pub const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS mailboxes (
id BLOB PRIMARY KEY NOT NULL,
post_hash BLOB NOT NULL,
fetch_hash BLOB NOT NULL,
created_day INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS blobs (
mailbox_id BLOB NOT NULL,
ciphertext BLOB NOT NULL,
size INTEGER NOT NULL,
received_hour INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS blobs_by_mailbox ON blobs (mailbox_id);
CREATE TABLE IF NOT EXISTS invites (
id BLOB PRIMARY KEY NOT NULL,
secret_hash BLOB NOT NULL,
key_package BLOB NOT NULL,
expiry INTEGER NOT NULL
);
";
/// Why a request was refused. Deliberately coarse: it says nothing about which part was wrong.
#[derive(Debug, PartialEq, Eq)]
pub enum Refused {
/// Unknown id, wrong token, or an expired invite: indistinguishable on purpose.
NotFound,
/// The id is already taken.
Exists,
/// Over a protocol limit.
TooLarge,
/// The database failed; nothing about the request is in the error.
Storage,
}
impl From<rusqlite::Error> for Refused {
fn from(_: rusqlite::Error) -> Self {
Refused::Storage
}
}
pub struct Store {
conn: Mutex<Connection>,
}
/// What a purge removed.
#[derive(Debug, PartialEq, Eq, Default)]
pub struct Purged {
pub blobs: usize,
pub invites: usize,
}
fn same_hash(stored: &[u8], presented: &Sha256Hash) -> bool {
stored.len() == 32 && bool::from(stored.ct_eq(presented.as_bytes()))
}
impl Store {
pub fn open(path: &Path) -> Result<Self, rusqlite::Error> {
Self::init(Connection::open(path)?)
}
pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
Self::init(Connection::open_in_memory()?)
}
fn init(conn: Connection) -> Result<Self, rusqlite::Error> {
// Deleted rows are overwritten in the file, and there is no -wal copy of anything.
conn.pragma_update(None, "secure_delete", "ON")?;
conn.pragma_update(None, "journal_mode", "DELETE")?;
conn.execute_batch(SCHEMA)?;
Ok(Self {
conn: Mutex::new(conn),
})
}
fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
// A panic while holding the lock leaves SQLite consistent (every write is one statement or
// one transaction), so a poisoned lock is still safe to use.
self.conn.lock().unwrap_or_else(|p| p.into_inner())
}
pub fn create_mailbox(&self, req: &CreateMailbox, now: i64) -> Result<(), Refused> {
let changed = self.conn().execute(
"INSERT OR IGNORE INTO mailboxes (id, post_hash, fetch_hash, created_day)
VALUES (?1, ?2, ?3, ?4)",
params![
&req.id.as_bytes()[..],
&req.post_token_hash.as_bytes()[..],
&req.fetch_token_hash.as_bytes()[..],
day_of(now)
],
)?;
if changed == 0 {
return Err(Refused::Exists);
}
Ok(())
}
/// Checks a token against the mailbox's stored hash (`post_hash` or `fetch_hash`).
fn authorize(
conn: &Connection,
id: &MailboxId,
token: &Token,
column: Column,
) -> Result<(), Refused> {
let sql = match column {
Column::Post => "SELECT post_hash FROM mailboxes WHERE id = ?1",
Column::Fetch => "SELECT fetch_hash FROM mailboxes WHERE id = ?1",
};
let stored: Option<Vec<u8>> = conn
.query_row(sql, [&id.as_bytes()[..]], |r| r.get(0))
.optional()?;
let presented = token.hash();
// Compare against something even when the mailbox is unknown, so both cases take the same path.
let stored = stored.unwrap_or_else(|| vec![0; 32]);
let known = !stored.iter().all(|b| *b == 0);
if known & same_hash(&stored, &presented) {
Ok(())
} else {
Err(Refused::NotFound)
}
}
pub fn post(
&self,
id: &MailboxId,
token: &Token,
blob: &[u8],
now: i64,
) -> Result<(), Refused> {
if blob.len() > MAX_BLOB_BYTES {
return Err(Refused::TooLarge);
}
let conn = self.conn();
Self::authorize(&conn, id, token, Column::Post)?;
conn.execute(
"INSERT INTO blobs (mailbox_id, ciphertext, size, received_hour) VALUES (?1, ?2, ?3, ?4)",
params![&id.as_bytes()[..], blob, blob.len() as i64, hour_of(now)],
)?;
Ok(())
}
/// The waiting blobs, oldest first, at most [`MAX_BLOBS_PER_FETCH`]. Fetching deletes nothing:
/// a blob goes only when it is acknowledged, or at the TTL.
pub fn fetch(&self, id: &MailboxId, token: &Token) -> Result<Vec<FetchedBlob>, Refused> {
let conn = self.conn();
Self::authorize(&conn, id, token, Column::Fetch)?;
let mut stmt = conn.prepare(
"SELECT ciphertext, received_hour FROM blobs WHERE mailbox_id = ?1
ORDER BY received_hour, rowid LIMIT ?2",
)?;
let rows = stmt.query_map(
params![&id.as_bytes()[..], MAX_BLOBS_PER_FETCH as i64],
|r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)),
)?;
let mut out = Vec::new();
for row in rows {
let (bytes, received_hour) = row?;
let blob = BlobBytes::new(bytes).map_err(|_| Refused::Storage)?;
out.push(FetchedBlob {
blob,
received_hour,
});
}
Ok(out)
}
/// Deletes this mailbox's blob whose SHA-256 is `hash`. Unknown hash = [`Refused::NotFound`].
pub fn acknowledge(
&self,
id: &MailboxId,
token: &Token,
hash: &Sha256Hash,
) -> Result<(), Refused> {
let mut conn = self.conn();
Self::authorize(&conn, id, token, Column::Fetch)?;
let tx = conn.transaction()?;
let rowid: Option<i64> = {
let mut stmt =
tx.prepare("SELECT rowid, ciphertext FROM blobs WHERE mailbox_id = ?1")?;
let mut rows = stmt.query([&id.as_bytes()[..]])?;
let mut found = None;
while let Some(row) = rows.next()? {
let bytes: Vec<u8> = row.get(1)?;
if blob_hash(&bytes) == *hash {
found = Some(row.get(0)?);
break;
}
}
found
};
let rowid = rowid.ok_or(Refused::NotFound)?;
tx.execute("DELETE FROM blobs WHERE rowid = ?1", [rowid])?;
tx.commit()?;
Ok(())
}
/// Blocking: the owner (fetch token) gives the mailbox a new post token hash.
pub fn rotate_post_token(
&self,
id: &MailboxId,
fetch: &Token,
new_hash: &Sha256Hash,
) -> Result<(), Refused> {
let conn = self.conn();
Self::authorize(&conn, id, fetch, Column::Fetch)?;
conn.execute(
"UPDATE mailboxes SET post_hash = ?2 WHERE id = ?1",
params![&id.as_bytes()[..], &new_hash.as_bytes()[..]],
)?;
Ok(())
}
pub fn create_invite(&self, req: &CreateInvite, now: i64) -> Result<(), Refused> {
// Expiry rounded up to the hour: the exact second the invite was made is not kept.
let expiry = (hour_of(now + INVITE_TTL_SECS) + 1) * 3600;
let changed = self.conn().execute(
"INSERT OR IGNORE INTO invites (id, secret_hash, key_package, expiry) VALUES (?1, ?2, ?3, ?4)",
params![
&req.id.as_bytes()[..],
&req.secret_hash.as_bytes()[..],
req.key_package.bytes(),
expiry
],
)?;
if changed == 0 {
return Err(Refused::Exists);
}
Ok(())
}
/// Hands the KeyPackage out once and deletes the invite. Expired = not found.
pub fn claim_invite(
&self,
id: &InviteId,
secret: &Token,
now: i64,
) -> Result<ClaimedInvite, Refused> {
let mut conn = self.conn();
let tx = conn.transaction()?;
let row: Option<(Vec<u8>, Vec<u8>, i64)> = tx
.query_row(
"SELECT secret_hash, key_package, expiry FROM invites WHERE id = ?1",
[&id.as_bytes()[..]],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?;
let (stored, key_package, expiry) =
row.unwrap_or_else(|| (vec![0; 32], Vec::new(), i64::MIN));
let ok =
same_hash(&stored, &secret.hash()) & (now < expiry) & !stored.iter().all(|b| *b == 0);
if !ok {
return Err(Refused::NotFound);
}
tx.execute("DELETE FROM invites WHERE id = ?1", [&id.as_bytes()[..]])?;
tx.commit()?;
Ok(ClaimedInvite {
key_package: KeyPackageBytes::new(key_package).map_err(|_| Refused::Storage)?,
})
}
/// Deletes blobs older than 30 days and invites past their expiry.
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
let conn = self.conn();
// A blob that arrived in hour h is gone once h is more than 30 days before now's hour.
let oldest_kept = hour_of(now - BLOB_TTL_SECS);
let blobs = conn.execute("DELETE FROM blobs WHERE received_hour < ?1", [oldest_kept])?;
let invites = conn.execute("DELETE FROM invites WHERE expiry <= ?1", [now])?;
Ok(Purged { blobs, invites })
}
/// The live schema: (table, columns) for every table, in name order. For the §5 test.
pub fn live_schema(&self) -> Result<Vec<(String, Vec<String>)>, rusqlite::Error> {
let conn = self.conn();
let mut stmt =
conn.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")?;
let tables: Vec<String> = stmt
.query_map([], |r| r.get(0))?
.collect::<Result<_, _>>()?;
let mut out = Vec::new();
for table in tables {
let mut cols = conn.prepare(&format!("PRAGMA table_info(\"{table}\")"))?;
let names: Vec<String> = cols
.query_map([], |r| r.get(1))?
.collect::<Result<_, _>>()?;
out.push((table, names));
}
Ok(out)
}
}
#[derive(Clone, Copy)]
enum Column {
Post,
Fetch,
}
+743
View File
@@ -0,0 +1,743 @@
//! The relay against `docs/PROTOCOL.md` §5 and §7, through HTTP where the claim is about the wire.
//! Tokens and ids are generated per test (CLAUDE.md §2.5): no secret is in the repository.
use axum::body::Body;
use axum::http::{header, Method, Request, StatusCode};
use http_body_util::BodyExt;
use std::io::{Read, Write};
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::Arc;
use tabellarius_protocol::*;
use tabellarius_relay::http::{router, AppState, Clock};
use tabellarius_relay::store::{Refused, Store};
use tabellarius_relay::{parse_args, DEFAULT_LISTEN};
use tower::ServiceExt;
const T0: i64 = 1_794_000_000; // 2026-11-07, a fixed point; the clock moves only when a test moves it.
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 create_body(&self) -> String {
serde_json::to_string(&CreateMailbox {
id: self.id,
post_token_hash: self.post.hash(),
fetch_token_hash: self.fetch.hash(),
})
.expect("json")
}
fn blobs_path(&self) -> String {
format!("/v0/mailboxes/{}/blobs", self.id.to_wire())
}
}
struct Relay {
app: axum::Router,
store: Arc<Store>,
now: Arc<AtomicI64>,
}
impl Relay {
fn in_memory() -> Self {
Self::with(Store::open_in_memory().expect("store"))
}
fn with(store: Store) -> Self {
let store = Arc::new(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 {
store: Arc::clone(&store),
clock,
});
Self { app, store, now }
}
fn advance(&self, secs: i64) {
self.now.fetch_add(secs, Ordering::SeqCst);
}
async fn call(
&self,
method: Method,
path: &str,
auth: Option<&Token>,
body: Vec<u8>,
) -> (StatusCode, Vec<u8>) {
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 bytes = resp
.into_body()
.collect()
.await
.expect("body")
.to_bytes()
.to_vec();
(status, bytes)
}
async fn create(&self, m: &Mailbox) -> StatusCode {
self.call(
Method::POST,
"/v0/mailboxes",
None,
m.create_body().into_bytes(),
)
.await
.0
}
async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode {
self.call(Method::POST, &m.blobs_path(), Some(token), blob.to_vec())
.await
.0
}
async fn fetch(&self, m: &Mailbox, token: &Token) -> (StatusCode, Vec<FetchedBlob>) {
let (s, body) = self
.call(Method::GET, &m.blobs_path(), Some(token), vec![])
.await;
let blobs = if s == StatusCode::OK {
serde_json::from_slice::<FetchedBlobs>(&body)
.expect("blobs")
.blobs
} else {
assert!(body.is_empty(), "a refusal has no body");
vec![]
};
(s, blobs)
}
async fn ack(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode {
let path = format!("{}/{}", m.blobs_path(), blob_hash(blob).to_wire());
self.call(Method::DELETE, &path, Some(token), vec![])
.await
.0
}
}
#[test]
fn schema_is_exactly_protocol_section_5() {
let store = Store::open_in_memory().expect("store");
let live = store.live_schema().expect("schema");
let expected: Vec<(String, Vec<String>)> = vec![
(
"blobs".into(),
vec![
"mailbox_id".into(),
"ciphertext".into(),
"size".into(),
"received_hour".into(),
],
),
(
"invites".into(),
vec![
"id".into(),
"secret_hash".into(),
"key_package".into(),
"expiry".into(),
],
),
(
"mailboxes".into(),
vec![
"id".into(),
"post_hash".into(),
"fetch_hash".into(),
"created_day".into(),
],
),
];
assert_eq!(
live, expected,
"a new table or column is a protocol change (CLAUDE.md §2.2)"
);
}
#[tokio::test]
async fn only_the_post_token_posts_and_only_the_fetch_token_fetches() {
let relay = Relay::in_memory();
let m = Mailbox::new();
assert_eq!(relay.create(&m).await, StatusCode::CREATED);
assert_eq!(relay.create(&m).await, StatusCode::CONFLICT);
let stranger = Token::from_bytes(random());
assert_eq!(relay.post(&m, &stranger, b"x").await, StatusCode::NOT_FOUND);
assert_eq!(relay.post(&m, &m.fetch, b"x").await, StatusCode::NOT_FOUND);
let (s, _) = relay
.call(Method::POST, &m.blobs_path(), None, b"x".to_vec())
.await;
assert_eq!(s, StatusCode::NOT_FOUND, "no token at all");
assert_eq!(relay.post(&m, &m.post, b"hello").await, StatusCode::CREATED);
assert_eq!(relay.fetch(&m, &m.post).await.0, StatusCode::NOT_FOUND);
assert_eq!(relay.fetch(&m, &stranger).await.0, StatusCode::NOT_FOUND);
let (s, blobs) = relay.fetch(&m, &m.fetch).await;
assert_eq!(s, StatusCode::OK);
assert_eq!(blobs.len(), 1);
assert_eq!(blobs[0].blob.bytes(), b"hello");
assert_eq!(blobs[0].received_hour, hour_of(T0));
}
#[tokio::test]
async fn an_unknown_mailbox_looks_exactly_like_a_wrong_token() {
let relay = Relay::in_memory();
let known = Mailbox::new();
relay.create(&known).await;
let unknown = Mailbox::new();
let wrong = relay
.call(
Method::POST,
&known.blobs_path(),
Some(&unknown.post),
b"x".to_vec(),
)
.await;
let missing = relay
.call(
Method::POST,
&unknown.blobs_path(),
Some(&unknown.post),
b"x".to_vec(),
)
.await;
let malformed = relay
.call(
Method::POST,
"/v0/mailboxes/not-an-id/blobs",
Some(&unknown.post),
b"x".to_vec(),
)
.await;
assert_eq!(wrong, (StatusCode::NOT_FOUND, vec![]));
assert_eq!(missing, wrong);
assert_eq!(malformed, wrong);
}
#[tokio::test]
async fn after_rotation_the_old_post_token_is_refused() {
let relay = Relay::in_memory();
let m = Mailbox::new();
relay.create(&m).await;
let new_post = Token::from_bytes(random());
let body = serde_json::to_vec(&RotatePostToken {
post_token_hash: new_post.hash(),
})
.expect("json");
let path = format!("/v0/mailboxes/{}/post-token", m.id.to_wire());
// Only the owner (fetch token) can rotate.
let (s, _) = relay
.call(Method::PUT, &path, Some(&m.post), body.clone())
.await;
assert_eq!(s, StatusCode::NOT_FOUND);
let (s, _) = relay.call(Method::PUT, &path, Some(&m.fetch), body).await;
assert_eq!(s, StatusCode::NO_CONTENT);
assert_eq!(
relay.post(&m, &m.post, b"from the blocked person").await,
StatusCode::NOT_FOUND
);
assert_eq!(
relay.post(&m, &new_post, b"from everyone else").await,
StatusCode::CREATED
);
let (_, blobs) = relay.fetch(&m, &m.fetch).await;
assert_eq!(blobs.len(), 1);
assert_eq!(blobs[0].blob.bytes(), b"from everyone else");
}
#[tokio::test]
async fn an_acknowledged_blob_is_gone_and_no_other_is_touched() {
let relay = Relay::in_memory();
let a = Mailbox::new();
let b = Mailbox::new();
relay.create(&a).await;
relay.create(&b).await;
relay.post(&a, &a.post, b"same bytes").await;
relay.post(&a, &a.post, b"second").await;
relay.post(&b, &b.post, b"same bytes").await;
// b's owner cannot acknowledge a's blob, even with identical bytes.
let path = format!("{}/{}", a.blobs_path(), blob_hash(b"same bytes").to_wire());
let (s, _) = relay
.call(Method::DELETE, &path, Some(&b.fetch), vec![])
.await;
assert_eq!(s, StatusCode::NOT_FOUND);
assert_eq!(
relay.ack(&a, &a.fetch, b"same bytes").await,
StatusCode::NO_CONTENT
);
assert_eq!(
relay.ack(&a, &a.fetch, b"same bytes").await,
StatusCode::NOT_FOUND,
"already gone"
);
let (_, left) = relay.fetch(&a, &a.fetch).await;
assert_eq!(
left.iter()
.map(|f| f.blob.bytes().to_vec())
.collect::<Vec<_>>(),
vec![b"second".to_vec()]
);
let (_, other) = relay.fetch(&b, &b.fetch).await;
assert_eq!(other.len(), 1, "the other mailbox keeps its copy");
}
#[tokio::test]
async fn an_unacknowledged_blob_is_purged_after_30_days_not_before() {
let relay = Relay::in_memory();
let m = Mailbox::new();
relay.create(&m).await;
relay.post(&m, &m.post, b"waiting").await;
relay.advance(BLOB_TTL_SECS - 3600);
let now = relay.now.load(Ordering::SeqCst);
assert_eq!(relay.store.purge(now).expect("purge").blobs, 0);
assert_eq!(
relay.fetch(&m, &m.fetch).await.1.len(),
1,
"kept an hour before 30 days"
);
relay.advance(2 * 3600);
let now = relay.now.load(Ordering::SeqCst);
assert_eq!(relay.store.purge(now).expect("purge").blobs, 1);
assert!(
relay.fetch(&m, &m.fetch).await.1.is_empty(),
"gone an hour after 30 days"
);
}
#[tokio::test]
async fn a_fetch_returns_at_most_a_hundred_oldest_first() {
let relay = Relay::in_memory();
let m = Mailbox::new();
relay.create(&m).await;
for i in 0..105u8 {
relay.post(&m, &m.post, &[i]).await;
}
let (_, blobs) = relay.fetch(&m, &m.fetch).await;
assert_eq!(blobs.len(), MAX_BLOBS_PER_FETCH);
assert_eq!(blobs[0].blob.bytes(), &[0]);
assert_eq!(blobs[99].blob.bytes(), &[99]);
}
#[tokio::test]
async fn a_blob_over_256_kib_is_refused() {
let relay = Relay::in_memory();
let m = Mailbox::new();
relay.create(&m).await;
assert_eq!(
relay.post(&m, &m.post, &vec![1; MAX_BLOB_BYTES]).await,
StatusCode::CREATED
);
assert_eq!(
relay.post(&m, &m.post, &vec![1; MAX_BLOB_BYTES + 1]).await,
StatusCode::PAYLOAD_TOO_LARGE
);
}
#[tokio::test]
async fn a_bad_body_is_a_bare_400() {
let relay = Relay::in_memory();
let (s, body) = relay
.call(
Method::POST,
"/v0/mailboxes",
None,
br#"{"id":"Eva","name":"Eva"}"#.to_vec(),
)
.await;
assert_eq!(s, StatusCode::BAD_REQUEST);
assert!(body.is_empty(), "nothing of the request comes back");
}
fn invite_body(id: &InviteId, secret: &Token, kp: &[u8]) -> Vec<u8> {
serde_json::to_vec(&CreateInvite {
id: *id,
secret_hash: secret.hash(),
key_package: KeyPackageBytes::new(kp.to_vec()).expect("small"),
})
.expect("json")
}
#[tokio::test]
async fn an_invite_is_claimed_once_with_its_secret_only() {
let relay = Relay::in_memory();
let id = InviteId::from_bytes(random());
let secret = Token::from_bytes(random());
let (s, _) = relay
.call(
Method::POST,
"/v0/invites",
None,
invite_body(&id, &secret, b"key package"),
)
.await;
assert_eq!(s, StatusCode::CREATED);
let path = format!("/v0/invites/{}", id.to_wire());
let (s, _) = relay
.call(
Method::GET,
&path,
Some(&Token::from_bytes(random())),
vec![],
)
.await;
assert_eq!(s, StatusCode::NOT_FOUND, "wrong secret");
let (s, body) = relay.call(Method::GET, &path, Some(&secret), vec![]).await;
assert_eq!(s, StatusCode::OK);
let claimed: ClaimedInvite = serde_json::from_slice(&body).expect("invite");
assert_eq!(claimed.key_package.bytes(), b"key package");
let (s, _) = relay.call(Method::GET, &path, Some(&secret), vec![]).await;
assert_eq!(s, StatusCode::NOT_FOUND, "one time only");
}
#[tokio::test]
async fn an_invite_expires_after_7_days() {
let relay = Relay::in_memory();
let id = InviteId::from_bytes(random());
let secret = Token::from_bytes(random());
relay
.call(
Method::POST,
"/v0/invites",
None,
invite_body(&id, &secret, b"kp"),
)
.await;
let path = format!("/v0/invites/{}", id.to_wire());
relay.advance(INVITE_TTL_SECS + 2 * 3600);
let (s, _) = relay.call(Method::GET, &path, Some(&secret), vec![]).await;
assert_eq!(s, StatusCode::NOT_FOUND, "expired, even before a purge");
let now = relay.now.load(Ordering::SeqCst);
assert_eq!(relay.store.purge(now).expect("purge").invites, 1);
}
#[test]
fn an_invite_is_still_good_just_before_7_days() {
let store = Store::open_in_memory().expect("store");
let id = InviteId::from_bytes(random());
let secret = Token::from_bytes(random());
let req = CreateInvite {
id,
secret_hash: secret.hash(),
key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"),
};
store.create_invite(&req, T0).expect("created");
assert!(store
.claim_invite(&id, &secret, T0 + INVITE_TTL_SECS - 1)
.is_ok());
assert_eq!(
store
.claim_invite(&id, &secret, T0)
.expect_err("claimed already"),
Refused::NotFound,
"claimed already"
);
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
}
/// Sends one raw HTTP/1.1 request over a real TCP connection from 127.0.0.1.
fn raw_http(addr: std::net::SocketAddr, request: &str, body: &[u8]) -> String {
let mut s = std::net::TcpStream::connect(addr).expect("connect");
s.write_all(request.as_bytes()).expect("write");
s.write_all(body).expect("write body");
let mut out = String::new();
s.read_to_string(&mut out).expect("read");
out
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn no_token_secret_or_address_reaches_the_database() {
let dir = tempfile::tempdir().expect("tempdir");
let db = dir.path().join("relay.db");
let relay = Relay::with(Store::open(&db).expect("store"));
// Over real TCP, so the server has a client address it could have stored.
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let addr = listener.local_addr().expect("addr");
let app = relay.app.clone();
let server = tokio::spawn(async move { axum::serve(listener, app).await });
let m = Mailbox::new();
let invite = InviteId::from_bytes(random());
let secret = Token::from_bytes(random());
let new_post = Token::from_bytes(random());
let steps: Vec<(String, Vec<u8>)> = vec![
("POST /v0/mailboxes".into(), m.create_body().into_bytes()),
(
format!("POST {} {}", m.blobs_path(), m.post.to_bearer()),
b"ciphertext".to_vec(),
),
(
format!("GET {} {}", m.blobs_path(), m.fetch.to_bearer()),
vec![],
),
(
format!(
"PUT /v0/mailboxes/{}/post-token {}",
m.id.to_wire(),
m.fetch.to_bearer()
),
serde_json::to_vec(&RotatePostToken {
post_token_hash: new_post.hash(),
})
.expect("json"),
),
(
"POST /v0/invites".into(),
invite_body(&invite, &secret, b"kp"),
),
];
for (line, body) in steps {
let mut parts = line.splitn(3, ' ');
let (method, path, auth) = (
parts.next().unwrap_or(""),
parts.next().unwrap_or(""),
parts.next(),
);
let auth_header = auth
.map(|a| format!("Authorization: {a}\r\n"))
.unwrap_or_default();
let req = format!(
"{method} {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nUser-Agent: canary-agent/1.0\r\n{auth_header}Content-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
let resp = raw_http(addr, &req, &body);
assert!(
resp.starts_with("HTTP/1.1 2"),
"{method} {path}: {}",
resp.lines().next().unwrap_or("")
);
}
server.abort();
drop(relay);
let bytes = std::fs::read(&db).expect("db file");
for (what, needle) in [
("post token", m.post.as_bytes().to_vec()),
("fetch token", m.fetch.as_bytes().to_vec()),
("new post token", new_post.as_bytes().to_vec()),
("invite secret", secret.as_bytes().to_vec()),
("post token, base64url", m.post.to_wire().into_bytes()),
("fetch token, base64url", m.fetch.to_wire().into_bytes()),
("client address", b"127.0.0.1".to_vec()),
(
"client address, binary",
vec![127, 0, 0, 1, (addr.port() >> 8) as u8],
),
("user agent", b"canary-agent".to_vec()),
] {
assert!(
!contains(&bytes, &needle),
"{what} found in the database file"
);
}
// What should be there is there: the hash, not the token.
assert!(
contains(&bytes, m.fetch.hash().as_bytes()),
"the fetch token's hash is stored"
);
let others: Vec<_> = std::fs::read_dir(dir.path())
.expect("dir")
.filter_map(|e| e.ok())
.map(|e| e.file_name())
.collect();
assert_eq!(
others.len(),
1,
"no -wal or -journal file left beside the database: {others:?}"
);
}
#[test]
fn a_deleted_blob_is_not_left_in_the_file() {
let dir = tempfile::tempdir().expect("tempdir");
let db = dir.path().join("relay.db");
let store = Store::open(&db).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 marker: Vec<u8> = b"DELETED-BLOB-MARKER-"
.iter()
.copied()
.chain(random::<16>())
.collect();
let aged: Vec<u8> = b"AGED-BLOB-MARKER-"
.iter()
.copied()
.chain(random::<16>())
.collect();
store.post(&m.id, &m.post, &marker, T0).expect("post");
store.post(&m.id, &m.post, &aged, T0).expect("post");
store
.acknowledge(&m.id, &m.fetch, &blob_hash(&marker))
.expect("ack");
store.purge(T0 + BLOB_TTL_SECS + 7200).expect("purge");
drop(store);
let bytes = std::fs::read(&db).expect("db file");
assert!(
!contains(&bytes, &marker),
"an acknowledged blob's bytes stay in the file"
);
assert!(
!contains(&bytes, &aged),
"a purged blob's bytes stay in the file"
);
}
#[test]
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!(parse_args(["--listen".to_string()]).is_err());
assert!(parse_args(["--verbose".to_string()]).is_err());
}
#[test]
fn the_binary_serves_its_version_and_prints_no_request() {
let dir = tempfile::tempdir().expect("tempdir");
let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_tabellarius-relay"))
.args(["--listen", "127.0.0.1:0", "--db"])
.arg(dir.path().join("relay.db"))
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn");
let mut stdout = child.stdout.take().expect("stdout");
// The one start line: "... listening on 127.0.0.1:<port>\n"
let mut line = Vec::new();
let mut byte = [0u8; 1];
while stdout.read(&mut byte).expect("read") == 1 && byte[0] != b'\n' {
line.push(byte[0]);
}
let line = String::from_utf8(line).expect("utf8");
let addr: std::net::SocketAddr = line
.rsplit(' ')
.next()
.and_then(|a| a.parse().ok())
.expect("address in the start line");
assert!(addr.ip().is_loopback(), "{line}");
let resp = raw_http(
addr,
"GET /version HTTP/1.1\r\nHost: x\r\nUser-Agent: canary-agent/1.0\r\nConnection: close\r\n\r\n",
&[],
);
assert!(resp.starts_with("HTTP/1.1 200"), "{resp}");
assert!(resp.contains("\"protocol\":\"v0\""), "{resp}");
child.kill().expect("kill");
let mut rest = String::new();
stdout.read_to_string(&mut rest).expect("stdout");
let mut err = String::new();
child
.stderr
.take()
.expect("stderr")
.read_to_string(&mut err)
.expect("stderr");
let _ = child.wait();
assert!(
rest.is_empty() && err.is_empty(),
"the relay printed after start: {rest:?} {err:?}"
);
}
/// Random bodies, paths and headers at every route: a 4xx or a success, never a 500 or a panic.
#[tokio::test]
async fn no_random_request_breaks_the_relay() {
let relay = Relay::in_memory();
let m = Mailbox::new();
relay.create(&m).await;
let routes = [
(Method::POST, "/v0/mailboxes".to_string()),
(Method::POST, m.blobs_path()),
(Method::GET, m.blobs_path()),
(
Method::PUT,
format!("/v0/mailboxes/{}/post-token", m.id.to_wire()),
),
(Method::POST, "/v0/invites".to_string()),
(
Method::GET,
format!("/v0/invites/{}", InviteId::from_bytes(random()).to_wire()),
),
];
for i in 0..3000usize {
let len = random::<1>()[0] as usize * (1 + i % 4);
let mut body = vec![0u8; len];
getrandom::fill(&mut body).expect("randomness");
if i % 3 == 0 {
// JSON-shaped noise reaches deeper into the parsers than raw bytes.
body = format!(
"{{\"id\":\"{}\",\"postTokenHash\":{},\"keyPackage\":\"{}\"}}",
String::from_utf8_lossy(&body[..len.min(30)]),
len,
"A".repeat(len)
)
.into_bytes();
}
let (method, path) = &routes[i % routes.len()];
let token = if i % 2 == 0 { Some(&m.fetch) } else { None };
let (status, _) = relay.call(method.clone(), path, token, body).await;
assert!(
!status.is_server_error(),
"{method} {path} answered {status}"
);
}
// Garbage paths too.
for _ in 0..500 {
let id: String = random::<12>()
.iter()
.map(|b| (b'A' + b % 26) as char)
.collect();
let (status, _) = relay
.call(
Method::GET,
&format!("/v0/mailboxes/{id}/blobs"),
Some(&m.fetch),
vec![],
)
.await;
assert_eq!(status, StatusCode::NOT_FOUND);
}
}