Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cfabc97d20 | |||
| 0e6be38280 | |||
| 0fbcb34b53 | |||
| dd576f9feb | |||
| 2a8daa7570 | |||
| 3ac2075ec6 | |||
| 4f78101735 | |||
| 6f939be758 | |||
| 21bee2d633 | |||
| 47ed9eef18 | |||
| b62317d552 | |||
| 6c66cabb69 | |||
| 580b8d50e3 | |||
| 4a4e82e0e9 | |||
| 8517b0bbd9 | |||
| b502e57d93 | |||
| 80a27d9181 | |||
| 841236dc87 | |||
| 710e1f87fb | |||
| 870e78e81a | |||
| 1e7bc8e328 | |||
| 51158216ca | |||
| a4404428ea | |||
| a19a4697c3 |
@@ -0,0 +1,68 @@
|
||||
# F24 — Block, unblock, and *delivered*
|
||||
|
||||
Analysis, 2026-11-17. Issues Amicitia #52 (F24). It builds on F21/F22a (`client.md`,
|
||||
`client-state.md`). `PROTOCOL.md` §3 already says what block is: *the owner rotates the post token;
|
||||
the old one is refused. The blocked person is not told.* The relay route exists (§8, `PUT
|
||||
…/post-token`); the client never used it.
|
||||
|
||||
## 1. Why and what
|
||||
- **Block:** someone who turns hostile can no longer put anything in your mailbox. Nothing is sent
|
||||
to them, so they are not told. What they posted before the block, and what you already fetched,
|
||||
is dropped and never shown.
|
||||
- **Unblock:** a mistake can be undone. A fresh post token goes to them inside MLS, and their
|
||||
client switches to it, including for what waited in their outbox.
|
||||
- ***Delivered*:** you see when your message reached the other person's app (fetched and saved
|
||||
there). Each text carries a sequence number; the receiving client answers with a **receipt**
|
||||
`upto = n` once it has saved them. **Reciprocal and switchable:** with receipts off, a client
|
||||
neither sends them nor reports the other side's. The cost is said where the switch is: a
|
||||
receipt tells the sender roughly when your app was open.
|
||||
|
||||
## 2. Design
|
||||
### Everything is a staged step
|
||||
F22a's rule holds: nothing reaches the relay before the app has saved. So `Outgoing` grows from
|
||||
"one blob to post" to **one relay operation**: post a blob, or rotate a post token.
|
||||
| Call | Local change | Returned for the app to deliver after saving |
|
||||
|:--|:--|:--|
|
||||
| `block(contact)` | marks the contact blocked | a **rotate** to the hash of a fresh random token, which nobody gets |
|
||||
| `unblock(contact)` | clears the mark | a **rotate** to a new token, then a **post** of `inbox {postToken}` to them, inside MLS |
|
||||
| `compose` | `seq` + 1 for that contact | the text, now with its `seq` |
|
||||
| `receive` | texts from a blocked contact dropped; the highest `seq` received per contact | a **receipt** per contact that sent texts (receipts on, not blocked) |
|
||||
- `deliver` performs either operation. A rotate delivered twice is harmless: the same hash again.
|
||||
- `readdress(&Outgoing)`: a post waiting in an app's outbox carries the token it was sealed with.
|
||||
After an `inbox` payload changed the token, `readdress` swaps in the current one. The sealed
|
||||
blob does not change. Apps call it before delivering from the outbox.
|
||||
- An app learns a message's `seq` from `sent_seq(contact)` right after `compose`.
|
||||
|
||||
### Payloads inside MLS *(documented in `PROTOCOL.md` §4, new: `seq`, `receipt`, `inbox`)*
|
||||
```json
|
||||
{"kind":"hello","mailbox":"…","postToken":"…","name":"…"}
|
||||
{"kind":"text","body":"…","seq":7}
|
||||
{"kind":"receipt","upto":7}
|
||||
{"kind":"inbox","postToken":"…"}
|
||||
```
|
||||
- `inbox` changes only the token for the mailbox we already know: the sender cannot redirect us to
|
||||
another mailbox (F21's *second hello* rule still holds). MLS authenticates that it is theirs.
|
||||
- A `receipt` with `upto` above what we sent is capped to what we sent; it cannot mark the future.
|
||||
- The relay sees none of this: all of it is MLS ciphertext, and a rotate is §8's existing route.
|
||||
|
||||
### What the blocked person can tell
|
||||
Their posts get **404**: the same answer as any wrong token. Their app keeps the message as *not
|
||||
sent yet* and retries. Nothing in the protocol tells them it was a block rather than, say, an
|
||||
expired mailbox. Their client cannot ask. Stated: someone whose messages never leave the outbox
|
||||
may guess.
|
||||
|
||||
## 3. Tests — written first
|
||||
1. Block: the blocked side's next post is refused (404); nothing reaches us; what they posted
|
||||
just before the block, still waiting, is fetched, dropped, never shown, and acknowledged.
|
||||
2. Block works offline: the rotate waits as an `Outgoing`, and after a restart from the snapshot it
|
||||
still applies.
|
||||
3. Unblock: they get the new token, their waiting outbox post is readdressed and arrives, and new
|
||||
texts flow both ways.
|
||||
4. Receipts: Eva sends 3, Jan receives, Eva gets `Delivered{upto: 3}`. Receipts off on Jan: none
|
||||
sent. Off on Eva: Jan's receipts are ignored. A receipt `upto` above what was sent is capped.
|
||||
5. A snapshot from before F24 (no `blocked`, `seq`, `receipts`) still restores, with receipts on.
|
||||
6. `inbox` cannot change the mailbox, only the token.
|
||||
|
||||
Planted bugs: block that also posts something to the blocked person; texts from a blocked contact
|
||||
shown; the rotate done inside `block` (not staged); receipts sent while off; a receipt marking
|
||||
beyond what was sent; `readdress` leaving the old token.
|
||||
@@ -0,0 +1,107 @@
|
||||
# F22a — The client survives a restart, and never sends what it has not saved
|
||||
|
||||
Analysis, 2026-11-16. Part of F22 (chat in Amicitia, `../amicitia/.agents/features/chat.md`). It
|
||||
builds on F21 (`client.md`), whose state lived in memory only (its review, finding F6).
|
||||
|
||||
## 1. Why and what
|
||||
An app must be able to close and reopen without losing a conversation, and must never get into a
|
||||
state that MLS cannot recover from. Two things are needed:
|
||||
1. **A snapshot.** `Client::snapshot()` gives the whole client state as bytes, and
|
||||
`Client::restore(bytes, transport)` brings it back. The app keeps the bytes in its own encrypted
|
||||
store (Amicitia: the SQLCipher database). The library never writes a file.
|
||||
2. **Save before the network sees it.** Everything that reaches the relay after a state change goes
|
||||
out only after the app has saved the snapshot. Otherwise a crash can leave the relay ahead of the
|
||||
saved state.
|
||||
|
||||
### What goes wrong without step 2
|
||||
| Crash between… | Then, after restoring the older snapshot |
|
||||
|:--|:--|
|
||||
| a text posted and the snapshot saved | the next text reuses the same MLS generation; the other side cannot decrypt it, and every later one fails too |
|
||||
| the blobs acknowledged and the snapshot saved | the messages are gone from the relay and from the app |
|
||||
| the inviter's `hello` posted and the snapshot saved | the inviter joins again from the same Welcome and sends a second `hello` with a new mailbox; the other side refuses it (F21's *second hello* rule) and posts to a mailbox the inviter no longer knows |
|
||||
|
||||
## 2. Design
|
||||
### The staged calls
|
||||
Each call that changes state does its **local** work and returns what still has to reach the relay:
|
||||
|
||||
| Call | Network inside the call | Returned for the app to deliver after saving |
|
||||
|:--|:--|:--|
|
||||
| `compose(contact, text)` | none | one `Outgoing` |
|
||||
| `accept(invite)` | claim the KeyPackage; create our mailbox | `ContactId`, and the Welcome and `hello` as `Outgoing`s |
|
||||
| `receive()` | fetch; create our mailbox when a `hello` asks us to answer | a `Received`: the events, our answering `hello`s as `Outgoing`s, and the blobs to acknowledge |
|
||||
| `create_invite()` | create the welcome mailbox and the invite | the `Invite` (the app shows the link only after saving) |
|
||||
|
||||
Then `deliver(&Outgoing)` posts one blob, and `finish(&Received)` delivers its `Outgoing`s, then
|
||||
acknowledges its blobs, then drops each welcome mailbox whose contact has said hello. The app saves
|
||||
the snapshot again after `finish`. The drop waits for `finish` on purpose. A snapshot saved between
|
||||
`receive` and `finish` must still know the welcome mailbox, so that a restored client fetches its
|
||||
blobs again and acknowledges them. Dropping it inside `receive` left the Welcome and the `hello` on
|
||||
the relay for 30 days; test 3 found that while this was being built. `Outgoing` is serialisable, so an app can keep it in an outbox and deliver
|
||||
it again after a crash.
|
||||
|
||||
The F21 calls stay, for apps and tests without persistence: `send` = `compose` + `deliver`,
|
||||
`accept_invite` = `accept` + deliver, `poll` = `receive` + `finish`.
|
||||
|
||||
### Why a crash is now harmless
|
||||
| Crash after saving, before… | What happens on the next start |
|
||||
|:--|:--|
|
||||
| delivering an `Outgoing` | the app delivers it from its outbox. If the crash came after the post, the blob arrives twice; MLS refuses the second copy as a replay, and it is dropped |
|
||||
| acknowledging | the blobs are fetched again; MLS refuses them as already processed, and the client drops them and acknowledges them. The events were saved with the snapshot, so nothing is shown twice |
|
||||
| saving at all | nothing reached the relay, apart from a mailbox or an invite nobody knows about: no harm. A claimed invite is used up (the link says *ask for a new one*) |
|
||||
|
||||
### The snapshot
|
||||
- JSON, versioned (`"v": 1`). It contains:
|
||||
- our name and the 16 identity bytes;
|
||||
- the signature public key; the private key is in OpenMLS's storage;
|
||||
- each contact: id, MLS group id, name, our mailbox and fetch token, their mailbox and post token;
|
||||
- the welcome mailboxes;
|
||||
- **all of OpenMLS's storage** (`MemoryStorage::values`, a public map of keys and values,
|
||||
base64url).
|
||||
- Restoring rebuilds the provider with that map. It loads each group with `MlsGroup::load` and the
|
||||
signer with `SignatureKeyPair::read`. A snapshot that does not parse, has another version, or
|
||||
names a group that is not in the storage is refused (`ClientError::State`). A half-restored client
|
||||
is never returned.
|
||||
- **It holds every secret of the identity**: MLS private keys, fetch tokens, post tokens. It must
|
||||
live only in encrypted storage. The library never logs it, and its `Debug` prints no bytes.
|
||||
- **Size:** a few KB per contact (two MLS epochs of secrets). Writing it whole after each change is
|
||||
fine for 1:1 chats with dozens of people. A table per key would scale better; that is for later,
|
||||
when measured.
|
||||
|
||||
## 3. Tests — written first
|
||||
1. **Restart both sides mid-conversation:** pair, talk, snapshot both, restore both into new clients,
|
||||
then talk both ways.
|
||||
2. **Restart with an invite waiting:** create an invite, snapshot, restore; the invitee accepts; the
|
||||
restored inviter joins.
|
||||
3. **Crash between receive and finish** (on the inviter's side, when the `hello` is answered): save
|
||||
the snapshot with the `Received`, drop the client, restore, deliver the saved `Outgoing`s, receive
|
||||
again. The pairing completes, and no event is shown twice.
|
||||
4. **Crash after deliver, before marking it delivered:** the blob is posted twice; the receiver shows
|
||||
the text once.
|
||||
5. **Nothing reaches the relay before the app saves.** `compose` and `receive` post nothing (the
|
||||
relay's blob count is unchanged), and `receive` acknowledges nothing.
|
||||
6. **A bad snapshot is refused:** truncated, wrong version, or a contact whose group is missing.
|
||||
7. **The snapshot carries no name in clear on the relay:** not a relay test. The relay never sees a
|
||||
snapshot, and the F21 tests still hold.
|
||||
|
||||
8. **The relay fails:** `finish` acknowledges nothing when delivering fails (an app without an
|
||||
outbox depends on that). A `receive` whose relay fails part-way returns what it processed,
|
||||
because the client's state already includes it.
|
||||
9. **A used welcome mailbox is no longer fetched**, even after a restart. Neither is a forgotten
|
||||
invite's: `forget_invite(id)`, which the app calls when an invite is cancelled or older than the
|
||||
relay's 7 days (the library has no clock). Without it an unclaimed invite's mailbox is fetched
|
||||
for ever.
|
||||
|
||||
10. **A forgotten contact leaves nothing behind** (`forget_contact`, added 2026-11-16 for Amicitia's
|
||||
*Remove person*): its name is gone from the snapshot, its MLS group from storage (putting the
|
||||
contact back into the snapshot is refused), and its mailbox is no longer fetched. The other side
|
||||
is not told.
|
||||
|
||||
Planted bugs, for the review: `receive` acknowledges inside the call; `compose` posts; `restore`
|
||||
skips the storage map; `finish` acknowledges before it delivers; a restored client starts
|
||||
`next_contact` at 0, so two contacts share an id.
|
||||
|
||||
## 4. Not in this part
|
||||
- How Amicitia stores the snapshot, events and outbox in one transaction (F22b).
|
||||
- Several devices per identity (Phase 2 has one; HANDOVER).
|
||||
- Encrypting the snapshot inside the library: the app's store is already encrypted, and a second
|
||||
key would have to live somewhere too.
|
||||
@@ -0,0 +1,99 @@
|
||||
# F21 — The client: MLS 1:1, a mailbox per contact, invites
|
||||
|
||||
Analysis, 2026-11-14. Issues #3 (OpenMLS check) and #6 (client). It builds on F20: the relay and
|
||||
`PROTOCOL.md` §8.
|
||||
|
||||
## 1. Why and what
|
||||
Chat must be end-to-end encrypted with MLS, and the relay must learn nothing readable. The client
|
||||
library is the one place where that happens. Amicitia embeds it in F22, and any other app could too.
|
||||
|
||||
After F21, two clients in one test can:
|
||||
1. pair through an invite;
|
||||
2. learn each other's mailbox and post token *inside* MLS;
|
||||
3. exchange text both ways through a real relay.
|
||||
|
||||
A canary string in a message, and both display names, never appear in the relay's database.
|
||||
|
||||
### The OpenMLS check (#3), measured 2026-11-14
|
||||
| Question | Answer |
|
||||
|:--|:--|
|
||||
| Version | `openmls` 0.9.2, `openmls_rust_crypto` / `_basic_credential` / `_traits` 0.6.0; MSRV 1.91 (we pin 1.99) |
|
||||
| Licence | OpenMLS crates **MIT**. The whole tree is MIT, Apache-2.0 or BSD, except **`hpke-rs` 0.7 (MPL-2.0)**, OpenMLS's HPKE. MPL-2.0 is file-level copyleft: an app that ships it unmodified must say where its source is. That goes into Amicitia's licence notices (F22) |
|
||||
| C code | none: no `cc`, `cmake` or `-sys` crate in the tree. The crypto is RustCrypto (pure Rust) |
|
||||
| Android | `cargo build -p tabellarius-client` passes for `aarch64-linux-android`, `x86_64-linux-android` and `armv7-linux-androideabi`. The client's tests also *run* on the x86_64 emulator (§5) |
|
||||
|
||||
## 2. Architecture
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant A as Inviter A
|
||||
participant R as Relay
|
||||
participant B as Invitee B
|
||||
A->>R: POST /v0/mailboxes Mw (id and post token derived from the secret)
|
||||
A->>R: POST /v0/invites {id, hash(secret), KeyPackage(A)}
|
||||
A-->>B: link: relay, invite id, secret (QR or link, outside the relay)
|
||||
B->>R: GET /v0/invites/{id} (secret) → KeyPackage(A), invite deleted
|
||||
B->>B: create group G, add A → Welcome
|
||||
B->>R: POST Mw: Welcome; then an MLS message {hello: mailbox M_B, post token P_B, name}
|
||||
A->>R: GET Mw → join G, read hello
|
||||
A->>R: POST M_B: MLS {hello: mailbox M_A, post token P_A, name}
|
||||
B->>R: GET M_B → read hello
|
||||
Note over A,B: A posts to M_B, B posts to M_A. One MLS group per pair.
|
||||
```
|
||||
- **Identity:** an Ed25519 key made on the device, behind a `BasicCredential` that carries 16
|
||||
random bytes, not a name. The display name travels only inside MLS (`PROTOCOL.md` §2).
|
||||
- **Ciphersuite:** `MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519`, RFC 9420's mandatory one.
|
||||
- **The welcome mailbox, Mw.** The link carries three things (§4): the relay, the invite id and the
|
||||
secret. The invitee's first reply needs somewhere to go, so its id and post token are **derived
|
||||
from the invite secret** with HKDF-SHA256 (crate `hkdf`, labels `tabellarius v0 welcome mailbox`
|
||||
and `… post`). The inviter creates Mw and keeps a random fetch token for it. To the relay it is an
|
||||
ordinary mailbox, so §5 and §8 are unchanged.
|
||||
- **The invitee creates the group.** It holds the inviter's KeyPackage, so it can add the inviter at
|
||||
once and send the Welcome. §4 says the invitee *replies with their own* KeyPackage. That is not
|
||||
needed when the invitee creates the group, so §4's text changes (§4 below).
|
||||
- **Payloads inside MLS** are JSON: `{"kind":"hello","mailbox","postToken","name"}` and
|
||||
`{"kind":"text","body"}`. The relay sees only MLS ciphertext.
|
||||
- **Blob framing:** each blob is one TLS-serialised `MlsMessageOut` (a Welcome, or a private
|
||||
message).
|
||||
- **Transport is a trait.** `Transport` covers create mailbox, post, fetch, acknowledge, create
|
||||
invite and claim invite. The library makes no network calls itself. F22 gives it an HTTP
|
||||
implementation. The tests use the real relay over loopback, plus an in-memory double for the run
|
||||
on Android.
|
||||
- **Poll:** fetch every own mailbox, process blobs in order, and acknowledge each one processed
|
||||
(or refused as not MLS). Each call returns events: `Joined {contact, name}`,
|
||||
`Message {contact, text}`.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy:**
|
||||
- The relay sees: mailbox ids, token hashes, ciphertext sizes and hours, and the KeyPackage (A's
|
||||
public key and the random credential id).
|
||||
- It does not see: names, text, or which two mailboxes belong to one pair.
|
||||
- The welcome mailbox's id is derived from the secret. Whoever has the link can post there, which
|
||||
is exactly the invite's capability. Mw is used once, but a mailbox cannot be deleted in v0 (F20
|
||||
§4), so it stays empty.
|
||||
- **Crypto:** none written here. MLS, HKDF and SHA-256 come from OpenMLS, `hkdf` and `sha2`.
|
||||
- **State:** in memory in F21. Keeping MLS state across restarts, in Amicitia's encrypted `mls`
|
||||
table, is F22.
|
||||
- **A stolen link:** whoever opens it first becomes the contact. The inviter sees the joiner's name
|
||||
and can block. Safety footprints (F26) are the real answer, and the link is meant to be shared in
|
||||
person or privately.
|
||||
|
||||
## 4. Gaps and designed solutions
|
||||
| Gap | Solution |
|
||||
|:--|:--|
|
||||
| §4 says the invitee *replies with their own KeyPackage*, and the reply channel (Mw) is not described | Change §4 to this flow: the invitee creates the group; the first reply goes to a mailbox derived from the secret. **Needs Mark's approval** before merging (CLAUDE.md §3) |
|
||||
| RFC 9420 test vectors | OpenMLS runs them in its own CI. Here, interop is tested between two of our clients, plus OpenMLS's validation of every message |
|
||||
| State across restarts | F22 (an `mls` table, an SQLite storage provider) |
|
||||
| Deleting the used welcome mailbox | protocol v1 (F20 §4) |
|
||||
| Block, delivery state | F24 |
|
||||
| Several devices per person | Phase 5 (G04) |
|
||||
|
||||
## 5. Verification matrix
|
||||
| Case | Kind | Test |
|
||||
|:--|:--|:--|
|
||||
| Two clients pair through an invite and exchange text both ways, through the real relay over loopback | integration | `client` `pair_and_talk_through_a_real_relay` |
|
||||
| A canary in a message, and both names, never appear in the relay's database file | integration | `client` `the_relay_never_sees_a_name_or_a_word` |
|
||||
| A link opened twice: the second claim fails, and nobody else joins | integration | `client` |
|
||||
| A blob that is not MLS, or not for this group, is acknowledged and skipped, never shown | integration | `client` |
|
||||
| The welcome mailbox derivation is fixed (a test vector) | unit | `client` |
|
||||
| Pairing and talking run **on the Android emulator** (an in-memory transport) | device | `cargo test --target x86_64-linux-android` binary run with `adb` |
|
||||
| The client does not depend on the relay (except in its tests) | CI | `scripts/check-deps.sh` (normal edges only) |
|
||||
@@ -0,0 +1,83 @@
|
||||
# F23 — The relay on a home server: quotas, a NixOS module, TLS
|
||||
|
||||
Analysis, 2026-11-16. Issues T#8 (deploy) and Amicitia #51. The container image of T#8 is left for later: the NixOS module is what the home server runs. It builds on F20 (the relay) and
|
||||
`relay.md` §3–4, which put two things before any relay that faces the internet: **quotas**, and a
|
||||
**reverse proxy that logs no IP address**.
|
||||
|
||||
## 1. Why and what
|
||||
Two people on two machines can only chat through a relay both can reach. Mark's home server is the
|
||||
first one. After F23:
|
||||
- the relay refuses to fill its disk: per-mailbox and relay-wide caps, answered with a bare **507**;
|
||||
- `deploy/nixos/module.nix` runs it on NixOS, listening on loopback only, behind **Caddy** with TLS
|
||||
from Let's Encrypt, and **no access log, no error log with an address in it**;
|
||||
- a NixOS VM test boots that configuration, sends requests through the proxy from a known address,
|
||||
and fails if that address appears anywhere in the journal or under `/var/log`;
|
||||
- Amicitia accepts an `https://` relay address (its own PR).
|
||||
|
||||
## 2. Design
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[app] -->|TLS 443| C[Caddy: TLS, no logs]
|
||||
C -->|HTTP 127.0.0.1:8470| R[tabellarius-relay: systemd, DynamicUser, loopback only]
|
||||
R --> D[(SQLite: PROTOCOL.md section 5)]
|
||||
```
|
||||
### Quotas *(protocol change, §8: a new status)*
|
||||
| Limit | Default | Set by |
|
||||
|:--|:--|:--|
|
||||
| waiting blobs in one mailbox | 1 000 | the protocol |
|
||||
| waiting bytes in one mailbox | 32 MiB | the protocol |
|
||||
| waiting bytes on the relay | 1 GiB | `--max-bytes` |
|
||||
| mailboxes on the relay | 100 000 | `--max-mailboxes` |
|
||||
| unclaimed invites on the relay | 10 000 | `--max-invites` |
|
||||
|
||||
- Over a limit, the relay answers **507 Insufficient Storage**, bare, like every refusal. The
|
||||
per-mailbox caps are checked **after** the post token, so 507 tells nothing to someone without
|
||||
the token. The relay-wide caps say only that the relay is full.
|
||||
- **No identity is needed to count**: nothing new is stored; the counts come from §5's own columns
|
||||
(`size`, the rows). No IP address is kept, not even in memory: rate limits by address would need
|
||||
one. A flood can fill the relay up to its caps; then it refuses, and the operator sees it.
|
||||
- The client already handles it: 507 is a failure, so the message waits in the outbox.
|
||||
- **Mailboxes are never deleted yet** (`relay.md` §4): an abandoned mailbox counts against the
|
||||
100 000 until a protocol version can delete one. Stated.
|
||||
|
||||
### The NixOS module (`deploy/nixos/module.nix`)
|
||||
- `services.tabellarius.enable`, `.domain`, `.maxBytes`, `.maxMailboxes`, `.maxInvites`, `.package`
|
||||
(the flake's own build).
|
||||
- **The relay:** a systemd service with `DynamicUser`, `StateDirectory=tabellarius` (the database),
|
||||
`--listen 127.0.0.1:8470`. Hardened: `ProtectSystem=strict`, `ProtectHome`, `PrivateTmp`,
|
||||
`PrivateDevices`, `NoNewPrivileges`, `MemoryDenyWriteExecute`, `RestrictAddressFamilies=AF_INET
|
||||
AF_INET6`, `SystemCallFilter=@system-service`, and **`IPAddressDeny=any` with
|
||||
`IPAddressAllow=localhost`**: even a bug cannot make it talk to anything but the proxy.
|
||||
- **The proxy:** `services.caddy`, one virtual host, `reverse_proxy 127.0.0.1:8470`. The NixOS
|
||||
module writes an access log per host by default; the host's `logFormat` is set to
|
||||
`output discard`, and Caddy's default logger too. Caddy's own TLS-handshake and proxy errors can
|
||||
name a client address, so no log is the rule; an operator who needs one turns it on and knows
|
||||
why. Headers: none added.
|
||||
- **journald:** the relay prints one line at start. Nothing per request.
|
||||
|
||||
### The VM test (`deploy/nixos/test.nix`, `nix flake check`)
|
||||
Two machines: `server` with the module (TLS from Caddy's internal CA instead of Let's Encrypt), and
|
||||
`client` at a fixed address. The client creates a mailbox, posts, fetches, acknowledges, makes a
|
||||
mistake (a wrong token, a malformed request), and fills a mailbox to its 507. Then the test greps
|
||||
the server's whole journal and `/var/log` for the client's address and fails if it appears.
|
||||
|
||||
**Not run here.** This machine has neither Nix nor WSL. The module and the test are written to be
|
||||
run with `nix flake check` on Linux, and the PR says so. Mark's server is the first real run.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy:** the logs are the risk this feature exists to close. The VM test is its proof, once
|
||||
it runs. The network layer (a router, the ISP) still sees addresses and timing (§1).
|
||||
- **Abuse:** caps bound the disk; they do not stop someone from filling them. Proof of work or
|
||||
invite-only mailbox creation is for a later protocol version.
|
||||
- **Reproducibility:** the module uses the flake's package, so the relay that runs is the one built
|
||||
from this commit (`docs/VERIFY.md`).
|
||||
|
||||
## 4. Tests — written first
|
||||
1. Each cap: the post or create that would cross it gets 507; one under it succeeds; after an
|
||||
acknowledgement (or a purge) there is room again.
|
||||
2. The per-mailbox cap answers 404, not 507, to a wrong token.
|
||||
3. The CLI reads `--max-bytes`, `--max-mailboxes`, `--max-invites`; a bad value is refused.
|
||||
4. The VM test (§2), on Linux.
|
||||
|
||||
Planted bugs: the mailbox cap checked before the token; an acknowledgement not freeing space; the
|
||||
global byte cap ignored; the invite cap counting claimed invites; the CLI option ignored.
|
||||
@@ -0,0 +1,122 @@
|
||||
# F20 — Wire types and the relay, on loopback first
|
||||
|
||||
Analysis, 2026-11-11. Issues #4 (protocol crate) and #5 (relay). It builds on `docs/PROTOCOL.md` v0,
|
||||
approved 2026-11-08. The home-server deploy (#8) and the client (#6) come later.
|
||||
|
||||
## 1. Why and what
|
||||
Chat needs somewhere for a message to wait until the other person's device fetches it. The relay is
|
||||
that place, and it is the part of the system most open to abuse of trust: whoever runs it sees every
|
||||
connection. So it is built to `PROTOCOL.md` §5 exactly, and every claim in §7 that this feature can
|
||||
prove is proved by a test.
|
||||
|
||||
After F20 a developer can run `tabellarius-relay` on `127.0.0.1` and:
|
||||
- create a mailbox;
|
||||
- post an opaque blob to it with a post token;
|
||||
- fetch the mailbox's blobs with the fetch token;
|
||||
- acknowledge a blob, which deletes it;
|
||||
- rotate the post token (block);
|
||||
- leave an invite with a KeyPackage, and fetch it once with the invite's secret.
|
||||
|
||||
The relay never sees a plaintext message: it receives bytes and stores them. Encryption is the
|
||||
client's job (F21).
|
||||
|
||||
## 2. Architecture
|
||||
```mermaid
|
||||
flowchart LR
|
||||
client[client, F21] -- HTTP/1.1 JSON + octets, /v0/... --> api[relay: axum router]
|
||||
api --> core[relay::Store — every rule, clock passed in]
|
||||
core --> db[(SQLite: mailboxes, blobs, invites)]
|
||||
proto[protocol crate: ids, tokens, limits, request/response types, parsers] --> api
|
||||
proto --> client
|
||||
```
|
||||
### Wire types (`tabellarius-protocol`, no I/O)
|
||||
- `MailboxId`, `InviteId`: 16 random bytes. `Token` (post, fetch, invite secret): 32 random bytes.
|
||||
Each travels as unpadded base64url. Parsing is strict: an exact length, the alphabet only, and the
|
||||
canonical form only, so one value has exactly one spelling.
|
||||
- `TokenHash`: SHA-256 of a token, 32 bytes. The client sends hashes when it creates a mailbox or an
|
||||
invite. The relay therefore never sees a fetch token until it is used, and stores only what it was
|
||||
given.
|
||||
- Limits: a blob is at most 256 KiB, and a KeyPackage at most 16 KiB.
|
||||
- Request and response bodies are `serde` structs with `deny_unknown_fields`. The version is in the
|
||||
path (`/v0/`).
|
||||
|
||||
### Endpoints (`/v0`)
|
||||
| Method and path | Auth (`Authorization: Bearer <base64url>`) | Effect |
|
||||
|:--|:--|:--|
|
||||
| `POST /v0/mailboxes` `{id, postTokenHash, fetchTokenHash}` | none | creates the mailbox; `created_day` = today; 409 if the id exists |
|
||||
| `POST /v0/mailboxes/{id}/blobs` (octets) | post token | stores the blob with `size` and the hour it arrived |
|
||||
| `GET /v0/mailboxes/{id}/blobs` | fetch token | `[{blob: base64url, receivedHour}]`, oldest first, at most 100 |
|
||||
| `DELETE /v0/mailboxes/{id}/blobs/{sha256}` | fetch token | acknowledges: deletes that mailbox's blob whose SHA-256 is given |
|
||||
| `PUT /v0/mailboxes/{id}/post-token` `{postTokenHash}` | fetch token | rotates the post token; the old one is refused from now on |
|
||||
| `POST /v0/invites` `{id, secretHash, keyPackage}` | none | stores the invite; it expires after 7 days |
|
||||
| `GET /v0/invites/{id}` | invite secret | returns the KeyPackage once, then deletes the invite |
|
||||
| `GET /version` | none | crate version and build commit |
|
||||
|
||||
- **Acknowledging by the blob's SHA-256**, not by a relay-assigned id. §5 has no id column. A
|
||||
sequential row id would also tell clients how much traffic the relay carries. The client knows the
|
||||
hash of what it fetched; the relay computes it over that mailbox's blobs only.
|
||||
- **A wrong token, an unknown mailbox and an unknown invite give the same 404.** Nobody can probe
|
||||
which mailboxes exist. Hashes are compared in constant time (`subtle`).
|
||||
- **The clock is passed in.** The store's methods take `now`. The server reads the system clock once
|
||||
per request, and tests pass their own.
|
||||
- **Purge:** `Store::purge(now)` deletes blobs older than 30 days and invites past their expiry. The
|
||||
server runs it every hour and at start.
|
||||
- **No logs of requests.** No `tracing` subscriber. The server prints one line at start: the
|
||||
version and the bind address. There is no per-request log of IPs, user agents or bodies. Counts
|
||||
are not built yet.
|
||||
- **Bind address:** `127.0.0.1:8470` by default. Another address must be given explicitly
|
||||
(`--listen`). TLS is the reverse proxy's job (F23).
|
||||
|
||||
### Storage — exactly §5
|
||||
```sql
|
||||
mailboxes(id BLOB PRIMARY KEY, post_hash BLOB, fetch_hash BLOB, created_day INTEGER)
|
||||
blobs(mailbox_id BLOB, ciphertext BLOB, size INTEGER, received_hour INTEGER)
|
||||
invites(id BLOB PRIMARY KEY, secret_hash BLOB, key_package BLOB, expiry INTEGER)
|
||||
```
|
||||
- `received_hour` is the arrival time rounded down to the hour (unix seconds / 3600), and
|
||||
`created_day` the day (/ 86400). `expiry` is rounded up to the hour.
|
||||
- `secure_delete` is on, so deleted blobs are overwritten in the file and not left in free pages.
|
||||
WAL is off (`journal_mode=DELETE`), so there is no second copy in a `-wal` file.
|
||||
- A test compares the live schema (`sqlite_master`, `PRAGMA table_info`) with this list. A column
|
||||
added in passing fails it. The SQLite row id stays internal and is never sent.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy, by the operator's own logs:** the relay keeps none. A reverse proxy might, and that is
|
||||
F23's NixOS module. Timing and IP at connection time stay visible to an operator who logs at the
|
||||
network layer (§1, stated).
|
||||
- **Privacy, metadata in the database:** `size` and `received_hour` are in §5 on purpose, coarse by
|
||||
design. Nothing links two mailboxes to one person.
|
||||
- **Abuse:** creating a mailbox and an invite needs no account, so anyone who can reach the relay can
|
||||
fill its disk. v0 caps sizes, not counts. On a home relay behind a private address that is
|
||||
acceptable. Quotas without identity (proof of work, per-mailbox caps) are a gap, before any public
|
||||
relay (§4).
|
||||
- **Crypto:** none is written here. SHA-256 comes from `sha2`, the constant-time compare from
|
||||
`subtle`, and randomness only in tests and the client.
|
||||
- **Offline:** the relay is only the post office. The app works offline for everything else.
|
||||
|
||||
## 4. Gaps and designed solutions
|
||||
| Gap | Solution |
|
||||
|:--|:--|
|
||||
| No per-mailbox or global quota | a blob count and a byte cap per mailbox, refused with 507; before any public relay |
|
||||
| `cargo fuzz` needs nightly and Linux, and the CI runners are Windows | parsers are hammered with `proptest` (random and mutated input, 10,000 cases each) in `cargo test`; `cargo fuzz` targets are added with the Linux runner |
|
||||
| Deleting a whole mailbox (leaving the app, erase everything) | not in §5's operations; proposed for v1 of the protocol, with the client |
|
||||
| Counts for the operator (requests, blobs) | an in-memory counter at `/metrics` on loopback; later |
|
||||
| The canary in a *message* (§7, first test) | needs MLS, so it is proved end to end in F21. F20 proves the canary for tokens and addresses |
|
||||
|
||||
## 5. Verification matrix
|
||||
| Case | Kind | Test |
|
||||
|:--|:--|:--|
|
||||
| Ids and tokens round-trip; wrong length, alphabet, padding or non-canonical spelling refused | unit + property | `protocol` |
|
||||
| Any byte string given to any parser: an error, never a panic | property (10,000 cases) | `protocol` |
|
||||
| Unknown JSON field refused | unit | `protocol` |
|
||||
| The live database schema is exactly §5 | integration | `relay` `schema_is_exactly_protocol_section_5` |
|
||||
| Post with no, a wrong or the fetch token: 404; with the post token: 201 | integration (HTTP) | `relay` |
|
||||
| After rotation the old post token is refused and the new one accepted | integration | `relay` |
|
||||
| An acknowledged blob is gone; another mailbox's blob with the same bytes is not | integration | `relay` |
|
||||
| A blob is purged after 30 days and kept at 29 (clock injected) | integration | `relay` |
|
||||
| An invite is fetched once, with the right secret only; it is gone after 7 days | integration | `relay` |
|
||||
| Tokens, invite secrets and the client address never appear in the database file (byte search) | integration | `relay` `no_token_or_address_reaches_the_database` |
|
||||
| A deleted blob's bytes are not left in the file (`secure_delete`) | integration | `relay` |
|
||||
| A blob over 256 KiB is refused with 413 | integration | `relay` |
|
||||
| The binary binds loopback by default and serves `/version` | integration (spawned binary) | `relay` |
|
||||
| `relay` does not depend on `client`; `protocol` depends on nothing here | CI | `scripts/check-deps.sh` |
|
||||
@@ -0,0 +1,14 @@
|
||||
# Review — `feature/protocol-http` (PROTOCOL.md §8, the v0 routes)
|
||||
|
||||
2026-11-14. Documents only. Mark approved adding the routes on 2026-11-14.
|
||||
|
||||
**F1 — the routes match the code.** The table repeats `.agents/features/relay.md` §2 as built and
|
||||
tested in F20 (`crates/relay/tests/relay.rs`, 17 tests). No route, limit or status is new here.
|
||||
|
||||
**F2 — privacy.** §8 adds no stored field (§5 is unchanged) and loosens no promise. Two choices are
|
||||
written down as protocol commitments:
|
||||
- the uniform bare 404;
|
||||
- acknowledging by SHA-256 instead of an id.
|
||||
|
||||
**F3 — what is not here.** No quotas yet (`relay.md` §4). A future change to §8 is a version bump,
|
||||
like any change to this file.
|
||||
@@ -0,0 +1,86 @@
|
||||
# Review — `feature/relay` (F20: wire types and the relay, on loopback)
|
||||
|
||||
Adversarial self-review, 2026-11-11. Base: `main` at a19a469. Analysis: `.agents/features/relay.md`.
|
||||
|
||||
## Evidence
|
||||
| What | Result |
|
||||
|:--|:--|
|
||||
| `cargo test --workspace --locked` | protocol **14** (9 unit, 5 property tests of 10,000 cases each), relay **17**, client 0 — **31 passed, 0 failed** |
|
||||
| `cargo clippy --workspace --all-targets --locked -- -D warnings`, `cargo fmt --all --check` | clean |
|
||||
| `scripts/check-deps.sh` | relay does not depend on client; protocol depends on nothing here |
|
||||
| `scripts/test-hooks.sh` | 7 passed |
|
||||
| Planted bugs (`mutate_relay.py`, one at a time, then restored) | **12/12 caught** after one test was fixed (F1) |
|
||||
|
||||
| Planted bug | Caught by |
|
||||
|:--|:--|
|
||||
| Any token accepted | 4 tests, among them *only the post token posts…* |
|
||||
| `secure_delete` off | *a deleted blob is not left in the file* |
|
||||
| WAL journal (a `-wal` copy) | *no token, secret or address reaches the database* |
|
||||
| A `sender_ip` column slipped in | *schema is exactly protocol section 5* |
|
||||
| Blob TTL a day short | *purged after 30 days, not before* (after F1) |
|
||||
| Blob TTL two hours long | the same, and *a deleted blob is not left…* |
|
||||
| An invite not deleted on claim | *claimed once…*, *still good just before 7 days* |
|
||||
| An invite that never expires | *an invite expires after 7 days* |
|
||||
| Rotation that changes nothing | *after rotation the old post token is refused* |
|
||||
| Acknowledging across mailboxes | *an acknowledged blob is gone and no other is touched* |
|
||||
| An unknown mailbox answered 403 instead of 404 | 5 tests, among them *an unknown mailbox looks exactly like a wrong token* |
|
||||
| A request printed to stderr | *the binary serves its version and prints no request* |
|
||||
|
||||
## Findings
|
||||
**F1 — test honesty, found by a planted bug, fixed.** The purge test first checked at 29 days and
|
||||
at 31 days. A TTL one day short still passed it. The test now checks one hour before and one hour
|
||||
after the 30-day boundary. A TTL that is a day short or two hours long both fail it.
|
||||
|
||||
**F2 — privacy, the canary in §7 is only half proved here.** *A canary string sent in a message
|
||||
never appears in the relay's database* is a property of the client's encryption. The relay stores
|
||||
whatever bytes it is given. F20 proves the relay's half: no token, invite secret, client address or
|
||||
user agent ever reaches the database file. The file was searched byte by byte after real TCP
|
||||
requests. The message canary is F21's first end-to-end test.
|
||||
|
||||
**F3 — privacy, what the relay does keep.**
|
||||
- **Per mailbox:** the token hashes and the day it was made.
|
||||
- **Per blob:** the ciphertext, its size and the hour it arrived.
|
||||
- **Per invite:** the secret's hash, the KeyPackage and the expiry, rounded up to the hour.
|
||||
|
||||
All of it is §5's list, checked by the schema test. A KeyPackage holds the inviter's MLS public key
|
||||
and credential. That is §4 by design: it is how the invitee starts the conversation. It is deleted
|
||||
when claimed, or at expiry.
|
||||
|
||||
**F4 — correctness, acknowledging by hash.** Two identical blobs in one mailbox: one acknowledgement
|
||||
deletes one of them, and the second waits for its own. MLS ciphertexts do not repeat, so this only
|
||||
matters for a misbehaving client. The cost is reading the mailbox's blobs on each acknowledgement:
|
||||
at most 100 are fetched at a time, which is fine for a home relay. If it ever matters, a per-blob
|
||||
hash column would be a protocol change.
|
||||
|
||||
**F5 — abuse, open by design (relay.md §4).** Mailbox and invite creation need no account. A relay
|
||||
reachable by strangers can be filled. v0 caps sizes (a blob ≤ 256 KiB, JSON ≤ 32 KiB), not counts.
|
||||
The relay listens on loopback by default; quotas come before any public relay.
|
||||
|
||||
**F6 — the HTTP routes are not in `PROTOCOL.md` yet.** The routes, the uniform 404 and acknowledging
|
||||
by hash live in `relay.md` §2 and in the protocol crate. None of it adds a stored field or loosens a
|
||||
promise. They are still part of *what crosses the wire*, so adding them to `PROTOCOL.md` (a new §8)
|
||||
needs Mark's approval.
|
||||
|
||||
**F7 — concurrency.** One SQLite connection behind a mutex, used briefly inside async handlers. On a
|
||||
home relay that is fine. Under load it would block a runtime thread. `spawn_blocking` or a pool is
|
||||
the fix when it matters.
|
||||
|
||||
**F8 — scope.**
|
||||
- Fuzzing uses `proptest`: 50,000 parser cases and 3,500 random requests per run. `cargo fuzz`
|
||||
waits for a Linux runner (relay.md §4).
|
||||
- Not tested: the hourly purge timer in `main.rs`. The purge itself is tested, with the clock passed
|
||||
in.
|
||||
- Not checked: the reproducible Nix build, by hand in WSL; there is no Nix there yet.
|
||||
|
||||
## Privacy — every path a byte could leave
|
||||
- **Off the relay:** only the responses to the token holder. A refusal is a bare status with no body.
|
||||
- **Into a log:** one line at start (version and bind address). Nothing per request, tested on the
|
||||
real binary.
|
||||
- **Into the database:** §5 only, tested by the schema test and by a byte search of the file.
|
||||
|
||||
## Not verified
|
||||
- TLS and a reverse proxy (F23).
|
||||
- A real network beyond loopback.
|
||||
- Load.
|
||||
- The Nix build.
|
||||
- Windows only: the CI runners are Windows, and so is this machine.
|
||||
@@ -28,9 +28,13 @@ deploy/container/ # container image
|
||||
|
||||
## 3. Workflow
|
||||
Same as Amicitia: analysis document in `.agents/features/` before code ((D)TDD), branch per feature,
|
||||
adversarial self-review in `.agents/reviews/`, merge `--no-ff`, push and verify the remote hash. The
|
||||
agent merges its own PR once local checks pass and the review is written, and reports afterwards
|
||||
(Mark, 2026-11-08); a change to `docs/PROTOCOL.md` still needs Mark's approval first.
|
||||
PR. **The adversarial self-review is posted in the PR** as a Gitea review: the evidence (test counts
|
||||
per crate, planted bugs) in its body and a comment on each line a finding is about. The PR is the
|
||||
record; `.agents/reviews/` holds the reviews from before 2026-11-14 only.
|
||||
**The agent merges every PR itself**, a change to `docs/PROTOCOL.md` included, once local checks pass
|
||||
and the review is posted: merge `--no-ff`, push, verify the remote hash, say in the merge commit which
|
||||
PR holds the review, and report to Mark afterwards (Mark, 2026-11-14). A protocol change still says in
|
||||
`docs/PROTOCOL.md` what changed, when and why.
|
||||
**No AI attribution in commits, ever.** Quote test counts per crate; an exit code is not a count.
|
||||
|
||||
## 4. Known traps
|
||||
|
||||
Generated
+2637
File diff suppressed because it is too large
Load Diff
@@ -8,6 +8,26 @@ publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tabellarius-protocol = { path = "../protocol" }
|
||||
# MLS (RFC 9420). Pure-Rust crypto provider (RustCrypto), so Android and iOS need no C toolchain.
|
||||
openmls = "0.9"
|
||||
openmls_rust_crypto = "0.6"
|
||||
openmls_basic_credential = "0.6"
|
||||
openmls_traits = "0.6"
|
||||
# Derives the welcome mailbox from an invite secret (client.md §2).
|
||||
hkdf = "0.12"
|
||||
sha2 = "0.10"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
# The snapshot's byte fields (already in the tree through the protocol crate).
|
||||
base64 = "0.22"
|
||||
|
||||
[dev-dependencies]
|
||||
# The real relay, for the end-to-end test only. `check-deps.sh` checks normal edges: the client
|
||||
# library itself never depends on the relay.
|
||||
tabellarius-relay = { path = "../relay" }
|
||||
axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] }
|
||||
tokio = { version = "1", features = ["rt", "net"] }
|
||||
tempfile = "3"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
+929
-2
@@ -1,2 +1,929 @@
|
||||
//! Client library: MLS (via OpenMLS) and the mailbox client.
|
||||
//! Empty until the protocol review is approved. No cryptography is ever written here by hand.
|
||||
//! The Tabellarius client: MLS 1:1 conversations (OpenMLS), a mailbox per contact, invites.
|
||||
//! No cryptography is written here by hand: MLS is OpenMLS, HKDF and SHA-256 are RustCrypto.
|
||||
//!
|
||||
//! Pairing (`.agents/features/client.md` §2):
|
||||
//! 1. The inviter makes a KeyPackage and a link (invite id + secret). It also makes a *welcome
|
||||
//! mailbox*, whose id and post token are derived from the secret.
|
||||
//! 2. The invitee claims the KeyPackage, creates the MLS group, and posts the Welcome and an MLS
|
||||
//! `hello` (its own mailbox and post token, and its name) to the welcome mailbox.
|
||||
//! 3. The inviter joins, and answers with its own `hello` to the invitee's mailbox.
|
||||
//!
|
||||
//! The relay only ever holds MLS ciphertext, KeyPackages, ids and token hashes.
|
||||
//!
|
||||
//! **An app that keeps the client across restarts** (`.agents/features/client-state.md`) uses the
|
||||
//! staged calls — [`Client::compose`], [`Client::accept`], [`Client::receive`] — then saves
|
||||
//! [`Client::snapshot`] together with what they returned, and only then calls [`Client::deliver`]
|
||||
//! or [`Client::finish`]. Nothing reaches the relay after a state change before the app has saved
|
||||
//! it. [`Client::send`], [`Client::accept_invite`] and [`Client::poll`] do both steps at once, for
|
||||
//! use without persistence.
|
||||
|
||||
pub mod transport;
|
||||
|
||||
mod snapshot;
|
||||
pub use snapshot::SNAPSHOT_VERSION;
|
||||
|
||||
use hkdf::Hkdf;
|
||||
use openmls::prelude::tls_codec::{Deserialize as _, Serialize as _};
|
||||
use openmls::prelude::*;
|
||||
use openmls_basic_credential::SignatureKeyPair;
|
||||
use openmls_rust_crypto::OpenMlsRustCrypto;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::Sha256;
|
||||
use snapshot::Bytes;
|
||||
use std::fmt;
|
||||
use tabellarius_protocol::{
|
||||
blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, Sha256Hash,
|
||||
Token, MAX_BLOB_BYTES,
|
||||
};
|
||||
pub use transport::{MemoryTransport, Transport, TransportError};
|
||||
|
||||
/// RFC 9420's mandatory ciphersuite.
|
||||
pub const CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;
|
||||
/// The longest display name sent in a `hello`.
|
||||
pub const MAX_NAME_CHARS: usize = 64;
|
||||
/// The longest text message, in bytes; well under a blob's limit once encrypted.
|
||||
pub const MAX_TEXT_BYTES: usize = 64 * 1024;
|
||||
|
||||
const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox";
|
||||
const WELCOME_POST_LABEL: &[u8] = b"tabellarius v0 welcome mailbox post";
|
||||
|
||||
/// Why something failed. Never carries a message's text, a name, or a token.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ClientError {
|
||||
Transport(TransportError),
|
||||
/// MLS refused: a bad KeyPackage, a Welcome that is not for us, a message that does not verify.
|
||||
Mls,
|
||||
/// No randomness from the system.
|
||||
Random,
|
||||
/// A name or text over its limit.
|
||||
TooLong,
|
||||
/// No such contact, or a contact whose mailbox is not known yet.
|
||||
UnknownContact,
|
||||
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
|
||||
State,
|
||||
}
|
||||
|
||||
impl From<TransportError> for ClientError {
|
||||
fn from(e: TransportError) -> Self {
|
||||
ClientError::Transport(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the link to share carries, besides the relay's address.
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Invite {
|
||||
pub id: InviteId,
|
||||
pub secret: Token,
|
||||
}
|
||||
|
||||
/// The welcome mailbox's id and post token, derived from an invite secret with HKDF-SHA256.
|
||||
pub fn welcome_mailbox(secret: &Token) -> (MailboxId, Token) {
|
||||
let hk = Hkdf::<Sha256>::new(None, secret.as_bytes());
|
||||
let mut id = [0u8; 16];
|
||||
let mut post = [0u8; 32];
|
||||
// Lengths within HKDF's limit (255 × 32 bytes): expand cannot fail here.
|
||||
let _ = hk.expand(WELCOME_ID_LABEL, &mut id);
|
||||
let _ = hk.expand(WELCOME_POST_LABEL, &mut post);
|
||||
(MailboxId::from_bytes(id), Token::from_bytes(post))
|
||||
}
|
||||
|
||||
/// A local handle for a contact. Means nothing outside this client.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
|
||||
pub struct ContactId(pub u32);
|
||||
|
||||
/// What [`Client::receive`] found.
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub enum Event {
|
||||
/// The other side's `hello` arrived: the conversation can be used both ways. On the
|
||||
/// inviter's side, `via` is the invite it came through; on the invitee's side it is `None`
|
||||
/// (the app already knows the contact from [`Client::accept`]).
|
||||
Joined {
|
||||
contact: ContactId,
|
||||
name: String,
|
||||
via: Option<InviteId>,
|
||||
},
|
||||
Message {
|
||||
contact: ContactId,
|
||||
text: String,
|
||||
},
|
||||
/// The other side's app has saved our texts up to `upto` (a `seq` from
|
||||
/// [`Client::sent_seq`]). Only while receipts are on ([`Client::set_receipts`]).
|
||||
Delivered {
|
||||
contact: ContactId,
|
||||
upto: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// One operation for the relay, to deliver once the app has saved the snapshot: a blob to post,
|
||||
/// or a post token to rotate (block, unblock). An app may keep it in an outbox and deliver it
|
||||
/// again after a crash: a second post is refused by MLS as a replay, a second rotate changes
|
||||
/// nothing. `Debug` shows no token and no bytes.
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Outgoing(Op);
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "camelCase", deny_unknown_fields)]
|
||||
enum Op {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Post {
|
||||
to: MailboxId,
|
||||
post: Token,
|
||||
blob: Bytes,
|
||||
},
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Rotate {
|
||||
mailbox: MailboxId,
|
||||
fetch: Token,
|
||||
post_token_hash: Sha256Hash,
|
||||
},
|
||||
}
|
||||
|
||||
impl Outgoing {
|
||||
fn post(to: MailboxId, post: Token, blob: Vec<u8>) -> Outgoing {
|
||||
Outgoing(Op::Post {
|
||||
to,
|
||||
post,
|
||||
blob: Bytes(blob),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Outgoing {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match &self.0 {
|
||||
Op::Post { blob, .. } => write!(f, "Outgoing({} bytes)", blob.0.len()),
|
||||
Op::Rotate { .. } => f.write_str("Outgoing(rotate)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fetched blob to acknowledge once the app has saved what it produced.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct Ack {
|
||||
mailbox: MailboxId,
|
||||
fetch: Token,
|
||||
hash: Sha256Hash,
|
||||
}
|
||||
|
||||
/// What one [`Client::receive`] produced. Save the snapshot and the events, keep the `outgoing`
|
||||
/// blobs if the app has an outbox, then call [`Client::finish`].
|
||||
#[derive(Debug)]
|
||||
pub struct Received {
|
||||
pub events: Vec<Event>,
|
||||
/// Our answering `hello`s, and receipts.
|
||||
pub outgoing: Vec<Outgoing>,
|
||||
/// The relay failed part-way: what was fetched before it is here, the rest waits there.
|
||||
pub interrupted: Option<TransportError>,
|
||||
acks: Vec<Ack>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Ack {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Ack")
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON inside an MLS application message. The relay never sees it.
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
|
||||
enum Payload {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Hello {
|
||||
mailbox: MailboxId,
|
||||
post_token: Token,
|
||||
name: String,
|
||||
},
|
||||
/// `seq` counts this sender's texts to this contact, from 1.
|
||||
Text { body: String, seq: u64 },
|
||||
/// The receiver has saved our texts up to `upto`.
|
||||
Receipt { upto: u64 },
|
||||
/// A new post token for the mailbox the receiver already knows (unblock).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Inbox { post_token: Token },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct Mailbox {
|
||||
id: MailboxId,
|
||||
fetch: Token,
|
||||
}
|
||||
|
||||
/// A welcome mailbox and the invite it belongs to.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct WelcomeBox {
|
||||
mailbox: Mailbox,
|
||||
invite: InviteId,
|
||||
}
|
||||
|
||||
struct Contact {
|
||||
id: ContactId,
|
||||
group: MlsGroup,
|
||||
name: Option<String>,
|
||||
/// Where the other side posts to us. `None` on the inviter's side until our `hello` is ready.
|
||||
inbox: Option<Mailbox>,
|
||||
/// Where we post to the other side: their mailbox and its post token.
|
||||
outbox: Option<(MailboxId, Token)>,
|
||||
/// The invite this contact came through, on the inviter's side.
|
||||
via: Option<InviteId>,
|
||||
/// Blocked: their mailbox token rotated away; what still arrives from them is dropped.
|
||||
blocked: bool,
|
||||
/// The `seq` of our last text to them.
|
||||
sent_seq: u64,
|
||||
/// The highest `seq` of their texts we have received.
|
||||
received_seq: u64,
|
||||
}
|
||||
|
||||
pub struct Client<T: Transport> {
|
||||
provider: OpenMlsRustCrypto,
|
||||
signer: SignatureKeyPair,
|
||||
credential: CredentialWithKey,
|
||||
identity: Vec<u8>,
|
||||
name: String,
|
||||
transport: T,
|
||||
contacts: Vec<Contact>,
|
||||
welcome_boxes: Vec<WelcomeBox>,
|
||||
next_contact: u32,
|
||||
/// Send receipts and report the other side's (reciprocal). On by default.
|
||||
receipts: bool,
|
||||
}
|
||||
|
||||
impl<T: Transport> Client<T> {
|
||||
/// A new identity: an Ed25519 key and a credential holding 16 random bytes, never a name.
|
||||
pub fn new(name: &str, transport: T) -> Result<Self, ClientError> {
|
||||
if name.chars().count() > MAX_NAME_CHARS {
|
||||
return Err(ClientError::TooLong);
|
||||
}
|
||||
let provider = OpenMlsRustCrypto::default();
|
||||
let signer = SignatureKeyPair::new(CIPHERSUITE.signature_algorithm())
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
signer
|
||||
.store(provider.storage())
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
let identity: [u8; 16] = provider
|
||||
.rand()
|
||||
.random_array()
|
||||
.map_err(|_| ClientError::Random)?;
|
||||
let credential = credential_with_key(&identity, &signer);
|
||||
Ok(Self {
|
||||
provider,
|
||||
signer,
|
||||
credential,
|
||||
identity: identity.to_vec(),
|
||||
name: name.to_string(),
|
||||
transport,
|
||||
contacts: Vec::new(),
|
||||
welcome_boxes: Vec::new(),
|
||||
next_contact: 0,
|
||||
receipts: true,
|
||||
})
|
||||
}
|
||||
|
||||
fn random<const N: usize>(&self) -> Result<[u8; N], ClientError> {
|
||||
self.provider
|
||||
.rand()
|
||||
.random_array()
|
||||
.map_err(|_| ClientError::Random)
|
||||
}
|
||||
|
||||
/// A fresh mailbox on the relay: we keep the fetch token, the post token goes to the contact.
|
||||
fn new_mailbox(&self) -> Result<(Mailbox, Token), ClientError> {
|
||||
let id = MailboxId::from_bytes(self.random()?);
|
||||
let post = Token::from_bytes(self.random()?);
|
||||
let fetch = Token::from_bytes(self.random()?);
|
||||
self.transport.create_mailbox(&CreateMailbox {
|
||||
id,
|
||||
post_token_hash: post.hash(),
|
||||
fetch_token_hash: fetch.hash(),
|
||||
})?;
|
||||
Ok((Mailbox { id, fetch }, post))
|
||||
}
|
||||
|
||||
/// Step 1: a KeyPackage on the relay and a welcome mailbox. Save the snapshot, then share the
|
||||
/// result as a link.
|
||||
pub fn create_invite(&mut self) -> Result<Invite, ClientError> {
|
||||
let bundle = KeyPackage::builder()
|
||||
.build(
|
||||
CIPHERSUITE,
|
||||
&self.provider,
|
||||
&self.signer,
|
||||
self.credential.clone(),
|
||||
)
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
let kp = bundle
|
||||
.key_package()
|
||||
.tls_serialize_detached()
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
let invite = Invite {
|
||||
id: InviteId::from_bytes(self.random()?),
|
||||
secret: Token::from_bytes(self.random()?),
|
||||
};
|
||||
let (welcome_id, welcome_post) = welcome_mailbox(&invite.secret);
|
||||
let fetch = Token::from_bytes(self.random()?);
|
||||
self.transport.create_mailbox(&CreateMailbox {
|
||||
id: welcome_id,
|
||||
post_token_hash: welcome_post.hash(),
|
||||
fetch_token_hash: fetch.hash(),
|
||||
})?;
|
||||
self.transport.create_invite(&CreateInvite {
|
||||
id: invite.id,
|
||||
secret_hash: invite.secret.hash(),
|
||||
key_package: KeyPackageBytes::new(kp).map_err(|_| ClientError::Mls)?,
|
||||
})?;
|
||||
self.welcome_boxes.push(WelcomeBox {
|
||||
mailbox: Mailbox {
|
||||
id: welcome_id,
|
||||
fetch,
|
||||
},
|
||||
invite: invite.id,
|
||||
});
|
||||
Ok(invite)
|
||||
}
|
||||
|
||||
/// Stops fetching an invite's welcome mailbox: the invite was cancelled, or is older than the
|
||||
/// relay keeps unclaimed invites (7 days; the app has the clock, the library has none).
|
||||
/// Otherwise an unclaimed invite's mailbox is fetched for ever. Save the snapshot after it.
|
||||
pub fn forget_invite(&mut self, invite: &InviteId) {
|
||||
self.welcome_boxes.retain(|w| w.invite != *invite);
|
||||
}
|
||||
|
||||
/// Forgets a contact: its MLS group is deleted from storage, its name and tokens from the
|
||||
/// client, and its mailbox is no longer fetched. The other side is not told, and anything it
|
||||
/// still posts waits on the relay until it expires. Save the snapshot after it. Returns whether
|
||||
/// there was such a contact.
|
||||
pub fn forget_contact(&mut self, contact: ContactId) -> Result<bool, ClientError> {
|
||||
let Some(index) = self.contacts.iter().position(|c| c.id == contact) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let mut c = self.contacts.remove(index);
|
||||
c.group
|
||||
.delete(self.provider.storage())
|
||||
.map_err(|_| ClientError::State)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Step 2, on the other device, staged: claims the KeyPackage (which uses the link up) and
|
||||
/// creates our mailbox, then makes the group. The Welcome and our `hello` come back for the
|
||||
/// app to deliver after saving.
|
||||
pub fn accept(&mut self, invite: &Invite) -> Result<(ContactId, Vec<Outgoing>), ClientError> {
|
||||
let kp_bytes = self.transport.claim_invite(&invite.id, &invite.secret)?;
|
||||
let key_package = KeyPackageIn::tls_deserialize_exact(&kp_bytes)
|
||||
.map_err(|_| ClientError::Mls)?
|
||||
.validate(self.provider.crypto(), ProtocolVersion::Mls10)
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
let (inbox, inbox_post) = self.new_mailbox()?;
|
||||
let config = MlsGroupCreateConfig::builder()
|
||||
.ciphersuite(CIPHERSUITE)
|
||||
.use_ratchet_tree_extension(true)
|
||||
.build();
|
||||
let mut group = MlsGroup::new(
|
||||
&self.provider,
|
||||
&self.signer,
|
||||
&config,
|
||||
self.credential.clone(),
|
||||
)
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
let (_commit, welcome, _info) = group
|
||||
.add_members(&self.provider, &self.signer, &[key_package])
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
group
|
||||
.merge_pending_commit(&self.provider)
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
|
||||
let hello = Payload::Hello {
|
||||
mailbox: inbox.id,
|
||||
post_token: inbox_post,
|
||||
name: self.name.clone(),
|
||||
};
|
||||
let (welcome_id, welcome_post) = welcome_mailbox(&invite.secret);
|
||||
let welcome = welcome
|
||||
.tls_serialize_detached()
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?;
|
||||
let out = vec![
|
||||
Outgoing::post(welcome_id, welcome_post, welcome),
|
||||
Outgoing::post(welcome_id, welcome_post, hello),
|
||||
];
|
||||
let id = self.add_contact(group, Some(inbox), None, None);
|
||||
Ok((id, out))
|
||||
}
|
||||
|
||||
/// [`Client::accept`] and delivering at once, for use without persistence.
|
||||
pub fn accept_invite(&mut self, invite: &Invite) -> Result<ContactId, ClientError> {
|
||||
let (id, out) = self.accept(invite)?;
|
||||
for o in &out {
|
||||
self.deliver(o)?;
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn add_contact(
|
||||
&mut self,
|
||||
group: MlsGroup,
|
||||
inbox: Option<Mailbox>,
|
||||
outbox: Option<(MailboxId, Token)>,
|
||||
via: Option<InviteId>,
|
||||
) -> ContactId {
|
||||
let id = ContactId(self.next_contact);
|
||||
self.next_contact += 1;
|
||||
self.contacts.push(Contact {
|
||||
id,
|
||||
group,
|
||||
name: None,
|
||||
inbox,
|
||||
outbox,
|
||||
via,
|
||||
blocked: false,
|
||||
sent_seq: 0,
|
||||
received_seq: 0,
|
||||
});
|
||||
id
|
||||
}
|
||||
|
||||
fn seal(
|
||||
provider: &OpenMlsRustCrypto,
|
||||
signer: &SignatureKeyPair,
|
||||
group: &mut MlsGroup,
|
||||
payload: &Payload,
|
||||
) -> Result<Vec<u8>, ClientError> {
|
||||
let json = serde_json::to_vec(payload).map_err(|_| ClientError::Mls)?;
|
||||
let blob = group
|
||||
.create_message(provider, signer, &json)
|
||||
.map_err(|_| ClientError::Mls)?
|
||||
.tls_serialize_detached()
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
if blob.len() > MAX_BLOB_BYTES {
|
||||
return Err(ClientError::TooLong);
|
||||
}
|
||||
Ok(blob)
|
||||
}
|
||||
|
||||
/// Encrypts text for a contact whose `hello` has arrived. No network: save the snapshot, then
|
||||
/// [`Client::deliver`] the result.
|
||||
pub fn compose(&mut self, contact: ContactId, text: &str) -> Result<Outgoing, ClientError> {
|
||||
if text.len() > MAX_TEXT_BYTES {
|
||||
return Err(ClientError::TooLong);
|
||||
}
|
||||
let c = self
|
||||
.contacts
|
||||
.iter_mut()
|
||||
.find(|c| c.id == contact)
|
||||
.ok_or(ClientError::UnknownContact)?;
|
||||
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||||
let seq = c.sent_seq + 1;
|
||||
let blob = Self::seal(
|
||||
&self.provider,
|
||||
&self.signer,
|
||||
&mut c.group,
|
||||
&Payload::Text {
|
||||
body: text.to_string(),
|
||||
seq,
|
||||
},
|
||||
)?;
|
||||
c.sent_seq = seq;
|
||||
Ok(Outgoing::post(to, post, blob))
|
||||
}
|
||||
|
||||
/// The `seq` of our last text to a contact: right after [`Client::compose`], the one it made.
|
||||
pub fn sent_seq(&self, contact: ContactId) -> Option<u64> {
|
||||
self.contacts
|
||||
.iter()
|
||||
.find(|c| c.id == contact)
|
||||
.map(|c| c.sent_seq)
|
||||
}
|
||||
|
||||
/// Performs one operation on the relay: posts a blob, or rotates a post token.
|
||||
pub fn deliver(&self, out: &Outgoing) -> Result<(), ClientError> {
|
||||
match &out.0 {
|
||||
Op::Post { to, post, blob } => self.transport.post(to, post, &blob.0)?,
|
||||
Op::Rotate {
|
||||
mailbox,
|
||||
fetch,
|
||||
post_token_hash,
|
||||
} => self
|
||||
.transport
|
||||
.rotate_post_token(mailbox, fetch, post_token_hash)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A post waiting in an app's outbox, with the contact's current post token: after an
|
||||
/// unblock on their side, the token it was sealed with is refused. The blob is unchanged.
|
||||
pub fn readdress(&self, out: &Outgoing) -> Outgoing {
|
||||
if let Op::Post { to, blob, .. } = &out.0 {
|
||||
if let Some((_, post)) = self
|
||||
.contacts
|
||||
.iter()
|
||||
.filter_map(|c| c.outbox)
|
||||
.find(|(mailbox, _)| mailbox == to)
|
||||
{
|
||||
return Outgoing::post(*to, post, blob.0.clone());
|
||||
}
|
||||
}
|
||||
out.clone()
|
||||
}
|
||||
|
||||
/// Blocks a contact, staged: they are marked, and their way into our mailbox is closed by a
|
||||
/// rotate to the hash of a fresh token that nobody gets. Nothing is sent to them. Save the
|
||||
/// snapshot, then deliver the result.
|
||||
pub fn block(&mut self, contact: ContactId) -> Result<Outgoing, ClientError> {
|
||||
let token = Token::from_bytes(self.random()?);
|
||||
let c = self
|
||||
.contacts
|
||||
.iter_mut()
|
||||
.find(|c| c.id == contact)
|
||||
.ok_or(ClientError::UnknownContact)?;
|
||||
let inbox = c.inbox.ok_or(ClientError::UnknownContact)?;
|
||||
c.blocked = true;
|
||||
Ok(Outgoing(Op::Rotate {
|
||||
mailbox: inbox.id,
|
||||
fetch: inbox.fetch,
|
||||
post_token_hash: token.hash(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Unblocks, staged: a rotate to a new token, then that token to them inside MLS.
|
||||
pub fn unblock(&mut self, contact: ContactId) -> Result<Vec<Outgoing>, ClientError> {
|
||||
let token = Token::from_bytes(self.random()?);
|
||||
let c = self
|
||||
.contacts
|
||||
.iter_mut()
|
||||
.find(|c| c.id == contact)
|
||||
.ok_or(ClientError::UnknownContact)?;
|
||||
let inbox = c.inbox.ok_or(ClientError::UnknownContact)?;
|
||||
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||||
let blob = Self::seal(
|
||||
&self.provider,
|
||||
&self.signer,
|
||||
&mut c.group,
|
||||
&Payload::Inbox { post_token: token },
|
||||
)?;
|
||||
c.blocked = false;
|
||||
Ok(vec![
|
||||
Outgoing(Op::Rotate {
|
||||
mailbox: inbox.id,
|
||||
fetch: inbox.fetch,
|
||||
post_token_hash: token.hash(),
|
||||
}),
|
||||
Outgoing::post(to, post, blob),
|
||||
])
|
||||
}
|
||||
|
||||
pub fn is_blocked(&self, contact: ContactId) -> bool {
|
||||
self.contacts.iter().any(|c| c.id == contact && c.blocked)
|
||||
}
|
||||
|
||||
/// Receipts on or off: off, we send none and report none of theirs. Save the snapshot after.
|
||||
pub fn set_receipts(&mut self, on: bool) {
|
||||
self.receipts = on;
|
||||
}
|
||||
|
||||
pub fn receipts(&self) -> bool {
|
||||
self.receipts
|
||||
}
|
||||
|
||||
/// [`Client::compose`] and [`Client::deliver`] at once, for use without persistence.
|
||||
pub fn send(&mut self, contact: ContactId, text: &str) -> Result<(), ClientError> {
|
||||
let out = self.compose(contact, text)?;
|
||||
self.deliver(&out)
|
||||
}
|
||||
|
||||
/// The contact's name, once its `hello` has arrived.
|
||||
pub fn contact_name(&self, contact: ContactId) -> Option<&str> {
|
||||
self.contacts
|
||||
.iter()
|
||||
.find(|c| c.id == contact)
|
||||
.and_then(|c| c.name.as_deref())
|
||||
}
|
||||
|
||||
/// Fetches every own mailbox and processes each blob in order. Posts nothing and acknowledges
|
||||
/// nothing: save the snapshot and the events, then call [`Client::finish`]. A blob that is
|
||||
/// not valid MLS for one of our groups is dropped without a trace: nothing from it is shown,
|
||||
/// and it is acknowledged with the rest.
|
||||
///
|
||||
/// If the relay fails part-way, what was processed so far is returned (with `interrupted`
|
||||
/// set), because the client's state already includes it.
|
||||
pub fn receive(&mut self) -> Result<Received, ClientError> {
|
||||
let mut got = Received {
|
||||
events: Vec::new(),
|
||||
outgoing: Vec::new(),
|
||||
interrupted: None,
|
||||
acks: Vec::new(),
|
||||
};
|
||||
let mut sources: Vec<(Mailbox, Option<InviteId>)> = self
|
||||
.welcome_boxes
|
||||
.iter()
|
||||
.map(|w| (w.mailbox, Some(w.invite)))
|
||||
.collect();
|
||||
sources.extend(
|
||||
self.contacts
|
||||
.iter()
|
||||
.filter_map(|c| c.inbox.map(|m| (m, None))),
|
||||
);
|
||||
let before: Vec<(ContactId, u64)> = self
|
||||
.contacts
|
||||
.iter()
|
||||
.map(|c| (c.id, c.received_seq))
|
||||
.collect();
|
||||
for (mailbox, via) in sources {
|
||||
let blobs = match self.transport.fetch(&mailbox.id, &mailbox.fetch) {
|
||||
Ok(blobs) => blobs,
|
||||
Err(e) => {
|
||||
got.interrupted = Some(e);
|
||||
break;
|
||||
}
|
||||
};
|
||||
for blob in blobs {
|
||||
// A failure to understand one blob must not stop the rest, nor be shown.
|
||||
if let Ok(Some(event)) = self.process(&blob, via) {
|
||||
got.events.push(event);
|
||||
}
|
||||
got.acks.push(Ack {
|
||||
mailbox: mailbox.id,
|
||||
fetch: mailbox.fetch,
|
||||
hash: blob_hash(&blob),
|
||||
});
|
||||
}
|
||||
}
|
||||
// The inviter's side: each contact whose `hello` arrived gets ours, with a new mailbox. A
|
||||
// relay that fails here leaves the contact owing its answer until the next receive.
|
||||
for index in 0..self.contacts.len() {
|
||||
let c = &self.contacts[index];
|
||||
let Some((to, post)) = c.outbox else { continue };
|
||||
if c.inbox.is_some() || got.interrupted.is_some() {
|
||||
continue;
|
||||
}
|
||||
match self.new_mailbox() {
|
||||
Ok((inbox, inbox_post)) => {
|
||||
let hello = Payload::Hello {
|
||||
mailbox: inbox.id,
|
||||
post_token: inbox_post,
|
||||
name: self.name.clone(),
|
||||
};
|
||||
let c = &mut self.contacts[index];
|
||||
// Failing to seal leaves the answer owed, like a relay failure: the events
|
||||
// already processed must still reach the app.
|
||||
let Ok(blob) = Self::seal(&self.provider, &self.signer, &mut c.group, &hello)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
c.inbox = Some(inbox);
|
||||
got.outgoing.push(Outgoing::post(to, post, blob));
|
||||
}
|
||||
Err(ClientError::Transport(e)) => got.interrupted = Some(e),
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
// Receipts, for every contact whose texts arrived now. Delivered by `finish`, so only
|
||||
// after the app has saved the texts.
|
||||
if self.receipts {
|
||||
for (id, was) in before {
|
||||
let Some(c) = self.contacts.iter_mut().find(|c| c.id == id) else {
|
||||
continue;
|
||||
};
|
||||
let Some((to, post)) = c.outbox else { continue };
|
||||
if c.received_seq == was || c.blocked {
|
||||
continue;
|
||||
}
|
||||
let receipt = Payload::Receipt {
|
||||
upto: c.received_seq,
|
||||
};
|
||||
if let Ok(blob) = Self::seal(&self.provider, &self.signer, &mut c.group, &receipt) {
|
||||
got.outgoing.push(Outgoing::post(to, post, blob));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(got)
|
||||
}
|
||||
|
||||
/// After saving: delivers the `outgoing` blobs, then acknowledges the fetched ones. On an
|
||||
/// error, call it again later; anything delivered twice is refused by MLS as a replay.
|
||||
///
|
||||
/// Then a welcome mailbox whose contact has said hello is dropped, so junk posted to it later
|
||||
/// is never fetched. Not before: a snapshot saved between `receive` and `finish` must still
|
||||
/// know the mailbox, so that a restored client fetches its blobs again and acknowledges them.
|
||||
/// Save the snapshot again after `finish`.
|
||||
///
|
||||
/// A post the relay refuses with 404 is skipped: that mailbox's token is gone (we may be
|
||||
/// blocked), and trying again cannot help. Without the skip, one refused receipt would keep
|
||||
/// everything fetched from being acknowledged, for ever.
|
||||
pub fn finish(&mut self, received: &Received) -> Result<(), ClientError> {
|
||||
for out in &received.outgoing {
|
||||
match self.deliver(out) {
|
||||
Ok(()) | Err(ClientError::Transport(TransportError::NotFound)) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
for ack in &received.acks {
|
||||
self.transport
|
||||
.acknowledge(&ack.mailbox, &ack.fetch, &ack.hash)?;
|
||||
}
|
||||
let joined: Vec<InviteId> = self
|
||||
.contacts
|
||||
.iter()
|
||||
.filter(|c| c.name.is_some())
|
||||
.filter_map(|c| c.via)
|
||||
.collect();
|
||||
self.welcome_boxes.retain(|w| !joined.contains(&w.invite));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`Client::receive`] and [`Client::finish`] at once, for use without persistence.
|
||||
pub fn poll(&mut self) -> Result<Vec<Event>, ClientError> {
|
||||
let got = self.receive()?;
|
||||
self.finish(&got)?;
|
||||
match got.interrupted {
|
||||
Some(e) if got.events.is_empty() => Err(ClientError::Transport(e)),
|
||||
_ => Ok(got.events),
|
||||
}
|
||||
}
|
||||
|
||||
fn process(
|
||||
&mut self,
|
||||
blob: &[u8],
|
||||
via: Option<InviteId>,
|
||||
) -> Result<Option<Event>, ClientError> {
|
||||
let message = MlsMessageIn::tls_deserialize_exact(blob).map_err(|_| ClientError::Mls)?;
|
||||
match message.extract() {
|
||||
// Only a welcome mailbox carries a Welcome.
|
||||
MlsMessageBodyIn::Welcome(welcome) if via.is_some() => {
|
||||
let config = MlsGroupJoinConfig::builder()
|
||||
.use_ratchet_tree_extension(true)
|
||||
.build();
|
||||
let staged =
|
||||
StagedWelcome::new_from_welcome(&self.provider, &config, welcome, None)
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
// The same group twice (a Welcome fetched again after a crash): refused.
|
||||
let group_id = staged.group_context().group_id();
|
||||
if self.contacts.iter().any(|c| c.group.group_id() == group_id) {
|
||||
return Err(ClientError::Mls);
|
||||
}
|
||||
let group = staged
|
||||
.into_group(&self.provider)
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
// Not a contact to show yet: the hello right behind the Welcome makes it one.
|
||||
self.add_contact(group, None, None, via);
|
||||
Ok(None)
|
||||
}
|
||||
MlsMessageBodyIn::PrivateMessage(private) => {
|
||||
let protocol: ProtocolMessage = private.into();
|
||||
let group_id = protocol.group_id().clone();
|
||||
let index = self
|
||||
.contacts
|
||||
.iter()
|
||||
.position(|c| c.group.group_id() == &group_id)
|
||||
.ok_or(ClientError::UnknownContact)?;
|
||||
let processed = self.contacts[index]
|
||||
.group
|
||||
.process_message(&self.provider, protocol)
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
let ProcessedMessageContent::ApplicationMessage(app) = processed.into_content()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let payload: Payload =
|
||||
serde_json::from_slice(&app.into_bytes()).map_err(|_| ClientError::Mls)?;
|
||||
self.receive_payload(index, payload)
|
||||
}
|
||||
_ => Err(ClientError::Mls),
|
||||
}
|
||||
}
|
||||
|
||||
fn receive_payload(
|
||||
&mut self,
|
||||
index: usize,
|
||||
payload: Payload,
|
||||
) -> Result<Option<Event>, ClientError> {
|
||||
match payload {
|
||||
Payload::Hello {
|
||||
mailbox,
|
||||
post_token,
|
||||
name,
|
||||
} => {
|
||||
if name.chars().count() > MAX_NAME_CHARS || self.contacts[index].name.is_some() {
|
||||
return Err(ClientError::Mls);
|
||||
}
|
||||
let c = &mut self.contacts[index];
|
||||
c.outbox = Some((mailbox, post_token));
|
||||
c.name = Some(name.clone());
|
||||
Ok(Some(Event::Joined {
|
||||
contact: c.id,
|
||||
name,
|
||||
via: c.via,
|
||||
}))
|
||||
}
|
||||
Payload::Text { body, seq } => {
|
||||
let c = &mut self.contacts[index];
|
||||
if c.name.is_none() {
|
||||
// Text before hello: not from a conversation that has been set up.
|
||||
return Err(ClientError::Mls);
|
||||
}
|
||||
if c.blocked {
|
||||
// Posted before the block, or fetched after it: dropped, never shown.
|
||||
return Ok(None);
|
||||
}
|
||||
c.received_seq = c.received_seq.max(seq);
|
||||
Ok(Some(Event::Message {
|
||||
contact: c.id,
|
||||
text: body,
|
||||
}))
|
||||
}
|
||||
Payload::Receipt { upto } => {
|
||||
let c = &self.contacts[index];
|
||||
if !self.receipts || c.name.is_none() || c.blocked {
|
||||
return Ok(None);
|
||||
}
|
||||
// A receipt cannot mark what was never sent.
|
||||
Ok(Some(Event::Delivered {
|
||||
contact: c.id,
|
||||
upto: upto.min(c.sent_seq),
|
||||
}))
|
||||
}
|
||||
Payload::Inbox { post_token } => {
|
||||
let c = &mut self.contacts[index];
|
||||
// Only the token changes: the mailbox stays the one their hello named.
|
||||
let Some((mailbox, _)) = c.outbox else {
|
||||
return Err(ClientError::Mls);
|
||||
};
|
||||
c.outbox = Some((mailbox, post_token));
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn credential_with_key(identity: &[u8], signer: &SignatureKeyPair) -> CredentialWithKey {
|
||||
CredentialWithKey {
|
||||
credential: BasicCredential::new(identity.to_vec()).into(),
|
||||
signature_key: signer.public().into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A contact who sends a second `hello` must not redirect our messages to another mailbox,
|
||||
/// nor rename themselves. Only the contact can send one (MLS authenticates it), so this guards
|
||||
/// against a misbehaving contact or a replayed message.
|
||||
#[test]
|
||||
fn a_second_hello_changes_nothing() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
let joined = eva.poll().expect("poll");
|
||||
assert_eq!(joined.len(), 1);
|
||||
let before = eva.contacts[0].outbox.map(|(m, _)| m);
|
||||
|
||||
let other = MailboxId::from_bytes([9; 16]);
|
||||
let again = Payload::Hello {
|
||||
mailbox: other,
|
||||
post_token: Token::from_bytes([9; 32]),
|
||||
name: "Mallory".into(),
|
||||
};
|
||||
assert_eq!(eva.receive_payload(0, again), Err(ClientError::Mls));
|
||||
assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before);
|
||||
assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan"));
|
||||
}
|
||||
|
||||
/// `inbox` (unblock) changes only the token for the mailbox their hello named.
|
||||
#[test]
|
||||
fn an_inbox_payload_changes_the_token_not_the_mailbox() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
let (mailbox, before) = eva.contacts[0].outbox.expect("outbox");
|
||||
let fresh = Token::from_bytes([5; 32]);
|
||||
let inbox = Payload::Inbox { post_token: fresh };
|
||||
assert_eq!(eva.receive_payload(0, inbox), Ok(None));
|
||||
let (still, after) = eva.contacts[0].outbox.expect("outbox");
|
||||
assert_eq!(still, mailbox);
|
||||
assert_ne!(after.hash(), before.hash());
|
||||
assert_eq!(after.hash(), fresh.hash());
|
||||
}
|
||||
|
||||
/// A receipt cannot mark texts that were never sent.
|
||||
#[test]
|
||||
fn a_receipt_is_capped_at_what_was_sent() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
eva.send(eva.contacts[0].id, "jedna").expect("send");
|
||||
let got = eva.receive_payload(0, Payload::Receipt { upto: 99 });
|
||||
assert_eq!(
|
||||
got,
|
||||
Ok(Some(Event::Delivered {
|
||||
contact: eva.contacts[0].id,
|
||||
upto: 1
|
||||
}))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! The client's whole state as bytes, for the app's encrypted store
|
||||
//! (`.agents/features/client-state.md` §2). It holds every secret of the identity: MLS private
|
||||
//! keys, fetch tokens and post tokens. `Debug` is not implemented for any of it.
|
||||
|
||||
use crate::{
|
||||
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, Transport, WelcomeBox,
|
||||
CIPHERSUITE, MAX_NAME_CHARS,
|
||||
};
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine as _;
|
||||
use openmls::prelude::{GroupId, MlsGroup, OpenMlsProvider as _};
|
||||
use openmls_basic_credential::SignatureKeyPair;
|
||||
use openmls_rust_crypto::OpenMlsRustCrypto;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::collections::HashSet;
|
||||
use tabellarius_protocol::{InviteId, MailboxId, Token};
|
||||
|
||||
/// The snapshot format's version. Another number is refused, never guessed at.
|
||||
pub const SNAPSHOT_VERSION: u32 = 1;
|
||||
|
||||
/// Bytes as unpadded base64url in JSON.
|
||||
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) struct Bytes(pub(crate) Vec<u8>);
|
||||
|
||||
impl Serialize for Bytes {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&URL_SAFE_NO_PAD.encode(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Bytes {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let s = String::deserialize(d)?;
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(s.as_bytes())
|
||||
.map(Bytes)
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct ContactState {
|
||||
id: ContactId,
|
||||
group: Bytes,
|
||||
name: Option<String>,
|
||||
inbox: Option<Mailbox>,
|
||||
outbox: Option<(MailboxId, Token)>,
|
||||
via: Option<InviteId>,
|
||||
// F24; absent in older snapshots.
|
||||
#[serde(default)]
|
||||
blocked: bool,
|
||||
#[serde(default)]
|
||||
sent_seq: u64,
|
||||
#[serde(default)]
|
||||
received_seq: u64,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct State {
|
||||
v: u32,
|
||||
name: String,
|
||||
identity: Bytes,
|
||||
signer_public: Bytes,
|
||||
contacts: Vec<ContactState>,
|
||||
welcome_boxes: Vec<WelcomeBox>,
|
||||
next_contact: u32,
|
||||
#[serde(default = "yes")]
|
||||
receipts: bool,
|
||||
/// OpenMLS's storage: every key and value, sorted by key so equal states give equal bytes.
|
||||
storage: Vec<(Bytes, Bytes)>,
|
||||
}
|
||||
|
||||
impl<T: Transport> Client<T> {
|
||||
/// The whole state, to keep in the app's encrypted store. Secret: never log it, never send it.
|
||||
pub fn snapshot(&self) -> Result<Vec<u8>, ClientError> {
|
||||
let mut storage: Vec<(Bytes, Bytes)> = self
|
||||
.provider
|
||||
.storage()
|
||||
.values
|
||||
.read()
|
||||
.map_err(|_| ClientError::State)?
|
||||
.iter()
|
||||
.map(|(k, v)| (Bytes(k.clone()), Bytes(v.clone())))
|
||||
.collect();
|
||||
storage.sort();
|
||||
let state = State {
|
||||
v: SNAPSHOT_VERSION,
|
||||
name: self.name.clone(),
|
||||
identity: Bytes(self.identity.clone()),
|
||||
signer_public: Bytes(self.signer.to_public_vec()),
|
||||
contacts: self
|
||||
.contacts
|
||||
.iter()
|
||||
.map(|c| ContactState {
|
||||
id: c.id,
|
||||
group: Bytes(c.group.group_id().as_slice().to_vec()),
|
||||
name: c.name.clone(),
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
blocked: c.blocked,
|
||||
sent_seq: c.sent_seq,
|
||||
received_seq: c.received_seq,
|
||||
})
|
||||
.collect(),
|
||||
welcome_boxes: self.welcome_boxes.clone(),
|
||||
next_contact: self.next_contact,
|
||||
receipts: self.receipts,
|
||||
storage,
|
||||
};
|
||||
serde_json::to_vec(&state).map_err(|_| ClientError::State)
|
||||
}
|
||||
|
||||
/// A client from a snapshot. All or nothing: a snapshot that does not parse, has another
|
||||
/// version, or does not match its own storage is refused with [`ClientError::State`].
|
||||
pub fn restore(snapshot: &[u8], transport: T) -> Result<Self, ClientError> {
|
||||
let state: State = serde_json::from_slice(snapshot).map_err(|_| ClientError::State)?;
|
||||
if state.v != SNAPSHOT_VERSION || state.name.chars().count() > MAX_NAME_CHARS {
|
||||
return Err(ClientError::State);
|
||||
}
|
||||
let provider = OpenMlsRustCrypto::default();
|
||||
{
|
||||
let mut values = provider
|
||||
.storage()
|
||||
.values
|
||||
.write()
|
||||
.map_err(|_| ClientError::State)?;
|
||||
for (k, v) in state.storage {
|
||||
values.insert(k.0, v.0);
|
||||
}
|
||||
}
|
||||
let signer = SignatureKeyPair::read(
|
||||
provider.storage(),
|
||||
&state.signer_public.0,
|
||||
CIPHERSUITE.signature_algorithm(),
|
||||
)
|
||||
.ok_or(ClientError::State)?;
|
||||
let credential = credential_with_key(&state.identity.0, &signer);
|
||||
|
||||
let mut ids = HashSet::new();
|
||||
let mut contacts = Vec::with_capacity(state.contacts.len());
|
||||
for c in state.contacts {
|
||||
// Ids are unique and below the next one, or two contacts could end up sharing one.
|
||||
if c.id.0 >= state.next_contact || !ids.insert(c.id) {
|
||||
return Err(ClientError::State);
|
||||
}
|
||||
let group = MlsGroup::load(provider.storage(), &GroupId::from_slice(&c.group.0))
|
||||
.map_err(|_| ClientError::State)?
|
||||
.ok_or(ClientError::State)?;
|
||||
contacts.push(Contact {
|
||||
id: c.id,
|
||||
group,
|
||||
name: c.name,
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
blocked: c.blocked,
|
||||
sent_seq: c.sent_seq,
|
||||
received_seq: c.received_seq,
|
||||
});
|
||||
}
|
||||
Ok(Client {
|
||||
provider,
|
||||
signer,
|
||||
credential,
|
||||
identity: state.identity.0,
|
||||
name: state.name,
|
||||
transport,
|
||||
contacts,
|
||||
welcome_boxes: state.welcome_boxes,
|
||||
next_contact: state.next_contact,
|
||||
receipts: state.receipts,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bytes_round_trip_as_base64url() {
|
||||
let b = Bytes(vec![0, 1, 254, 255]);
|
||||
let json = serde_json::to_string(&b).expect("json");
|
||||
assert_eq!(json, "\"AAH-_w\"");
|
||||
let back: Bytes = serde_json::from_str(&json).expect("back");
|
||||
assert!(back == b);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! How the client reaches a relay. The library makes no network calls itself: an app gives it a
|
||||
//! [`Transport`] (HTTP in Amicitia, F22). [`MemoryTransport`] is a stand-in with the relay's rules,
|
||||
//! for tests and for running the client on a device without a relay.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tabellarius_protocol::{
|
||||
blob_hash, CreateInvite, CreateMailbox, InviteId, MailboxId, Sha256Hash, Token,
|
||||
};
|
||||
|
||||
/// Why the relay said no. Carries nothing of the request.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TransportError {
|
||||
/// 404: unknown, wrong token, expired, or already claimed.
|
||||
NotFound,
|
||||
/// 409: the id is taken.
|
||||
Conflict,
|
||||
/// Anything else: the network, a 5xx, a body that did not parse.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// The relay's operations (`PROTOCOL.md` §8), one method each.
|
||||
pub trait Transport {
|
||||
fn create_mailbox(&self, req: &CreateMailbox) -> Result<(), TransportError>;
|
||||
fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError>;
|
||||
/// The waiting blobs, oldest first.
|
||||
fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result<Vec<Vec<u8>>, TransportError>;
|
||||
fn acknowledge(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError>;
|
||||
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError>;
|
||||
/// Block: the mailbox's post token becomes `new_hash`'s; the old one is refused from now on.
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
new_hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError>;
|
||||
/// The KeyPackage, once.
|
||||
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError>;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Boxes {
|
||||
mailboxes: HashMap<MailboxId, (Sha256Hash, Sha256Hash, Vec<Vec<u8>>)>,
|
||||
invites: HashMap<InviteId, (Sha256Hash, Vec<u8>)>,
|
||||
}
|
||||
|
||||
/// An in-memory relay with the same rules as the real one (no expiry: there is no clock here).
|
||||
/// Clone it to give two clients the same relay.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct MemoryTransport(Arc<Mutex<Boxes>>);
|
||||
|
||||
impl MemoryTransport {
|
||||
fn boxes(&self) -> std::sync::MutexGuard<'_, Boxes> {
|
||||
self.0.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
/// How many blobs wait on the relay, in all mailboxes: what was not acknowledged.
|
||||
pub fn waiting_blobs(&self) -> usize {
|
||||
self.boxes()
|
||||
.mailboxes
|
||||
.values()
|
||||
.map(|(_, _, b)| b.len())
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Every byte the relay holds, for privacy tests: ids, hashes, blobs and KeyPackages.
|
||||
pub fn everything_stored(&self) -> Vec<u8> {
|
||||
let b = self.boxes();
|
||||
let mut out = Vec::new();
|
||||
for (id, (post, fetch, blobs)) in &b.mailboxes {
|
||||
out.extend_from_slice(id.as_bytes());
|
||||
out.extend_from_slice(post.as_bytes());
|
||||
out.extend_from_slice(fetch.as_bytes());
|
||||
blobs.iter().for_each(|blob| out.extend_from_slice(blob));
|
||||
}
|
||||
for (id, (hash, kp)) in &b.invites {
|
||||
out.extend_from_slice(id.as_bytes());
|
||||
out.extend_from_slice(hash.as_bytes());
|
||||
out.extend_from_slice(kp);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for MemoryTransport {
|
||||
fn create_mailbox(&self, req: &CreateMailbox) -> Result<(), TransportError> {
|
||||
let mut b = self.boxes();
|
||||
if b.mailboxes.contains_key(&req.id) {
|
||||
return Err(TransportError::Conflict);
|
||||
}
|
||||
b.mailboxes.insert(
|
||||
req.id,
|
||||
(req.post_token_hash, req.fetch_token_hash, Vec::new()),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError> {
|
||||
match self.boxes().mailboxes.get_mut(id) {
|
||||
Some((hash, _, blobs)) if *hash == post.hash() => {
|
||||
blobs.push(blob.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(TransportError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result<Vec<Vec<u8>>, TransportError> {
|
||||
match self.boxes().mailboxes.get(id) {
|
||||
Some((_, hash, blobs)) if *hash == fetch.hash() => Ok(blobs.clone()),
|
||||
_ => Err(TransportError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn acknowledge(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
match self.boxes().mailboxes.get_mut(id) {
|
||||
Some((_, f, blobs)) if *f == fetch.hash() => {
|
||||
let at = blobs
|
||||
.iter()
|
||||
.position(|b| blob_hash(b) == *hash)
|
||||
.ok_or(TransportError::NotFound)?;
|
||||
blobs.remove(at);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(TransportError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
new_hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
match self.boxes().mailboxes.get_mut(id) {
|
||||
Some((post, f, _)) if *f == fetch.hash() => {
|
||||
*post = *new_hash;
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(TransportError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> {
|
||||
let mut b = self.boxes();
|
||||
if b.invites.contains_key(&req.id) {
|
||||
return Err(TransportError::Conflict);
|
||||
}
|
||||
b.invites
|
||||
.insert(req.id, (req.secret_hash, req.key_package.bytes().to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError> {
|
||||
let mut b = self.boxes();
|
||||
match b.invites.get(id) {
|
||||
Some((hash, _)) if *hash == secret.hash() => b
|
||||
.invites
|
||||
.remove(id)
|
||||
.map(|(_, kp)| kp)
|
||||
.ok_or(TransportError::NotFound),
|
||||
_ => Err(TransportError::NotFound),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Block, unblock and receipts (`.agents/features/block-and-receipts.md` §3). No I/O: runs on the
|
||||
//! Android emulator too.
|
||||
|
||||
use tabellarius_client::*;
|
||||
|
||||
type C = Client<MemoryTransport>;
|
||||
|
||||
fn pair(relay: &MemoryTransport) -> (C, ContactId, C, ContactId) {
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
let Some(Event::Joined {
|
||||
contact: eva_side, ..
|
||||
}) = eva.poll().expect("poll").first().cloned()
|
||||
else {
|
||||
panic!("no join")
|
||||
};
|
||||
jan.poll().expect("poll");
|
||||
(eva, eva_side, jan, jan_side)
|
||||
}
|
||||
|
||||
fn texts(events: &[Event]) -> Vec<String> {
|
||||
events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::Message { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_contact_reaches_us_no_more_and_is_not_told() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
// Jan writes once before the block; it waits on the relay.
|
||||
jan.send(jan_side, "před blokem").expect("send");
|
||||
let waiting = relay.waiting_blobs();
|
||||
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
assert_eq!(
|
||||
relay.waiting_blobs(),
|
||||
waiting,
|
||||
"block posts nothing to anyone"
|
||||
);
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
assert!(eva.is_blocked(eva_side));
|
||||
|
||||
// Jan's next post is refused, the same 404 as any wrong token.
|
||||
assert_eq!(
|
||||
jan.send(jan_side, "po bloku"),
|
||||
Err(ClientError::Transport(TransportError::NotFound))
|
||||
);
|
||||
// What he posted before the block is fetched, dropped, never shown, and acknowledged.
|
||||
let events = eva.poll().expect("poll");
|
||||
assert!(texts(&events).is_empty(), "{events:?}");
|
||||
assert_eq!(relay.waiting_blobs(), 0);
|
||||
// Eva can still write to him: block closes her mailbox, not his. His receipt for it is
|
||||
// refused, and that does not stop his app from acknowledging what it fetched.
|
||||
assert!(jan.receipts());
|
||||
eva.send(eva_side, "jen já tobě").expect("send");
|
||||
assert_eq!(texts(&jan.poll().expect("poll")), ["jen já tobě"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_made_offline_waits_and_survives_a_restart() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
// Staged: nothing reached the relay, so Jan can still post until the rotate is delivered.
|
||||
jan.send(jan_side, "ještě to prošlo")
|
||||
.expect("not blocked on the relay yet");
|
||||
let saved = eva.snapshot().expect("snapshot");
|
||||
let kept = serde_json::to_vec(&rotate).expect("outbox");
|
||||
drop(eva); // the relay was away; the app closes
|
||||
|
||||
let eva = Client::restore(&saved, relay.clone()).expect("restore");
|
||||
assert!(eva.is_blocked(eva_side));
|
||||
let rotate: Outgoing = serde_json::from_slice(&kept).expect("outbox");
|
||||
assert_eq!(format!("{rotate:?}"), "Outgoing(rotate)");
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
eva.deliver(&rotate).expect("a second time changes nothing");
|
||||
assert!(jan.send(jan_side, "x").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unblocking_readdresses_what_waited_and_both_can_talk_again() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
// Jan's app keeps what it could not send in its outbox.
|
||||
let stuck = jan.compose(jan_side, "čekalo to").expect("compose");
|
||||
assert!(jan.deliver(&stuck).is_err());
|
||||
|
||||
for out in eva.unblock(eva_side).expect("unblock") {
|
||||
eva.deliver(&out).expect("deliver");
|
||||
}
|
||||
assert!(!eva.is_blocked(eva_side));
|
||||
jan.poll().expect("Jan receives the new token");
|
||||
// The old token is still refused; readdressed, the same sealed message goes through.
|
||||
assert!(jan.deliver(&stuck).is_err());
|
||||
jan.deliver(&jan.readdress(&stuck)).expect("readdressed");
|
||||
jan.send(jan_side, "a teď nová").expect("send");
|
||||
assert_eq!(
|
||||
texts(&eva.poll().expect("poll")),
|
||||
["čekalo to", "a teď nová"]
|
||||
);
|
||||
eva.send(eva_side, "vítej zpátky").expect("send");
|
||||
assert_eq!(texts(&jan.poll().expect("poll")), ["vítej zpátky"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipts_say_what_arrived_and_only_while_both_want_them() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
for t in ["jedna", "dvě", "tři"] {
|
||||
eva.send(eva_side, t).expect("send");
|
||||
}
|
||||
assert_eq!(eva.sent_seq(eva_side), Some(3));
|
||||
assert_eq!(texts(&jan.poll().expect("poll")).len(), 3);
|
||||
assert!(eva.poll().expect("poll").contains(&Event::Delivered {
|
||||
contact: eva_side,
|
||||
upto: 3
|
||||
}));
|
||||
|
||||
// Jan turns them off: he sends none.
|
||||
jan.set_receipts(false);
|
||||
eva.send(eva_side, "čtyři").expect("send");
|
||||
jan.poll().expect("poll");
|
||||
assert!(!eva
|
||||
.poll()
|
||||
.expect("poll")
|
||||
.iter()
|
||||
.any(|e| matches!(e, Event::Delivered { .. })));
|
||||
|
||||
// Eva turns them off: Jan's are ignored (reciprocal).
|
||||
jan.set_receipts(true);
|
||||
eva.set_receipts(false);
|
||||
eva.send(eva_side, "pět").expect("send");
|
||||
jan.poll().expect("poll");
|
||||
assert!(!eva
|
||||
.poll()
|
||||
.expect("poll")
|
||||
.iter()
|
||||
.any(|e| matches!(e, Event::Delivered { .. })));
|
||||
// And she sends none for Jan's.
|
||||
jan.send(jan_side, "ahoj").expect("send");
|
||||
eva.poll().expect("poll");
|
||||
assert!(!jan
|
||||
.poll()
|
||||
.expect("poll")
|
||||
.iter()
|
||||
.any(|e| matches!(e, Event::Delivered { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_contact_gets_no_receipt() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
jan.send(jan_side, "x").expect("send");
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
eva.poll().expect("poll");
|
||||
assert!(!jan
|
||||
.poll()
|
||||
.expect("poll")
|
||||
.iter()
|
||||
.any(|e| matches!(e, Event::Delivered { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipts_are_kept_across_a_restart_and_default_to_on() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, _jan, _) = pair(&relay);
|
||||
assert!(eva.receipts());
|
||||
eva.set_receipts(false);
|
||||
eva.send(eva_side, "x").expect("send");
|
||||
let saved = eva.snapshot().expect("snapshot");
|
||||
let eva = Client::restore(&saved, relay.clone()).expect("restore");
|
||||
assert!(!eva.receipts());
|
||||
assert_eq!(eva.sent_seq(eva_side), Some(1));
|
||||
|
||||
// A snapshot from before F24 has none of the new fields: it restores, receipts on.
|
||||
let mut old: serde_json::Value = serde_json::from_slice(&saved).expect("json");
|
||||
old.as_object_mut().expect("object").remove("receipts");
|
||||
for c in old["contacts"].as_array_mut().expect("contacts") {
|
||||
let c = c.as_object_mut().expect("contact");
|
||||
for f in ["blocked", "sentSeq", "receivedSeq"] {
|
||||
c.remove(f);
|
||||
}
|
||||
}
|
||||
let old = serde_json::to_vec(&old).expect("json");
|
||||
let eva = Client::restore(&old, relay.clone()).expect("an old snapshot");
|
||||
assert!(eva.receipts());
|
||||
assert!(!eva.is_blocked(eva_side));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_receipt_does_not_keep_the_blocked_side_from_acknowledging() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay);
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
eva.send(eva_side, "jedna").expect("send");
|
||||
eva.send(eva_side, "dvě").expect("send");
|
||||
assert_eq!(texts(&jan.poll().expect("poll")), ["jedna", "dvě"]);
|
||||
assert_eq!(
|
||||
relay.waiting_blobs(),
|
||||
0,
|
||||
"acknowledged, the refused receipt skipped"
|
||||
);
|
||||
assert!(jan.poll().expect("poll").is_empty());
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Pairing and talking through an in-memory relay. These tests have no I/O, so the same binary runs
|
||||
//! on an Android emulator (`.agents/features/client.md` §5).
|
||||
|
||||
use tabellarius_client::*;
|
||||
use tabellarius_protocol::Token;
|
||||
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
/// Eva invites, Jan accepts; both polls exchange the hellos.
|
||||
fn pair(
|
||||
relay: &MemoryTransport,
|
||||
) -> (
|
||||
Client<MemoryTransport>,
|
||||
ContactId,
|
||||
Client<MemoryTransport>,
|
||||
ContactId,
|
||||
) {
|
||||
let mut eva = Client::new("Eva Nováková", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
// Receipts (F24) have their own tests; here they would only add events and blobs.
|
||||
eva.set_receipts(false);
|
||||
jan.set_receipts(false);
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
let eva_events = eva.poll().expect("eva polls");
|
||||
let Some(Event::Joined {
|
||||
contact: eva_side,
|
||||
name,
|
||||
..
|
||||
}) = eva_events.first().cloned()
|
||||
else {
|
||||
panic!("Eva did not see Jan join: {eva_events:?}");
|
||||
};
|
||||
assert_eq!(name, "Jan");
|
||||
let jan_events = jan.poll().expect("jan polls");
|
||||
assert_eq!(
|
||||
jan_events,
|
||||
vec![Event::Joined {
|
||||
contact: jan_side,
|
||||
name: "Eva Nováková".into(),
|
||||
via: None,
|
||||
}]
|
||||
);
|
||||
(eva, eva_side, jan, jan_side)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_people_pair_through_an_invite_and_talk_both_ways() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
|
||||
eva.send(eva_side, "Ahoj Jane, pivo ve čtvrtek?")
|
||||
.expect("send");
|
||||
eva.send(eva_side, "V sedm.").expect("send");
|
||||
assert_eq!(
|
||||
jan.poll().expect("poll"),
|
||||
vec![
|
||||
Event::Message {
|
||||
contact: jan_side,
|
||||
text: "Ahoj Jane, pivo ve čtvrtek?".into()
|
||||
},
|
||||
Event::Message {
|
||||
contact: jan_side,
|
||||
text: "V sedm.".into()
|
||||
},
|
||||
]
|
||||
);
|
||||
jan.send(jan_side, "Platí 🍺").expect("send");
|
||||
assert_eq!(
|
||||
eva.poll().expect("poll"),
|
||||
vec![Event::Message {
|
||||
contact: eva_side,
|
||||
text: "Platí 🍺".into()
|
||||
}]
|
||||
);
|
||||
// Everything delivered was acknowledged: nothing waits on the relay, and a second poll is
|
||||
// empty on both sides.
|
||||
assert_eq!(relay.waiting_blobs(), 0);
|
||||
assert!(eva.poll().expect("poll").is_empty());
|
||||
assert!(jan.poll().expect("poll").is_empty());
|
||||
assert_eq!(eva.contact_name(eva_side), Some("Jan"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_relay_holds_no_name_and_no_word() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
let canary = "CANARY-7f3a91-the-relay-must-never-see-this";
|
||||
eva.send(eva_side, canary).expect("send");
|
||||
jan.send(jan_side, canary).expect("send");
|
||||
// Before anyone fetches: the canaries are waiting on the relay, encrypted.
|
||||
let stored = relay.everything_stored();
|
||||
assert!(!stored.is_empty());
|
||||
for (what, needle) in [
|
||||
("canary", canary.as_bytes()),
|
||||
("inviter's name", "Eva Nováková".as_bytes()),
|
||||
("invitee's name", b"Jan".as_slice()),
|
||||
] {
|
||||
assert!(
|
||||
!contains(&stored, needle),
|
||||
"{what} is readable on the relay"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_works_once() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let mut mallory = Client::new("Mallory", relay.clone()).expect("mallory");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("first");
|
||||
assert_eq!(
|
||||
mallory.accept_invite(&invite),
|
||||
Err(ClientError::Transport(TransportError::NotFound))
|
||||
);
|
||||
let joined: Vec<_> = eva.poll().expect("poll");
|
||||
assert_eq!(joined.len(), 1, "exactly one person joined: {joined:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_secret_claims_nothing() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let mut invite = eva.create_invite().expect("invite");
|
||||
invite.secret = Token::from_bytes([7; 32]);
|
||||
assert!(jan.accept_invite(&invite).is_err());
|
||||
assert!(eva.poll().expect("poll").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_in_a_mailbox_is_dropped_and_never_shown() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
// Whoever holds the link can post to Eva's welcome mailbox: before, between and after the
|
||||
// real Welcome and hello, bytes that are not MLS.
|
||||
let (welcome_box, welcome_post) = welcome_mailbox(&invite.secret);
|
||||
relay
|
||||
.post(&welcome_box, &welcome_post, b"not MLS at all")
|
||||
.expect("post");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
relay
|
||||
.post(&welcome_box, &welcome_post, &[0x00, 0x01, 0x00, 0x05])
|
||||
.expect("post");
|
||||
let events = eva.poll().expect("poll");
|
||||
assert_eq!(events.len(), 1, "only the join is shown: {events:?}");
|
||||
assert!(matches!(events[0], Event::Joined { .. }));
|
||||
assert_eq!(
|
||||
relay.waiting_blobs(),
|
||||
1,
|
||||
"junk acknowledged too; only Eva's hello to Jan waits"
|
||||
);
|
||||
jan.poll().expect("poll");
|
||||
jan.send(jan_side, "still here").expect("send");
|
||||
let Event::Joined {
|
||||
contact: eva_side, ..
|
||||
} = events[0].clone()
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(
|
||||
eva.poll().expect("poll"),
|
||||
vec![Event::Message {
|
||||
contact: eva_side,
|
||||
text: "still here".into()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_before_a_hello_is_not_shown() {
|
||||
// A Welcome alone makes a group, not a contact: nothing is shown until the hello arrives.
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
assert_eq!(
|
||||
jan.send(jan_side, "too early"),
|
||||
Err(ClientError::UnknownContact)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_are_kept() {
|
||||
let relay = MemoryTransport::default();
|
||||
assert!(Client::new(&"x".repeat(MAX_NAME_CHARS + 1), relay.clone()).is_err());
|
||||
let (mut eva, eva_side, _jan, _) = pair(&relay);
|
||||
assert_eq!(
|
||||
eva.send(eva_side, &"x".repeat(MAX_TEXT_BYTES + 1)),
|
||||
Err(ClientError::TooLong)
|
||||
);
|
||||
assert_eq!(
|
||||
eva.send(ContactId(99), "hi"),
|
||||
Err(ClientError::UnknownContact)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_welcome_mailbox_derivation_is_fixed() {
|
||||
// A pinned vector: changing labels or the KDF breaks pairing between versions, so it must be
|
||||
// a deliberate protocol change, not an accident.
|
||||
let (id, post) = welcome_mailbox(&Token::from_bytes([0; 32]));
|
||||
let (id2, post2) = welcome_mailbox(&Token::from_bytes([0; 32]));
|
||||
assert_eq!((id, post.to_wire()), (id2, post2.to_wire()));
|
||||
assert_ne!(
|
||||
id.as_bytes()[..],
|
||||
post.as_bytes()[..16],
|
||||
"id and post token are independent"
|
||||
);
|
||||
assert_eq!(id.to_wire(), WELCOME_ID_VECTOR);
|
||||
assert_eq!(post.to_wire(), WELCOME_POST_VECTOR);
|
||||
}
|
||||
|
||||
// Computed independently: HKDF-SHA256 (RFC 5869, empty salt) written out with Python's hmac module.
|
||||
const WELCOME_ID_VECTOR: &str = "tsx3c7bagkEGmf1aDem6SA";
|
||||
const WELCOME_POST_VECTOR: &str = "FE6Xgv4j9CYnZA1EF_l4UaCNkxrZrfXmkNXnwm9K02w";
|
||||
@@ -0,0 +1,224 @@
|
||||
//! Two clients through the real relay over loopback TCP, then a byte search of the relay's
|
||||
//! database file: the canary in a message, and both names, must not be in it (`PROTOCOL.md` §7).
|
||||
//! The relay is a dev-dependency only; the client library never depends on it.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::sync::Arc;
|
||||
use tabellarius_client::*;
|
||||
use tabellarius_protocol::*;
|
||||
use tabellarius_relay::http::{router, AppState, Clock};
|
||||
use tabellarius_relay::store::Store;
|
||||
|
||||
/// A deliberately small blocking HTTP/1.1 transport for the test: one connection per request.
|
||||
#[derive(Clone)]
|
||||
struct Http(SocketAddr);
|
||||
|
||||
impl Http {
|
||||
fn call(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
auth: Option<&Token>,
|
||||
body: &[u8],
|
||||
json: bool,
|
||||
) -> Result<Vec<u8>, TransportError> {
|
||||
let mut s = TcpStream::connect(self.0).map_err(|_| TransportError::Failed)?;
|
||||
let auth = auth
|
||||
.map(|t| format!("Authorization: {}\r\n", t.to_bearer()))
|
||||
.unwrap_or_default();
|
||||
let ctype = if json {
|
||||
"Content-Type: application/json\r\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let head = format!(
|
||||
"{method} {path} HTTP/1.1\r\nHost: relay\r\n{auth}{ctype}Content-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
);
|
||||
s.write_all(head.as_bytes())
|
||||
.map_err(|_| TransportError::Failed)?;
|
||||
s.write_all(body).map_err(|_| TransportError::Failed)?;
|
||||
let mut resp = Vec::new();
|
||||
s.read_to_end(&mut resp)
|
||||
.map_err(|_| TransportError::Failed)?;
|
||||
let split = resp
|
||||
.windows(4)
|
||||
.position(|w| w == b"\r\n\r\n")
|
||||
.ok_or(TransportError::Failed)?;
|
||||
let status = std::str::from_utf8(&resp[9..12]).map_err(|_| TransportError::Failed)?;
|
||||
match status {
|
||||
"200" | "201" | "204" => Ok(resp[split + 4..].to_vec()),
|
||||
"404" => Err(TransportError::NotFound),
|
||||
"409" => Err(TransportError::Conflict),
|
||||
_ => Err(TransportError::Failed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Http {
|
||||
fn create_mailbox(&self, req: &CreateMailbox) -> Result<(), TransportError> {
|
||||
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
|
||||
self.call("POST", "/v0/mailboxes", None, &body, true)
|
||||
.map(|_| ())
|
||||
}
|
||||
fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError> {
|
||||
self.call(
|
||||
"POST",
|
||||
&format!("/v0/mailboxes/{}/blobs", id.to_wire()),
|
||||
Some(post),
|
||||
blob,
|
||||
false,
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result<Vec<Vec<u8>>, TransportError> {
|
||||
let body = self.call(
|
||||
"GET",
|
||||
&format!("/v0/mailboxes/{}/blobs", id.to_wire()),
|
||||
Some(fetch),
|
||||
&[],
|
||||
false,
|
||||
)?;
|
||||
let blobs: FetchedBlobs =
|
||||
serde_json::from_slice(&body).map_err(|_| TransportError::Failed)?;
|
||||
Ok(blobs
|
||||
.blobs
|
||||
.into_iter()
|
||||
.map(|b| b.blob.bytes().to_vec())
|
||||
.collect())
|
||||
}
|
||||
fn acknowledge(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
let path = format!("/v0/mailboxes/{}/blobs/{}", id.to_wire(), hash.to_wire());
|
||||
self.call("DELETE", &path, Some(fetch), &[], false)
|
||||
.map(|_| ())
|
||||
}
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
new_hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
let body = serde_json::to_vec(&RotatePostToken {
|
||||
post_token_hash: *new_hash,
|
||||
})
|
||||
.map_err(|_| TransportError::Failed)?;
|
||||
let path = format!("/v0/mailboxes/{}/post-token", id.to_wire());
|
||||
self.call("PUT", &path, Some(fetch), &body, true)
|
||||
.map(|_| ())
|
||||
}
|
||||
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> {
|
||||
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
|
||||
self.call("POST", "/v0/invites", None, &body, true)
|
||||
.map(|_| ())
|
||||
}
|
||||
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError> {
|
||||
let body = self.call(
|
||||
"GET",
|
||||
&format!("/v0/invites/{}", id.to_wire()),
|
||||
Some(secret),
|
||||
&[],
|
||||
false,
|
||||
)?;
|
||||
let claimed: ClaimedInvite =
|
||||
serde_json::from_slice(&body).map_err(|_| TransportError::Failed)?;
|
||||
Ok(claimed.key_package.bytes().to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the real relay on 127.0.0.1:<free port> with its database in `db`.
|
||||
fn start_relay(db: &std::path::Path) -> SocketAddr {
|
||||
let store = Arc::new(Store::open(db).expect("store"));
|
||||
let clock: Clock = Arc::new(|| 1_794_000_000);
|
||||
let app = router(AppState { store, clock });
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("runtime");
|
||||
rt.block_on(async move {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind");
|
||||
tx.send(listener.local_addr().expect("addr"))
|
||||
.expect("send addr");
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
});
|
||||
rx.recv().expect("relay address")
|
||||
}
|
||||
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let db = dir.path().join("relay.db");
|
||||
let relay = Http(start_relay(&db));
|
||||
|
||||
let mut eva = Client::new("Eva Nováková", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan Dvořák", relay.clone()).expect("jan");
|
||||
eva.set_receipts(false);
|
||||
jan.set_receipts(false);
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
// While the invite waits, the relay holds Eva's KeyPackage: it must not carry her name.
|
||||
let invited = std::fs::read(&db).expect("db");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
let events = eva.poll().expect("poll");
|
||||
let Some(Event::Joined {
|
||||
contact: eva_side,
|
||||
name,
|
||||
..
|
||||
}) = events.first().cloned()
|
||||
else {
|
||||
panic!("no join: {events:?}");
|
||||
};
|
||||
assert_eq!(name, "Jan Dvořák");
|
||||
assert_eq!(jan.poll().expect("poll").len(), 1);
|
||||
|
||||
let canary = "CANARY-relay-test-4b2e-never-in-the-database";
|
||||
eva.send(eva_side, canary).expect("send");
|
||||
jan.send(jan_side, &format!("re: {canary}")).expect("send");
|
||||
|
||||
// Snapshot the database while both messages wait, before anyone fetches.
|
||||
let waiting = std::fs::read(&db).expect("db");
|
||||
assert_eq!(
|
||||
jan.poll().expect("poll"),
|
||||
vec![Event::Message {
|
||||
contact: jan_side,
|
||||
text: canary.into()
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
eva.poll().expect("poll"),
|
||||
vec![Event::Message {
|
||||
contact: eva_side,
|
||||
text: format!("re: {canary}")
|
||||
}]
|
||||
);
|
||||
let after = std::fs::read(&db).expect("db");
|
||||
|
||||
for snapshot in [&invited, &waiting, &after] {
|
||||
for (what, needle) in [
|
||||
("canary", canary.as_bytes()),
|
||||
("inviter's name", "Eva Nováková".as_bytes()),
|
||||
("invitee's name", "Jan Dvořák".as_bytes()),
|
||||
("invite secret", invite.secret.as_bytes().as_slice()),
|
||||
] {
|
||||
assert!(
|
||||
!contains(snapshot, needle),
|
||||
"{what} is readable in the relay's database"
|
||||
);
|
||||
}
|
||||
}
|
||||
// The messages were there, as ciphertext: the database grew while they waited.
|
||||
assert!(waiting.len() >= 4096, "the relay stored something");
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
//! The client survives a restart, and nothing reaches the relay before the app has saved
|
||||
//! (`.agents/features/client-state.md` §3). No I/O: runs on the Android emulator too.
|
||||
|
||||
use tabellarius_client::*;
|
||||
|
||||
type C = Client<MemoryTransport>;
|
||||
|
||||
/// Receipts off: these tests count events and waiting blobs, and receipts (F24) have their own.
|
||||
fn quiet<T: Transport>(mut c: Client<T>) -> Client<T> {
|
||||
c.set_receipts(false);
|
||||
c
|
||||
}
|
||||
|
||||
/// Pairs Eva (inviter) and Jan through the staged calls, saving nothing. Returns both sides' ids.
|
||||
fn pair(relay: &MemoryTransport) -> (C, ContactId, C, ContactId) {
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
let events = eva.poll().expect("poll");
|
||||
let Some(Event::Joined {
|
||||
contact: eva_side,
|
||||
via,
|
||||
..
|
||||
}) = events.first().cloned()
|
||||
else {
|
||||
panic!("no join: {events:?}");
|
||||
};
|
||||
assert_eq!(
|
||||
via,
|
||||
Some(invite.id),
|
||||
"the inviter learns which invite was used"
|
||||
);
|
||||
assert_eq!(jan.poll().expect("poll").len(), 1);
|
||||
(eva, eva_side, jan, jan_side)
|
||||
}
|
||||
|
||||
fn restart(client: &C, relay: &MemoryTransport) -> C {
|
||||
let saved = client.snapshot().expect("snapshot");
|
||||
Client::restore(&saved, relay.clone()).expect("restore")
|
||||
}
|
||||
|
||||
fn texts(events: Vec<Event>) -> Vec<String> {
|
||||
events
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::Message { text, .. } => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_sides_restart_mid_conversation_and_keep_talking() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
eva.send(eva_side, "před restartem").expect("send");
|
||||
assert_eq!(texts(jan.poll().expect("poll")), ["před restartem"]);
|
||||
|
||||
let mut eva = restart(&eva, &relay);
|
||||
let mut jan = restart(&jan, &relay);
|
||||
assert_eq!(eva.contact_name(eva_side), Some("Jan"));
|
||||
eva.send(eva_side, "po restartu").expect("send");
|
||||
jan.send(jan_side, "taky po restartu").expect("send");
|
||||
assert_eq!(texts(jan.poll().expect("poll")), ["po restartu"]);
|
||||
assert_eq!(texts(eva.poll().expect("poll")), ["taky po restartu"]);
|
||||
assert_eq!(relay.waiting_blobs(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invite_waiting_survives_a_restart() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let mut eva = restart(&eva, &relay);
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
let events = eva.poll().expect("poll");
|
||||
assert!(
|
||||
matches!(&events[..], [Event::Joined { name, via, .. }] if name == "Jan" && *via == Some(invite.id)),
|
||||
"{events:?}"
|
||||
);
|
||||
jan.poll().expect("poll");
|
||||
jan.send(jan_side, "ahoj").expect("send");
|
||||
assert_eq!(texts(eva.poll().expect("poll")), ["ahoj"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_client_gives_a_new_contact_a_new_id() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (eva, eva_side, _jan, _) = pair(&relay);
|
||||
let mut eva = restart(&eva, &relay);
|
||||
let mut petr = quiet(Client::new("Petr", relay.clone()).expect("petr"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
petr.accept_invite(&invite).expect("accept");
|
||||
let events = eva.poll().expect("poll");
|
||||
let Some(Event::Joined { contact, .. }) = events.first() else {
|
||||
panic!("no join: {events:?}");
|
||||
};
|
||||
assert_ne!(*contact, eva_side);
|
||||
assert_eq!(eva.contact_name(eva_side), Some("Jan"));
|
||||
assert_eq!(eva.contact_name(*contact), Some("Petr"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_staged_calls_post_nothing_and_acknowledge_nothing() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
|
||||
let (jan_side, out) = jan.accept(&invite).expect("accept");
|
||||
assert_eq!(out.len(), 2, "the Welcome and the hello");
|
||||
assert_eq!(relay.waiting_blobs(), 0, "accept posts nothing");
|
||||
out.iter().for_each(|o| jan.deliver(o).expect("deliver"));
|
||||
assert_eq!(relay.waiting_blobs(), 2);
|
||||
|
||||
let got = eva.receive().expect("receive");
|
||||
assert_eq!(got.events.len(), 1);
|
||||
assert_eq!(got.outgoing.len(), 1, "Eva's answering hello");
|
||||
assert_eq!(
|
||||
relay.waiting_blobs(),
|
||||
2,
|
||||
"receive acknowledges nothing and posts nothing"
|
||||
);
|
||||
eva.finish(&got).expect("finish");
|
||||
assert_eq!(
|
||||
relay.waiting_blobs(),
|
||||
1,
|
||||
"Welcome and hello acknowledged; Eva's hello waits"
|
||||
);
|
||||
|
||||
jan.poll().expect("poll");
|
||||
let text = jan.compose(jan_side, "ještě neodesláno").expect("compose");
|
||||
assert_eq!(relay.waiting_blobs(), 0, "compose posts nothing");
|
||||
jan.deliver(&text).expect("deliver");
|
||||
assert_eq!(relay.waiting_blobs(), 1);
|
||||
}
|
||||
|
||||
/// The inviter answers a `hello` inside `receive`. Crash after saving, before `finish`: the saved
|
||||
/// answer is delivered from the outbox, the same blobs are fetched again and dropped, and the pair
|
||||
/// works with nothing shown twice.
|
||||
#[test]
|
||||
fn a_crash_between_receive_and_finish_loses_nothing_and_shows_nothing_twice() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
// Jan cannot write before Eva's hello gives him her mailbox.
|
||||
assert_eq!(jan.send(jan_side, "x"), Err(ClientError::UnknownContact));
|
||||
|
||||
let got = eva.receive().expect("receive");
|
||||
assert_eq!(got.events.len(), 1);
|
||||
let saved = eva.snapshot().expect("snapshot");
|
||||
let outbox = got.outgoing.clone();
|
||||
drop(eva); // the crash: finish never ran
|
||||
|
||||
let mut eva = Client::restore(&saved, relay.clone()).expect("restore");
|
||||
outbox.iter().for_each(|o| eva.deliver(o).expect("deliver"));
|
||||
let again = eva.poll().expect("poll again");
|
||||
assert!(
|
||||
again.is_empty(),
|
||||
"the Welcome and hello are not shown twice: {again:?}"
|
||||
);
|
||||
assert_eq!(relay.waiting_blobs(), 1, "only Eva's hello to Jan waits");
|
||||
|
||||
assert_eq!(jan.poll().expect("poll").len(), 1, "Jan sees Eva join");
|
||||
jan.send(jan_side, "funguje to").expect("send");
|
||||
let Event::Joined { contact, .. } = got.events[0].clone() else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(
|
||||
eva.poll().expect("poll"),
|
||||
[Event::Message {
|
||||
contact,
|
||||
text: "funguje to".into()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blob_delivered_twice_is_shown_once() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay);
|
||||
let out = eva.compose(eva_side, "jednou").expect("compose");
|
||||
eva.deliver(&out).expect("deliver");
|
||||
eva.deliver(&out).expect("deliver again, after a crash");
|
||||
assert_eq!(texts(jan.poll().expect("poll")), ["jednou"]);
|
||||
assert_eq!(relay.waiting_blobs(), 0, "the copy is acknowledged too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_outgoing_survives_the_outbox() {
|
||||
// An app keeps undelivered blobs in its outbox as JSON; Debug shows no token and no bytes.
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay);
|
||||
let out = eva.compose(eva_side, "z outboxu").expect("compose");
|
||||
let kept = serde_json::to_vec(&out).expect("json");
|
||||
let back: Outgoing = serde_json::from_slice(&kept).expect("back");
|
||||
assert_eq!(back, out);
|
||||
assert!(format!("{back:?}").starts_with("Outgoing("));
|
||||
eva.deliver(&back).expect("deliver");
|
||||
assert_eq!(texts(jan.poll().expect("poll")), ["z outboxu"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_snapshot_is_refused() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (eva, _, _jan, _) = pair(&relay);
|
||||
let good = eva.snapshot().expect("snapshot");
|
||||
let mut json: serde_json::Value = serde_json::from_slice(&good).expect("json");
|
||||
|
||||
let refused =
|
||||
|bytes: &[u8]| matches!(C::restore(bytes, relay.clone()), Err(ClientError::State));
|
||||
assert!(refused(&good[..good.len() / 2]), "truncated");
|
||||
assert!(refused(b"{}"), "empty");
|
||||
|
||||
let mut other = json.clone();
|
||||
other["v"] = 2.into();
|
||||
assert!(
|
||||
refused(&serde_json::to_vec(&other).expect("json")),
|
||||
"another version"
|
||||
);
|
||||
|
||||
let mut no_storage = json.clone();
|
||||
no_storage["storage"] = serde_json::json!([]);
|
||||
assert!(
|
||||
refused(&serde_json::to_vec(&no_storage).expect("json")),
|
||||
"storage missing"
|
||||
);
|
||||
|
||||
let mut wrong_group = json.clone();
|
||||
wrong_group["contacts"][0]["group"] = "AAAA".into();
|
||||
assert!(
|
||||
refused(&serde_json::to_vec(&wrong_group).expect("json")),
|
||||
"group missing"
|
||||
);
|
||||
|
||||
let mut id_too_high = json.clone();
|
||||
id_too_high["nextContact"] = 0.into();
|
||||
assert!(
|
||||
refused(&serde_json::to_vec(&id_too_high).expect("json")),
|
||||
"ids would repeat"
|
||||
);
|
||||
|
||||
json["unexpected"] = true.into();
|
||||
assert!(
|
||||
refused(&serde_json::to_vec(&json).expect("json")),
|
||||
"unknown field"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_states_give_equal_snapshots() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (eva, _, _jan, _) = pair(&relay);
|
||||
let once = eva.snapshot().expect("snapshot");
|
||||
let restored = Client::restore(&once, relay.clone()).expect("restore");
|
||||
assert_eq!(restored.snapshot().expect("snapshot"), once);
|
||||
}
|
||||
|
||||
/// A relay that can be told to fail: posts, or every fetch after the first `n`.
|
||||
#[derive(Clone, Default)]
|
||||
struct Flaky {
|
||||
inner: MemoryTransport,
|
||||
fail_posts: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
fetches_left: std::sync::Arc<std::sync::atomic::AtomicI32>,
|
||||
}
|
||||
|
||||
impl Flaky {
|
||||
fn new(inner: &MemoryTransport) -> Flaky {
|
||||
let f = Flaky {
|
||||
inner: inner.clone(),
|
||||
..Flaky::default()
|
||||
};
|
||||
f.fetches_left
|
||||
.store(i32::MAX, std::sync::atomic::Ordering::SeqCst);
|
||||
f
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Flaky {
|
||||
fn create_mailbox(
|
||||
&self,
|
||||
r: &tabellarius_protocol::CreateMailbox,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.create_mailbox(r)
|
||||
}
|
||||
fn post(
|
||||
&self,
|
||||
id: &tabellarius_protocol::MailboxId,
|
||||
post: &tabellarius_protocol::Token,
|
||||
blob: &[u8],
|
||||
) -> Result<(), TransportError> {
|
||||
if self.fail_posts.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
return Err(TransportError::Failed);
|
||||
}
|
||||
self.inner.post(id, post, blob)
|
||||
}
|
||||
fn fetch(
|
||||
&self,
|
||||
id: &tabellarius_protocol::MailboxId,
|
||||
fetch: &tabellarius_protocol::Token,
|
||||
) -> Result<Vec<Vec<u8>>, TransportError> {
|
||||
if self
|
||||
.fetches_left
|
||||
.fetch_sub(1, std::sync::atomic::Ordering::SeqCst)
|
||||
<= 0
|
||||
{
|
||||
return Err(TransportError::Failed);
|
||||
}
|
||||
self.inner.fetch(id, fetch)
|
||||
}
|
||||
fn acknowledge(
|
||||
&self,
|
||||
id: &tabellarius_protocol::MailboxId,
|
||||
fetch: &tabellarius_protocol::Token,
|
||||
hash: &tabellarius_protocol::Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.acknowledge(id, fetch, hash)
|
||||
}
|
||||
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
|
||||
self.inner.create_invite(r)
|
||||
}
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &tabellarius_protocol::MailboxId,
|
||||
fetch: &tabellarius_protocol::Token,
|
||||
new_hash: &tabellarius_protocol::Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.rotate_post_token(id, fetch, new_hash)
|
||||
}
|
||||
fn claim_invite(
|
||||
&self,
|
||||
id: &tabellarius_protocol::InviteId,
|
||||
secret: &tabellarius_protocol::Token,
|
||||
) -> Result<Vec<u8>, TransportError> {
|
||||
self.inner.claim_invite(id, secret)
|
||||
}
|
||||
}
|
||||
|
||||
/// Without an outbox (`poll`), the answering hello must be delivered before anything is
|
||||
/// acknowledged: if delivering fails, the blobs stay on the relay and the next try answers again.
|
||||
#[test]
|
||||
fn finish_acknowledges_nothing_when_delivering_fails() {
|
||||
let relay = MemoryTransport::default();
|
||||
let flaky = Flaky::new(&relay);
|
||||
let mut eva = quiet(Client::new("Eva", flaky.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
|
||||
let got = eva.receive().expect("receive");
|
||||
flaky
|
||||
.fail_posts
|
||||
.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
assert!(eva.finish(&got).is_err());
|
||||
assert_eq!(relay.waiting_blobs(), 2, "nothing acknowledged");
|
||||
flaky
|
||||
.fail_posts
|
||||
.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
eva.finish(&got).expect("finish, again");
|
||||
assert_eq!(
|
||||
relay.waiting_blobs(),
|
||||
1,
|
||||
"now acknowledged; Eva's hello waits"
|
||||
);
|
||||
assert_eq!(jan.poll().expect("poll").len(), 1);
|
||||
jan.send(jan_side, "ok").expect("send");
|
||||
assert_eq!(texts(eva.poll().expect("poll")), ["ok"]);
|
||||
}
|
||||
|
||||
/// The relay fails after the first mailbox: what was processed comes back, the rest waits.
|
||||
#[test]
|
||||
fn a_relay_failing_part_way_returns_what_was_processed() {
|
||||
let relay = MemoryTransport::default();
|
||||
let flaky = Flaky::new(&relay);
|
||||
let mut eva = quiet(Client::new("Eva", flaky.clone()).expect("eva"));
|
||||
let mut friends = Vec::new();
|
||||
for name in ["Jan", "Petr"] {
|
||||
let mut friend = quiet(Client::new(name, relay.clone()).expect("friend"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let side = friend.accept_invite(&invite).expect("accept");
|
||||
friends.push((friend, side));
|
||||
}
|
||||
assert_eq!(eva.poll().expect("poll").len(), 2);
|
||||
for (friend, side) in &mut friends {
|
||||
friend.poll().expect("poll");
|
||||
friend.send(*side, "zpráva").expect("send");
|
||||
}
|
||||
flaky
|
||||
.fetches_left
|
||||
.store(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let got = eva.receive().expect("partial, not an error");
|
||||
assert_eq!(texts(got.events.clone()), ["zpráva"]);
|
||||
assert_eq!(got.interrupted, Some(TransportError::Failed));
|
||||
eva.finish(&got).expect("finish");
|
||||
flaky
|
||||
.fetches_left
|
||||
.store(i32::MAX, std::sync::atomic::Ordering::SeqCst);
|
||||
assert_eq!(
|
||||
texts(eva.poll().expect("poll")),
|
||||
["zpráva"],
|
||||
"the other one, now"
|
||||
);
|
||||
assert_eq!(relay.waiting_blobs(), 0);
|
||||
}
|
||||
|
||||
/// Once its contact has said hello, a welcome mailbox is no longer fetched: whoever still holds the
|
||||
/// link can post to it, but it is never read again (it expires on the relay).
|
||||
#[test]
|
||||
fn a_used_welcome_mailbox_is_no_longer_fetched() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
jan.poll().expect("poll");
|
||||
let (welcome, post) = welcome_mailbox(&invite.secret);
|
||||
relay.post(&welcome, &post, b"later junk").expect("post");
|
||||
let mut eva = restart(&eva, &relay);
|
||||
assert!(eva.poll().expect("poll").is_empty());
|
||||
assert_eq!(relay.waiting_blobs(), 1, "the junk was never fetched");
|
||||
}
|
||||
|
||||
/// A forgotten invite's mailbox is no longer fetched, even if someone uses the link afterwards.
|
||||
#[test]
|
||||
fn a_forgotten_invite_is_no_longer_fetched() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
eva.forget_invite(&invite.id);
|
||||
let mut eva = restart(&eva, &relay);
|
||||
jan.accept_invite(&invite).expect("the relay still has it");
|
||||
assert!(eva.poll().expect("poll").is_empty());
|
||||
assert_eq!(
|
||||
relay.waiting_blobs(),
|
||||
2,
|
||||
"the Welcome and hello wait, never fetched"
|
||||
);
|
||||
}
|
||||
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
/// Forgetting a contact leaves no name in the snapshot, stops fetching its mailbox, and survives a
|
||||
/// restart; the other contacts are untouched.
|
||||
#[test]
|
||||
fn a_forgotten_contact_leaves_nothing_behind() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
let mut petr = quiet(Client::new("Petr Zapomenutý", relay.clone()).expect("petr"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let petr_side = petr.accept_invite(&invite).expect("accept");
|
||||
let Some(Event::Joined {
|
||||
contact: forgotten, ..
|
||||
}) = eva.poll().expect("poll").first().cloned()
|
||||
else {
|
||||
panic!("no join")
|
||||
};
|
||||
petr.poll().expect("poll");
|
||||
let before: serde_json::Value =
|
||||
serde_json::from_slice(&eva.snapshot().expect("snapshot")).expect("json");
|
||||
assert!(before.to_string().contains("Petr Zapomenutý"));
|
||||
let petr_state = before["contacts"][1].clone();
|
||||
|
||||
assert_eq!(eva.forget_contact(forgotten), Ok(true));
|
||||
assert_eq!(eva.forget_contact(forgotten), Ok(false), "only once");
|
||||
let saved = eva.snapshot().expect("snapshot");
|
||||
assert!(
|
||||
!contains(&saved, "Petr Zapomenutý".as_bytes()),
|
||||
"the name is gone"
|
||||
);
|
||||
// The group's MLS state is gone from storage too: putting the contact back is refused.
|
||||
let mut back: serde_json::Value = serde_json::from_slice(&saved).expect("json");
|
||||
back["contacts"]
|
||||
.as_array_mut()
|
||||
.expect("contacts")
|
||||
.push(petr_state);
|
||||
let back = serde_json::to_vec(&back).expect("json");
|
||||
assert!(matches!(
|
||||
C::restore(&back, relay.clone()),
|
||||
Err(ClientError::State)
|
||||
));
|
||||
let mut eva = Client::restore(&saved, relay.clone()).expect("restore");
|
||||
assert_eq!(eva.contact_name(forgotten), None);
|
||||
|
||||
petr.send(petr_side, "slyšíš mě?")
|
||||
.expect("the relay still takes it");
|
||||
jan.send(jan_side, "já ano").expect("send");
|
||||
assert_eq!(texts(eva.poll().expect("poll")), ["já ano"]);
|
||||
assert_eq!(relay.waiting_blobs(), 1, "Petr's message was never fetched");
|
||||
assert_eq!(
|
||||
eva.compose(forgotten, "x"),
|
||||
Err(ClientError::UnknownContact)
|
||||
);
|
||||
eva.send(eva_side, "Jan still works").expect("send");
|
||||
}
|
||||
@@ -7,6 +7,13 @@ edition.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
sha2 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = "1.11"
|
||||
serde_json = "1"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
+329
-2
@@ -1,2 +1,329 @@
|
||||
//! Wire types for the Tabellarius protocol (`docs/PROTOCOL.md`).
|
||||
//! Empty until the protocol review is approved.
|
||||
//! Wire types for the Tabellarius protocol v0 (`docs/PROTOCOL.md`, approved 2026-11-08).
|
||||
//!
|
||||
//! No I/O. Every value that crosses the wire has exactly one spelling: ids and tokens are unpadded
|
||||
//! base64url of a fixed number of bytes, and parsing refuses anything else with a [`ParseError`].
|
||||
//! The HTTP routes that carry these types are listed in `.agents/features/relay.md` §2.
|
||||
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::borrow::Cow;
|
||||
use std::fmt;
|
||||
|
||||
/// The protocol version, as it appears in every path (`/v0/...`).
|
||||
pub const VERSION: &str = "v0";
|
||||
/// The largest blob (one MLS message) the relay accepts.
|
||||
pub const MAX_BLOB_BYTES: usize = 256 * 1024;
|
||||
/// The largest KeyPackage an invite may carry.
|
||||
pub const MAX_KEY_PACKAGE_BYTES: usize = 16 * 1024;
|
||||
/// At most this many blobs come back from one fetch; the rest wait for the next.
|
||||
pub const MAX_BLOBS_PER_FETCH: usize = 100;
|
||||
/// A blob not acknowledged is deleted after this many seconds (30 days, `PROTOCOL.md` §5).
|
||||
pub const BLOB_TTL_SECS: i64 = 30 * 24 * 3600;
|
||||
/// An unclaimed invite expires after this many seconds (7 days, `PROTOCOL.md` §4).
|
||||
pub const INVITE_TTL_SECS: i64 = 7 * 24 * 3600;
|
||||
|
||||
/// Why a value from the wire was refused. Carries no part of the input.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ParseError {
|
||||
/// Not unpadded base64url, or not its one canonical spelling.
|
||||
Encoding,
|
||||
/// Decoded to the wrong number of bytes.
|
||||
Length { expected: usize, got: usize },
|
||||
/// The bearer header is missing its `Bearer ` prefix.
|
||||
Scheme,
|
||||
/// More bytes than the protocol allows.
|
||||
TooLarge { max: usize },
|
||||
}
|
||||
|
||||
impl fmt::Display for ParseError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ParseError::Encoding => write!(f, "not canonical unpadded base64url"),
|
||||
ParseError::Length { expected, got } => {
|
||||
write!(f, "expected {expected} bytes, got {got}")
|
||||
}
|
||||
ParseError::Scheme => write!(f, "expected 'Bearer <token>'"),
|
||||
ParseError::TooLarge { max } => write!(f, "more than {max} bytes"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ParseError {}
|
||||
|
||||
fn is_base64url(text: &str) -> bool {
|
||||
text.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
|
||||
/// Decodes canonical unpadded base64url: refuses other alphabets, padding, and spellings whose
|
||||
/// unused trailing bits are not zero (those would give one value a second spelling).
|
||||
fn decode_canonical(text: &str) -> Result<Vec<u8>, ParseError> {
|
||||
if !is_base64url(text) {
|
||||
return Err(ParseError::Encoding);
|
||||
}
|
||||
let bytes = URL_SAFE_NO_PAD
|
||||
.decode(text)
|
||||
.map_err(|_| ParseError::Encoding)?;
|
||||
if URL_SAFE_NO_PAD.encode(&bytes) != text {
|
||||
return Err(ParseError::Encoding);
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn decode_exact<const N: usize>(text: &str) -> Result<[u8; N], ParseError> {
|
||||
// A cheap bound first: anything longer than N bytes' worth of characters is refused unread.
|
||||
if text.len() > N.div_ceil(3) * 4 {
|
||||
return Err(ParseError::Length {
|
||||
expected: N,
|
||||
got: text.len() / 4 * 3,
|
||||
});
|
||||
}
|
||||
let bytes = decode_canonical(text)?;
|
||||
let got = bytes.len();
|
||||
bytes
|
||||
.try_into()
|
||||
.map_err(|_| ParseError::Length { expected: N, got })
|
||||
}
|
||||
|
||||
macro_rules! fixed_bytes {
|
||||
($(#[$doc:meta])* $name:ident, $len:expr) => {
|
||||
$(#[$doc])*
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct $name([u8; $len]);
|
||||
|
||||
impl $name {
|
||||
pub const LEN: usize = $len;
|
||||
|
||||
pub fn from_bytes(bytes: [u8; $len]) -> Self {
|
||||
Self(bytes)
|
||||
}
|
||||
|
||||
pub fn as_bytes(&self) -> &[u8; $len] {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Parses the wire spelling: unpadded base64url of exactly `LEN` bytes.
|
||||
pub fn parse(text: &str) -> Result<Self, ParseError> {
|
||||
decode_exact::<$len>(text).map(Self)
|
||||
}
|
||||
|
||||
pub fn to_wire(&self) -> String {
|
||||
URL_SAFE_NO_PAD.encode(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for $name {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&self.to_wire())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for $name {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let text = Cow::<'de, str>::deserialize(d)?;
|
||||
Self::parse(&text).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fixed_bytes!(
|
||||
/// A mailbox: 16 random bytes made by its owner. One per contact (`PROTOCOL.md` §3).
|
||||
MailboxId,
|
||||
16
|
||||
);
|
||||
fixed_bytes!(
|
||||
/// An invite: 16 random bytes made by the inviter (`PROTOCOL.md` §4).
|
||||
InviteId,
|
||||
16
|
||||
);
|
||||
fixed_bytes!(
|
||||
/// SHA-256 of a token, or of a blob when it is acknowledged. The relay stores token hashes only.
|
||||
Sha256Hash,
|
||||
32
|
||||
);
|
||||
fixed_bytes!(
|
||||
/// A capability: a post token, a fetch token or an invite's one-time secret. 32 random bytes.
|
||||
/// Never stored by the relay; only its [`Sha256Hash`] is.
|
||||
Token,
|
||||
32
|
||||
);
|
||||
|
||||
impl Token {
|
||||
/// The hash the relay stores and compares against.
|
||||
pub fn hash(&self) -> Sha256Hash {
|
||||
Sha256Hash(Sha256::digest(self.0).into())
|
||||
}
|
||||
|
||||
/// Parses an `Authorization` header value: `Bearer <token>`.
|
||||
pub fn from_bearer(header: &str) -> Result<Self, ParseError> {
|
||||
let token = header.strip_prefix("Bearer ").ok_or(ParseError::Scheme)?;
|
||||
Self::parse(token)
|
||||
}
|
||||
|
||||
pub fn to_bearer(&self) -> String {
|
||||
format!("Bearer {}", self.to_wire())
|
||||
}
|
||||
}
|
||||
|
||||
// Tokens are secrets: never printed, not even in a debug log.
|
||||
impl fmt::Debug for Token {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Token(..)")
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! debug_as_wire {
|
||||
($($name:ident),*) => {$(
|
||||
impl fmt::Debug for $name {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}({})", stringify!($name), self.to_wire())
|
||||
}
|
||||
}
|
||||
)*};
|
||||
}
|
||||
debug_as_wire!(MailboxId, InviteId, Sha256Hash);
|
||||
|
||||
/// The SHA-256 of a blob: how its recipient acknowledges it.
|
||||
pub fn blob_hash(blob: &[u8]) -> Sha256Hash {
|
||||
Sha256Hash(Sha256::digest(blob).into())
|
||||
}
|
||||
|
||||
/// Bytes inside JSON as unpadded base64url, with an upper bound checked before decoding.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct WireBytes(pub Vec<u8>);
|
||||
|
||||
impl WireBytes {
|
||||
pub fn parse(text: &str, max: usize) -> Result<Self, ParseError> {
|
||||
// 4 characters carry 3 bytes: anything longer cannot fit, and is refused before decoding.
|
||||
if text.len() > max.div_ceil(3) * 4 {
|
||||
return Err(ParseError::TooLarge { max });
|
||||
}
|
||||
let bytes = decode_canonical(text)?;
|
||||
if bytes.len() > max {
|
||||
return Err(ParseError::TooLarge { max });
|
||||
}
|
||||
Ok(Self(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for WireBytes {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "WireBytes({} bytes)", self.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for WireBytes {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&URL_SAFE_NO_PAD.encode(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! bounded_bytes {
|
||||
($(#[$doc:meta])* $name:ident, $max:expr) => {
|
||||
$(#[$doc])*
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct $name(pub WireBytes);
|
||||
|
||||
impl $name {
|
||||
pub fn new(bytes: Vec<u8>) -> Result<Self, ParseError> {
|
||||
if bytes.len() > $max {
|
||||
return Err(ParseError::TooLarge { max: $max });
|
||||
}
|
||||
Ok(Self(WireBytes(bytes)))
|
||||
}
|
||||
|
||||
pub fn bytes(&self) -> &[u8] {
|
||||
&self.0 .0
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for $name {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let text = Cow::<'de, str>::deserialize(d)?;
|
||||
WireBytes::parse(&text, $max)
|
||||
.map(Self)
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
bounded_bytes!(
|
||||
/// A KeyPackage inside an invite, at most [`MAX_KEY_PACKAGE_BYTES`].
|
||||
KeyPackageBytes,
|
||||
MAX_KEY_PACKAGE_BYTES
|
||||
);
|
||||
bounded_bytes!(
|
||||
/// A blob inside a fetch response, at most [`MAX_BLOB_BYTES`].
|
||||
BlobBytes,
|
||||
MAX_BLOB_BYTES
|
||||
);
|
||||
|
||||
/// `POST /v0/mailboxes`. The owner sends hashes, so the relay never sees the tokens themselves here.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CreateMailbox {
|
||||
pub id: MailboxId,
|
||||
pub post_token_hash: Sha256Hash,
|
||||
pub fetch_token_hash: Sha256Hash,
|
||||
}
|
||||
|
||||
/// `PUT /v0/mailboxes/{id}/post-token`: blocking someone = giving everyone else a new post token.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct RotatePostToken {
|
||||
pub post_token_hash: Sha256Hash,
|
||||
}
|
||||
|
||||
/// One waiting blob in `GET /v0/mailboxes/{id}/blobs`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct FetchedBlob {
|
||||
pub blob: BlobBytes,
|
||||
/// Unix time in hours, rounded down: all the relay keeps of when it arrived.
|
||||
pub received_hour: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct FetchedBlobs {
|
||||
pub blobs: Vec<FetchedBlob>,
|
||||
}
|
||||
|
||||
/// `POST /v0/invites`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CreateInvite {
|
||||
pub id: InviteId,
|
||||
pub secret_hash: Sha256Hash,
|
||||
pub key_package: KeyPackageBytes,
|
||||
}
|
||||
|
||||
/// `GET /v0/invites/{id}`: the inviter's KeyPackage, handed out once.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ClaimedInvite {
|
||||
pub key_package: KeyPackageBytes,
|
||||
}
|
||||
|
||||
/// `GET /version`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct VersionInfo {
|
||||
pub protocol: String,
|
||||
pub relay: String,
|
||||
}
|
||||
|
||||
/// Rounds unix seconds down to the hour, as the relay stores arrival times.
|
||||
pub fn hour_of(unix_secs: i64) -> i64 {
|
||||
unix_secs.div_euclid(3600)
|
||||
}
|
||||
|
||||
/// Rounds unix seconds down to the day, as the relay stores when a mailbox was made.
|
||||
pub fn day_of(unix_secs: i64) -> i64 {
|
||||
unix_secs.div_euclid(86_400)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
//! The wire spelling: one value, one spelling, and no input that panics a parser.
|
||||
|
||||
use proptest::prelude::*;
|
||||
use tabellarius_protocol::*;
|
||||
|
||||
#[test]
|
||||
fn ids_and_tokens_round_trip_through_their_wire_spelling() {
|
||||
let id = MailboxId::from_bytes([7; 16]);
|
||||
assert_eq!(id.to_wire().len(), 22);
|
||||
assert_eq!(MailboxId::parse(&id.to_wire()), Ok(id));
|
||||
let token = Token::from_bytes([9; 32]);
|
||||
assert_eq!(token.to_wire().len(), 43);
|
||||
assert_eq!(Token::from_bearer(&token.to_bearer()), Ok(token));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_length_alphabet_padding_or_spelling_is_refused() {
|
||||
let good = MailboxId::from_bytes([0xAB; 16]).to_wire();
|
||||
// one character short, one too many
|
||||
assert!(MailboxId::parse(&good[..21]).is_err());
|
||||
assert!(MailboxId::parse(&format!("{good}A")).is_err());
|
||||
// the standard alphabet and padding are not this protocol's
|
||||
assert_eq!(
|
||||
MailboxId::parse(&good.replace('-', "+").replace('_', "/").replace('q', "+")),
|
||||
Err(ParseError::Encoding)
|
||||
);
|
||||
assert_eq!(
|
||||
MailboxId::parse(&format!("{good}==")),
|
||||
Err(ParseError::Encoding)
|
||||
);
|
||||
// a Token is not a MailboxId
|
||||
assert!(matches!(
|
||||
MailboxId::parse(&Token::from_bytes([1; 32]).to_wire()),
|
||||
Err(ParseError::Length { expected: 16, .. })
|
||||
));
|
||||
assert_eq!(
|
||||
MailboxId::parse(""),
|
||||
Err(ParseError::Length {
|
||||
expected: 16,
|
||||
got: 0
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_spelling_of_the_same_bytes_is_refused() {
|
||||
// 16 bytes leave 4 unused bits in the last character. 'A' (000000) is canonical for a zero
|
||||
// tail; 'B' (000001) decodes to the same bytes with a non-zero unused bit.
|
||||
let canonical = MailboxId::from_bytes([0; 16]).to_wire();
|
||||
assert!(canonical.ends_with('A'));
|
||||
let other = format!("{}B", &canonical[..21]);
|
||||
assert_eq!(MailboxId::parse(&other), Err(ParseError::Encoding));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bearer_header_needs_its_scheme() {
|
||||
let token = Token::from_bytes([3; 32]);
|
||||
assert_eq!(
|
||||
Token::from_bearer(&token.to_wire()),
|
||||
Err(ParseError::Scheme)
|
||||
);
|
||||
assert_eq!(
|
||||
Token::from_bearer(&format!("bearer {}", token.to_wire())),
|
||||
Err(ParseError::Scheme)
|
||||
);
|
||||
assert!(Token::from_bearer(&format!("Bearer {}", token.to_wire())).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_is_never_printed() {
|
||||
let token = Token::from_bytes([0x5A; 32]);
|
||||
let shown = format!("{token:?}");
|
||||
assert_eq!(shown, "Token(..)");
|
||||
assert!(!shown.contains(&token.to_wire()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hash_of_a_token_is_its_sha256() {
|
||||
// SHA-256 of 32 zero bytes, a published value.
|
||||
let hash = Token::from_bytes([0; 32]).hash();
|
||||
let hex: String = hash.as_bytes().iter().map(|b| format!("{b:02x}")).collect();
|
||||
assert_eq!(
|
||||
hex,
|
||||
"66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_bodies_refuse_unknown_fields_and_bad_values() {
|
||||
let ok = serde_json::json!({
|
||||
"id": MailboxId::from_bytes([1; 16]).to_wire(),
|
||||
"postTokenHash": Sha256Hash::from_bytes([2; 32]).to_wire(),
|
||||
"fetchTokenHash": Sha256Hash::from_bytes([3; 32]).to_wire(),
|
||||
});
|
||||
let parsed: CreateMailbox = serde_json::from_value(ok.clone()).expect("valid body");
|
||||
assert_eq!(parsed.id, MailboxId::from_bytes([1; 16]));
|
||||
|
||||
let mut extra = ok.clone();
|
||||
extra["name"] = serde_json::json!("Eva");
|
||||
assert!(serde_json::from_value::<CreateMailbox>(extra).is_err());
|
||||
|
||||
let mut short = ok;
|
||||
short["id"] = serde_json::json!("AAAA");
|
||||
assert!(serde_json::from_value::<CreateMailbox>(short).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_package_over_the_limit_is_refused_before_decoding() {
|
||||
let at_limit = KeyPackageBytes::new(vec![0; MAX_KEY_PACKAGE_BYTES]).expect("at the limit");
|
||||
let body = serde_json::json!({
|
||||
"id": InviteId::from_bytes([1; 16]).to_wire(),
|
||||
"secretHash": Sha256Hash::from_bytes([2; 32]).to_wire(),
|
||||
"keyPackage": at_limit,
|
||||
});
|
||||
assert!(serde_json::from_value::<CreateInvite>(body.clone()).is_ok());
|
||||
let mut over = body;
|
||||
over["keyPackage"] = serde_json::json!("A".repeat(MAX_KEY_PACKAGE_BYTES / 3 * 4 + 8));
|
||||
let err = serde_json::from_value::<CreateInvite>(over).expect_err("over the limit");
|
||||
assert!(err.to_string().contains("more than"), "{err}");
|
||||
assert!(KeyPackageBytes::new(vec![0; MAX_KEY_PACKAGE_BYTES + 1]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_is_kept_only_to_the_hour_and_the_day() {
|
||||
assert_eq!(hour_of(7199), 1);
|
||||
assert_eq!(hour_of(-1), -1);
|
||||
assert_eq!(day_of(86_399), 0);
|
||||
assert_eq!(day_of(86_400), 1);
|
||||
}
|
||||
|
||||
fn config() -> ProptestConfig {
|
||||
ProptestConfig {
|
||||
cases: 10_000,
|
||||
..ProptestConfig::default()
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
/// Any string at all: every parser answers with a value or an error, never a panic.
|
||||
#[test]
|
||||
fn no_string_panics_a_parser(text in any::<String>()) {
|
||||
let _ = MailboxId::parse(&text);
|
||||
let _ = InviteId::parse(&text);
|
||||
let _ = Sha256Hash::parse(&text);
|
||||
let _ = Token::parse(&text);
|
||||
let _ = Token::from_bearer(&text);
|
||||
let _ = WireBytes::parse(&text, MAX_BLOB_BYTES);
|
||||
}
|
||||
|
||||
/// Strings from the base64url alphabet (the ones that get furthest into the decoder).
|
||||
#[test]
|
||||
fn no_base64url_string_panics_a_parser(text in "[A-Za-z0-9_=+/-]{0,90}") {
|
||||
let _ = MailboxId::parse(&text);
|
||||
let _ = Token::parse(&text);
|
||||
let _ = Token::from_bearer(&format!("Bearer {text}"));
|
||||
let _ = WireBytes::parse(&text, 64);
|
||||
}
|
||||
|
||||
/// Any JSON-ish bytes given to every request body: an error or a value, never a panic.
|
||||
#[test]
|
||||
fn no_body_panics_the_json_parsers(bytes in proptest::collection::vec(any::<u8>(), 0..300)) {
|
||||
let _ = serde_json::from_slice::<CreateMailbox>(&bytes);
|
||||
let _ = serde_json::from_slice::<RotatePostToken>(&bytes);
|
||||
let _ = serde_json::from_slice::<CreateInvite>(&bytes);
|
||||
let _ = serde_json::from_slice::<FetchedBlobs>(&bytes);
|
||||
let _ = serde_json::from_slice::<ClaimedInvite>(&bytes);
|
||||
}
|
||||
|
||||
/// Every id that parses has exactly the spelling it was given.
|
||||
#[test]
|
||||
fn whatever_parses_has_one_spelling(text in "[A-Za-z0-9_-]{22}") {
|
||||
if let Ok(id) = MailboxId::parse(&text) {
|
||||
prop_assert_eq!(id.to_wire(), text);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes survive the wire unchanged.
|
||||
#[test]
|
||||
fn bytes_round_trip(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
|
||||
let wire = serde_json::to_string(&BlobBytes::new(bytes.clone()).expect("small")).expect("json");
|
||||
let back: BlobBytes = serde_json::from_str(&wire).expect("parses");
|
||||
prop_assert_eq!(back.bytes(), &bytes[..]);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//! The HTTP face of the store. No logging, no connection info: a handler never sees the client's
|
||||
//! address, and nothing here writes a request anywhere.
|
||||
|
||||
use crate::store::{Refused, Store};
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{DefaultBodyLimit, Path, State};
|
||||
use axum::http::{header, HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{delete, get, post, put};
|
||||
use axum::{Json, Router};
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::sync::Arc;
|
||||
use tabellarius_protocol::{
|
||||
CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, Sha256Hash,
|
||||
Token, VersionInfo, MAX_BLOB_BYTES, VERSION,
|
||||
};
|
||||
|
||||
/// Unix seconds. The server passes the system clock; tests pass their own.
|
||||
pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub store: Arc<Store>,
|
||||
pub clock: Clock,
|
||||
}
|
||||
|
||||
/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url.
|
||||
const MAX_JSON_BYTES: usize = 32 * 1024;
|
||||
|
||||
pub fn router(state: AppState) -> Router {
|
||||
let blob_routes = Router::new()
|
||||
.route("/v0/mailboxes/{id}/blobs", post(post_blob).get(fetch_blobs))
|
||||
.layer(DefaultBodyLimit::max(MAX_BLOB_BYTES));
|
||||
Router::new()
|
||||
.route("/v0/mailboxes", post(create_mailbox))
|
||||
.route("/v0/mailboxes/{id}/blobs/{hash}", delete(acknowledge))
|
||||
.route("/v0/mailboxes/{id}/post-token", put(rotate_post_token))
|
||||
.route("/v0/invites", post(create_invite))
|
||||
.route("/v0/invites/{id}", get(claim_invite))
|
||||
.route("/version", get(version))
|
||||
.layer(DefaultBodyLimit::max(MAX_JSON_BYTES))
|
||||
.merge(blob_routes)
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Every refusal is a bare status code: no body that could echo the request back.
|
||||
struct Status(StatusCode);
|
||||
|
||||
impl IntoResponse for Status {
|
||||
fn into_response(self) -> Response {
|
||||
self.0.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Refused> for Status {
|
||||
fn from(r: Refused) -> Self {
|
||||
Status(match r {
|
||||
Refused::NotFound => StatusCode::NOT_FOUND,
|
||||
Refused::Exists => StatusCode::CONFLICT,
|
||||
Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Refused::Full => StatusCode::INSUFFICIENT_STORAGE,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a JSON body with the protocol's strict types; any failure is a plain 400.
|
||||
fn json<T: DeserializeOwned>(body: &Bytes) -> Result<T, Status> {
|
||||
serde_json::from_slice(body).map_err(|_| Status(StatusCode::BAD_REQUEST))
|
||||
}
|
||||
|
||||
/// A malformed id in the path is treated like an unknown one.
|
||||
fn mailbox(id: &str) -> Result<MailboxId, Status> {
|
||||
MailboxId::parse(id).map_err(|_| Status(StatusCode::NOT_FOUND))
|
||||
}
|
||||
|
||||
/// A missing or malformed bearer token is treated like a wrong one.
|
||||
fn bearer(headers: &HeaderMap) -> Result<Token, Status> {
|
||||
headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| Token::from_bearer(v).ok())
|
||||
.ok_or(Status(StatusCode::NOT_FOUND))
|
||||
}
|
||||
|
||||
async fn create_mailbox(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
|
||||
let req: CreateMailbox = json(&body)?;
|
||||
s.store.create_mailbox(&req, (s.clock)())?;
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
async fn post_blob(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
s.store.post(&id, &token, &body, (s.clock)())?;
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
async fn fetch_blobs(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<FetchedBlobs>, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
let blobs = s.store.fetch(&id, &token)?;
|
||||
Ok(Json(FetchedBlobs { blobs }))
|
||||
}
|
||||
|
||||
async fn acknowledge(
|
||||
State(s): State<AppState>,
|
||||
Path((id, hash)): Path<(String, String)>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
let hash = Sha256Hash::parse(&hash).map_err(|_| Status(StatusCode::NOT_FOUND))?;
|
||||
s.store.acknowledge(&id, &token, &hash)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn rotate_post_token(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
let req: RotatePostToken = json(&body)?;
|
||||
s.store
|
||||
.rotate_post_token(&id, &token, &req.post_token_hash)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn create_invite(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
|
||||
let req: CreateInvite = json(&body)?;
|
||||
s.store.create_invite(&req, (s.clock)())?;
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
async fn claim_invite(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, Status> {
|
||||
let id = InviteId::parse(&id).map_err(|_| Status(StatusCode::NOT_FOUND))?;
|
||||
let secret = bearer(&headers)?;
|
||||
let claimed = s.store.claim_invite(&id, &secret, (s.clock)())?;
|
||||
Ok(Json(claimed).into_response())
|
||||
}
|
||||
|
||||
async fn version() -> Json<VersionInfo> {
|
||||
Json(VersionInfo {
|
||||
protocol: VERSION.to_string(),
|
||||
relay: env!("CARGO_PKG_VERSION").to_string(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! 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,
|
||||
pub limits: store::Limits,
|
||||
}
|
||||
|
||||
/// `--listen <addr:port>`, `--db <path>`, and the relay-wide quotas `--max-bytes`,
|
||||
/// `--max-mailboxes`, `--max-invites` (positive integers). Anything else is refused with a usage
|
||||
/// line.
|
||||
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
|
||||
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] \
|
||||
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000]";
|
||||
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
|
||||
let mut db = PathBuf::from(DEFAULT_DB);
|
||||
let mut limits = store::Limits::default();
|
||||
let mut it = args.into_iter();
|
||||
let positive = |v: Option<String>| -> Result<i64, String> {
|
||||
v.and_then(|v| v.parse::<i64>().ok())
|
||||
.filter(|&n| n > 0)
|
||||
.ok_or_else(|| usage.to_string())
|
||||
};
|
||||
while let Some(arg) = it.next() {
|
||||
match arg.as_str() {
|
||||
"--max-bytes" => limits.total_bytes = positive(it.next())?,
|
||||
"--max-mailboxes" => limits.mailboxes = positive(it.next())?,
|
||||
"--max-invites" => limits.invites = positive(it.next())?,
|
||||
"--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, limits })
|
||||
}
|
||||
@@ -1,10 +1,78 @@
|
||||
//! 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] [--max-bytes N]
|
||||
//! [--max-mailboxes N] [--max-invites N]`
|
||||
//!
|
||||
//! 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_with(&args.db, args.limits) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
//! 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,
|
||||
/// A quota is reached (`PROTOCOL.md` §8, 507): the mailbox's, after its token, or the relay's.
|
||||
Full,
|
||||
}
|
||||
|
||||
/// How much the relay holds before it answers [`Refused::Full`]. The per-mailbox caps are the
|
||||
/// protocol's; the relay-wide ones are the operator's (`.agents/features/home-relay.md` §2).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
pub mailbox_blobs: i64,
|
||||
pub mailbox_bytes: i64,
|
||||
pub total_bytes: i64,
|
||||
pub mailboxes: i64,
|
||||
pub invites: i64,
|
||||
}
|
||||
|
||||
/// Waiting blobs in one mailbox (`PROTOCOL.md` §8).
|
||||
pub const MAILBOX_BLOBS: i64 = 1_000;
|
||||
/// Waiting bytes in one mailbox (`PROTOCOL.md` §8).
|
||||
pub const MAILBOX_BYTES: i64 = 32 * 1024 * 1024;
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
mailbox_blobs: MAILBOX_BLOBS,
|
||||
mailbox_bytes: MAILBOX_BYTES,
|
||||
total_bytes: 1024 * 1024 * 1024,
|
||||
mailboxes: 100_000,
|
||||
invites: 10_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<rusqlite::Error> for Refused {
|
||||
fn from(_: rusqlite::Error) -> Self {
|
||||
Refused::Storage
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
conn: Mutex<Connection>,
|
||||
limits: Limits,
|
||||
}
|
||||
|
||||
/// What a purge removed.
|
||||
#[derive(Debug, PartialEq, Eq, Default)]
|
||||
pub struct Purged {
|
||||
pub blobs: usize,
|
||||
pub invites: usize,
|
||||
}
|
||||
|
||||
fn same_hash(stored: &[u8], presented: &Sha256Hash) -> bool {
|
||||
stored.len() == 32 && bool::from(stored.ct_eq(presented.as_bytes()))
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn open(path: &Path) -> Result<Self, rusqlite::Error> {
|
||||
Self::init(Connection::open(path)?, Limits::default())
|
||||
}
|
||||
|
||||
pub fn open_with(path: &Path, limits: Limits) -> Result<Self, rusqlite::Error> {
|
||||
Self::init(Connection::open(path)?, limits)
|
||||
}
|
||||
|
||||
pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
|
||||
Self::init(Connection::open_in_memory()?, Limits::default())
|
||||
}
|
||||
|
||||
pub fn open_in_memory_with(limits: Limits) -> Result<Self, rusqlite::Error> {
|
||||
Self::init(Connection::open_in_memory()?, limits)
|
||||
}
|
||||
|
||||
fn init(conn: Connection, limits: Limits) -> Result<Self, rusqlite::Error> {
|
||||
// Deleted rows are overwritten in the file, and there is no -wal copy of anything.
|
||||
conn.pragma_update(None, "secure_delete", "ON")?;
|
||||
conn.pragma_update(None, "journal_mode", "DELETE")?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
Ok(Self {
|
||||
conn: Mutex::new(conn),
|
||||
limits,
|
||||
})
|
||||
}
|
||||
|
||||
/// One number from the database: a count or a sum, 0 for none.
|
||||
fn number(conn: &Connection, sql: &str, args: impl rusqlite::Params) -> Result<i64, Refused> {
|
||||
Ok(conn
|
||||
.query_row(sql, args, |r| r.get::<_, Option<i64>>(0))?
|
||||
.unwrap_or(0))
|
||||
}
|
||||
|
||||
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 conn = self.conn();
|
||||
if Self::number(&conn, "SELECT count(*) FROM mailboxes", [])? >= self.limits.mailboxes {
|
||||
return Err(Refused::Full);
|
||||
}
|
||||
let changed = conn.execute(
|
||||
"INSERT OR IGNORE INTO mailboxes (id, post_hash, fetch_hash, created_day)
|
||||
VALUES (?1, ?2, ?3, ?4)",
|
||||
params![
|
||||
&req.id.as_bytes()[..],
|
||||
&req.post_token_hash.as_bytes()[..],
|
||||
&req.fetch_token_hash.as_bytes()[..],
|
||||
day_of(now)
|
||||
],
|
||||
)?;
|
||||
if changed == 0 {
|
||||
return Err(Refused::Exists);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks a token against the mailbox's stored hash (`post_hash` or `fetch_hash`).
|
||||
fn authorize(
|
||||
conn: &Connection,
|
||||
id: &MailboxId,
|
||||
token: &Token,
|
||||
column: Column,
|
||||
) -> Result<(), Refused> {
|
||||
let sql = match column {
|
||||
Column::Post => "SELECT post_hash FROM mailboxes WHERE id = ?1",
|
||||
Column::Fetch => "SELECT fetch_hash FROM mailboxes WHERE id = ?1",
|
||||
};
|
||||
let stored: Option<Vec<u8>> = conn
|
||||
.query_row(sql, [&id.as_bytes()[..]], |r| r.get(0))
|
||||
.optional()?;
|
||||
let presented = token.hash();
|
||||
// Compare against something even when the mailbox is unknown, so both cases take the same path.
|
||||
let stored = stored.unwrap_or_else(|| vec![0; 32]);
|
||||
let known = !stored.iter().all(|b| *b == 0);
|
||||
if known & same_hash(&stored, &presented) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Refused::NotFound)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn post(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
token: &Token,
|
||||
blob: &[u8],
|
||||
now: i64,
|
||||
) -> Result<(), Refused> {
|
||||
if blob.len() > MAX_BLOB_BYTES {
|
||||
return Err(Refused::TooLarge);
|
||||
}
|
||||
let conn = self.conn();
|
||||
Self::authorize(&conn, id, token, Column::Post)?;
|
||||
// After the token: a stranger learns nothing about this mailbox from a 507.
|
||||
let size = blob.len() as i64;
|
||||
let (count, bytes): (i64, Option<i64>) = conn.query_row(
|
||||
"SELECT count(*), sum(size) FROM blobs WHERE mailbox_id = ?1",
|
||||
[&id.as_bytes()[..]],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
let total = Self::number(&conn, "SELECT sum(size) FROM blobs", [])?;
|
||||
if count >= self.limits.mailbox_blobs
|
||||
|| bytes.unwrap_or(0) + size > self.limits.mailbox_bytes
|
||||
|| total + size > self.limits.total_bytes
|
||||
{
|
||||
return Err(Refused::Full);
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO blobs (mailbox_id, ciphertext, size, received_hour) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![&id.as_bytes()[..], blob, blob.len() as i64, hour_of(now)],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The waiting blobs, oldest first, at most [`MAX_BLOBS_PER_FETCH`]. Fetching deletes nothing:
|
||||
/// a blob goes only when it is acknowledged, or at the TTL.
|
||||
pub fn fetch(&self, id: &MailboxId, token: &Token) -> Result<Vec<FetchedBlob>, Refused> {
|
||||
let conn = self.conn();
|
||||
Self::authorize(&conn, id, token, Column::Fetch)?;
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT ciphertext, received_hour FROM blobs WHERE mailbox_id = ?1
|
||||
ORDER BY received_hour, rowid LIMIT ?2",
|
||||
)?;
|
||||
let rows = stmt.query_map(
|
||||
params![&id.as_bytes()[..], MAX_BLOBS_PER_FETCH as i64],
|
||||
|r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)),
|
||||
)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let (bytes, received_hour) = row?;
|
||||
let blob = BlobBytes::new(bytes).map_err(|_| Refused::Storage)?;
|
||||
out.push(FetchedBlob {
|
||||
blob,
|
||||
received_hour,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Deletes this mailbox's blob whose SHA-256 is `hash`. Unknown hash = [`Refused::NotFound`].
|
||||
pub fn acknowledge(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
token: &Token,
|
||||
hash: &Sha256Hash,
|
||||
) -> Result<(), Refused> {
|
||||
let mut conn = self.conn();
|
||||
Self::authorize(&conn, id, token, Column::Fetch)?;
|
||||
let tx = conn.transaction()?;
|
||||
let rowid: Option<i64> = {
|
||||
let mut stmt =
|
||||
tx.prepare("SELECT rowid, ciphertext FROM blobs WHERE mailbox_id = ?1")?;
|
||||
let mut rows = stmt.query([&id.as_bytes()[..]])?;
|
||||
let mut found = None;
|
||||
while let Some(row) = rows.next()? {
|
||||
let bytes: Vec<u8> = row.get(1)?;
|
||||
if blob_hash(&bytes) == *hash {
|
||||
found = Some(row.get(0)?);
|
||||
break;
|
||||
}
|
||||
}
|
||||
found
|
||||
};
|
||||
let rowid = rowid.ok_or(Refused::NotFound)?;
|
||||
tx.execute("DELETE FROM blobs WHERE rowid = ?1", [rowid])?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Blocking: the owner (fetch token) gives the mailbox a new post token hash.
|
||||
pub fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
new_hash: &Sha256Hash,
|
||||
) -> Result<(), Refused> {
|
||||
let conn = self.conn();
|
||||
Self::authorize(&conn, id, fetch, Column::Fetch)?;
|
||||
conn.execute(
|
||||
"UPDATE mailboxes SET post_hash = ?2 WHERE id = ?1",
|
||||
params![&id.as_bytes()[..], &new_hash.as_bytes()[..]],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_invite(&self, req: &CreateInvite, now: i64) -> Result<(), Refused> {
|
||||
// Expiry rounded up to the hour: the exact second the invite was made is not kept.
|
||||
let expiry = (hour_of(now + INVITE_TTL_SECS) + 1) * 3600;
|
||||
let conn = self.conn();
|
||||
// Expired invites wait for the hourly purge; they do not count against new ones.
|
||||
let waiting = Self::number(
|
||||
&conn,
|
||||
"SELECT count(*) FROM invites WHERE expiry > ?1",
|
||||
[now],
|
||||
)?;
|
||||
if waiting >= self.limits.invites {
|
||||
return Err(Refused::Full);
|
||||
}
|
||||
let changed = conn.execute(
|
||||
"INSERT OR IGNORE INTO invites (id, secret_hash, key_package, expiry) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![
|
||||
&req.id.as_bytes()[..],
|
||||
&req.secret_hash.as_bytes()[..],
|
||||
req.key_package.bytes(),
|
||||
expiry
|
||||
],
|
||||
)?;
|
||||
if changed == 0 {
|
||||
return Err(Refused::Exists);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hands the KeyPackage out once and deletes the invite. Expired = not found.
|
||||
pub fn claim_invite(
|
||||
&self,
|
||||
id: &InviteId,
|
||||
secret: &Token,
|
||||
now: i64,
|
||||
) -> Result<ClaimedInvite, Refused> {
|
||||
let mut conn = self.conn();
|
||||
let tx = conn.transaction()?;
|
||||
let row: Option<(Vec<u8>, Vec<u8>, i64)> = tx
|
||||
.query_row(
|
||||
"SELECT secret_hash, key_package, expiry FROM invites WHERE id = ?1",
|
||||
[&id.as_bytes()[..]],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let (stored, key_package, expiry) =
|
||||
row.unwrap_or_else(|| (vec![0; 32], Vec::new(), i64::MIN));
|
||||
let ok =
|
||||
same_hash(&stored, &secret.hash()) & (now < expiry) & !stored.iter().all(|b| *b == 0);
|
||||
if !ok {
|
||||
return Err(Refused::NotFound);
|
||||
}
|
||||
tx.execute("DELETE FROM invites WHERE id = ?1", [&id.as_bytes()[..]])?;
|
||||
tx.commit()?;
|
||||
Ok(ClaimedInvite {
|
||||
key_package: KeyPackageBytes::new(key_package).map_err(|_| Refused::Storage)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Deletes blobs older than 30 days and invites past their expiry.
|
||||
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
|
||||
let conn = self.conn();
|
||||
// A blob that arrived in hour h is gone once h is more than 30 days before now's hour.
|
||||
let oldest_kept = hour_of(now - BLOB_TTL_SECS);
|
||||
let blobs = conn.execute("DELETE FROM blobs WHERE received_hour < ?1", [oldest_kept])?;
|
||||
let invites = conn.execute("DELETE FROM invites WHERE expiry <= ?1", [now])?;
|
||||
Ok(Purged { blobs, invites })
|
||||
}
|
||||
|
||||
/// The live schema: (table, columns) for every table, in name order. For the §5 test.
|
||||
pub fn live_schema(&self) -> Result<Vec<(String, Vec<String>)>, rusqlite::Error> {
|
||||
let conn = self.conn();
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")?;
|
||||
let tables: Vec<String> = stmt
|
||||
.query_map([], |r| r.get(0))?
|
||||
.collect::<Result<_, _>>()?;
|
||||
let mut out = Vec::new();
|
||||
for table in tables {
|
||||
let mut cols = conn.prepare(&format!("PRAGMA table_info(\"{table}\")"))?;
|
||||
let names: Vec<String> = cols
|
||||
.query_map([], |r| r.get(1))?
|
||||
.collect::<Result<_, _>>()?;
|
||||
out.push((table, names));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Column {
|
||||
Post,
|
||||
Fetch,
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
//! Quotas (`.agents/features/home-relay.md` §4, `PROTOCOL.md` §8): over a limit the relay answers a
|
||||
//! bare 507; the per-mailbox caps only after the post token. Small limits, so the tests are quick.
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{header, Method, Request, StatusCode};
|
||||
use http_body_util::BodyExt;
|
||||
use std::sync::Arc;
|
||||
use tabellarius_protocol::*;
|
||||
use tabellarius_relay::http::{router, AppState, Clock};
|
||||
use tabellarius_relay::parse_args;
|
||||
use tabellarius_relay::store::{Limits, Store, MAILBOX_BLOBS, MAILBOX_BYTES};
|
||||
use tower::ServiceExt;
|
||||
|
||||
const T0: i64 = 1_794_000_000;
|
||||
|
||||
fn random<const N: usize>() -> [u8; N] {
|
||||
let mut b = [0u8; N];
|
||||
getrandom::fill(&mut b).expect("system randomness");
|
||||
b
|
||||
}
|
||||
|
||||
struct Mailbox {
|
||||
id: MailboxId,
|
||||
post: Token,
|
||||
fetch: Token,
|
||||
}
|
||||
|
||||
impl Mailbox {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
id: MailboxId::from_bytes(random()),
|
||||
post: Token::from_bytes(random()),
|
||||
fetch: Token::from_bytes(random()),
|
||||
}
|
||||
}
|
||||
fn path(&self) -> String {
|
||||
format!("/v0/mailboxes/{}/blobs", self.id.to_wire())
|
||||
}
|
||||
}
|
||||
|
||||
struct Relay(axum::Router);
|
||||
|
||||
impl Relay {
|
||||
fn with(limits: Limits) -> Self {
|
||||
let store = Arc::new(Store::open_in_memory_with(limits).expect("store"));
|
||||
let clock: Clock = Arc::new(|| T0);
|
||||
Relay(router(AppState { store, clock }))
|
||||
}
|
||||
async fn call(
|
||||
&self,
|
||||
method: Method,
|
||||
path: &str,
|
||||
auth: Option<&Token>,
|
||||
body: Vec<u8>,
|
||||
) -> StatusCode {
|
||||
let mut req = Request::builder().method(method).uri(path);
|
||||
if let Some(t) = auth {
|
||||
req = req.header(header::AUTHORIZATION, t.to_bearer());
|
||||
}
|
||||
let resp = self
|
||||
.0
|
||||
.clone()
|
||||
.oneshot(req.body(Body::from(body)).expect("request"))
|
||||
.await
|
||||
.expect("infallible");
|
||||
let status = resp.status();
|
||||
let body = resp.into_body().collect().await.expect("body").to_bytes();
|
||||
if !status.is_success() {
|
||||
assert!(body.is_empty(), "a refusal has no body");
|
||||
}
|
||||
status
|
||||
}
|
||||
async fn create(&self, m: &Mailbox) -> StatusCode {
|
||||
let body = serde_json::to_vec(&CreateMailbox {
|
||||
id: m.id,
|
||||
post_token_hash: m.post.hash(),
|
||||
fetch_token_hash: m.fetch.hash(),
|
||||
})
|
||||
.expect("json");
|
||||
self.call(Method::POST, "/v0/mailboxes", None, body).await
|
||||
}
|
||||
async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode {
|
||||
self.call(Method::POST, &m.path(), Some(token), blob.to_vec())
|
||||
.await
|
||||
}
|
||||
async fn ack(&self, m: &Mailbox, blob: &[u8]) -> StatusCode {
|
||||
let path = format!("{}/{}", m.path(), blob_hash(blob).to_wire());
|
||||
self.call(Method::DELETE, &path, Some(&m.fetch), vec![])
|
||||
.await
|
||||
}
|
||||
async fn invite(&self) -> (StatusCode, InviteId, Token) {
|
||||
let id = InviteId::from_bytes(random());
|
||||
let secret = Token::from_bytes(random());
|
||||
let body = serde_json::to_vec(&CreateInvite {
|
||||
id,
|
||||
secret_hash: secret.hash(),
|
||||
key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"),
|
||||
})
|
||||
.expect("json");
|
||||
(
|
||||
self.call(Method::POST, "/v0/invites", None, body).await,
|
||||
id,
|
||||
secret,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn small(f: impl FnOnce(&mut Limits)) -> Limits {
|
||||
let mut l = Limits::default();
|
||||
f(&mut l);
|
||||
l
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_protocol_caps_are_the_documented_ones() {
|
||||
assert_eq!(MAILBOX_BLOBS, 1_000);
|
||||
assert_eq!(MAILBOX_BYTES, 32 * 1024 * 1024);
|
||||
let l = Limits::default();
|
||||
assert_eq!(
|
||||
(l.total_bytes, l.mailboxes, l.invites),
|
||||
(1 << 30, 100_000, 10_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_mailbox_holds_a_thousand_blobs_then_says_full_until_one_is_acknowledged() {
|
||||
let relay = Relay::with(Limits::default());
|
||||
let m = Mailbox::new();
|
||||
assert_eq!(relay.create(&m).await, StatusCode::CREATED);
|
||||
for i in 0..MAILBOX_BLOBS {
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &i.to_le_bytes()).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
}
|
||||
let one_more = b"one more";
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, one_more).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE
|
||||
);
|
||||
// A stranger without the token learns nothing: 404, as for any wrong token.
|
||||
let stranger = Token::from_bytes(random());
|
||||
assert_eq!(
|
||||
relay.post(&m, &stranger, one_more).await,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(
|
||||
relay.ack(&m, &0i64.to_le_bytes()).await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
assert_eq!(relay.post(&m, &m.post, one_more).await, StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_mailbox_holds_at_most_its_bytes() {
|
||||
let relay = Relay::with(small(|l| l.mailbox_bytes = 1000));
|
||||
let m = Mailbox::new();
|
||||
relay.create(&m).await;
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &[1u8; 600]).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &[2u8; 400]).await,
|
||||
StatusCode::CREATED,
|
||||
"exactly at the cap"
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &[3u8; 1]).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE
|
||||
);
|
||||
// Another mailbox is not affected.
|
||||
let other = Mailbox::new();
|
||||
relay.create(&other).await;
|
||||
assert_eq!(
|
||||
relay.post(&other, &other.post, &[4u8; 600]).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_relay_holds_at_most_its_bytes_across_mailboxes() {
|
||||
let relay = Relay::with(small(|l| l.total_bytes = 1000));
|
||||
let (a, b) = (Mailbox::new(), Mailbox::new());
|
||||
relay.create(&a).await;
|
||||
relay.create(&b).await;
|
||||
assert_eq!(
|
||||
relay.post(&a, &a.post, &[1u8; 700]).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&b, &b.post, &[2u8; 301]).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&b, &b.post, &[2u8; 300]).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
assert_eq!(relay.ack(&a, &[1u8; 700]).await, StatusCode::NO_CONTENT);
|
||||
assert_eq!(
|
||||
relay.post(&b, &b.post, &[3u8; 700]).await,
|
||||
StatusCode::CREATED,
|
||||
"room again after an acknowledgement"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_relay_holds_at_most_its_mailboxes() {
|
||||
let relay = Relay::with(small(|l| l.mailboxes = 3));
|
||||
for _ in 0..3 {
|
||||
assert_eq!(relay.create(&Mailbox::new()).await, StatusCode::CREATED);
|
||||
}
|
||||
assert_eq!(
|
||||
relay.create(&Mailbox::new()).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_relay_holds_at_most_its_unclaimed_invites() {
|
||||
let relay = Relay::with(small(|l| l.invites = 2));
|
||||
let (s, id, secret) = relay.invite().await;
|
||||
assert_eq!(s, StatusCode::CREATED);
|
||||
assert_eq!(relay.invite().await.0, StatusCode::CREATED);
|
||||
assert_eq!(relay.invite().await.0, StatusCode::INSUFFICIENT_STORAGE);
|
||||
// A claimed invite is gone and makes room.
|
||||
let path = format!("/v0/invites/{}", id.to_wire());
|
||||
assert_eq!(
|
||||
relay.call(Method::GET, &path, Some(&secret), vec![]).await,
|
||||
StatusCode::OK
|
||||
);
|
||||
assert_eq!(relay.invite().await.0, StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_operator_sets_the_relay_wide_caps() {
|
||||
let args = parse_args(
|
||||
[
|
||||
"--max-bytes",
|
||||
"5000",
|
||||
"--max-mailboxes",
|
||||
"7",
|
||||
"--max-invites",
|
||||
"9",
|
||||
]
|
||||
.map(String::from),
|
||||
)
|
||||
.expect("args");
|
||||
assert_eq!(
|
||||
(
|
||||
args.limits.total_bytes,
|
||||
args.limits.mailboxes,
|
||||
args.limits.invites
|
||||
),
|
||||
(5000, 7, 9)
|
||||
);
|
||||
assert_eq!(
|
||||
args.limits.mailbox_blobs, MAILBOX_BLOBS,
|
||||
"not the operator's"
|
||||
);
|
||||
for bad in [
|
||||
vec!["--max-bytes"],
|
||||
vec!["--max-bytes", "0"],
|
||||
vec!["--max-bytes", "-5"],
|
||||
vec!["--max-mailboxes", "many"],
|
||||
vec!["--max-invites", "1.5"],
|
||||
] {
|
||||
assert!(
|
||||
parse_args(bad.iter().map(|s| s.to_string())).is_err(),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_expired_invite_does_not_count_against_new_ones() {
|
||||
let store = Store::open_in_memory_with(small(|l| l.invites = 1)).expect("store");
|
||||
let invite = || CreateInvite {
|
||||
id: InviteId::from_bytes(random()),
|
||||
secret_hash: Token::from_bytes(random()).hash(),
|
||||
key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"),
|
||||
};
|
||||
store.create_invite(&invite(), T0).expect("first");
|
||||
assert_eq!(
|
||||
store.create_invite(&invite(), T0 + 3600),
|
||||
Err(tabellarius_relay::store::Refused::Full)
|
||||
);
|
||||
// Eight days on, the first has expired, though the hourly purge has not run yet.
|
||||
store
|
||||
.create_invite(&invite(), T0 + 8 * 24 * 3600)
|
||||
.expect("room after the expiry");
|
||||
}
|
||||
@@ -0,0 +1,743 @@
|
||||
//! The relay against `docs/PROTOCOL.md` §5 and §7, through HTTP where the claim is about the wire.
|
||||
//! Tokens and ids are generated per test (CLAUDE.md §2.5): no secret is in the repository.
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{header, Method, Request, StatusCode};
|
||||
use http_body_util::BodyExt;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::atomic::{AtomicI64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use tabellarius_protocol::*;
|
||||
use tabellarius_relay::http::{router, AppState, Clock};
|
||||
use tabellarius_relay::store::{Refused, Store};
|
||||
use tabellarius_relay::{parse_args, DEFAULT_LISTEN};
|
||||
use tower::ServiceExt;
|
||||
|
||||
const T0: i64 = 1_794_000_000; // 2026-11-07, a fixed point; the clock moves only when a test moves it.
|
||||
|
||||
fn random<const N: usize>() -> [u8; N] {
|
||||
let mut b = [0u8; N];
|
||||
getrandom::fill(&mut b).expect("system randomness");
|
||||
b
|
||||
}
|
||||
|
||||
struct Mailbox {
|
||||
id: MailboxId,
|
||||
post: Token,
|
||||
fetch: Token,
|
||||
}
|
||||
|
||||
impl Mailbox {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
id: MailboxId::from_bytes(random()),
|
||||
post: Token::from_bytes(random()),
|
||||
fetch: Token::from_bytes(random()),
|
||||
}
|
||||
}
|
||||
fn create_body(&self) -> String {
|
||||
serde_json::to_string(&CreateMailbox {
|
||||
id: self.id,
|
||||
post_token_hash: self.post.hash(),
|
||||
fetch_token_hash: self.fetch.hash(),
|
||||
})
|
||||
.expect("json")
|
||||
}
|
||||
fn blobs_path(&self) -> String {
|
||||
format!("/v0/mailboxes/{}/blobs", self.id.to_wire())
|
||||
}
|
||||
}
|
||||
|
||||
struct Relay {
|
||||
app: axum::Router,
|
||||
store: Arc<Store>,
|
||||
now: Arc<AtomicI64>,
|
||||
}
|
||||
|
||||
impl Relay {
|
||||
fn in_memory() -> Self {
|
||||
Self::with(Store::open_in_memory().expect("store"))
|
||||
}
|
||||
fn with(store: Store) -> Self {
|
||||
let store = Arc::new(store);
|
||||
let now = Arc::new(AtomicI64::new(T0));
|
||||
let n = Arc::clone(&now);
|
||||
let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst));
|
||||
let app = router(AppState {
|
||||
store: Arc::clone(&store),
|
||||
clock,
|
||||
});
|
||||
Self { app, store, now }
|
||||
}
|
||||
fn advance(&self, secs: i64) {
|
||||
self.now.fetch_add(secs, Ordering::SeqCst);
|
||||
}
|
||||
async fn call(
|
||||
&self,
|
||||
method: Method,
|
||||
path: &str,
|
||||
auth: Option<&Token>,
|
||||
body: Vec<u8>,
|
||||
) -> (StatusCode, Vec<u8>) {
|
||||
let mut req = Request::builder().method(method).uri(path);
|
||||
if let Some(t) = auth {
|
||||
req = req.header(header::AUTHORIZATION, t.to_bearer());
|
||||
}
|
||||
let resp = self
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(req.body(Body::from(body)).expect("request"))
|
||||
.await
|
||||
.expect("infallible");
|
||||
let status = resp.status();
|
||||
let bytes = resp
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.expect("body")
|
||||
.to_bytes()
|
||||
.to_vec();
|
||||
(status, bytes)
|
||||
}
|
||||
async fn create(&self, m: &Mailbox) -> StatusCode {
|
||||
self.call(
|
||||
Method::POST,
|
||||
"/v0/mailboxes",
|
||||
None,
|
||||
m.create_body().into_bytes(),
|
||||
)
|
||||
.await
|
||||
.0
|
||||
}
|
||||
async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode {
|
||||
self.call(Method::POST, &m.blobs_path(), Some(token), blob.to_vec())
|
||||
.await
|
||||
.0
|
||||
}
|
||||
async fn fetch(&self, m: &Mailbox, token: &Token) -> (StatusCode, Vec<FetchedBlob>) {
|
||||
let (s, body) = self
|
||||
.call(Method::GET, &m.blobs_path(), Some(token), vec![])
|
||||
.await;
|
||||
let blobs = if s == StatusCode::OK {
|
||||
serde_json::from_slice::<FetchedBlobs>(&body)
|
||||
.expect("blobs")
|
||||
.blobs
|
||||
} else {
|
||||
assert!(body.is_empty(), "a refusal has no body");
|
||||
vec![]
|
||||
};
|
||||
(s, blobs)
|
||||
}
|
||||
async fn ack(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode {
|
||||
let path = format!("{}/{}", m.blobs_path(), blob_hash(blob).to_wire());
|
||||
self.call(Method::DELETE, &path, Some(token), vec![])
|
||||
.await
|
||||
.0
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_is_exactly_protocol_section_5() {
|
||||
let store = Store::open_in_memory().expect("store");
|
||||
let live = store.live_schema().expect("schema");
|
||||
let expected: Vec<(String, Vec<String>)> = vec![
|
||||
(
|
||||
"blobs".into(),
|
||||
vec![
|
||||
"mailbox_id".into(),
|
||||
"ciphertext".into(),
|
||||
"size".into(),
|
||||
"received_hour".into(),
|
||||
],
|
||||
),
|
||||
(
|
||||
"invites".into(),
|
||||
vec![
|
||||
"id".into(),
|
||||
"secret_hash".into(),
|
||||
"key_package".into(),
|
||||
"expiry".into(),
|
||||
],
|
||||
),
|
||||
(
|
||||
"mailboxes".into(),
|
||||
vec![
|
||||
"id".into(),
|
||||
"post_hash".into(),
|
||||
"fetch_hash".into(),
|
||||
"created_day".into(),
|
||||
],
|
||||
),
|
||||
];
|
||||
assert_eq!(
|
||||
live, expected,
|
||||
"a new table or column is a protocol change (CLAUDE.md §2.2)"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_the_post_token_posts_and_only_the_fetch_token_fetches() {
|
||||
let relay = Relay::in_memory();
|
||||
let m = Mailbox::new();
|
||||
assert_eq!(relay.create(&m).await, StatusCode::CREATED);
|
||||
assert_eq!(relay.create(&m).await, StatusCode::CONFLICT);
|
||||
|
||||
let stranger = Token::from_bytes(random());
|
||||
assert_eq!(relay.post(&m, &stranger, b"x").await, StatusCode::NOT_FOUND);
|
||||
assert_eq!(relay.post(&m, &m.fetch, b"x").await, StatusCode::NOT_FOUND);
|
||||
let (s, _) = relay
|
||||
.call(Method::POST, &m.blobs_path(), None, b"x".to_vec())
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND, "no token at all");
|
||||
assert_eq!(relay.post(&m, &m.post, b"hello").await, StatusCode::CREATED);
|
||||
|
||||
assert_eq!(relay.fetch(&m, &m.post).await.0, StatusCode::NOT_FOUND);
|
||||
assert_eq!(relay.fetch(&m, &stranger).await.0, StatusCode::NOT_FOUND);
|
||||
let (s, blobs) = relay.fetch(&m, &m.fetch).await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(blobs.len(), 1);
|
||||
assert_eq!(blobs[0].blob.bytes(), b"hello");
|
||||
assert_eq!(blobs[0].received_hour, hour_of(T0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unknown_mailbox_looks_exactly_like_a_wrong_token() {
|
||||
let relay = Relay::in_memory();
|
||||
let known = Mailbox::new();
|
||||
relay.create(&known).await;
|
||||
let unknown = Mailbox::new();
|
||||
let wrong = relay
|
||||
.call(
|
||||
Method::POST,
|
||||
&known.blobs_path(),
|
||||
Some(&unknown.post),
|
||||
b"x".to_vec(),
|
||||
)
|
||||
.await;
|
||||
let missing = relay
|
||||
.call(
|
||||
Method::POST,
|
||||
&unknown.blobs_path(),
|
||||
Some(&unknown.post),
|
||||
b"x".to_vec(),
|
||||
)
|
||||
.await;
|
||||
let malformed = relay
|
||||
.call(
|
||||
Method::POST,
|
||||
"/v0/mailboxes/not-an-id/blobs",
|
||||
Some(&unknown.post),
|
||||
b"x".to_vec(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(wrong, (StatusCode::NOT_FOUND, vec![]));
|
||||
assert_eq!(missing, wrong);
|
||||
assert_eq!(malformed, wrong);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn after_rotation_the_old_post_token_is_refused() {
|
||||
let relay = Relay::in_memory();
|
||||
let m = Mailbox::new();
|
||||
relay.create(&m).await;
|
||||
let new_post = Token::from_bytes(random());
|
||||
let body = serde_json::to_vec(&RotatePostToken {
|
||||
post_token_hash: new_post.hash(),
|
||||
})
|
||||
.expect("json");
|
||||
let path = format!("/v0/mailboxes/{}/post-token", m.id.to_wire());
|
||||
// Only the owner (fetch token) can rotate.
|
||||
let (s, _) = relay
|
||||
.call(Method::PUT, &path, Some(&m.post), body.clone())
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND);
|
||||
let (s, _) = relay.call(Method::PUT, &path, Some(&m.fetch), body).await;
|
||||
assert_eq!(s, StatusCode::NO_CONTENT);
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, b"from the blocked person").await,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&m, &new_post, b"from everyone else").await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
let (_, blobs) = relay.fetch(&m, &m.fetch).await;
|
||||
assert_eq!(blobs.len(), 1);
|
||||
assert_eq!(blobs[0].blob.bytes(), b"from everyone else");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_acknowledged_blob_is_gone_and_no_other_is_touched() {
|
||||
let relay = Relay::in_memory();
|
||||
let a = Mailbox::new();
|
||||
let b = Mailbox::new();
|
||||
relay.create(&a).await;
|
||||
relay.create(&b).await;
|
||||
relay.post(&a, &a.post, b"same bytes").await;
|
||||
relay.post(&a, &a.post, b"second").await;
|
||||
relay.post(&b, &b.post, b"same bytes").await;
|
||||
|
||||
// b's owner cannot acknowledge a's blob, even with identical bytes.
|
||||
let path = format!("{}/{}", a.blobs_path(), blob_hash(b"same bytes").to_wire());
|
||||
let (s, _) = relay
|
||||
.call(Method::DELETE, &path, Some(&b.fetch), vec![])
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND);
|
||||
|
||||
assert_eq!(
|
||||
relay.ack(&a, &a.fetch, b"same bytes").await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
assert_eq!(
|
||||
relay.ack(&a, &a.fetch, b"same bytes").await,
|
||||
StatusCode::NOT_FOUND,
|
||||
"already gone"
|
||||
);
|
||||
let (_, left) = relay.fetch(&a, &a.fetch).await;
|
||||
assert_eq!(
|
||||
left.iter()
|
||||
.map(|f| f.blob.bytes().to_vec())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![b"second".to_vec()]
|
||||
);
|
||||
let (_, other) = relay.fetch(&b, &b.fetch).await;
|
||||
assert_eq!(other.len(), 1, "the other mailbox keeps its copy");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unacknowledged_blob_is_purged_after_30_days_not_before() {
|
||||
let relay = Relay::in_memory();
|
||||
let m = Mailbox::new();
|
||||
relay.create(&m).await;
|
||||
relay.post(&m, &m.post, b"waiting").await;
|
||||
|
||||
relay.advance(BLOB_TTL_SECS - 3600);
|
||||
let now = relay.now.load(Ordering::SeqCst);
|
||||
assert_eq!(relay.store.purge(now).expect("purge").blobs, 0);
|
||||
assert_eq!(
|
||||
relay.fetch(&m, &m.fetch).await.1.len(),
|
||||
1,
|
||||
"kept an hour before 30 days"
|
||||
);
|
||||
|
||||
relay.advance(2 * 3600);
|
||||
let now = relay.now.load(Ordering::SeqCst);
|
||||
assert_eq!(relay.store.purge(now).expect("purge").blobs, 1);
|
||||
assert!(
|
||||
relay.fetch(&m, &m.fetch).await.1.is_empty(),
|
||||
"gone an hour after 30 days"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_fetch_returns_at_most_a_hundred_oldest_first() {
|
||||
let relay = Relay::in_memory();
|
||||
let m = Mailbox::new();
|
||||
relay.create(&m).await;
|
||||
for i in 0..105u8 {
|
||||
relay.post(&m, &m.post, &[i]).await;
|
||||
}
|
||||
let (_, blobs) = relay.fetch(&m, &m.fetch).await;
|
||||
assert_eq!(blobs.len(), MAX_BLOBS_PER_FETCH);
|
||||
assert_eq!(blobs[0].blob.bytes(), &[0]);
|
||||
assert_eq!(blobs[99].blob.bytes(), &[99]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_blob_over_256_kib_is_refused() {
|
||||
let relay = Relay::in_memory();
|
||||
let m = Mailbox::new();
|
||||
relay.create(&m).await;
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &vec![1; MAX_BLOB_BYTES]).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &vec![1; MAX_BLOB_BYTES + 1]).await,
|
||||
StatusCode::PAYLOAD_TOO_LARGE
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bad_body_is_a_bare_400() {
|
||||
let relay = Relay::in_memory();
|
||||
let (s, body) = relay
|
||||
.call(
|
||||
Method::POST,
|
||||
"/v0/mailboxes",
|
||||
None,
|
||||
br#"{"id":"Eva","name":"Eva"}"#.to_vec(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::BAD_REQUEST);
|
||||
assert!(body.is_empty(), "nothing of the request comes back");
|
||||
}
|
||||
|
||||
fn invite_body(id: &InviteId, secret: &Token, kp: &[u8]) -> Vec<u8> {
|
||||
serde_json::to_vec(&CreateInvite {
|
||||
id: *id,
|
||||
secret_hash: secret.hash(),
|
||||
key_package: KeyPackageBytes::new(kp.to_vec()).expect("small"),
|
||||
})
|
||||
.expect("json")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_invite_is_claimed_once_with_its_secret_only() {
|
||||
let relay = Relay::in_memory();
|
||||
let id = InviteId::from_bytes(random());
|
||||
let secret = Token::from_bytes(random());
|
||||
let (s, _) = relay
|
||||
.call(
|
||||
Method::POST,
|
||||
"/v0/invites",
|
||||
None,
|
||||
invite_body(&id, &secret, b"key package"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::CREATED);
|
||||
let path = format!("/v0/invites/{}", id.to_wire());
|
||||
|
||||
let (s, _) = relay
|
||||
.call(
|
||||
Method::GET,
|
||||
&path,
|
||||
Some(&Token::from_bytes(random())),
|
||||
vec![],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND, "wrong secret");
|
||||
let (s, body) = relay.call(Method::GET, &path, Some(&secret), vec![]).await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
let claimed: ClaimedInvite = serde_json::from_slice(&body).expect("invite");
|
||||
assert_eq!(claimed.key_package.bytes(), b"key package");
|
||||
let (s, _) = relay.call(Method::GET, &path, Some(&secret), vec![]).await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND, "one time only");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_invite_expires_after_7_days() {
|
||||
let relay = Relay::in_memory();
|
||||
let id = InviteId::from_bytes(random());
|
||||
let secret = Token::from_bytes(random());
|
||||
relay
|
||||
.call(
|
||||
Method::POST,
|
||||
"/v0/invites",
|
||||
None,
|
||||
invite_body(&id, &secret, b"kp"),
|
||||
)
|
||||
.await;
|
||||
let path = format!("/v0/invites/{}", id.to_wire());
|
||||
|
||||
relay.advance(INVITE_TTL_SECS + 2 * 3600);
|
||||
let (s, _) = relay.call(Method::GET, &path, Some(&secret), vec![]).await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND, "expired, even before a purge");
|
||||
let now = relay.now.load(Ordering::SeqCst);
|
||||
assert_eq!(relay.store.purge(now).expect("purge").invites, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invite_is_still_good_just_before_7_days() {
|
||||
let store = Store::open_in_memory().expect("store");
|
||||
let id = InviteId::from_bytes(random());
|
||||
let secret = Token::from_bytes(random());
|
||||
let req = CreateInvite {
|
||||
id,
|
||||
secret_hash: secret.hash(),
|
||||
key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"),
|
||||
};
|
||||
store.create_invite(&req, T0).expect("created");
|
||||
assert!(store
|
||||
.claim_invite(&id, &secret, T0 + INVITE_TTL_SECS - 1)
|
||||
.is_ok());
|
||||
assert_eq!(
|
||||
store
|
||||
.claim_invite(&id, &secret, T0)
|
||||
.expect_err("claimed already"),
|
||||
Refused::NotFound,
|
||||
"claimed already"
|
||||
);
|
||||
}
|
||||
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
/// Sends one raw HTTP/1.1 request over a real TCP connection from 127.0.0.1.
|
||||
fn raw_http(addr: std::net::SocketAddr, request: &str, body: &[u8]) -> String {
|
||||
let mut s = std::net::TcpStream::connect(addr).expect("connect");
|
||||
s.write_all(request.as_bytes()).expect("write");
|
||||
s.write_all(body).expect("write body");
|
||||
let mut out = String::new();
|
||||
s.read_to_string(&mut out).expect("read");
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn no_token_secret_or_address_reaches_the_database() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let db = dir.path().join("relay.db");
|
||||
let relay = Relay::with(Store::open(&db).expect("store"));
|
||||
|
||||
// Over real TCP, so the server has a client address it could have stored.
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind");
|
||||
let addr = listener.local_addr().expect("addr");
|
||||
let app = relay.app.clone();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await });
|
||||
|
||||
let m = Mailbox::new();
|
||||
let invite = InviteId::from_bytes(random());
|
||||
let secret = Token::from_bytes(random());
|
||||
let new_post = Token::from_bytes(random());
|
||||
let steps: Vec<(String, Vec<u8>)> = vec![
|
||||
("POST /v0/mailboxes".into(), m.create_body().into_bytes()),
|
||||
(
|
||||
format!("POST {} {}", m.blobs_path(), m.post.to_bearer()),
|
||||
b"ciphertext".to_vec(),
|
||||
),
|
||||
(
|
||||
format!("GET {} {}", m.blobs_path(), m.fetch.to_bearer()),
|
||||
vec![],
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"PUT /v0/mailboxes/{}/post-token {}",
|
||||
m.id.to_wire(),
|
||||
m.fetch.to_bearer()
|
||||
),
|
||||
serde_json::to_vec(&RotatePostToken {
|
||||
post_token_hash: new_post.hash(),
|
||||
})
|
||||
.expect("json"),
|
||||
),
|
||||
(
|
||||
"POST /v0/invites".into(),
|
||||
invite_body(&invite, &secret, b"kp"),
|
||||
),
|
||||
];
|
||||
for (line, body) in steps {
|
||||
let mut parts = line.splitn(3, ' ');
|
||||
let (method, path, auth) = (
|
||||
parts.next().unwrap_or(""),
|
||||
parts.next().unwrap_or(""),
|
||||
parts.next(),
|
||||
);
|
||||
let auth_header = auth
|
||||
.map(|a| format!("Authorization: {a}\r\n"))
|
||||
.unwrap_or_default();
|
||||
let req = format!(
|
||||
"{method} {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nUser-Agent: canary-agent/1.0\r\n{auth_header}Content-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
);
|
||||
let resp = raw_http(addr, &req, &body);
|
||||
assert!(
|
||||
resp.starts_with("HTTP/1.1 2"),
|
||||
"{method} {path}: {}",
|
||||
resp.lines().next().unwrap_or("")
|
||||
);
|
||||
}
|
||||
server.abort();
|
||||
drop(relay);
|
||||
|
||||
let bytes = std::fs::read(&db).expect("db file");
|
||||
for (what, needle) in [
|
||||
("post token", m.post.as_bytes().to_vec()),
|
||||
("fetch token", m.fetch.as_bytes().to_vec()),
|
||||
("new post token", new_post.as_bytes().to_vec()),
|
||||
("invite secret", secret.as_bytes().to_vec()),
|
||||
("post token, base64url", m.post.to_wire().into_bytes()),
|
||||
("fetch token, base64url", m.fetch.to_wire().into_bytes()),
|
||||
("client address", b"127.0.0.1".to_vec()),
|
||||
(
|
||||
"client address, binary",
|
||||
vec![127, 0, 0, 1, (addr.port() >> 8) as u8],
|
||||
),
|
||||
("user agent", b"canary-agent".to_vec()),
|
||||
] {
|
||||
assert!(
|
||||
!contains(&bytes, &needle),
|
||||
"{what} found in the database file"
|
||||
);
|
||||
}
|
||||
// What should be there is there: the hash, not the token.
|
||||
assert!(
|
||||
contains(&bytes, m.fetch.hash().as_bytes()),
|
||||
"the fetch token's hash is stored"
|
||||
);
|
||||
let others: Vec<_> = std::fs::read_dir(dir.path())
|
||||
.expect("dir")
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
others.len(),
|
||||
1,
|
||||
"no -wal or -journal file left beside the database: {others:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_blob_is_not_left_in_the_file() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let db = dir.path().join("relay.db");
|
||||
let store = Store::open(&db).expect("store");
|
||||
let m = Mailbox::new();
|
||||
store
|
||||
.create_mailbox(
|
||||
&CreateMailbox {
|
||||
id: m.id,
|
||||
post_token_hash: m.post.hash(),
|
||||
fetch_token_hash: m.fetch.hash(),
|
||||
},
|
||||
T0,
|
||||
)
|
||||
.expect("mailbox");
|
||||
let marker: Vec<u8> = b"DELETED-BLOB-MARKER-"
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(random::<16>())
|
||||
.collect();
|
||||
let aged: Vec<u8> = b"AGED-BLOB-MARKER-"
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(random::<16>())
|
||||
.collect();
|
||||
store.post(&m.id, &m.post, &marker, T0).expect("post");
|
||||
store.post(&m.id, &m.post, &aged, T0).expect("post");
|
||||
store
|
||||
.acknowledge(&m.id, &m.fetch, &blob_hash(&marker))
|
||||
.expect("ack");
|
||||
store.purge(T0 + BLOB_TTL_SECS + 7200).expect("purge");
|
||||
drop(store);
|
||||
let bytes = std::fs::read(&db).expect("db file");
|
||||
assert!(
|
||||
!contains(&bytes, &marker),
|
||||
"an acknowledged blob's bytes stay in the file"
|
||||
);
|
||||
assert!(
|
||||
!contains(&bytes, &aged),
|
||||
"a purged blob's bytes stay in the file"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_relay_listens_on_loopback_unless_told_otherwise() {
|
||||
let args = parse_args(Vec::<String>::new()).expect("defaults");
|
||||
assert_eq!(args.listen.to_string(), DEFAULT_LISTEN);
|
||||
assert!(args.listen.ip().is_loopback());
|
||||
assert!(parse_args(["--listen".to_string()]).is_err());
|
||||
assert!(parse_args(["--verbose".to_string()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_binary_serves_its_version_and_prints_no_request() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_tabellarius-relay"))
|
||||
.args(["--listen", "127.0.0.1:0", "--db"])
|
||||
.arg(dir.path().join("relay.db"))
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn");
|
||||
let mut stdout = child.stdout.take().expect("stdout");
|
||||
// The one start line: "... listening on 127.0.0.1:<port>\n"
|
||||
let mut line = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
while stdout.read(&mut byte).expect("read") == 1 && byte[0] != b'\n' {
|
||||
line.push(byte[0]);
|
||||
}
|
||||
let line = String::from_utf8(line).expect("utf8");
|
||||
let addr: std::net::SocketAddr = line
|
||||
.rsplit(' ')
|
||||
.next()
|
||||
.and_then(|a| a.parse().ok())
|
||||
.expect("address in the start line");
|
||||
assert!(addr.ip().is_loopback(), "{line}");
|
||||
|
||||
let resp = raw_http(
|
||||
addr,
|
||||
"GET /version HTTP/1.1\r\nHost: x\r\nUser-Agent: canary-agent/1.0\r\nConnection: close\r\n\r\n",
|
||||
&[],
|
||||
);
|
||||
assert!(resp.starts_with("HTTP/1.1 200"), "{resp}");
|
||||
assert!(resp.contains("\"protocol\":\"v0\""), "{resp}");
|
||||
|
||||
child.kill().expect("kill");
|
||||
let mut rest = String::new();
|
||||
stdout.read_to_string(&mut rest).expect("stdout");
|
||||
let mut err = String::new();
|
||||
child
|
||||
.stderr
|
||||
.take()
|
||||
.expect("stderr")
|
||||
.read_to_string(&mut err)
|
||||
.expect("stderr");
|
||||
let _ = child.wait();
|
||||
assert!(
|
||||
rest.is_empty() && err.is_empty(),
|
||||
"the relay printed after start: {rest:?} {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Random bodies, paths and headers at every route: a 4xx or a success, never a 500 or a panic.
|
||||
#[tokio::test]
|
||||
async fn no_random_request_breaks_the_relay() {
|
||||
let relay = Relay::in_memory();
|
||||
let m = Mailbox::new();
|
||||
relay.create(&m).await;
|
||||
let routes = [
|
||||
(Method::POST, "/v0/mailboxes".to_string()),
|
||||
(Method::POST, m.blobs_path()),
|
||||
(Method::GET, m.blobs_path()),
|
||||
(
|
||||
Method::PUT,
|
||||
format!("/v0/mailboxes/{}/post-token", m.id.to_wire()),
|
||||
),
|
||||
(Method::POST, "/v0/invites".to_string()),
|
||||
(
|
||||
Method::GET,
|
||||
format!("/v0/invites/{}", InviteId::from_bytes(random()).to_wire()),
|
||||
),
|
||||
];
|
||||
for i in 0..3000usize {
|
||||
let len = random::<1>()[0] as usize * (1 + i % 4);
|
||||
let mut body = vec![0u8; len];
|
||||
getrandom::fill(&mut body).expect("randomness");
|
||||
if i % 3 == 0 {
|
||||
// JSON-shaped noise reaches deeper into the parsers than raw bytes.
|
||||
body = format!(
|
||||
"{{\"id\":\"{}\",\"postTokenHash\":{},\"keyPackage\":\"{}\"}}",
|
||||
String::from_utf8_lossy(&body[..len.min(30)]),
|
||||
len,
|
||||
"A".repeat(len)
|
||||
)
|
||||
.into_bytes();
|
||||
}
|
||||
let (method, path) = &routes[i % routes.len()];
|
||||
let token = if i % 2 == 0 { Some(&m.fetch) } else { None };
|
||||
let (status, _) = relay.call(method.clone(), path, token, body).await;
|
||||
assert!(
|
||||
!status.is_server_error(),
|
||||
"{method} {path} answered {status}"
|
||||
);
|
||||
}
|
||||
// Garbage paths too.
|
||||
for _ in 0..500 {
|
||||
let id: String = random::<12>()
|
||||
.iter()
|
||||
.map(|b| (b'A' + b % 26) as char)
|
||||
.collect();
|
||||
let (status, _) = relay
|
||||
.call(
|
||||
Method::GET,
|
||||
&format!("/v0/mailboxes/{id}/blobs"),
|
||||
Some(&m.fetch),
|
||||
vec![],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# Running the relay on NixOS
|
||||
|
||||
The relay listens on `127.0.0.1` only. Caddy sits in front with TLS from Let's Encrypt, and writes
|
||||
no log that holds an address (`.agents/features/home-relay.md`).
|
||||
|
||||
## 1. Before
|
||||
- A DNS name for the relay (an `A` and/or `AAAA` record) pointing at the machine.
|
||||
- Ports **80** and **443** reachable from the internet. 80 is for Let's Encrypt's challenge; Caddy
|
||||
redirects everything else on it to 443.
|
||||
|
||||
## 2. The configuration
|
||||
In the machine's flake:
|
||||
```nix
|
||||
{
|
||||
inputs.tabellarius.url = "git+https://gitea.marek-novak.cz/mnovak/Amicitia-Tabellarius?ref=main";
|
||||
|
||||
outputs = { nixpkgs, tabellarius, ... }: {
|
||||
nixosConfigurations.home = nixpkgs.lib.nixosSystem {
|
||||
system = "x86_64-linux";
|
||||
modules = [
|
||||
tabellarius.nixosModules.default
|
||||
{
|
||||
services.tabellarius = {
|
||||
enable = true;
|
||||
domain = "relay.example.cz";
|
||||
# Optional, the defaults shown:
|
||||
# maxBytes = 1073741824; maxMailboxes = 100000; maxInvites = 10000;
|
||||
};
|
||||
}
|
||||
./configuration.nix
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
Pin `tabellarius` in `flake.lock`, as for any input. Then `nixos-rebuild switch --flake .#home`.
|
||||
|
||||
## 3. What it sets up
|
||||
| Part | What it does |
|
||||
|:--|:--|
|
||||
| `tabellarius.service` | `--listen 127.0.0.1:8470`, its database in `/var/lib/private/tabellarius`, a dynamic user, and a systemd sandbox. It may talk to localhost only (`IPAddressAllow=localhost`) |
|
||||
| Caddy | one virtual host, `reverse_proxy` to the relay. No access log, no error log. `X-Forwarded-For`, `X-Real-IP` and `Forwarded` are removed, so the relay never learns who connected |
|
||||
| Firewall | 80 and 443 open. `logRefusedConnections` off by default: a relay that keeps no address keeps no stranger's either |
|
||||
|
||||
## 4. Check it
|
||||
- From another machine: `curl https://relay.example.cz/version` answers with the versions.
|
||||
- On the server, after some use, the address of the machine you used must appear nowhere:
|
||||
`journalctl -o verbose | grep -F <that address>` and `grep -rF <that address> /var/log` find
|
||||
nothing.
|
||||
- The same check runs automatically in a VM: `nix flake check` in this repository (Linux, KVM).
|
||||
|
||||
> **Not run yet (2026-11-16).** This module and its VM test were written on a machine without Nix
|
||||
> and have never been evaluated. Until `nix flake check` passes on Linux, and the check above is
|
||||
> done on the real server, *Caddy keeps no address* is the design, not a tested fact.
|
||||
|
||||
## 5. In the app
|
||||
Settings → *Your message relay*: `https://relay.example.cz`. Until the app accepts `https://`
|
||||
addresses (Amicitia F23), it takes a loopback address only.
|
||||
|
||||
## 6. What the operator still sees
|
||||
Caddy and the relay keep nothing, but the machine's network still carries the connections while
|
||||
they happen. A router or ISP log, or `tcpdump` on the server, would show addresses and timing
|
||||
(`docs/PROTOCOL.md` §1). Turning Caddy's log on, even for a while, writes addresses. Do it only
|
||||
knowing that.
|
||||
@@ -0,0 +1,142 @@
|
||||
# The Tabellarius relay on NixOS, behind Caddy with TLS, and no log that holds an address
|
||||
# (.agents/features/home-relay.md). Import it from the flake: `tabellarius.nixosModules.default`.
|
||||
#
|
||||
# services.tabellarius = {
|
||||
# enable = true;
|
||||
# domain = "relay.example.cz"; # its DNS name points at this machine; ports 80 and 443 open
|
||||
# };
|
||||
{ self }:
|
||||
{ config, lib, pkgs, ... }:
|
||||
let
|
||||
cfg = config.services.tabellarius;
|
||||
system = pkgs.stdenv.hostPlatform.system;
|
||||
in
|
||||
{
|
||||
options.services.tabellarius = {
|
||||
enable = lib.mkEnableOption "the Tabellarius message relay, behind Caddy with TLS and no logs";
|
||||
|
||||
domain = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
example = "relay.example.cz";
|
||||
description = "The relay's DNS name. Caddy gets its certificate from Let's Encrypt.";
|
||||
};
|
||||
|
||||
package = lib.mkOption {
|
||||
type = lib.types.package;
|
||||
default = self.packages.${system}.default;
|
||||
defaultText = lib.literalExpression "tabellarius.packages.\${system}.default";
|
||||
description = "The relay, built from this flake: the code that runs is the code published.";
|
||||
};
|
||||
|
||||
port = lib.mkOption {
|
||||
type = lib.types.port;
|
||||
default = 8470;
|
||||
description = "The loopback port between Caddy and the relay. Never exposed.";
|
||||
};
|
||||
|
||||
maxBytes = lib.mkOption {
|
||||
type = lib.types.ints.positive;
|
||||
default = 1073741824;
|
||||
description = "Waiting blobs the relay holds, in bytes, before it answers 507 (PROTOCOL.md section 8).";
|
||||
};
|
||||
|
||||
maxMailboxes = lib.mkOption {
|
||||
type = lib.types.ints.positive;
|
||||
default = 100000;
|
||||
description = "Mailboxes the relay holds before it answers 507.";
|
||||
};
|
||||
|
||||
maxInvites = lib.mkOption {
|
||||
type = lib.types.ints.positive;
|
||||
default = 10000;
|
||||
description = "Unclaimed invites the relay holds before it answers 507.";
|
||||
};
|
||||
|
||||
openFirewall = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = "Open ports 80 (the ACME challenge, then a redirect) and 443.";
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
systemd.services.tabellarius = {
|
||||
description = "Tabellarius message relay (loopback only; Caddy in front)";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "network.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = lib.escapeShellArgs [
|
||||
"${cfg.package}/bin/tabellarius-relay"
|
||||
"--listen" "127.0.0.1:${toString cfg.port}"
|
||||
"--db" "/var/lib/tabellarius/relay.db"
|
||||
"--max-bytes" (toString cfg.maxBytes)
|
||||
"--max-mailboxes" (toString cfg.maxMailboxes)
|
||||
"--max-invites" (toString cfg.maxInvites)
|
||||
];
|
||||
Restart = "on-failure";
|
||||
DynamicUser = true;
|
||||
StateDirectory = "tabellarius";
|
||||
StateDirectoryMode = "0700";
|
||||
UMask = "0077";
|
||||
|
||||
# It talks to Caddy on loopback and to nothing else, even if it had a bug.
|
||||
IPAddressDeny = "any";
|
||||
IPAddressAllow = "localhost";
|
||||
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
|
||||
|
||||
CapabilityBoundingSet = "";
|
||||
NoNewPrivileges = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
PrivateTmp = true;
|
||||
PrivateDevices = true;
|
||||
PrivateUsers = true;
|
||||
ProtectHostname = true;
|
||||
ProtectClock = true;
|
||||
ProtectKernelTunables = true;
|
||||
ProtectKernelModules = true;
|
||||
ProtectKernelLogs = true;
|
||||
ProtectControlGroups = true;
|
||||
ProtectProc = "invisible";
|
||||
ProcSubset = "pid";
|
||||
RestrictNamespaces = true;
|
||||
RestrictRealtime = true;
|
||||
RestrictSUIDSGID = true;
|
||||
RemoveIPC = true;
|
||||
LockPersonality = true;
|
||||
MemoryDenyWriteExecute = true;
|
||||
SystemCallArchitectures = "native";
|
||||
SystemCallFilter = [ "@system-service" "~@privileged" ];
|
||||
};
|
||||
};
|
||||
|
||||
services.caddy = {
|
||||
enable = true;
|
||||
# Caddy's own logger: errors about TLS handshakes or upstreams can name a client's address.
|
||||
# No log is the rule; an operator who needs one turns it on for a while, knowing why.
|
||||
logFormat = ''
|
||||
output discard
|
||||
'';
|
||||
virtualHosts.${cfg.domain} = {
|
||||
# The NixOS module writes an access log per host by default; this one writes none.
|
||||
logFormat = ''
|
||||
output discard
|
||||
'';
|
||||
extraConfig = ''
|
||||
reverse_proxy 127.0.0.1:${toString cfg.port} {
|
||||
# The relay never learns who connected: Caddy adds these by default.
|
||||
header_up -X-Forwarded-For
|
||||
header_up -X-Real-IP
|
||||
header_up -Forwarded
|
||||
}
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ 80 443 ];
|
||||
# NixOS logs every refused connection with its source address by default. Those are strangers,
|
||||
# not users, but a relay that keeps no address should not keep theirs either. mkDefault: the
|
||||
# machine's owner can turn it back on.
|
||||
networking.firewall.logRefusedConnections = lib.mkDefault false;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# `nix flake check` (Linux, KVM): two machines. `server` runs the module; `client` talks to it
|
||||
# through Caddy with TLS, does everything the protocol allows and some things it refuses, fills a
|
||||
# mailbox cap to its 507, and then the test fails if the client's address appears anywhere in the
|
||||
# server's journal or under /var/log, or in the relay's database (.agents/features/home-relay.md).
|
||||
{ self, pkgs }:
|
||||
pkgs.testers.runNixOSTest {
|
||||
name = "tabellarius-relay-keeps-no-address";
|
||||
|
||||
nodes.server = { lib, ... }: {
|
||||
imports = [ self.nixosModules.default ];
|
||||
services.tabellarius = {
|
||||
enable = true;
|
||||
domain = "relay.test";
|
||||
maxMailboxes = 3;
|
||||
};
|
||||
# No Let's Encrypt inside a VM: Caddy's own CA instead.
|
||||
services.caddy.virtualHosts."relay.test".extraConfig = lib.mkBefore "tls internal";
|
||||
};
|
||||
|
||||
nodes.client = { pkgs, ... }: {
|
||||
environment.systemPackages = [ pkgs.curl pkgs.python3 ];
|
||||
};
|
||||
|
||||
testScript = ''
|
||||
import base64, hashlib, json, os
|
||||
|
||||
def b64(raw):
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
||||
|
||||
start_all()
|
||||
server.wait_for_unit("tabellarius.service")
|
||||
server.wait_for_unit("caddy.service")
|
||||
server.wait_for_open_port(443)
|
||||
client.wait_for_unit("multi-user.target")
|
||||
|
||||
client_ip = client.succeed("ip -4 -o addr show dev eth1 | awk '{print $4}' | cut -d/ -f1").strip()
|
||||
server_ip = server.succeed("ip -4 -o addr show dev eth1 | awk '{print $4}' | cut -d/ -f1").strip()
|
||||
assert client_ip and server_ip and client_ip != server_ip, (client_ip, server_ip)
|
||||
|
||||
def call(method, path, token=None, body=None, json_body=False):
|
||||
cmd = ["curl", "-sk", "-o", "/dev/null", "-w", "%{http_code}",
|
||||
"--resolve", "relay.test:443:" + server_ip, "-X", method]
|
||||
if token:
|
||||
cmd += ["-H", "Authorization: Bearer " + token]
|
||||
if body is not None:
|
||||
client.succeed("cat > /tmp/body <<'EOF'\n" + body + "\nEOF")
|
||||
client.succeed("truncate -s -1 /tmp/body")
|
||||
cmd += ["--data-binary", "@/tmp/body"]
|
||||
if json_body:
|
||||
cmd += ["-H", "Content-Type: application/json"]
|
||||
cmd.append("https://relay.test" + path)
|
||||
return client.succeed(" ".join("'" + c + "'" for c in cmd)).strip()
|
||||
|
||||
def mailbox():
|
||||
mid, post, fetch = os.urandom(16), os.urandom(32), os.urandom(32)
|
||||
body = json.dumps({"id": b64(mid), "postTokenHash": b64(hashlib.sha256(post).digest()),
|
||||
"fetchTokenHash": b64(hashlib.sha256(fetch).digest())})
|
||||
return b64(mid), b64(post), b64(fetch), body
|
||||
|
||||
assert call("GET", "/version") == "200"
|
||||
mid, post, fetch, body = mailbox()
|
||||
assert call("POST", "/v0/mailboxes", body=body, json_body=True) == "201"
|
||||
blob = "sealed-envelope-for-the-test"
|
||||
assert call("POST", "/v0/mailboxes/" + mid + "/blobs", token=post, body=blob) == "201"
|
||||
assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=fetch) == "200"
|
||||
digest = b64(hashlib.sha256(blob.encode()).digest())
|
||||
assert call("DELETE", "/v0/mailboxes/" + mid + "/blobs/" + digest, token=fetch) == "204"
|
||||
# Refusals: a wrong token, a malformed id, a body that is not JSON.
|
||||
assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=b64(os.urandom(32))) == "404"
|
||||
assert call("GET", "/v0/mailboxes/nonsense/blobs", token=fetch) == "404"
|
||||
assert call("POST", "/v0/mailboxes", body="not json", json_body=True) == "400"
|
||||
# The cap: three mailboxes, then 507.
|
||||
for _ in range(2):
|
||||
assert call("POST", "/v0/mailboxes", body=mailbox()[3], json_body=True) == "201"
|
||||
assert call("POST", "/v0/mailboxes", body=mailbox()[3], json_body=True) == "507"
|
||||
|
||||
# Nowhere on the server: not in the journal, not under /var/log, not in the relay's data.
|
||||
server.succeed("journalctl --sync")
|
||||
server.fail("journalctl --no-pager -o verbose | grep -F '" + client_ip + "'")
|
||||
server.fail("grep -rF '" + client_ip + "' /var/log /var/lib/private/tabellarius")
|
||||
'';
|
||||
}
|
||||
+60
-5
@@ -1,7 +1,8 @@
|
||||
# Tabellarius protocol v0 — what crosses the wire, and what the relay learns
|
||||
|
||||
**Approved 2026-11-08 (Mark)** as v0, before any relay code. Every claim below must have a test. A change
|
||||
is a protocol version bump: documented, reviewed, approved (`CLAUDE.md` §2.2).
|
||||
is a protocol version bump: documented here with its date and reason, and reviewed in its PR
|
||||
(`CLAUDE.md` §2.2, §3).
|
||||
|
||||
## 1. Threat model
|
||||
| Adversary | Protected | Not protected |
|
||||
@@ -27,10 +28,36 @@ is a protocol version bump: documented, reviewed, approved (`CLAUDE.md` §2.2).
|
||||
- **Block** = the owner rotates the post token; the old one is refused. The blocked person is not told.
|
||||
|
||||
## 4. Invitations
|
||||
A QR code (in person) or a link carries: relay URL, an invite id, and a one-time fetch secret. The
|
||||
invitee fetches the inviter's MLS KeyPackage from the relay with it, replies with their own, and
|
||||
both sides exchange mailbox ids and post tokens **inside** MLS. Unclaimed invites expire after
|
||||
**7 days** *(decided 2026-11-08)*.
|
||||
A QR code (in person) or a link carries: relay URL, an invite id, and a one-time secret. Unclaimed
|
||||
invites expire after **7 days** *(decided 2026-11-08)*.
|
||||
1. **The inviter** leaves its MLS KeyPackage on the relay under the invite id and the secret's hash.
|
||||
It also creates a **welcome mailbox**, whose id and post token are derived from the secret with
|
||||
HKDF-SHA256: empty salt, info `tabellarius v0 welcome mailbox` (16 bytes) and
|
||||
`tabellarius v0 welcome mailbox post` (32 bytes).
|
||||
2. **The invitee** claims the KeyPackage with the secret, which deletes the invite. It creates the
|
||||
MLS group with the inviter in it, and posts to the welcome mailbox:
|
||||
- the Welcome;
|
||||
- an MLS message carrying its own mailbox id, a post token for it, and its name.
|
||||
3. **The inviter** joins from the Welcome and answers inside MLS with its own mailbox, post token and
|
||||
name.
|
||||
|
||||
From then on each side posts to the other's mailbox. Names and post tokens travel **only inside
|
||||
MLS**. To the relay, the welcome mailbox is an ordinary mailbox.
|
||||
*(Changed 2026-11-14, approved by Mark, from "the invitee replies with their own KeyPackage": the
|
||||
invitee needs no KeyPackage, because it creates the group itself.)*
|
||||
|
||||
### Payloads inside MLS *(added 2026-11-17, F24; `.agents/features/block-and-receipts.md`)*
|
||||
Every MLS application message carries one JSON object. The relay sees none of it.
|
||||
| `kind` | Fields | Meaning |
|
||||
|:--|:--|:--|
|
||||
| `hello` | `mailbox`, `postToken`, `name` | where and how to post to the sender; once per conversation |
|
||||
| `text` | `body`, `seq` | a message; `seq` counts the sender's texts to this contact from 1 |
|
||||
| `receipt` | `upto` | the receiver has saved the sender's texts up to `upto`. Sent only by a client with receipts on; a client with them off also ignores them |
|
||||
| `inbox` | `postToken` | a new post token for the mailbox the receiver already knows (after an unblock). It cannot name another mailbox |
|
||||
|
||||
**Block** (§3) is a rotate of the post token to the hash of a token nobody gets. Nothing is sent to
|
||||
the blocked person: their posts get §8's ordinary 404. What they posted before is fetched and
|
||||
dropped. **Unblock** rotates again and sends the new token in an `inbox` payload.
|
||||
|
||||
## 5. What the relay stores — the complete list
|
||||
| Table | Columns |
|
||||
@@ -61,3 +88,31 @@ The platform facts above are Claude's understanding, to be verified in `.agents/
|
||||
- A delivered blob is gone; an undelivered blob is gone after the TTL (clock injected).
|
||||
- Parsers are fuzzed (`cargo fuzz`) for every message type.
|
||||
- Every check in `VERIFY.md` §1 has a CI job or a documented manual procedure.
|
||||
|
||||
## 8. The wire (v0) — approved 2026-11-08, routes added 2026-11-14, quotas 2026-11-16
|
||||
HTTP/1.1 behind TLS (the reverse proxy, F23). Ids and tokens are unpadded base64url of a fixed length
|
||||
with one canonical spelling: ids are 16 bytes, and tokens and hashes are 32. JSON bodies refuse
|
||||
unknown fields. A blob is at most 256 KiB, and a KeyPackage at most 16 KiB.
|
||||
|
||||
| Method and path | Auth (`Authorization: Bearer`) | Effect |
|
||||
|:--|:--|:--|
|
||||
| `POST /v0/mailboxes` `{id, postTokenHash, fetchTokenHash}` | none | creates a mailbox. The owner sends **hashes**, so the relay never holds a token |
|
||||
| `POST /v0/mailboxes/{id}/blobs` (bytes) | post token | stores the blob with its size and the hour it arrived |
|
||||
| `GET /v0/mailboxes/{id}/blobs` | fetch token | the waiting blobs, oldest first, at most 100. Fetching deletes nothing |
|
||||
| `DELETE /v0/mailboxes/{id}/blobs/{sha256}` | fetch token | acknowledges: deletes that mailbox's blob with this SHA-256. §5 has no blob id, and a sequential id would leak how busy the relay is |
|
||||
| `PUT /v0/mailboxes/{id}/post-token` `{postTokenHash}` | fetch token | blocks: the old post token is refused from now on |
|
||||
| `POST /v0/invites` `{id, secretHash, keyPackage}` | none | stores an invite. It expires after 7 days, rounded up to the hour |
|
||||
| `GET /v0/invites/{id}` | invite secret | returns the KeyPackage once, then deletes the invite |
|
||||
| `GET /version` | none | the protocol and relay versions |
|
||||
|
||||
- A wrong token, an unknown id and a malformed id all give the same bare **404**, so nobody can probe
|
||||
what exists.
|
||||
- **Quotas** *(added 2026-11-16, F23, so a relay can face the internet; `.agents/features/home-relay.md`)*:
|
||||
a mailbox holds at most **1 000 waiting blobs** and **32 MiB**, and a relay at most what its
|
||||
operator sets (by default 1 GiB of blobs, 100 000 mailboxes, 10 000 unclaimed invites). Over a
|
||||
limit the answer is a bare **507**. The per-mailbox caps are checked only after the post token,
|
||||
so a 507 tells a stranger nothing about a mailbox. Nothing new is stored to count: the counts
|
||||
come from §5's own rows and `size`. A client treats 507 like any failure and tries again later.
|
||||
- A refusal has no body.
|
||||
- The relay prints no request.
|
||||
- Tests: `crates/relay/tests/relay.rs`, `crates/protocol/tests/wire.rs`.
|
||||
|
||||
@@ -21,6 +21,13 @@
|
||||
};
|
||||
});
|
||||
|
||||
# The relay on NixOS: loopback only, behind Caddy with TLS and no logs (deploy/nixos).
|
||||
nixosModules.default = import ./deploy/nixos/module.nix { inherit self; };
|
||||
|
||||
# A VM test that the server keeps no client address anywhere (needs Linux and KVM).
|
||||
checks.x86_64-linux.relay-keeps-no-address =
|
||||
import ./deploy/nixos/test.nix { inherit self; pkgs = nixpkgs.legacyPackages.x86_64-linux; };
|
||||
|
||||
devShells = forAll (pkgs: {
|
||||
default = pkgs.mkShell {
|
||||
packages = with pkgs; [ cargo rustc clippy rustfmt ];
|
||||
|
||||
Reference in New Issue
Block a user