diff --git a/.agents/features/relay.md b/.agents/features/relay.md new file mode 100644 index 0000000..05d6aec --- /dev/null +++ b/.agents/features/relay.md @@ -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 `) | 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` | diff --git a/.agents/reviews/feature-relay.md b/.agents/reviews/feature-relay.md new file mode 100644 index 0000000..0032c88 --- /dev/null +++ b/.agents/reviews/feature-relay.md @@ -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. diff --git a/Cargo.lock b/Cargo.lock index ff4c686..a4ca4ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,802 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" +dependencies = [ + "borsh", + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libsqlite3-sys" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "chacha20", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.41.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867" +dependencies = [ + "cc", + "rsqlite-vfs", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + [[package]] name = "tabellarius-client" version = "0.0.0" @@ -12,10 +808,233 @@ dependencies = [ [[package]] name = "tabellarius-protocol" version = "0.0.0" +dependencies = [ + "base64", + "proptest", + "serde", + "serde_json", + "sha2", +] [[package]] name = "tabellarius-relay" version = "0.0.0" dependencies = [ + "axum", + "getrandom 0.3.4", + "http-body-util", + "rusqlite", + "serde", + "serde_json", + "subtle", "tabellarius-protocol", + "tempfile", + "tokio", + "tower", ] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/protocol/Cargo.toml b/crates/protocol/Cargo.toml index 813ad60..01b9813 100644 --- a/crates/protocol/Cargo.toml +++ b/crates/protocol/Cargo.toml @@ -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 diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index 38795cb..6af4536 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -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 '"), + 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, 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(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 { + 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(&self, s: S) -> Result { + s.serialize_str(&self.to_wire()) + } + } + + impl<'de> Deserialize<'de> for $name { + fn deserialize>(d: D) -> Result { + 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 `. + pub fn from_bearer(header: &str) -> Result { + 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); + +impl WireBytes { + pub fn parse(text: &str, max: usize) -> Result { + // 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(&self, s: S) -> Result { + 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) -> Result { + 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: D) -> Result { + 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, +} + +/// `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) +} diff --git a/crates/protocol/tests/wire.rs b/crates/protocol/tests/wire.rs new file mode 100644 index 0000000..05e946b --- /dev/null +++ b/crates/protocol/tests/wire.rs @@ -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::(extra).is_err()); + + let mut short = ok; + short["id"] = serde_json::json!("AAAA"); + assert!(serde_json::from_value::(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::(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::(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::()) { + 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::(), 0..300)) { + let _ = serde_json::from_slice::(&bytes); + let _ = serde_json::from_slice::(&bytes); + let _ = serde_json::from_slice::(&bytes); + let _ = serde_json::from_slice::(&bytes); + let _ = serde_json::from_slice::(&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::(), 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[..]); + } +} diff --git a/crates/relay/Cargo.toml b/crates/relay/Cargo.toml index d4d9da7..edcaf0a 100644 --- a/crates/relay/Cargo.toml +++ b/crates/relay/Cargo.toml @@ -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 diff --git a/crates/relay/src/http.rs b/crates/relay/src/http.rs new file mode 100644 index 0000000..9965298 --- /dev/null +++ b/crates/relay/src/http.rs @@ -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 i64 + Send + Sync>; + +#[derive(Clone)] +pub struct AppState { + pub store: Arc, + 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 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(body: &Bytes) -> Result { + 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::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 { + 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, body: Bytes) -> Result { + let req: CreateMailbox = json(&body)?; + s.store.create_mailbox(&req, (s.clock)())?; + Ok(StatusCode::CREATED) +} + +async fn post_blob( + State(s): State, + Path(id): Path, + headers: HeaderMap, + body: Bytes, +) -> Result { + 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, + Path(id): Path, + headers: HeaderMap, +) -> Result, 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, + Path((id, hash)): Path<(String, String)>, + headers: HeaderMap, +) -> Result { + 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, + Path(id): Path, + headers: HeaderMap, + body: Bytes, +) -> Result { + 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, body: Bytes) -> Result { + let req: CreateInvite = json(&body)?; + s.store.create_invite(&req, (s.clock)())?; + Ok(StatusCode::CREATED) +} + +async fn claim_invite( + State(s): State, + Path(id): Path, + headers: HeaderMap, +) -> Result { + 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 { + Json(VersionInfo { + protocol: VERSION.to_string(), + relay: env!("CARGO_PKG_VERSION").to_string(), + }) +} diff --git a/crates/relay/src/lib.rs b/crates/relay/src/lib.rs new file mode 100644 index 0000000..1e9756e --- /dev/null +++ b/crates/relay/src/lib.rs @@ -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 `, `--db `. Anything else is refused with a usage line. +pub fn parse_args>(args: I) -> Result { + 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 }) +} diff --git a/crates/relay/src/main.rs b/crates/relay/src/main.rs index d4e327e..78273ef 100644 --- a/crates/relay/src/main.rs +++ b/crates/relay/src/main.rs @@ -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); + } } diff --git a/crates/relay/src/store.rs b/crates/relay/src/store.rs new file mode 100644 index 0000000..18bae43 --- /dev/null +++ b/crates/relay/src/store.rs @@ -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 for Refused { + fn from(_: rusqlite::Error) -> Self { + Refused::Storage + } +} + +pub struct Store { + conn: Mutex, +} + +/// 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::init(Connection::open(path)?) + } + + pub fn open_in_memory() -> Result { + Self::init(Connection::open_in_memory()?) + } + + fn init(conn: Connection) -> Result { + // 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> = 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, 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>(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 = { + 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 = 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 { + let mut conn = self.conn(); + let tx = conn.transaction()?; + let row: Option<(Vec, Vec, 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 { + 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)>, 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 = stmt + .query_map([], |r| r.get(0))? + .collect::>()?; + let mut out = Vec::new(); + for table in tables { + let mut cols = conn.prepare(&format!("PRAGMA table_info(\"{table}\")"))?; + let names: Vec = cols + .query_map([], |r| r.get(1))? + .collect::>()?; + out.push((table, names)); + } + Ok(out) + } +} + +#[derive(Clone, Copy)] +enum Column { + Post, + Fetch, +} diff --git a/crates/relay/tests/relay.rs b/crates/relay/tests/relay.rs new file mode 100644 index 0000000..0558d53 --- /dev/null +++ b/crates/relay/tests/relay.rs @@ -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() -> [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, + now: Arc, +} + +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, + ) -> (StatusCode, Vec) { + 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) { + let (s, body) = self + .call(Method::GET, &m.blobs_path(), Some(token), vec![]) + .await; + let blobs = if s == StatusCode::OK { + serde_json::from_slice::(&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)> = 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![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 { + 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)> = 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 = b"DELETED-BLOB-MARKER-" + .iter() + .copied() + .chain(random::<16>()) + .collect(); + let aged: Vec = 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::::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:\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); + } +}