Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3a0944ebff | |||
| 4d0dac0591 | |||
| d24e4f4f53 | |||
| 65f56e306c | |||
| 056a68de17 | |||
| abb0a87471 | |||
| 9d9d63c02b | |||
| 1d7f08927d | |||
| f852b1a6d1 | |||
| f075fae0e3 | |||
| 1ccae752d7 | |||
| dff1bec275 | |||
| cfabc97d20 | |||
| 0e6be38280 |
@@ -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,205 @@
|
||||
# Files — a relay route for encrypted chunks, and a `file` payload (`PROTOCOL.md` §4, §5, §7, §8)
|
||||
|
||||
Amicitia F29, step 4 of its full-chat plan (`Amicitia/.agents/features/full-chat.md` §2, §4, §5.5).
|
||||
Unlike F27 and F28 this **changes what the relay stores**: two tables and four routes. Everything
|
||||
readable about a file — its name, its type, its size to the byte, its thumbnail and its key — travels
|
||||
**inside MLS**, in a `file` payload. The relay holds same-size ciphertext chunks under a random id.
|
||||
|
||||
## 1. Why and what
|
||||
A chat people move to sends a photo of the menu, a short video of the kids, a PDF of the tickets. A
|
||||
blob is at most 256 KiB, and a photo is several MiB, so a file cannot ride in a message. It goes to
|
||||
the relay in **chunks**, encrypted on the device with a key that only the message carries.
|
||||
|
||||
So this change adds:
|
||||
1. **The relay's `files` route**: an uploader creates a file (a random id, the hashes of an upload
|
||||
token and a fetch token it made, the number of chunks), puts its chunks with the upload token,
|
||||
and may delete it early; the recipient gets each chunk with the fetch token. Chunks go after 30
|
||||
days, like blobs. A per-file and a relay-wide quota answer 507.
|
||||
2. **The client's chunked encryption**: a fresh key per file, the file padded to whole chunks, every
|
||||
chunk exactly the same size on the wire, each sealed with ChaCha20-Poly1305 in the STREAM
|
||||
construction (the `aead` crate's `StreamBE32`), so a chunk tampered with, swapped, dropped from the
|
||||
end or taken from another file is refused.
|
||||
3. **A `file` payload**, a message that shares the sender's `seq` with `text` and `poll`: the file's
|
||||
id, fetch token and key, its name, type and size, and a small thumbnail.
|
||||
|
||||
## 2. Design
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant A as Anna's app
|
||||
participant C as Client (Anna)
|
||||
participant R as Relay
|
||||
participant D as Client (Ben)
|
||||
participant B as Ben's app
|
||||
A->>C: start_upload(size) → FileUpload (id, tokens, key; no network)
|
||||
A->>A: saves the FileUpload in its outbox
|
||||
C->>R: POST /v0/files {id, uploadTokenHash, fetchTokenHash, chunks}
|
||||
loop every chunk i
|
||||
C->>R: PUT /v0/files/{id}/chunks/{i} (256 000 bytes) — upload token
|
||||
end
|
||||
A->>C: compose_file(ben, &upload, name, mime, thumb) → seq 9
|
||||
C->>R: MLS blob {"kind":"file","seq":9,"file":…,"fetchToken":…,"key":…,"name":…,"mime":…,"size":…,"thumb":…}
|
||||
R->>D: fetch
|
||||
D->>B: Event::File{seq 9, file: FileRef, name, mime, size, thumb}
|
||||
loop every chunk i
|
||||
D->>R: GET /v0/files/{id}/chunks/{i} — fetch token
|
||||
D->>B: open(i) → plaintext, or FileDamaged
|
||||
end
|
||||
```
|
||||
|
||||
### 2.1 Sizes
|
||||
| Constant | Value | Why |
|
||||
|:--|:--|:--|
|
||||
| `FILE_CHUNK_BYTES` | **256 000** ciphertext bytes (250 KiB) | Amicitia's plan (§5.5) and G41: every chunk is this size on the wire, the last one too |
|
||||
| `FILE_CHUNK_PLAIN` | 255 984 | the chunk minus the 16-byte Poly1305 tag |
|
||||
| `MAX_FILE_BYTES` | 100 MiB (104 857 600) | Amicitia's plan (§5.5); *via Arca* for bigger ones later |
|
||||
| `MAX_FILE_CHUNKS` | 410 | ⌈100 MiB / 255 984⌉ |
|
||||
| `MAX_THUMB_BYTES` | 32 KiB | a JPEG; it rides in the MLS blob (base64url ≈ 43 KiB, well under 256 KiB) |
|
||||
| `MAX_FILE_NAME_CHARS` | 255 | what file systems allow |
|
||||
| `MAX_MIME_BYTES` | 127 | RFC 6838's limit on each half, roughly |
|
||||
|
||||
A file of `size` bytes has `chunks = ⌈size / 255 984⌉` chunks. The relay learns `chunks`, i.e. the
|
||||
size **rounded up to 250 KiB**, and nothing finer (G41).
|
||||
|
||||
### 2.2 The encryption
|
||||
- **Key**: 32 random bytes from the provider's randomness, made for this one file and never reused.
|
||||
- **AEAD**: ChaCha20-Poly1305 (RustCrypto `chacha20poly1305` 0.10, already in the tree through
|
||||
`openmls_rust_crypto`), in **STREAM** (`aead::stream::StreamBE32`, Hoang–Reyhanitabar–Rogaway–Vizár):
|
||||
the nonce is a 7-byte prefix (zeros: the key is fresh per file), the chunk's index as a 32-bit
|
||||
big-endian counter, and a byte that is 1 for the last chunk only. So chunk *i* opens only at
|
||||
position *i*, and only the true last chunk opens as last: a reordered, repeated or missing chunk,
|
||||
or a file cut short, fails to open. No associated data: a key belongs to one file.
|
||||
- **Padding**: the file is padded with zero bytes to `chunks × 255 984`; the padding is inside the
|
||||
AEAD. The receiver truncates to `size` and checks the padding is zeros.
|
||||
- **Deterministic**: the same key, index and bytes give the same chunk. An upload interrupted by a
|
||||
crash resumes by putting chunks again; the relay accepts a chunk it already holds when the bytes
|
||||
are the same, and refuses different bytes (409), so a file never changes once a chunk is up.
|
||||
- No cryptography is written here: `StreamBE32` is the `aead` crate's, the cipher RustCrypto's.
|
||||
|
||||
### 2.3 The relay: what it stores (§5) and the routes (§8)
|
||||
| Table | Columns |
|
||||
|:--|:--|
|
||||
| `files` | id, hash(upload token), hash(fetch token), chunks, uploaded hour (rounded) |
|
||||
| `chunks` | file id, index, ciphertext |
|
||||
|
||||
No size column (every chunk is `FILE_CHUNK_BYTES`), no name, no type, no sender, no recipient, **no
|
||||
fetch count**: the relay sees each `GET` as it serves it, and keeps no count of them.
|
||||
|
||||
| Method and path | Auth | Effect |
|
||||
|:--|:--|:--|
|
||||
| `POST /v0/files` `{id, uploadTokenHash, fetchTokenHash, chunks}` | none | creates a file of `chunks` (1–410) chunks. 201; 409 if the id is taken; 400 if `chunks` is out of range; 507 if the relay's file quota would be passed |
|
||||
| `PUT /v0/files/{id}/chunks/{index}` (exactly 256 000 bytes) | upload token | stores chunk `index`. 201; again with the same bytes 201; with other bytes 409; an index at or past `chunks` 507 (the file's quota, after the token); another size 413 |
|
||||
| `GET /v0/files/{id}/chunks/{index}` | fetch token | the chunk's bytes. A chunk not (yet) there is 404, like a wrong token |
|
||||
| `DELETE /v0/files/{id}` | upload token | the uploader deletes the file and its chunks early. 204 |
|
||||
|
||||
- **Uploads only with a token the uploader made**: the relay stores only the hashes it was given at
|
||||
`POST`; a stranger who learns a file id can neither add, replace nor delete a chunk.
|
||||
- **Quotas**: per file, at most its declared chunks, each exactly 256 000 bytes, and at most 410;
|
||||
relay-wide, at most `--max-files` files (default **10 000**) and `--max-file-bytes` reserved
|
||||
(default **4 GiB**), counting each file as `chunks × 256 000` **from the moment it is created**, so
|
||||
an upload under way is never cut off half-way by another. Separate from the blob quota, so files
|
||||
cannot starve messages. Over a limit, a bare **507**. Nothing new is stored to count: `chunks` and
|
||||
the rows are enough.
|
||||
- **Purge** (hourly, with blobs): a file whose uploaded hour is more than 30 days old goes with its
|
||||
chunks; so does a file **still incomplete after 24 hours** (an upload abandoned, or a stranger
|
||||
reserving the quota with files never filled).
|
||||
- 404 for a wrong token, an unknown id, a malformed id or index, as everywhere (§8).
|
||||
- **A refusal has no body** (§8), the 413 of a body over a route's limit included. *(Found while
|
||||
writing this: axum's own 413 carried a text, on the blob and JSON routes too; every route now
|
||||
answers a bare 413, with a test.)*
|
||||
|
||||
### 2.4 The `file` payload (§4)
|
||||
```json
|
||||
{"kind":"file","seq":9,"file":"<22 chars>","fetchToken":"<43>","key":"<43>","name":"Menu.jpg","mime":"image/jpeg","size":2483022,"thumb":"<base64url of a JPEG>"}
|
||||
```
|
||||
- `file` the relay's file id; `fetchToken` the capability to get its chunks; `key` the file key.
|
||||
- `name` 1–255 characters, no control character, no `/` or `\`; `mime` `type/subtype`, 3–127
|
||||
printable ASCII bytes with one `/` and no space; `size` 1 to `MAX_FILE_BYTES`.
|
||||
- `thumb` (optional) at most 32 KiB, and it must start like a JPEG (`FF D8 FF`); otherwise the
|
||||
receiver keeps the file and drops the thumbnail, as a text keeps its words and loses a bad reply.
|
||||
- It shares the sender's one `seq` counter; a receipt covers it; a reply and a reaction can name it.
|
||||
- The relay sees a blob of the usual kind, larger by up to the thumbnail.
|
||||
|
||||
### 2.5 What the receiving client checks
|
||||
| Received | Dropped when | Otherwise |
|
||||
|:--|:--|:--|
|
||||
| `file` | `seq` 0; a name, type or size outside §2.4; the sender is blocked | `Event::File`, its `seq` counts like a text's; a thumbnail that is too big or not a JPEG is left out |
|
||||
| a chunk | it is not 256 000 bytes, does not open at its index (or as the last), or the padding is not zeros | `ClientError::FileDamaged`: the app says the file could not be opened and offers to try again |
|
||||
Sending checks the same and refuses with `ClientError::BadFile` (a name, type or size outside
|
||||
§2.4, a chunk index outside the file, or plaintext of the wrong length).
|
||||
|
||||
### 2.6 The client's API (Amicitia pins it)
|
||||
- `start_upload(size) -> FileUpload`: id, upload token, fetch token, key; no network. `FileUpload`
|
||||
is `Serialize`/`Deserialize` (an app keeps it in its outbox to resume) and its `Debug` shows only
|
||||
the chunk count.
|
||||
- `create_file(&FileUpload)`, `put_chunk(&FileUpload, index, plain)`, `upload(&FileUpload, bytes)`
|
||||
(all chunks), `delete_file(&FileUpload)`: the network calls. `create_file` after a crash may meet
|
||||
its own file: 409 is taken as done (the id is 16 random bytes; nobody else made it).
|
||||
- `FileUpload::seal(index, plain)` and `FileRef::open(index, chunk)`: encryption without network.
|
||||
- `compose_file(contact, &FileUpload, name, mime, thumb) -> Outgoing`; `sent_seq` names it. The
|
||||
app delivers it **after** the upload: a recipient who fetches a chunk too early gets 404 and tries
|
||||
again later, but there is no reason to make them.
|
||||
- `get_chunk(&FileRef, index) -> plain` and `download(&FileRef) -> bytes`; `FileRef` (id, fetch
|
||||
token, key, size) is `Serialize`/`Deserialize` for the app's encrypted database; `Debug` hides
|
||||
the token and the key.
|
||||
- `Event::File { contact, seq, file: FileRef, name, mime, thumb }` (the size is `file.size()`).
|
||||
- `Transport` gains `create_file`, `put_chunk`, `get_chunk`, `delete_file`; `MemoryTransport` keeps
|
||||
files with the relay's rules.
|
||||
- The client keeps **no state** for files: nothing new in the snapshot (`SNAPSHOT_VERSION` stays 1).
|
||||
|
||||
### 2.7 An older client
|
||||
A client from F28 knows no `file`: it has a `seq`, so it shows *Update Amicitia to see this message*
|
||||
(F27's rule). An older relay has no `/v0/files`: `POST` is 404, the app says the relay cannot take
|
||||
files yet and keeps the message unsent.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy — the relay** learns a file id, its chunk count (the size rounded up to 250 KiB, G41),
|
||||
the hour it was created, and — as it serves them — each chunk's fetch and its timing. It does not
|
||||
learn the name, the type, the exact size, the thumbnail or the content, nor who sent it to whom:
|
||||
the file has no mailbox. It **can link** the upload to the sender's next post, and the fetches to
|
||||
the recipient's, by timing and address (§1's honest limit, already stated for blobs).
|
||||
- **Privacy — members** learn the name, type, size and thumbnail, and the content once downloaded.
|
||||
The app strips photo metadata (Amicitia's side; videos keep theirs, G43).
|
||||
- **The fetch token in the message**: anyone who holds the MLS message holds the file. That is the
|
||||
recipient — by design. A file forwarded later would need a fresh upload or the same token, a choice
|
||||
for that feature.
|
||||
- **Abuse**: anyone can create files, as anyone can create mailboxes. The quotas bound it, the 24-hour
|
||||
purge of incomplete files frees what was reserved and never filled, and the 30-day purge the rest.
|
||||
A relay facing the internet is still a resource strangers can fill up to its operator's limits
|
||||
(`home-relay.md`'s stated limit).
|
||||
- **Integrity**: the MLS message authenticates the sender, the key and the size; STREAM authenticates
|
||||
each chunk's content and position and the end of the file. A relay can withhold a chunk (the
|
||||
download fails, retried later), never change one.
|
||||
- **Memory**: `upload` and `download` hold the whole file (up to 100 MiB). `put_chunk` and
|
||||
`get_chunk` work one chunk at a time, for an app that streams to disk.
|
||||
- **Offline**: the `FileUpload` is saved before any network; every step can be repeated.
|
||||
|
||||
## 4. Gaps and designed solutions
|
||||
| Gap | Design |
|
||||
|:--|:--|
|
||||
| The size reaches the relay, rounded up to 250 KiB (G41) | Same-size chunks (this change); later, padding the chunk count to powers of two |
|
||||
| A stranger can reserve the file quota with files never filled | Incomplete after 24 h = purged; quotas; the operator's limits |
|
||||
| The relay sees when a file is fetched, and how often | Not stored; stated in §1/§5. A 1:1 file is fetched once per device |
|
||||
| Files bigger than 100 MiB | *Via Arca* (Amicitia's side, when Arca's share capability exists) |
|
||||
| A group (F32): one upload, many recipients | The same `file` payload sealed into each member's group; one upload serves all, the relay sees several fetch series of one file |
|
||||
| Two people on different relays | Not today: a client has one transport, so both sides of a conversation use one relay |
|
||||
|
||||
## 5. Verification
|
||||
| Case | Test |
|
||||
|:--|:--|
|
||||
| Create, put, get, delete; the routes' status codes | `relay/tests/files.rs` |
|
||||
| A put without the upload token, with the fetch token, or with another file's token is 404 | same |
|
||||
| A get without the fetch token, or with the upload token, is 404 | same |
|
||||
| A chunk of the wrong size is 413; an index past `chunks` is 507; `chunks` 0 or 411 is 400 | same |
|
||||
| The same chunk again: 201 with the same bytes, 409 with other bytes | same |
|
||||
| The relay-wide quota (files, reserved bytes) answers 507, and frees on delete and purge | same |
|
||||
| A file is gone after 30 days; an incomplete one after 24 h; a complete one is kept | same, clock injected |
|
||||
| The live schema is §5's, the two new tables included | `relay/tests/relay.rs` |
|
||||
| Every chunk on the wire is 256 000 bytes, whatever the file's size | `client/tests/files.rs` |
|
||||
| A file goes both ways and comes back byte for byte (1 byte, exactly one chunk, one chunk + 1, 3 chunks) | same |
|
||||
| A chunk tampered with, swapped with another, the last one missing or opened as not-last, or from another file: `FileDamaged` | same + unit |
|
||||
| The `file` event carries name, type, size, thumbnail; its `seq` counts; a receipt covers it; a reaction can name it | same |
|
||||
| A malformed name, type or size is refused when sending and dropped when received; a bad thumbnail is dropped and the file kept | unit through `receive_payload` |
|
||||
| A blocked contact's file is dropped | unit |
|
||||
| An F28 client shows a file as Unsupported | F27's rule: `a_newer_apps_message_is_unsupported_and_counts_for_receipts` (now with `sticker`) |
|
||||
| **The relay's database holds no file name, type, thumbnail or content** (canary, real relay) | `client/tests/real_relay.rs` |
|
||||
| Planted bugs | the review |
|
||||
@@ -0,0 +1,39 @@
|
||||
# The join page — an invite link a messenger can open
|
||||
|
||||
## 1. Why and what
|
||||
Amicitia (the app this relay serves) makes connecting seamless: *Invite Petr* opens the phone's
|
||||
share sheet with a message holding the invite link, and Petr taps it (Amicitia's
|
||||
`.agents/features/seamless-invite.md`). Messengers make `https://` links tappable, not
|
||||
`amicitia://`. So the link is `https://<relay>/join#<invite id>.<secret>`, and the relay serves the
|
||||
page it opens: one button, **Open Amicitia**, that hands the invite to the app.
|
||||
|
||||
## 2. Design
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant B as Browser
|
||||
participant R as Relay
|
||||
participant A as App
|
||||
B->>R: GET /join (the fragment #id.secret is never sent)
|
||||
R-->>B: static page: CSP default-src 'none' + hashes, no-store, no-referrer
|
||||
B->>A: tap → amicitia://invite?relay=<origin>#id.secret
|
||||
```
|
||||
- `crates/relay/assets/join.html`, served by `crates/relay/src/join.rs`. The CSP names the page's
|
||||
only script and style by SHA-256, computed from the page itself at start-up, so an edit to the
|
||||
page cannot run without its hash.
|
||||
- The script checks the fragment's shape (22 + 43 base64url characters) and only then sets the
|
||||
button's target; anything else shows *This invite link is incomplete*.
|
||||
- No automatic redirect: Chrome refuses a custom scheme opened without a tap.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy:** the relay learns that an address opened `/join` — no more than any client tells it.
|
||||
It stores nothing and prints no request. The secret stays in the fragment. A messenger's link
|
||||
preview fetches `/join` only.
|
||||
- **The page as an attack surface:** static, no input read on the server, no cookie, framing
|
||||
refused, nothing loaded from elsewhere.
|
||||
|
||||
## 4. Verification
|
||||
| Case | How |
|
||||
|:--|:--|
|
||||
| Static, strict headers, nothing external, no cookie | `the_join_page_is_static_and_loads_nothing_from_elsewhere` |
|
||||
| The policy's hashes match the page's script and style | `the_join_page_policy_hashes_its_own_script_and_style` |
|
||||
| The script builds the app link from a good fragment and refuses a bad one | Node, by hand (in the PR); Amicitia's phone test end to end |
|
||||
@@ -0,0 +1,124 @@
|
||||
# Polls — three payloads, and a poll the client keeps (`PROTOCOL.md` §4)
|
||||
|
||||
Amicitia F28, step 3 of its full-chat plan (`Amicitia/.agents/features/full-chat.md` §2). Everything
|
||||
here is **inside MLS**: the relay's view (§5, §8) does not change. No new route, no new column.
|
||||
|
||||
## 1. Why and what
|
||||
*Where shall we eat — the Italian place or the Thai one?* A chat people move to lets them ask a
|
||||
question with a few answers, lets everyone vote and change their vote, and shows who chose what. The
|
||||
person who asked closes it, and from then on the result is the same on every device.
|
||||
|
||||
So this change adds:
|
||||
1. `poll`, a message (it has a `seq`, so it can be replied to and reacted to, and a receipt covers
|
||||
it): a question, 2–10 options, single or multiple choice;
|
||||
2. `vote`, a member's choices in a poll, replacing their earlier vote; no choices takes it back;
|
||||
3. `pollClose`, sent by the asker only: the poll is closed, and **these are the final votes**.
|
||||
|
||||
## 2. Design
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant A as Anna's app
|
||||
participant C as Client (Anna)
|
||||
participant R as Relay
|
||||
participant D as Client (Ben)
|
||||
participant B as Ben's app
|
||||
A->>C: compose_poll(ben, "Where?", ["Italian","Thai"], false) → seq 8
|
||||
C->>R: {"kind":"poll","seq":8,"question":"Where?","options":["Italian","Thai"],"multiple":false}
|
||||
R->>D: fetch
|
||||
D->>B: Poll{seq 8, …}; D remembers (Anna, 8): 2 options, single choice, open
|
||||
B->>D: vote(anna, (Anna, 8), [1])
|
||||
D->>R: {"kind":"vote","poll":{"author":"…","seq":8},"choices":[1]}
|
||||
R->>C: fetch
|
||||
C->>A: Vote{poll (Anna, 8), choices [1]}
|
||||
A->>C: close_poll(ben, (Anna, 8))
|
||||
C->>R: {"kind":"pollClose","poll":{…},"ballots":[{"author":"<Ben>","choices":[1]}]}
|
||||
R->>D: fetch
|
||||
D->>B: PollClosed{poll, ballots}: the final result
|
||||
```
|
||||
### 2.1 The payloads
|
||||
```json
|
||||
{"kind":"poll","seq":8,"question":"Where?","options":["Italian","Thai"],"multiple":false}
|
||||
{"kind":"vote","poll":{"author":"<22 chars>","seq":8},"choices":[1]}
|
||||
{"kind":"vote","poll":{"author":"<22 chars>","seq":8},"choices":[]}
|
||||
{"kind":"pollClose","poll":{"author":"<22 chars>","seq":8},"ballots":[{"author":"<22 chars>","choices":[1]}]}
|
||||
```
|
||||
- **`poll`**: `question` 1–300 characters, `options` 2–10 of 1–100 characters each, all different;
|
||||
none blank, none with a control character. `multiple` says whether a vote may hold several choices.
|
||||
It shares the sender's one `seq` counter with `text`.
|
||||
- **`vote`**: `choices` are indexes into `options`, ascending, each once; with `multiple` false, at
|
||||
most one. `[]` takes the vote back. A vote replaces the sender's earlier one in that poll. No `seq`.
|
||||
- **`pollClose`**: only the poll's author may send it. `ballots` are the votes the author's client
|
||||
had accepted when it closed, one per member who has a vote (an empty vote is left out). No `seq`.
|
||||
|
||||
### 2.2 Why the close carries the votes
|
||||
Without them two devices can disagree for ever: Ben votes while Anna closes; Anna's client receives
|
||||
the vote after its close and drops it, Ben's app counted it. With `ballots`, the result after a close
|
||||
is *what the asker's device saw*, and every device shows that. A vote that crossed the close is not
|
||||
counted anywhere, and Ben's app sees that his vote is not in the result.
|
||||
|
||||
### 2.3 What the client keeps
|
||||
For each conversation, the polls in it: who asked and the `seq`, how many options, `multiple`,
|
||||
whether it is closed, and each member's current choices (at most two in a 1:1 chat). This goes into
|
||||
the snapshot (`polls`, absent in older snapshots, so `SNAPSHOT_VERSION` stays 1). With it the client
|
||||
— not each app — decides whether a vote or a close makes sense, and the close's `ballots` come from
|
||||
what it accepted, not from the app.
|
||||
|
||||
### 2.4 What the receiving client checks
|
||||
| Received | Dropped when | Otherwise |
|
||||
|:--|:--|:--|
|
||||
| `poll` | a field over its limit, fewer than 2 or more than 10 options, a blank or repeated option, a control character | `Event::Poll`; remembered; its `seq` counts like a text's |
|
||||
| `vote` | the poll is not one it remembers in this conversation, or is closed; a choice out of range, repeated, not ascending; two choices in a single-choice poll | `Event::Vote`; replaces the sender's choices |
|
||||
| `pollClose` | the sender is not the poll's author; the poll is unknown or already closed; a ballot by someone not in the conversation, twice for one person, empty, or invalid as a vote | `Event::PollClosed` with the ballots; the poll is closed, its votes are the ballots |
|
||||
Blocked contacts' polls, votes and closes are dropped, as their texts are. Sending checks the same
|
||||
rules and refuses with `ClientError::BadPoll` (a malformed poll or vote, a poll that is not ours to
|
||||
close) or `ClientError::PollClosed`.
|
||||
|
||||
### 2.5 The client's API (Amicitia pins it)
|
||||
- `compose_poll(contact, question, options: &[String], multiple) -> Outgoing`; `sent_seq` names it.
|
||||
- `vote(contact, poll: MessageRef, choices: &[u8]) -> Outgoing`.
|
||||
- `close_poll(contact, poll: MessageRef) -> Outgoing`; only our own poll.
|
||||
- `Event::Poll { contact, seq, question, options, multiple }`, `Event::Vote { contact, poll, choices }`,
|
||||
`Event::PollClosed { contact, poll, ballots: Vec<Ballot> }`; `Ballot { author, choices }`.
|
||||
- Constants `MIN_POLL_OPTIONS` 2, `MAX_POLL_OPTIONS` 10, `MAX_OPTION_CHARS` 100,
|
||||
`MAX_QUESTION_CHARS` 300.
|
||||
|
||||
### 2.6 An older client
|
||||
A client from F27 does not know these kinds: a `poll` (it has a `seq`) shows as *Update Amicitia to
|
||||
see this message*; a `vote` and a `pollClose` (no `seq`) are dropped. That is F27's rule working.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy:** the two members learn the question, the options and who voted for what — **there is
|
||||
no anonymous poll**: MLS authenticates every sender, so an anonymous vote could not be honest. The
|
||||
app says *Everyone in this chat sees who voted for what* on the poll. The relay sees three more
|
||||
kinds of blob, sized like short texts; the close's size grows with the number of votes (§5's note
|
||||
on sizes; padding is G41's later work).
|
||||
- **Integrity:** only a member can vote (MLS), only for themselves (a vote has no author field: it is
|
||||
the sender's), only the asker can close, and the close can only name members.
|
||||
- **Snapshot growth:** a few dozen bytes per poll, kept while the conversation exists.
|
||||
- **Events (Amicitia):** none — votes and closes are not check-ins; a poll is a message like a text.
|
||||
- **Offline:** staged as every payload; the app delivers them in order (F27's `deliver_older`).
|
||||
|
||||
## 4. Gaps and designed solutions
|
||||
| Gap | Design |
|
||||
|:--|:--|
|
||||
| A vote and a close cross | The close carries the ballots (§2.2) |
|
||||
| The app could invent a close's result | The client fills `ballots` from what it accepted (§2.3) |
|
||||
| A poll from before the client kept polls (none exist: nobody sent one) | — |
|
||||
| Polls in groups (F32): more members, more ballots | `Ballot` already names its author; F32 checks membership against the roster |
|
||||
| The close's size reveals roughly how many voted | Up to two ballots in 1:1; G41's padding later |
|
||||
| A peer reuses the `seq` of an earlier text for a poll, so one name means two messages (texts allow it too) | Later, for every kind with a `seq` at once: refuse a `seq` at or below the highest received, with care for a blob fetched again after a crash |
|
||||
|
||||
## 5. Verification
|
||||
| Case | Test |
|
||||
|:--|:--|
|
||||
| A poll arrives with its seq, question, options and `multiple`; a receipt covers it | `client/tests/polls.rs` |
|
||||
| A vote is set, replaced and taken back; both sides' own and their votes | same |
|
||||
| A close carries the ballots the asker had, and the result is the same on both sides | same |
|
||||
| A vote that crosses the close is not in the result anywhere | same |
|
||||
| Only the asker closes; a vote or a second close after the close is refused and dropped | same + unit |
|
||||
| Malformed polls, votes and closes are refused when sending and dropped when received | unit through `receive_payload` |
|
||||
| A blocked contact's poll and vote are dropped | unit |
|
||||
| The poll survives a snapshot and restore, closed or open, with its votes | `client/tests/polls.rs` |
|
||||
| An F27 client shows a poll as Unsupported | F27's rule, its own test (`a_newer_apps_message_is_unsupported_and_counts_for_receipts`, now with `file` as the newer kind) |
|
||||
| The relay's database holds no question and no option (canary; a choice is a small number, which no canary can find) | `real_relay.rs` |
|
||||
| Planted bugs | the review |
|
||||
@@ -0,0 +1,122 @@
|
||||
# Reactions and replies — two payloads, and messages that can be named (`PROTOCOL.md` §4)
|
||||
|
||||
Amicitia F27, step 2 of its full-chat plan (`Amicitia/.agents/features/full-chat.md` §2). Everything
|
||||
here is **inside MLS**: the relay's view (§5, §8) does not change. No new route, no new column.
|
||||
|
||||
## 1. Why and what
|
||||
A chat people move to needs the two smallest things every messenger has: a **reaction** on a message
|
||||
(👍, ❤️, 😂 …) and a **reply** that quotes the message it answers. Both need a message to have a name
|
||||
both sides agree on. Today a `text` carries a `seq`, but the receiving app is never told it, and
|
||||
nothing says *whose* `seq`.
|
||||
|
||||
So this change:
|
||||
1. names every message by **(author, seq)**: the author's 16-byte MLS credential identity (random,
|
||||
made on the device, already in every credential, never a name) and the author's own `seq`;
|
||||
2. adds `replyTo` to `text`, and a new payload `reaction`;
|
||||
3. tells the app a received message's `seq`, and both identities, so it can store and name messages;
|
||||
4. turns a payload of a **kind this client does not know** that carries a `seq` into an event
|
||||
*Unsupported*, so a later kind (polls, files, stickers) shows *Update the app to see this message*
|
||||
instead of vanishing. Today such a payload fails to parse and is dropped without a trace.
|
||||
|
||||
## 2. Design
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant A as Anna's app
|
||||
participant C as Client (Anna)
|
||||
participant R as Relay
|
||||
participant D as Client (Ben)
|
||||
participant B as Ben's app
|
||||
A->>C: compose_text(ben, "lunch?", None) → seq 7
|
||||
C->>R: MLS blob {"kind":"text","body":"lunch?","seq":7}
|
||||
R->>D: fetch
|
||||
D->>B: Message{seq 7, reply_to: None}; B names it (Anna, 7)
|
||||
B->>D: react(anna, (Anna, 7), Some("👍"))
|
||||
D->>R: MLS blob {"kind":"reaction","to":{"author":"…","seq":7},"emoji":"👍"}
|
||||
R->>C: fetch
|
||||
C->>A: Reaction{to (Anna, 7), emoji "👍"}
|
||||
```
|
||||
### 2.1 The payloads
|
||||
```json
|
||||
{"kind":"text","body":"…","seq":8,"replyTo":{"author":"<22 chars>","seq":7}}
|
||||
{"kind":"reaction","to":{"author":"<22 chars>","seq":7},"emoji":"👍"}
|
||||
{"kind":"reaction","to":{"author":"<22 chars>","seq":7}}
|
||||
```
|
||||
- **`MessageRef`** `{author, seq}`: `author` is unpadded base64url of 16 bytes (the protocol crate's
|
||||
new `Author`, like `MailboxId`); `seq` ≥ 1.
|
||||
- **`text.replyTo`** is optional; without it a `text` is byte-for-byte today's.
|
||||
- **`reaction`**: `emoji` present sets the sender's reaction to that message (replacing their
|
||||
earlier one); absent removes it. One reaction per person per message is the app's rule, and the
|
||||
wire makes it the only one expressible: there is no "add a second". `emoji` is 1–32 bytes of UTF-8
|
||||
with no control characters (the longest emoji ZWJ sequences are 28 bytes). Which emoji are offered
|
||||
is the app's choice; the client does not keep a list, so a newer app's emoji still arrives.
|
||||
- A reaction carries **no `seq`**: it is not a message, it cannot be replied to or reacted to, and a
|
||||
receipt does not cover it.
|
||||
|
||||
### 2.2 What the receiving client checks
|
||||
A reference names a message only if its author is one of the two members of this conversation and
|
||||
its `seq` is one that exists: ≤ our `sent_seq` when it names ours, ≤ their highest `seq` received
|
||||
when it names theirs (blobs from one sender arrive in order, so their message is always before a
|
||||
reaction to it).
|
||||
| Received | Bad reference | Result |
|
||||
|:--|:--|:--|
|
||||
| `reaction` | author not a member, `seq` 0, or a `seq` that does not exist yet | dropped, never shown (like any blob that does not make sense) |
|
||||
| `reaction` | emoji empty, over 32 bytes, or with a control character | dropped |
|
||||
| `text` with `replyTo` | as above | the text is shown, **without** the reference: the words are real, only the quote is not |
|
||||
| unknown `kind` with a `seq` ≥ 1 | — | `Unsupported{seq}`; counts for receipts like a text |
|
||||
| unknown `kind` without a `seq`, or not JSON | — | dropped, as today |
|
||||
A blocked contact's reactions and unsupported items are dropped, as their texts are.
|
||||
|
||||
### 2.3 The client's API (Amicitia pins it)
|
||||
- `Event::Message` gains `seq: u64` and `reply_to: Option<MessageRef>`.
|
||||
- New `Event::Reaction { contact, to: MessageRef, emoji: Option<String> }`.
|
||||
- New `Event::Unsupported { contact, seq }`.
|
||||
- `Client::author() -> Author` (ours) and `Client::contact_author(contact) -> Option<Author>` (theirs,
|
||||
read from the MLS group's other member — nothing new in the snapshot).
|
||||
- `Client::compose_text(contact, text, reply_to: Option<MessageRef>)`; `compose(contact, text)`
|
||||
stays and means `compose_text(…, None)`. A reply whose reference fails §2.2's check on our own
|
||||
side is refused with `ClientError::BadReference` before anything is sealed.
|
||||
- `Client::react(contact, to: MessageRef, emoji: Option<&str>) -> Outgoing`; the same checks, and
|
||||
`ClientError::TooLong` / `BadReference` for a bad emoji.
|
||||
|
||||
### 2.4 An older client
|
||||
A client before this change has `deny_unknown_fields` on `text` and no `reaction`: a reply or a
|
||||
reaction fails to parse there and is dropped (acknowledged, never shown). Nobody runs Amicitia
|
||||
outside development yet; from this change on, unknown kinds degrade to *Unsupported*. **Unknown
|
||||
fields in a known kind still fail** (`deny_unknown_fields` stays: a field the receiver ignores could
|
||||
change what the sender meant). So a later change that adds a field to `text` would make older
|
||||
clients drop those texts without a trace; new fields therefore go into **new kinds**, which older
|
||||
clients show as *Unsupported*. `PROTOCOL.md` §4 says so.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy:** members (the two people) learn the emoji and which message; they already see every
|
||||
message. The relay sees one more blob. **A reaction's blob is small** (about the size of a
|
||||
one-word text) — the relay could guess "a reaction or a very short text", which it can already do
|
||||
for short texts; padding is G41's later work. Stated in §5's note on sizes.
|
||||
- **Integrity:** a reaction can only come from a member (MLS authenticates the sender), so nobody else
|
||||
can react in someone's name. A member can react to a message that exists only; they cannot
|
||||
reference a message from another conversation (different authors).
|
||||
- **Events (`Amicitia`):** none — reactions are not check-ins (full-chat §4).
|
||||
- **Offline:** as every payload: staged, posted after the snapshot is saved.
|
||||
|
||||
## 4. Gaps and designed solutions
|
||||
| Gap | Design |
|
||||
|:--|:--|
|
||||
| Unknown kinds vanish today | `Unsupported{seq}` (§2.2) |
|
||||
| A known kind with new fields fails on older clients | New fields go into new kinds (§2.4), written into `PROTOCOL.md` §4 |
|
||||
| Reaction blobs are small (size leak) | Same as short texts today; padding to buckets is G41's (later) |
|
||||
| A reaction to a message the receiver deleted | The client cannot know; the app drops reactions to messages it does not have |
|
||||
|
||||
## 5. Verification
|
||||
| Case | Test |
|
||||
|:--|:--|
|
||||
| A reply arrives with its reference; the app is told `seq` and both authors match | `client/tests/reactions.rs` |
|
||||
| A reaction sets, replaces and removes (emoji absent) | same |
|
||||
| A reaction to a `seq` that does not exist, or by a non-member author, is dropped | unit test through `receive_payload` |
|
||||
| A reply with a bad reference is shown without the reference | unit test |
|
||||
| Emoji empty, 33 bytes, or with a control character: refused when composing, dropped when received | unit + integration |
|
||||
| An unknown kind with a `seq` → `Unsupported`, and a receipt covers it; without `seq` → nothing | unit test |
|
||||
| A blocked contact's reaction is dropped | integration |
|
||||
| `compose` unchanged on the wire (no `replyTo` key) | unit test on the JSON |
|
||||
| The relay's database holds no emoji and no reply text (canary) | `real_relay.rs`, `client/tests/state.rs` |
|
||||
| `Author` parses only canonical 22-char base64url of 16 bytes | protocol unit + proptest |
|
||||
| Planted bugs | the review |
|
||||
@@ -0,0 +1,114 @@
|
||||
# Wake-up — a closed Android app learns that something arrived (`PROTOCOL.md` §6, G03)
|
||||
|
||||
Amicitia F25b. The relay already lists the `push` table in §5 *(only if the user opts in, G03)*;
|
||||
this document designs it, its two routes and the request the relay sends. iOS (the publisher's
|
||||
gateway) is later: Amicitia F25c.
|
||||
|
||||
## 1. Why and what
|
||||
Amicitia's notices (F25a) work only while the app is open in the background: a closed app, or one
|
||||
Android has put to sleep, hears nothing until it is opened. On Android, **UnifiedPush** lets the
|
||||
person choose a *distributor* app (ntfy and others), which keeps one connection to its own push
|
||||
server and wakes the apps registered with it. The relay's part is small: hold one **endpoint URL**
|
||||
per mailbox, given by the mailbox's owner, and POST a constant to it when a blob arrives. The wake
|
||||
carries **no content, no sender and no mailbox id** — only "something arrived".
|
||||
|
||||
## 2. Design
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant D as Distributor app (phone)
|
||||
participant A as Amicitia (phone)
|
||||
participant R as Relay
|
||||
participant P as Push server (e.g. ntfy.sh)
|
||||
A->>D: REGISTER (one token per mailbox)
|
||||
D-->>A: NEW_ENDPOINT (a capability URL at P)
|
||||
A->>R: PUT /v0/mailboxes/{id}/push {endpoint} (fetch token)
|
||||
Note over R: a contact posts a blob (post token)
|
||||
R->>P: POST endpoint, a constant body, at most once a minute per mailbox
|
||||
P-->>D: the wake
|
||||
D-->>A: MESSAGE → the constant notice, no sync needed
|
||||
```
|
||||
### 2.1 The wire (§8 additions)
|
||||
| Method and path | Auth | Effect |
|
||||
|:--|:--|:--|
|
||||
| `PUT /v0/mailboxes/{id}/push` `{endpoint}` | fetch token | sets (or replaces) the mailbox's endpoint. 204 |
|
||||
| `DELETE /v0/mailboxes/{id}/push` | fetch token | removes it. 204, also when there was none |
|
||||
|
||||
- **The endpoint** (`PushEndpoint` in the protocol crate): at most 1 000 bytes (UnifiedPush's own
|
||||
limit), printable ASCII, `https://` with a host, no user info, no fragment. `http://` only to a
|
||||
loopback host (`127.0.0.1`, `[::1]`, `localhost`), and a relay accepts *those* only when started
|
||||
with `--push-loopback` (tests); otherwise 400.
|
||||
- A wrong token or unknown mailbox: §8's bare 404. A bad body: 400.
|
||||
|
||||
### 2.2 The wake (the relay's only outgoing request)
|
||||
- After a **successful** post (the post token checked, the blob stored), if the mailbox has an
|
||||
endpoint and was not woken in the last **60 s**, the relay POSTs to it — in the background, so the
|
||||
post's 201 never waits. The 60 s are remembered **in memory only** (mailbox id → second), never
|
||||
stored: §5 does not change.
|
||||
- The request: body `wake` (4 bytes, the same for every wake), headers `TTL: 86400`,
|
||||
`Urgency: normal`, `Content-Type: application/octet-stream`. No mailbox id, no size, no time.
|
||||
10 s timeout, **no redirects**.
|
||||
- **Where it may go:** the host is resolved by the relay, and every address that is not global is
|
||||
dropped before connecting (loopback, private, link-local, CGNAT `100.64/10`, multicast,
|
||||
unspecified, broadcast, documentation, ULA `fc00::/7`, `fe80::/10`, IPv4-mapped forms of all of
|
||||
these). No address left → no request. This is the guard against a mailbox owner using the relay to
|
||||
reach the relay's own network (SSRF). Loopback is kept only with `--push-loopback`.
|
||||
- **At most 16 wakes in flight;** beyond that a wake is dropped (the app syncs when opened anyway).
|
||||
- **A gone endpoint** (404 or 410) is removed — only if it is still the one that was woken.
|
||||
- The relay prints nothing about a wake, as it prints nothing about a request.
|
||||
|
||||
### 2.2b The NixOS module
|
||||
The module's sandbox let the relay reach localhost only (`IPAddressDeny=any`), which would have
|
||||
dropped every wake without a word. New option `services.tabellarius.wake` (default **on**,
|
||||
*decided by default*): the relay may reach global addresses; every non-global range stays denied by
|
||||
systemd too (a second wall behind §2.2), and `AF_UNIX` is allowed so names resolve through nscd.
|
||||
Off: localhost only, as before. Not run here (no Nix on this machine; `test.nix` is unrun since F23).
|
||||
|
||||
### 2.3 Storage (§5's `push` row, made concrete)
|
||||
`push (mailbox_id BLOB PRIMARY KEY, endpoint TEXT)`. One row per mailbox at most. The mailbox
|
||||
counts already bound the rows.
|
||||
|
||||
### 2.4 The client crate
|
||||
`Transport::set_push(id, fetch, Option<&PushEndpoint>)`; `Client::inboxes()` lists the mailboxes
|
||||
this client fetches (each contact's inbox and each open welcome mailbox); `Client::set_push(mailbox,
|
||||
endpoint)` calls the relay with that mailbox's fetch token. `MemoryTransport` keeps the relay's rules.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy — what the relay learns:** an endpoint per mailbox that opted in. The client registers
|
||||
**one endpoint per mailbox** (UnifiedPush allows many registrations per app), so the relay cannot
|
||||
link two of a person's mailboxes by their endpoint — but it sees the endpoint's **host**. On a big
|
||||
shared push server (ntfy.sh) that host says little; on a person's own server it links all their
|
||||
mailboxes. Amicitia says so where the choice is made.
|
||||
- **Privacy — what the push server learns:** that the relay's address sent a wake to a capability URL
|
||||
of one device, and when. Not the mailbox, not the sender, not the content (the body is a constant).
|
||||
The person chose that server through their distributor.
|
||||
- **SSRF:** §2.2's resolver filter, no redirects, a short timeout, a cap on wakes in flight.
|
||||
- **Abuse by a contact:** only a valid post token causes a wake, and at most one a minute per
|
||||
mailbox. A blocked contact's posts are refused before the wake.
|
||||
- **Web Push encryption (RFC 8291) and VAPID:** not done. UnifiedPush's Android spec says the
|
||||
message content follows RFC 8291; the relay's body is a public constant, so there is nothing to
|
||||
hide, and ntfy delivers a plain body. A distributor that insists on VAPID refuses the registration
|
||||
(`VAPID_REQUIRED`); Amicitia says it cannot use that distributor. Gap W1.
|
||||
- **Events / offline:** the relay has no events. A wake that fails is not retried: the next blob
|
||||
wakes again, and opening the app fetches everything.
|
||||
|
||||
## 4. Gaps
|
||||
- **W1 — Web Push encryption and VAPID** for distributors that need them (e.g. Mozilla's autopush
|
||||
behind some distributors). Designed: the client sends its P-256 public key and auth secret with
|
||||
the endpoint; the relay encrypts the constant with a vetted crate (`ece`) — a new protocol field,
|
||||
and a crate not in the cache today.
|
||||
- **W2 — iOS** through the publisher's gateway (§6), Amicitia F25c.
|
||||
|
||||
## 5. Verification
|
||||
| Case | Test |
|
||||
|:--|:--|
|
||||
| Endpoint rules: https; http only to loopback; length; no user info or fragment | `protocol/tests/wire.rs` |
|
||||
| PUT/DELETE need the fetch token; wrong token or unknown id → 404; bad body → 400 | `relay/tests/wake.rs` |
|
||||
| A post wakes once with the constant body; no mailbox id, no ciphertext in the request (canary) | `relay/tests/wake.rs`, a loopback push server |
|
||||
| Two posts within 60 s → one wake; after 60 s → another (clock injected) | `relay/tests/wake.rs` |
|
||||
| A refused post (wrong token, 507) wakes nothing; no endpoint → nothing | `relay/tests/wake.rs` |
|
||||
| 410 from the push server → the row is gone | `relay/tests/wake.rs` |
|
||||
| `http://` loopback refused without `--push-loopback` | `relay/tests/wake.rs` |
|
||||
| Non-global addresses dropped (v4, v6, mapped) | unit tests in `relay/src/wake.rs` |
|
||||
| §5's schema test includes `push (mailbox_id, endpoint)` | `relay/tests/relay.rs` |
|
||||
| A redirect is not followed; a gone answer does not remove an endpoint set since | `relay/tests/wake.rs` |
|
||||
| The client lists its inboxes and sets/clears an endpoint; memory transport and real relay | `client/tests/real_relay.rs`, `client/tests/state.rs` |
|
||||
Generated
+191
-10
@@ -118,6 +118,12 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
@@ -617,7 +623,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1389,7 +1395,7 @@ checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasi",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1908,6 +1914,20 @@ dependencies = [
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom 0.2.17",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rsqlite-vfs"
|
||||
version = "0.2.0"
|
||||
@@ -1957,7 +1977,42 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2167,7 +2222,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2198,9 +2253,9 @@ checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"
|
||||
|
||||
[[package]]
|
||||
name = "sqlite-wasm-rs"
|
||||
version = "0.6.3"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867"
|
||||
checksum = "36bd8e29bf08189a005b2df1df99823aa0861cabe9044e5f31ed54ca292ee618"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"rsqlite-vfs",
|
||||
@@ -2245,7 +2300,8 @@ name = "tabellarius-client"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"chacha20poly1305",
|
||||
"hkdf 0.12.4",
|
||||
"openmls",
|
||||
"openmls_basic_credential",
|
||||
@@ -2264,7 +2320,7 @@ dependencies = [
|
||||
name = "tabellarius-protocol"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2276,16 +2332,19 @@ name = "tabellarius-relay"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"getrandom 0.3.4",
|
||||
"http-body-util",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"subtle",
|
||||
"tabellarius-protocol",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tower",
|
||||
"ureq",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2298,7 +2357,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2356,7 +2415,7 @@ dependencies = [
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2455,6 +2514,46 @@ dependencies = [
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "3.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"ureq-proto",
|
||||
"utf8-zero",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ureq-proto"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8-zero"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.29.2"
|
||||
@@ -2546,12 +2645,30 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||
dependencies = [
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
@@ -2561,6 +2678,70 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.5"
|
||||
|
||||
@@ -20,6 +20,9 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
# The snapshot's byte fields (already in the tree through the protocol crate).
|
||||
base64 = "0.22"
|
||||
# Files (files.md §2.2): ChaCha20-Poly1305 in the aead crate's STREAM construction. Already in the
|
||||
# tree through openmls_rust_crypto (same version); `stream` adds no dependency.
|
||||
chacha20poly1305 = { version = "0.10", default-features = false, features = ["alloc", "stream"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# The real relay, for the end-to-end test only. `check-deps.sh` checks normal edges: the client
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
//! Files (`.agents/features/files.md`): a file is padded to whole chunks and each chunk sealed with
|
||||
//! ChaCha20-Poly1305 in the STREAM construction (`aead::stream::StreamBE32`, RustCrypto), under a
|
||||
//! key made for that one file. Every chunk on the wire is [`FILE_CHUNK_BYTES`]. Nothing here is
|
||||
//! hand-written cryptography: the cipher and the construction are the crates'.
|
||||
|
||||
use crate::ClientError;
|
||||
use chacha20poly1305::aead::stream::{NewStream, StreamBE32, StreamPrimitive};
|
||||
use chacha20poly1305::{ChaCha20Poly1305, KeyInit};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use tabellarius_protocol::{FileId, FileKey, Token, FILE_CHUNK_BYTES, MAX_FILE_CHUNKS};
|
||||
|
||||
/// The Poly1305 tag on every chunk.
|
||||
const TAG_BYTES: usize = 16;
|
||||
/// The plaintext in one chunk: the chunk minus its tag.
|
||||
pub const FILE_CHUNK_PLAIN: usize = FILE_CHUNK_BYTES - TAG_BYTES;
|
||||
/// The largest file sent through the relay (Amicitia's plan, full-chat.md §5.5).
|
||||
pub const MAX_FILE_BYTES: u64 = 100 * 1024 * 1024;
|
||||
/// The largest thumbnail inside a `file` payload: a JPEG.
|
||||
pub const MAX_THUMB_BYTES: usize = 32 * 1024;
|
||||
/// The longest file name, in characters.
|
||||
pub const MAX_FILE_NAME_CHARS: usize = 255;
|
||||
/// The longest media type, in bytes.
|
||||
pub const MAX_MIME_BYTES: usize = 127;
|
||||
|
||||
/// How many chunks a file of `size` bytes has, or `None` for an empty file or one over
|
||||
/// [`MAX_FILE_BYTES`].
|
||||
pub fn chunks_for(size: u64) -> Option<u32> {
|
||||
if size == 0 || size > MAX_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
let n = size.div_ceil(FILE_CHUNK_PLAIN as u64);
|
||||
u32::try_from(n).ok().filter(|&n| n <= MAX_FILE_CHUNKS)
|
||||
}
|
||||
|
||||
fn stream(key: &FileKey) -> StreamBE32<ChaCha20Poly1305> {
|
||||
// The nonce prefix is zeros: a key seals one file only, so a (key, nonce) pair never repeats.
|
||||
let prefix = Default::default();
|
||||
StreamBE32::from_aead(ChaCha20Poly1305::new(key.as_bytes().into()), &prefix)
|
||||
}
|
||||
|
||||
/// A file on its way up: what an app keeps in its outbox until the `file` message is delivered,
|
||||
/// so that an upload interrupted by a crash resumes. `Debug` shows only its size in chunks.
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct FileUpload {
|
||||
pub(crate) id: FileId,
|
||||
pub(crate) upload_token: Token,
|
||||
pub(crate) fetch_token: Token,
|
||||
pub(crate) key: FileKey,
|
||||
pub(crate) size: u64,
|
||||
}
|
||||
|
||||
impl fmt::Debug for FileUpload {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "FileUpload({} chunks)", self.chunks())
|
||||
}
|
||||
}
|
||||
|
||||
impl FileUpload {
|
||||
/// The file's size in bytes.
|
||||
pub fn size(&self) -> u64 {
|
||||
self.size
|
||||
}
|
||||
|
||||
/// The file's id on the relay.
|
||||
pub fn id(&self) -> FileId {
|
||||
self.id
|
||||
}
|
||||
|
||||
/// How many chunks it has.
|
||||
pub fn chunks(&self) -> u32 {
|
||||
// `start_upload` checked the size.
|
||||
chunks_for(self.size).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What the recipient needs to fetch and open it (the `file` payload carries it).
|
||||
pub fn file_ref(&self) -> FileRef {
|
||||
FileRef {
|
||||
id: self.id,
|
||||
fetch_token: self.fetch_token,
|
||||
key: self.key,
|
||||
size: self.size,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many plaintext bytes chunk `index` carries before padding.
|
||||
fn plain_len(&self, index: u32) -> Option<usize> {
|
||||
let n = self.chunks();
|
||||
if index >= n {
|
||||
return None;
|
||||
}
|
||||
let before = u64::from(index) * FILE_CHUNK_PLAIN as u64;
|
||||
Some((self.size - before).min(FILE_CHUNK_PLAIN as u64) as usize)
|
||||
}
|
||||
|
||||
/// Seals chunk `index`: exactly its share of the file (all of [`FILE_CHUNK_PLAIN`], or the rest
|
||||
/// for the last one), padded with zeros to the chunk size. The same bytes give the same chunk.
|
||||
/// Never seal other bytes for an index already sealed: see [`crate::Client::put_chunk`].
|
||||
pub fn seal(&self, index: u32, plain: &[u8]) -> Result<Vec<u8>, ClientError> {
|
||||
let want = self.plain_len(index).ok_or(ClientError::BadFile)?;
|
||||
if plain.len() != want {
|
||||
return Err(ClientError::BadFile);
|
||||
}
|
||||
let mut buffer = Vec::with_capacity(FILE_CHUNK_BYTES);
|
||||
buffer.extend_from_slice(plain);
|
||||
buffer.resize(FILE_CHUNK_PLAIN, 0);
|
||||
let last = index + 1 == self.chunks();
|
||||
stream(&self.key)
|
||||
.encrypt_in_place(index, last, b"", &mut buffer)
|
||||
.map_err(|_| ClientError::BadFile)?;
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
/// The part of `bytes` (the whole file) that chunk `index` carries.
|
||||
pub fn part<'a>(&self, bytes: &'a [u8], index: u32) -> Option<&'a [u8]> {
|
||||
let len = self.plain_len(index)?;
|
||||
let start = index as usize * FILE_CHUNK_PLAIN;
|
||||
bytes.get(start..start + len)
|
||||
}
|
||||
}
|
||||
|
||||
/// A file someone sent: where it is on the relay, the token to fetch it, its key and its size.
|
||||
/// An app keeps it in its encrypted database. `Debug` hides the token and the key.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct FileRef {
|
||||
pub(crate) id: FileId,
|
||||
pub(crate) fetch_token: Token,
|
||||
pub(crate) key: FileKey,
|
||||
pub(crate) size: u64,
|
||||
}
|
||||
|
||||
impl fmt::Debug for FileRef {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "FileRef({:?}, {} bytes)", self.id, self.size)
|
||||
}
|
||||
}
|
||||
|
||||
impl FileRef {
|
||||
pub fn id(&self) -> FileId {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn size(&self) -> u64 {
|
||||
self.size
|
||||
}
|
||||
|
||||
pub fn chunks(&self) -> u32 {
|
||||
chunks_for(self.size).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Opens chunk `index`: its plaintext, without the padding. A chunk that is not
|
||||
/// [`FILE_CHUNK_BYTES`], does not open at this index (or as the last one when it is), or whose
|
||||
/// padding is not zeros is [`ClientError::FileDamaged`].
|
||||
pub fn open(&self, index: u32, chunk: &[u8]) -> Result<Vec<u8>, ClientError> {
|
||||
let n = self.chunks();
|
||||
if index >= n || chunk.len() != FILE_CHUNK_BYTES {
|
||||
return Err(ClientError::FileDamaged);
|
||||
}
|
||||
let mut buffer = chunk.to_vec();
|
||||
let last = index + 1 == n;
|
||||
stream(&self.key)
|
||||
.decrypt_in_place(index, last, b"", &mut buffer)
|
||||
.map_err(|_| ClientError::FileDamaged)?;
|
||||
let before = u64::from(index) * FILE_CHUNK_PLAIN as u64;
|
||||
let len = (self.size - before).min(FILE_CHUNK_PLAIN as u64) as usize;
|
||||
if buffer[len..].iter().any(|&b| b != 0) {
|
||||
return Err(ClientError::FileDamaged);
|
||||
}
|
||||
buffer.truncate(len);
|
||||
Ok(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
/// A file name as the wire allows it: 1–255 characters, not blank, no control character, no `/`
|
||||
/// or `\` (a name is never a path).
|
||||
pub(crate) fn name_ok(name: &str) -> bool {
|
||||
!name.trim().is_empty()
|
||||
&& name.chars().count() <= MAX_FILE_NAME_CHARS
|
||||
&& !name
|
||||
.chars()
|
||||
.any(|c| c.is_control() || c == '/' || c == '\\')
|
||||
}
|
||||
|
||||
/// A media type as the wire allows it: `type/subtype`, 3–127 printable ASCII bytes, one `/` with
|
||||
/// something on each side, no space.
|
||||
pub(crate) fn mime_ok(mime: &str) -> bool {
|
||||
let printable = mime.bytes().all(|b| (0x21..=0x7e).contains(&b));
|
||||
let mut halves = mime.split('/');
|
||||
let shape = matches!(
|
||||
(halves.next(), halves.next(), halves.next()),
|
||||
(Some(t), Some(s), None) if !t.is_empty() && !s.is_empty()
|
||||
);
|
||||
(3..=MAX_MIME_BYTES).contains(&mime.len()) && printable && shape
|
||||
}
|
||||
|
||||
/// A thumbnail as the wire allows it: at most 32 KiB, and it starts like a JPEG.
|
||||
pub(crate) fn thumb_ok(thumb: &[u8]) -> bool {
|
||||
thumb.len() <= MAX_THUMB_BYTES && thumb.starts_with(&[0xFF, 0xD8, 0xFF])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn upload(size: u64, key: u8) -> FileUpload {
|
||||
FileUpload {
|
||||
id: FileId::from_bytes([1; 16]),
|
||||
upload_token: Token::from_bytes([2; 32]),
|
||||
fetch_token: Token::from_bytes([3; 32]),
|
||||
key: FileKey::from_bytes([key; 32]),
|
||||
size,
|
||||
}
|
||||
}
|
||||
|
||||
fn content(size: usize) -> Vec<u8> {
|
||||
(0..size).map(|i| (i % 251) as u8).collect()
|
||||
}
|
||||
|
||||
fn seal_all(up: &FileUpload, bytes: &[u8]) -> Vec<Vec<u8>> {
|
||||
(0..up.chunks())
|
||||
.map(|i| up.seal(i, up.part(bytes, i).expect("part")).expect("seal"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_counts_round_up_and_stop_at_the_limit() {
|
||||
assert_eq!(chunks_for(0), None);
|
||||
assert_eq!(chunks_for(1), Some(1));
|
||||
assert_eq!(chunks_for(FILE_CHUNK_PLAIN as u64), Some(1));
|
||||
assert_eq!(chunks_for(FILE_CHUNK_PLAIN as u64 + 1), Some(2));
|
||||
assert_eq!(chunks_for(MAX_FILE_BYTES), Some(MAX_FILE_CHUNKS));
|
||||
assert_eq!(chunks_for(MAX_FILE_BYTES + 1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_chunk_is_the_same_size_and_opens_back_to_the_file() {
|
||||
for size in [
|
||||
1,
|
||||
100,
|
||||
FILE_CHUNK_PLAIN,
|
||||
FILE_CHUNK_PLAIN + 1,
|
||||
3 * FILE_CHUNK_PLAIN - 7,
|
||||
] {
|
||||
let up = upload(size as u64, 9);
|
||||
let bytes = content(size);
|
||||
let sealed = seal_all(&up, &bytes);
|
||||
assert!(sealed.iter().all(|c| c.len() == FILE_CHUNK_BYTES), "{size}");
|
||||
let file = up.file_ref();
|
||||
let back: Vec<u8> = sealed
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, c)| file.open(i as u32, c).expect("open"))
|
||||
.collect();
|
||||
assert_eq!(back, bytes, "{size}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_tampered_swapped_cut_short_or_from_another_key_does_not_open() {
|
||||
let size = 2 * FILE_CHUNK_PLAIN + 5;
|
||||
let up = upload(size as u64, 9);
|
||||
let sealed = seal_all(&up, &content(size));
|
||||
let file = up.file_ref();
|
||||
let mut flipped = sealed[1].clone();
|
||||
flipped[500] ^= 1;
|
||||
assert_eq!(file.open(1, &flipped), Err(ClientError::FileDamaged));
|
||||
// Swapped: chunk 0 at position 1.
|
||||
assert_eq!(file.open(1, &sealed[0]), Err(ClientError::FileDamaged));
|
||||
// Cut short: a file that claims to end at chunk 1 cannot open it as its last.
|
||||
let shorter = FileRef {
|
||||
size: 2 * FILE_CHUNK_PLAIN as u64,
|
||||
..file
|
||||
};
|
||||
assert_eq!(shorter.open(1, &sealed[1]), Err(ClientError::FileDamaged));
|
||||
// The true last chunk does not open as a middle one.
|
||||
let longer = FileRef {
|
||||
size: 4 * FILE_CHUNK_PLAIN as u64,
|
||||
..file
|
||||
};
|
||||
assert_eq!(longer.open(2, &sealed[2]), Err(ClientError::FileDamaged));
|
||||
// Another file's key.
|
||||
let other = upload(size as u64, 8).file_ref();
|
||||
assert_eq!(other.open(0, &sealed[0]), Err(ClientError::FileDamaged));
|
||||
// The wrong length, or past the end.
|
||||
assert_eq!(file.open(0, &sealed[0][1..]), Err(ClientError::FileDamaged));
|
||||
assert_eq!(file.open(3, &sealed[2]), Err(ClientError::FileDamaged));
|
||||
assert!(file.open(0, &sealed[0]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_padding_must_be_zeros_and_the_size_must_match() {
|
||||
// A sender who claims 10 bytes but sealed 20 non-zero ones: the 10 past the size are not
|
||||
// padding, so the chunk is refused rather than silently cut.
|
||||
let honest = upload(20, 9);
|
||||
let sealed = honest.seal(0, &[7; 20]).expect("seal");
|
||||
let claims_less = FileRef {
|
||||
size: 10,
|
||||
..honest.file_ref()
|
||||
};
|
||||
assert_eq!(claims_less.open(0, &sealed), Err(ClientError::FileDamaged));
|
||||
assert_eq!(honest.file_ref().open(0, &sealed), Ok(vec![7; 20]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sealing_takes_exactly_each_chunks_share() {
|
||||
let up = upload(FILE_CHUNK_PLAIN as u64 + 3, 9);
|
||||
assert_eq!(up.seal(0, &[0; 3]), Err(ClientError::BadFile));
|
||||
assert_eq!(up.seal(1, &[0; 4]), Err(ClientError::BadFile));
|
||||
assert_eq!(up.seal(2, &[0; 3]), Err(ClientError::BadFile));
|
||||
assert!(up.seal(1, &[0; 3]).is_ok());
|
||||
assert_eq!(up.seal(1, &[1; 3]), up.seal(1, &[1; 3]), "deterministic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_types_and_thumbnails_follow_the_wire_rules() {
|
||||
assert!(name_ok("Menu.jpg"));
|
||||
assert!(name_ok(&"é".repeat(MAX_FILE_NAME_CHARS)));
|
||||
for bad in ["", " ", "a/b", "a\\b", "a\u{0}", "a\nb"] {
|
||||
assert!(!name_ok(bad), "{bad:?}");
|
||||
}
|
||||
assert!(!name_ok(&"x".repeat(MAX_FILE_NAME_CHARS + 1)));
|
||||
assert!(mime_ok("image/jpeg"));
|
||||
assert!(mime_ok("application/vnd.oasis.opendocument.text"));
|
||||
for bad in [
|
||||
"image",
|
||||
"/jpeg",
|
||||
"image/",
|
||||
"a/b/c",
|
||||
"image/ jpeg",
|
||||
"a/",
|
||||
"ö/x",
|
||||
] {
|
||||
assert!(!mime_ok(bad), "{bad:?}");
|
||||
}
|
||||
assert!(!mime_ok(&format!("a/{}", "b".repeat(MAX_MIME_BYTES))));
|
||||
assert!(thumb_ok(&[0xFF, 0xD8, 0xFF, 0xE0]));
|
||||
assert!(!thumb_ok(b"\x89PNG"));
|
||||
let mut big = vec![0xFF, 0xD8, 0xFF];
|
||||
big.resize(MAX_THUMB_BYTES + 1, 0);
|
||||
assert!(!thumb_ok(&big));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_shows_no_token_and_no_key() {
|
||||
let up = upload(5, 9);
|
||||
let shown = format!("{up:?} {:?}", up.file_ref());
|
||||
assert!(!shown.contains(&Token::from_bytes([3; 32]).to_wire()));
|
||||
assert!(!shown.contains(&FileKey::from_bytes([9; 32]).to_wire()));
|
||||
}
|
||||
}
|
||||
+1675
-45
File diff suppressed because it is too large
Load Diff
@@ -3,8 +3,8 @@
|
||||
//! 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,
|
||||
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, PollState, Transport,
|
||||
WelcomeBox, CIPHERSUITE, MAX_NAME_CHARS,
|
||||
};
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine as _;
|
||||
@@ -22,6 +22,13 @@ pub const SNAPSHOT_VERSION: u32 = 1;
|
||||
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) struct Bytes(pub(crate) Vec<u8>);
|
||||
|
||||
/// Shows the length only: these bytes are a group's state or a thumbnail.
|
||||
impl std::fmt::Debug for Bytes {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Bytes({})", self.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
@@ -47,6 +54,20 @@ struct ContactState {
|
||||
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,
|
||||
// F28 (`.agents/features/polls.md` §2.3); absent in older snapshots.
|
||||
#[serde(default)]
|
||||
polls: Vec<PollState>,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -59,6 +80,8 @@ struct State {
|
||||
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)>,
|
||||
}
|
||||
@@ -91,10 +114,15 @@ impl<T: Transport> Client<T> {
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
blocked: c.blocked,
|
||||
sent_seq: c.sent_seq,
|
||||
received_seq: c.received_seq,
|
||||
polls: c.polls.clone(),
|
||||
})
|
||||
.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)
|
||||
@@ -143,6 +171,10 @@ impl<T: Transport> Client<T> {
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
blocked: c.blocked,
|
||||
sent_seq: c.sent_seq,
|
||||
received_seq: c.received_seq,
|
||||
polls: c.polls,
|
||||
});
|
||||
}
|
||||
Ok(Client {
|
||||
@@ -155,6 +187,7 @@ impl<T: Transport> Client<T> {
|
||||
contacts,
|
||||
welcome_boxes: state.welcome_boxes,
|
||||
next_contact: state.next_contact,
|
||||
receipts: state.receipts,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tabellarius_protocol::{
|
||||
blob_hash, CreateInvite, CreateMailbox, InviteId, MailboxId, Sha256Hash, Token,
|
||||
blob_hash, CreateFile, CreateInvite, CreateMailbox, FileId, InviteId, MailboxId, PushEndpoint,
|
||||
Sha256Hash, Token, FILE_CHUNK_BYTES,
|
||||
};
|
||||
|
||||
/// Why the relay said no. Carries nothing of the request.
|
||||
@@ -13,8 +14,10 @@ use tabellarius_protocol::{
|
||||
pub enum TransportError {
|
||||
/// 404: unknown, wrong token, expired, or already claimed.
|
||||
NotFound,
|
||||
/// 409: the id is taken.
|
||||
/// 409: the id is taken, or a file chunk is already there with other bytes.
|
||||
Conflict,
|
||||
/// 507: a quota is reached — the relay's, a mailbox's, or a file's (`PROTOCOL.md` §8).
|
||||
Full,
|
||||
/// Anything else: the network, a 5xx, a body that did not parse.
|
||||
Failed,
|
||||
}
|
||||
@@ -32,14 +35,53 @@ pub trait Transport {
|
||||
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>;
|
||||
/// Where the relay wakes the mailbox's owner when a blob arrives (`Some`), or nowhere (`None`).
|
||||
/// `PROTOCOL.md` §6, `.agents/features/wake-up.md`.
|
||||
fn set_push(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
endpoint: Option<&PushEndpoint>,
|
||||
) -> Result<(), TransportError>;
|
||||
/// `POST /v0/files` (`.agents/features/files.md` §2.3).
|
||||
fn create_file(&self, req: &CreateFile) -> Result<(), TransportError>;
|
||||
/// `PUT /v0/files/{id}/chunks/{index}` with the upload token.
|
||||
fn put_chunk(
|
||||
&self,
|
||||
id: &FileId,
|
||||
upload: &Token,
|
||||
index: u32,
|
||||
chunk: &[u8],
|
||||
) -> Result<(), TransportError>;
|
||||
/// `GET /v0/files/{id}/chunks/{index}` with the fetch token.
|
||||
fn get_chunk(&self, id: &FileId, fetch: &Token, index: u32) -> Result<Vec<u8>, TransportError>;
|
||||
/// `DELETE /v0/files/{id}` with the upload token.
|
||||
fn delete_file(&self, id: &FileId, upload: &Token) -> Result<(), TransportError>;
|
||||
}
|
||||
|
||||
/// A file as the relay keeps it: the two hashes, the chunk count, and the chunks by index.
|
||||
struct StoredFile {
|
||||
upload: Sha256Hash,
|
||||
fetch: Sha256Hash,
|
||||
chunks: u32,
|
||||
held: HashMap<u32, Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Boxes {
|
||||
mailboxes: HashMap<MailboxId, (Sha256Hash, Sha256Hash, Vec<Vec<u8>>)>,
|
||||
invites: HashMap<InviteId, (Sha256Hash, Vec<u8>)>,
|
||||
push: HashMap<MailboxId, PushEndpoint>,
|
||||
files: HashMap<FileId, StoredFile>,
|
||||
}
|
||||
|
||||
/// An in-memory relay with the same rules as the real one (no expiry: there is no clock here).
|
||||
@@ -61,7 +103,22 @@ impl MemoryTransport {
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Every byte the relay holds, for privacy tests: ids, hashes, blobs and KeyPackages.
|
||||
/// The push endpoint a mailbox holds, if any.
|
||||
pub fn push_endpoint(&self, id: &MailboxId) -> Option<String> {
|
||||
self.boxes().push.get(id).map(|e| e.as_str().to_string())
|
||||
}
|
||||
|
||||
/// How many chunks the relay holds, in all files.
|
||||
pub fn stored_chunks(&self) -> Vec<Vec<u8>> {
|
||||
self.boxes()
|
||||
.files
|
||||
.values()
|
||||
.flat_map(|f| f.held.values().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every byte the relay holds, for privacy tests: ids, hashes, blobs, KeyPackages, endpoints,
|
||||
/// files and their chunks.
|
||||
pub fn everything_stored(&self) -> Vec<u8> {
|
||||
let b = self.boxes();
|
||||
let mut out = Vec::new();
|
||||
@@ -76,6 +133,16 @@ impl MemoryTransport {
|
||||
out.extend_from_slice(hash.as_bytes());
|
||||
out.extend_from_slice(kp);
|
||||
}
|
||||
for (id, endpoint) in &b.push {
|
||||
out.extend_from_slice(id.as_bytes());
|
||||
out.extend_from_slice(endpoint.as_str().as_bytes());
|
||||
}
|
||||
for (id, f) in &b.files {
|
||||
out.extend_from_slice(id.as_bytes());
|
||||
out.extend_from_slice(f.upload.as_bytes());
|
||||
out.extend_from_slice(f.fetch.as_bytes());
|
||||
f.held.values().for_each(|c| out.extend_from_slice(c));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -129,6 +196,21 @@ impl Transport for MemoryTransport {
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -150,4 +232,87 @@ impl Transport for MemoryTransport {
|
||||
_ => Err(TransportError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_push(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
endpoint: Option<&PushEndpoint>,
|
||||
) -> Result<(), TransportError> {
|
||||
let mut b = self.boxes();
|
||||
match b.mailboxes.get(id) {
|
||||
Some((_, f, _)) if *f == fetch.hash() => {}
|
||||
_ => return Err(TransportError::NotFound),
|
||||
}
|
||||
match endpoint {
|
||||
Some(e) => b.push.insert(*id, e.clone()),
|
||||
None => b.push.remove(id),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_file(&self, req: &CreateFile) -> Result<(), TransportError> {
|
||||
let mut b = self.boxes();
|
||||
if b.files.contains_key(&req.id) {
|
||||
return Err(TransportError::Conflict);
|
||||
}
|
||||
b.files.insert(
|
||||
req.id,
|
||||
StoredFile {
|
||||
upload: req.upload_token_hash,
|
||||
fetch: req.fetch_token_hash,
|
||||
chunks: req.chunks.get(),
|
||||
held: HashMap::new(),
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn put_chunk(
|
||||
&self,
|
||||
id: &FileId,
|
||||
upload: &Token,
|
||||
index: u32,
|
||||
chunk: &[u8],
|
||||
) -> Result<(), TransportError> {
|
||||
if chunk.len() != FILE_CHUNK_BYTES {
|
||||
return Err(TransportError::Failed);
|
||||
}
|
||||
let mut b = self.boxes();
|
||||
let f = match b.files.get_mut(id) {
|
||||
Some(f) if f.upload == upload.hash() => f,
|
||||
_ => return Err(TransportError::NotFound),
|
||||
};
|
||||
if index >= f.chunks {
|
||||
return Err(TransportError::Full);
|
||||
}
|
||||
match f.held.get(&index) {
|
||||
Some(held) if held.as_slice() == chunk => Ok(()),
|
||||
Some(_) => Err(TransportError::Conflict),
|
||||
None => {
|
||||
f.held.insert(index, chunk.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_chunk(&self, id: &FileId, fetch: &Token, index: u32) -> Result<Vec<u8>, TransportError> {
|
||||
match self.boxes().files.get(id) {
|
||||
Some(f) if f.fetch == fetch.hash() => {
|
||||
f.held.get(&index).cloned().ok_or(TransportError::NotFound)
|
||||
}
|
||||
_ => Err(TransportError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn delete_file(&self, id: &FileId, upload: &Token) -> Result<(), TransportError> {
|
||||
let mut b = self.boxes();
|
||||
match b.files.get(id) {
|
||||
Some(f) if f.upload == upload.hash() => {
|
||||
b.files.remove(id);
|
||||
Ok(())
|
||||
}
|
||||
_ => 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,365 @@
|
||||
//! Files (`.agents/features/files.md`). No I/O: runs on the Android emulator too.
|
||||
|
||||
use tabellarius_client::*;
|
||||
use tabellarius_protocol::{CreateFile, MailboxId, Sha256Hash, Token};
|
||||
|
||||
type C = Client<MemoryTransport>;
|
||||
|
||||
fn pair(relay: &MemoryTransport, receipts: bool) -> (C, ContactId, C, ContactId) {
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
eva.set_receipts(receipts);
|
||||
jan.set_receipts(receipts);
|
||||
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 content(size: usize, seed: u8) -> Vec<u8> {
|
||||
(0..size)
|
||||
.map(|i| ((i * 7 + seed as usize) % 253) as u8)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Sends `bytes` from `from` to its contact `to`, and returns the event the other side receives.
|
||||
fn send_file(from: &mut C, to: ContactId, other: &mut C, bytes: &[u8], name: &str) -> Event {
|
||||
let up = from.start_upload(bytes.len() as u64).expect("start");
|
||||
from.upload(&up, bytes).expect("upload");
|
||||
let out = from
|
||||
.compose_file(to, &up, name, "application/pdf", None)
|
||||
.expect("compose");
|
||||
from.deliver(&out).expect("deliver");
|
||||
let mut events = other.poll().expect("poll");
|
||||
assert_eq!(events.len(), 1, "{events:?}");
|
||||
events.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_of_every_shape_go_both_ways_and_come_back_byte_for_byte() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
|
||||
let sizes = [
|
||||
1,
|
||||
1000,
|
||||
FILE_CHUNK_PLAIN,
|
||||
FILE_CHUNK_PLAIN + 1,
|
||||
3 * FILE_CHUNK_PLAIN - 1,
|
||||
];
|
||||
for (i, size) in sizes.into_iter().enumerate() {
|
||||
let bytes = content(size, i as u8);
|
||||
let (from, to, other) = if i % 2 == 0 {
|
||||
(&mut eva, eva_side, &mut jan)
|
||||
} else {
|
||||
(&mut jan, jan_side, &mut eva)
|
||||
};
|
||||
let Event::File {
|
||||
file, name, seq, ..
|
||||
} = send_file(from, to, other, &bytes, "Lístky.pdf")
|
||||
else {
|
||||
panic!("not a file")
|
||||
};
|
||||
assert_eq!(name, "Lístky.pdf");
|
||||
assert_eq!(seq, i as u64 / 2 + 1, "a file shares the sender's seq");
|
||||
assert_eq!(file.size(), size as u64);
|
||||
assert_eq!(other.download(&file).expect("download"), bytes, "{size}");
|
||||
}
|
||||
// Every chunk on the relay is the same size, whatever the file's.
|
||||
let chunks = relay.stored_chunks();
|
||||
assert_eq!(chunks.len(), 1 + 1 + 1 + 2 + 3);
|
||||
assert!(chunks.iter().all(|c| c.len() == FILE_CHUNK_BYTES));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_is_a_message_a_receipt_covers_it_and_a_reaction_or_reply_can_name_it() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, true);
|
||||
eva.send(eva_side, "Posílám menu").expect("send");
|
||||
jan.poll().expect("poll");
|
||||
let Event::File { seq, .. } = send_file(&mut eva, eva_side, &mut jan, b"%PDF-1.7", "Menu.pdf")
|
||||
else {
|
||||
panic!("not a file")
|
||||
};
|
||||
assert_eq!(seq, 2);
|
||||
assert_eq!(eva.sent_seq(eva_side), Some(2));
|
||||
// Jan's receipt for it reached Eva.
|
||||
let events = eva.poll().expect("poll");
|
||||
assert!(
|
||||
events.contains(&Event::Delivered {
|
||||
contact: eva_side,
|
||||
upto: 2
|
||||
}),
|
||||
"{events:?}"
|
||||
);
|
||||
let the_file = MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 2,
|
||||
};
|
||||
let out = jan.react(jan_side, the_file, Some("👍")).expect("react");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
let out = jan
|
||||
.compose_text(jan_side, "Díky", Some(the_file))
|
||||
.expect("reply");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
let events = eva.poll().expect("poll");
|
||||
assert!(events.contains(&Event::Reaction {
|
||||
contact: eva_side,
|
||||
to: the_file,
|
||||
emoji: Some("👍".into())
|
||||
}));
|
||||
assert!(events.iter().any(|e| matches!(
|
||||
e,
|
||||
Event::Message { reply_to: Some(r), .. } if *r == the_file
|
||||
)));
|
||||
}
|
||||
|
||||
/// A relay that hands out another chunk than the one asked for, or a changed one.
|
||||
#[derive(Clone)]
|
||||
struct Lying {
|
||||
inner: MemoryTransport,
|
||||
how: fn(u32, Vec<u8>, &MemoryTransport, &tabellarius_protocol::FileId, &Token) -> Vec<u8>,
|
||||
}
|
||||
|
||||
impl Transport for Lying {
|
||||
fn create_mailbox(
|
||||
&self,
|
||||
r: &tabellarius_protocol::CreateMailbox,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.create_mailbox(r)
|
||||
}
|
||||
fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError> {
|
||||
self.inner.post(id, post, blob)
|
||||
}
|
||||
fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result<Vec<Vec<u8>>, TransportError> {
|
||||
self.inner.fetch(id, fetch)
|
||||
}
|
||||
fn acknowledge(&self, id: &MailboxId, f: &Token, h: &Sha256Hash) -> Result<(), TransportError> {
|
||||
self.inner.acknowledge(id, f, h)
|
||||
}
|
||||
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
|
||||
self.inner.create_invite(r)
|
||||
}
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
f: &Token,
|
||||
h: &Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.rotate_post_token(id, f, h)
|
||||
}
|
||||
fn claim_invite(
|
||||
&self,
|
||||
id: &tabellarius_protocol::InviteId,
|
||||
s: &Token,
|
||||
) -> Result<Vec<u8>, TransportError> {
|
||||
self.inner.claim_invite(id, s)
|
||||
}
|
||||
fn set_push(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
f: &Token,
|
||||
e: Option<&tabellarius_protocol::PushEndpoint>,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.set_push(id, f, e)
|
||||
}
|
||||
fn create_file(&self, r: &CreateFile) -> Result<(), TransportError> {
|
||||
self.inner.create_file(r)
|
||||
}
|
||||
fn put_chunk(
|
||||
&self,
|
||||
id: &tabellarius_protocol::FileId,
|
||||
u: &Token,
|
||||
i: u32,
|
||||
c: &[u8],
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.put_chunk(id, u, i, c)
|
||||
}
|
||||
fn get_chunk(
|
||||
&self,
|
||||
id: &tabellarius_protocol::FileId,
|
||||
f: &Token,
|
||||
i: u32,
|
||||
) -> Result<Vec<u8>, TransportError> {
|
||||
let honest = self.inner.get_chunk(id, f, i)?;
|
||||
Ok((self.how)(i, honest, &self.inner, id, f))
|
||||
}
|
||||
fn delete_file(
|
||||
&self,
|
||||
id: &tabellarius_protocol::FileId,
|
||||
u: &Token,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.delete_file(id, u)
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads a three-chunk file from Eva and gives Jan a client whose relay lies in the way `how`.
|
||||
fn through_a_lying_relay(
|
||||
how: fn(u32, Vec<u8>, &MemoryTransport, &tabellarius_protocol::FileId, &Token) -> Vec<u8>,
|
||||
) -> Result<Vec<u8>, ClientError> {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
|
||||
let bytes = content(2 * FILE_CHUNK_PLAIN + 10, 3);
|
||||
let Event::File { file, .. } = send_file(&mut eva, eva_side, &mut jan, &bytes, "a.bin") else {
|
||||
panic!("not a file")
|
||||
};
|
||||
let honest = jan.download(&file).expect("honest relay");
|
||||
assert_eq!(honest, bytes);
|
||||
let liar = Client::new("Jan", Lying { inner: relay, how }).expect("liar");
|
||||
liar.download(&file)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_tampered_with_swapped_or_repeated_on_the_relay_is_refused() {
|
||||
// One bit flipped in the middle chunk.
|
||||
let flipped = through_a_lying_relay(|i, mut c, _, _, _| {
|
||||
if i == 1 {
|
||||
c[1000] ^= 0x20;
|
||||
}
|
||||
c
|
||||
});
|
||||
assert_eq!(flipped, Err(ClientError::FileDamaged));
|
||||
// Chunks 0 and 1 swapped.
|
||||
let swapped = through_a_lying_relay(|i, c, inner, id, f| match i {
|
||||
0 => inner.get_chunk(id, f, 1).expect("chunk"),
|
||||
1 => inner.get_chunk(id, f, 0).expect("chunk"),
|
||||
_ => c,
|
||||
});
|
||||
assert_eq!(swapped, Err(ClientError::FileDamaged));
|
||||
// The middle chunk served as the last one too (a file cut short and padded out).
|
||||
let repeated = through_a_lying_relay(|i, c, inner, id, f| {
|
||||
if i == 2 {
|
||||
inner.get_chunk(id, f, 1).expect("chunk")
|
||||
} else {
|
||||
c
|
||||
}
|
||||
});
|
||||
assert_eq!(repeated, Err(ClientError::FileDamaged));
|
||||
// A chunk one byte short.
|
||||
let short = through_a_lying_relay(|_, mut c, _, _, _| {
|
||||
c.pop();
|
||||
c
|
||||
});
|
||||
assert_eq!(short, Err(ClientError::FileDamaged));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_from_another_file_does_not_open() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
|
||||
let bytes = content(100, 1);
|
||||
let Event::File { file: fa, .. } = send_file(&mut eva, eva_side, &mut jan, &bytes, "a") else {
|
||||
panic!("not a file")
|
||||
};
|
||||
let chunk_a = relay.stored_chunks().remove(0);
|
||||
assert!(fa.open(0, &chunk_a).is_ok());
|
||||
// The same bytes sent again: another key, so a's chunk does not open as b's.
|
||||
let Event::File { file: fb, .. } = send_file(&mut eva, eva_side, &mut jan, &bytes, "b") else {
|
||||
panic!("not a file")
|
||||
};
|
||||
assert_eq!(fb.open(0, &chunk_a), Err(ClientError::FileDamaged));
|
||||
assert_eq!(jan.download(&fb).expect("b"), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_chunk_is_not_found_and_the_download_works_once_it_is_up() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
|
||||
let bytes = content(FILE_CHUNK_PLAIN + 5, 9);
|
||||
let up = eva.start_upload(bytes.len() as u64).expect("start");
|
||||
eva.create_file(&up).expect("create");
|
||||
eva.put_chunk(&up, 0, up.part(&bytes, 0).expect("part"))
|
||||
.expect("chunk 0");
|
||||
// The message overtakes the upload.
|
||||
let out = eva
|
||||
.compose_file(eva_side, &up, "late.bin", "application/octet-stream", None)
|
||||
.expect("compose");
|
||||
eva.deliver(&out).expect("deliver");
|
||||
let Some(Event::File { file, .. }) = jan.poll().expect("poll").first().cloned() else {
|
||||
panic!("no file")
|
||||
};
|
||||
assert_eq!(
|
||||
jan.download(&file),
|
||||
Err(ClientError::Transport(TransportError::NotFound))
|
||||
);
|
||||
assert!(jan.get_chunk(&file, 0).is_ok(), "the first chunk is there");
|
||||
eva.put_chunk(&up, 1, up.part(&bytes, 1).expect("part"))
|
||||
.expect("chunk 1");
|
||||
assert_eq!(jan.download(&file).expect("download"), bytes);
|
||||
assert_eq!(
|
||||
jan.get_chunk(&file, 2),
|
||||
Err(ClientError::BadFile),
|
||||
"past the end"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_upload_resumes_after_a_crash_from_its_saved_form() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
|
||||
let bytes = content(3 * FILE_CHUNK_PLAIN, 4);
|
||||
let up = eva.start_upload(bytes.len() as u64).expect("start");
|
||||
let saved = serde_json::to_string(&up).expect("save");
|
||||
eva.create_file(&up).expect("create");
|
||||
eva.put_chunk(&up, 0, up.part(&bytes, 0).expect("part"))
|
||||
.expect("chunk 0");
|
||||
// Crash. The outbox gives the upload back; it starts again from the beginning.
|
||||
let again: FileUpload = serde_json::from_str(&saved).expect("restore");
|
||||
assert_eq!(again, up);
|
||||
eva.upload(&again, &bytes)
|
||||
.expect("create and chunk 0 again are accepted");
|
||||
let out = eva
|
||||
.compose_file(eva_side, &again, "a.bin", "application/octet-stream", None)
|
||||
.expect("compose");
|
||||
eva.deliver(&out).expect("deliver");
|
||||
let Some(Event::File { file, .. }) = jan.poll().expect("poll").first().cloned() else {
|
||||
panic!("no file")
|
||||
};
|
||||
assert_eq!(jan.download(&file).expect("download"), bytes);
|
||||
assert_eq!(relay.stored_chunks().len(), 3);
|
||||
// What is saved holds no plaintext, and its Debug shows no secret.
|
||||
assert!(!saved.contains("a.bin"));
|
||||
assert_eq!(format!("{up:?}"), "FileUpload(3 chunks)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wrong_bytes_for_a_file_are_refused_before_anything_is_sent() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (eva, _, _jan, _) = pair(&relay, false);
|
||||
let up = eva.start_upload(10).expect("start");
|
||||
assert_eq!(eva.upload(&up, &[1; 9]), Err(ClientError::BadFile));
|
||||
assert_eq!(eva.put_chunk(&up, 0, &[1; 11]), Err(ClientError::BadFile));
|
||||
assert_eq!(eva.put_chunk(&up, 1, &[1; 10]), Err(ClientError::BadFile));
|
||||
assert_eq!(relay.stored_chunks().len(), 0);
|
||||
assert_eq!(eva.start_upload(0).err(), Some(ClientError::BadFile));
|
||||
assert_eq!(
|
||||
eva.start_upload(MAX_FILE_BYTES + 1).err(),
|
||||
Some(ClientError::BadFile)
|
||||
);
|
||||
assert!(eva.start_upload(MAX_FILE_BYTES).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stranger_with_the_file_id_cannot_change_or_delete_it() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
|
||||
let bytes = content(50, 2);
|
||||
let Event::File { file, .. } = send_file(&mut eva, eva_side, &mut jan, &bytes, "a") else {
|
||||
panic!()
|
||||
};
|
||||
let stranger = Token::from_bytes([7; 32]);
|
||||
assert_eq!(
|
||||
relay.put_chunk(&file.id(), &stranger, 0, &vec![0; FILE_CHUNK_BYTES]),
|
||||
Err(TransportError::NotFound)
|
||||
);
|
||||
assert_eq!(
|
||||
relay.delete_file(&file.id(), &stranger),
|
||||
Err(TransportError::NotFound)
|
||||
);
|
||||
assert_eq!(jan.download(&file).expect("still there"), bytes);
|
||||
}
|
||||
@@ -19,6 +19,9 @@ fn pair(
|
||||
) {
|
||||
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");
|
||||
@@ -56,11 +59,15 @@ fn two_people_pair_through_an_invite_and_talk_both_ways() {
|
||||
vec![
|
||||
Event::Message {
|
||||
contact: jan_side,
|
||||
text: "Ahoj Jane, pivo ve čtvrtek?".into()
|
||||
text: "Ahoj Jane, pivo ve čtvrtek?".into(),
|
||||
seq: 1,
|
||||
reply_to: None,
|
||||
},
|
||||
Event::Message {
|
||||
contact: jan_side,
|
||||
text: "V sedm.".into()
|
||||
text: "V sedm.".into(),
|
||||
seq: 2,
|
||||
reply_to: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
@@ -69,7 +76,9 @@ fn two_people_pair_through_an_invite_and_talk_both_ways() {
|
||||
eva.poll().expect("poll"),
|
||||
vec![Event::Message {
|
||||
contact: eva_side,
|
||||
text: "Platí 🍺".into()
|
||||
text: "Platí 🍺".into(),
|
||||
seq: 1,
|
||||
reply_to: None,
|
||||
}]
|
||||
);
|
||||
// Everything delivered was acknowledged: nothing waits on the relay, and a second poll is
|
||||
@@ -165,7 +174,9 @@ fn junk_in_a_mailbox_is_dropped_and_never_shown() {
|
||||
eva.poll().expect("poll"),
|
||||
vec![Event::Message {
|
||||
contact: eva_side,
|
||||
text: "still here".into()
|
||||
text: "still here".into(),
|
||||
seq: 1,
|
||||
reply_to: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
//! Polls (`.agents/features/polls.md`). No I/O: runs on the Android emulator too.
|
||||
|
||||
use tabellarius_client::*;
|
||||
|
||||
type C = Client<MemoryTransport>;
|
||||
|
||||
fn pair(relay: &MemoryTransport, receipts: bool) -> (C, ContactId, C, ContactId) {
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
eva.set_receipts(receipts);
|
||||
jan.set_receipts(receipts);
|
||||
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 strings(xs: &[&str]) -> Vec<String> {
|
||||
xs.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
fn send(c: &mut C, out: Result<Outgoing, ClientError>) {
|
||||
let out = out.expect("compose");
|
||||
c.deliver(&out).expect("deliver");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_poll_arrives_votes_change_and_the_close_gives_both_sides_the_same_result() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
|
||||
eva.send(eva_side, "Ahoj").expect("send");
|
||||
let options = strings(&["Italská", "Thajská", "Doma"]);
|
||||
let out = eva.compose_poll(eva_side, "Kam na večeři?", &options, true);
|
||||
send(&mut eva, out);
|
||||
assert_eq!(eva.sent_seq(eva_side), Some(2), "a poll is a message");
|
||||
let poll = MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 2,
|
||||
};
|
||||
let got = jan.poll().expect("poll");
|
||||
assert_eq!(
|
||||
got[1],
|
||||
Event::Poll {
|
||||
contact: jan_side,
|
||||
seq: 2,
|
||||
question: "Kam na večeři?".into(),
|
||||
options: options.clone(),
|
||||
multiple: true,
|
||||
}
|
||||
);
|
||||
// Jan votes, changes his mind, takes it back, votes again; Eva votes in her own poll.
|
||||
for choices in [&[0u8][..], &[0, 1], &[], &[1, 2]] {
|
||||
let out = jan.vote(jan_side, poll, choices);
|
||||
send(&mut jan, out);
|
||||
}
|
||||
let out = eva.vote(eva_side, poll, &[1]);
|
||||
send(&mut eva, out);
|
||||
let votes: Vec<Vec<u8>> = eva
|
||||
.poll()
|
||||
.expect("poll")
|
||||
.into_iter()
|
||||
.map(|e| match e {
|
||||
Event::Vote {
|
||||
contact,
|
||||
poll: p,
|
||||
choices,
|
||||
} if contact == eva_side && p == poll => choices,
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(votes, vec![vec![0], vec![0, 1], vec![], vec![1, 2]]);
|
||||
assert_eq!(
|
||||
jan.poll().expect("poll"),
|
||||
vec![Event::Vote {
|
||||
contact: jan_side,
|
||||
poll,
|
||||
choices: vec![1]
|
||||
}]
|
||||
);
|
||||
// A poll can be answered and reacted to like a text.
|
||||
let out = jan.compose_text(jan_side, "Thajská!", Some(poll));
|
||||
send(&mut jan, out);
|
||||
let out = jan.react(jan_side, poll, Some("👍"));
|
||||
send(&mut jan, out);
|
||||
assert_eq!(eva.poll().expect("poll").len(), 2);
|
||||
|
||||
// Jan cannot close Eva's poll; Eva closes it.
|
||||
assert_eq!(
|
||||
jan.close_poll(jan_side, poll).err(),
|
||||
Some(ClientError::BadPoll)
|
||||
);
|
||||
let out = eva.close_poll(eva_side, poll);
|
||||
send(&mut eva, out);
|
||||
let final_ = vec![
|
||||
Ballot {
|
||||
author: jan.author(),
|
||||
choices: vec![1, 2],
|
||||
},
|
||||
Ballot {
|
||||
author: eva.author(),
|
||||
choices: vec![1],
|
||||
},
|
||||
];
|
||||
let got = jan.poll().expect("poll");
|
||||
let [Event::PollClosed {
|
||||
contact,
|
||||
poll: p,
|
||||
ballots,
|
||||
}] = got.as_slice()
|
||||
else {
|
||||
panic!("{got:?}")
|
||||
};
|
||||
assert_eq!((*contact, *p), (jan_side, poll));
|
||||
let mut sorted = ballots.clone();
|
||||
sorted.sort_by_key(|b| b.author.as_bytes().to_vec());
|
||||
let mut expected = final_.clone();
|
||||
expected.sort_by_key(|b| b.author.as_bytes().to_vec());
|
||||
assert_eq!(sorted, expected);
|
||||
assert_eq!(
|
||||
jan.vote(jan_side, poll, &[0]).err(),
|
||||
Some(ClientError::PollClosed)
|
||||
);
|
||||
assert_eq!(
|
||||
eva.vote(eva_side, poll, &[0]).err(),
|
||||
Some(ClientError::PollClosed)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vote_that_crosses_the_close_is_counted_nowhere() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
|
||||
let out = eva.compose_poll(eva_side, "Pátek?", &strings(&["ano", "ne"]), false);
|
||||
send(&mut eva, out);
|
||||
jan.poll().expect("poll");
|
||||
let poll = MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 1,
|
||||
};
|
||||
let out = jan.vote(jan_side, poll, &[0]);
|
||||
send(&mut jan, out);
|
||||
eva.poll().expect("poll");
|
||||
// Both at once: Jan changes his vote while Eva closes.
|
||||
let out = jan.vote(jan_side, poll, &[1]);
|
||||
send(&mut jan, out);
|
||||
let out = eva.close_poll(eva_side, poll);
|
||||
send(&mut eva, out);
|
||||
|
||||
assert_eq!(
|
||||
eva.poll().expect("poll"),
|
||||
vec![],
|
||||
"the late vote is dropped"
|
||||
);
|
||||
let got = jan.poll().expect("poll");
|
||||
assert_eq!(
|
||||
got,
|
||||
vec![Event::PollClosed {
|
||||
contact: jan_side,
|
||||
poll,
|
||||
ballots: vec![Ballot {
|
||||
author: jan.author(),
|
||||
choices: vec![0]
|
||||
}],
|
||||
}],
|
||||
"Jan's result is Eva's: his first vote, not the one that crossed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_receipt_covers_a_poll() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay, true);
|
||||
let out = eva.compose_poll(eva_side, "Pivo?", &strings(&["ano", "jasně"]), false);
|
||||
send(&mut eva, out);
|
||||
let got = jan.poll().expect("poll");
|
||||
assert!(
|
||||
matches!(got.as_slice(), [Event::Poll { seq: 1, .. }]),
|
||||
"{got:?}"
|
||||
);
|
||||
assert!(eva.poll().expect("poll").contains(&Event::Delivered {
|
||||
contact: eva_side,
|
||||
upto: 1
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_poll_survives_a_restart_open_or_closed_with_its_votes() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
|
||||
let out = eva.compose_poll(eva_side, "Kdy?", &strings(&["pá", "so", "ne"]), true);
|
||||
send(&mut eva, out);
|
||||
let out = eva.compose_poll(eva_side, "Kde?", &strings(&["u nás", "u vás"]), false);
|
||||
send(&mut eva, out);
|
||||
jan.poll().expect("poll");
|
||||
let when = MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 1,
|
||||
};
|
||||
let where_ = MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 2,
|
||||
};
|
||||
let out = jan.vote(jan_side, when, &[0, 2]);
|
||||
send(&mut jan, out);
|
||||
eva.poll().expect("poll");
|
||||
let out = eva.close_poll(eva_side, where_);
|
||||
send(&mut eva, out);
|
||||
jan.poll().expect("poll");
|
||||
|
||||
let mut eva = C::restore(&eva.snapshot().expect("snapshot"), relay.clone()).expect("eva");
|
||||
let mut jan = C::restore(&jan.snapshot().expect("snapshot"), relay.clone()).expect("jan");
|
||||
// Closed stays closed, on both sides.
|
||||
assert_eq!(
|
||||
jan.vote(jan_side, where_, &[0]).err(),
|
||||
Some(ClientError::PollClosed)
|
||||
);
|
||||
assert_eq!(
|
||||
eva.close_poll(eva_side, where_).err(),
|
||||
Some(ClientError::PollClosed)
|
||||
);
|
||||
// The open one keeps Jan's vote: Eva's close after the restart carries it.
|
||||
let out = eva.close_poll(eva_side, when);
|
||||
send(&mut eva, out);
|
||||
assert_eq!(
|
||||
jan.poll().expect("poll"),
|
||||
vec![Event::PollClosed {
|
||||
contact: jan_side,
|
||||
poll: when,
|
||||
ballots: vec![Ballot {
|
||||
author: jan.author(),
|
||||
choices: vec![0, 2]
|
||||
}],
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Wake-up (`.agents/features/wake-up.md` §2.4) on the in-memory relay: which mailboxes a client
|
||||
//! fetches, and an endpoint per mailbox, set only with that mailbox's fetch token.
|
||||
|
||||
use tabellarius_client::*;
|
||||
use tabellarius_protocol::PushEndpoint;
|
||||
|
||||
fn endpoint(path: &str) -> PushEndpoint {
|
||||
PushEndpoint::parse(&format!("https://push.invalid/{path}")).expect("endpoint")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inboxes_are_the_open_welcome_mailboxes_then_each_contacts_inbox() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
assert!(eva.inboxes().is_empty());
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let welcome = eva.inboxes();
|
||||
assert_eq!(
|
||||
welcome.len(),
|
||||
1,
|
||||
"the welcome mailbox, while the invite is open"
|
||||
);
|
||||
// Someone who joins wakes the inviter through it.
|
||||
eva.set_push(&welcome[0], Some(&endpoint("upWelcome")))
|
||||
.expect("set");
|
||||
assert_eq!(
|
||||
relay.push_endpoint(&welcome[0]).as_deref(),
|
||||
Some("https://push.invalid/upWelcome")
|
||||
);
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
assert_eq!(jan.inboxes().len(), 1);
|
||||
eva.poll().expect("poll");
|
||||
// Joined: the welcome mailbox is dropped, Jan's inbox at Eva's is there.
|
||||
let after = eva.inboxes();
|
||||
assert_eq!(after.len(), 1);
|
||||
assert_ne!(after[0], welcome[0]);
|
||||
// Every mailbox is different: one endpoint each never links them.
|
||||
let mut all = eva.inboxes();
|
||||
all.extend(jan.inboxes());
|
||||
all.sort_by_key(|m| m.to_wire());
|
||||
all.dedup();
|
||||
assert_eq!(all.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_mailbox_of_ones_own_takes_an_endpoint_and_clearing_removes_it() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
let (mine, his) = (eva.inboxes()[0], jan.inboxes()[0]);
|
||||
assert_eq!(
|
||||
eva.set_push(&his, Some(&endpoint("upX"))),
|
||||
Err(ClientError::UnknownContact)
|
||||
);
|
||||
assert_eq!(relay.push_endpoint(&his), None);
|
||||
eva.set_push(&mine, Some(&endpoint("upEva"))).expect("set");
|
||||
eva.set_push(&mine, Some(&endpoint("upEva2")))
|
||||
.expect("replace");
|
||||
assert_eq!(
|
||||
relay.push_endpoint(&mine).as_deref(),
|
||||
Some("https://push.invalid/upEva2")
|
||||
);
|
||||
eva.set_push(&mine, None).expect("clear");
|
||||
assert_eq!(relay.push_endpoint(&mine), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_contacts_inbox_is_still_listed() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
let out = jan.block(jan_side).expect("block");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
// Listed, so turning wake-ups off clears it too; nothing reaches it to wake anyone.
|
||||
assert_eq!(jan.inboxes().len(), 1);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//! Reactions and replies (`.agents/features/reactions-replies.md`). 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");
|
||||
// Receipts have their own tests; here they would only add events.
|
||||
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 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 contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_sides_name_a_message_the_same_way_and_a_reply_carries_its_reference() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
assert_ne!(eva.author(), jan.author());
|
||||
assert_eq!(jan.contact_author(jan_side), Some(eva.author()));
|
||||
assert_eq!(eva.contact_author(eva_side), Some(jan.author()));
|
||||
|
||||
eva.send(eva_side, "Oběd?").expect("send");
|
||||
let got = jan.poll().expect("poll");
|
||||
let [Event::Message { seq, .. }] = got.as_slice() else {
|
||||
panic!("{got:?}")
|
||||
};
|
||||
let lunch = MessageRef {
|
||||
author: jan.contact_author(jan_side).expect("author"),
|
||||
seq: *seq,
|
||||
};
|
||||
let out = jan
|
||||
.compose_text(jan_side, "Jasně, ve 12", Some(lunch))
|
||||
.expect("reply");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
assert_eq!(
|
||||
eva.poll().expect("poll"),
|
||||
vec![Event::Message {
|
||||
contact: eva_side,
|
||||
text: "Jasně, ve 12".into(),
|
||||
seq: 1,
|
||||
reply_to: Some(MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 1
|
||||
}),
|
||||
}]
|
||||
);
|
||||
// A reply to one's own message is a reply too.
|
||||
let own = MessageRef {
|
||||
author: jan.author(),
|
||||
seq: 1,
|
||||
};
|
||||
let out = jan
|
||||
.compose_text(jan_side, "Nebo ve 13?", Some(own))
|
||||
.expect("reply");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
let got = eva.poll().expect("poll");
|
||||
assert!(
|
||||
matches!(got.as_slice(), [Event::Message { seq: 2, reply_to: Some(r), .. }] if *r == MessageRef { author: jan.author(), seq: 1 }),
|
||||
"{got:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reaction_is_set_replaced_and_removed() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
eva.send(eva_side, "Mám novou práci!").expect("send");
|
||||
jan.poll().expect("poll");
|
||||
let news = MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 1,
|
||||
};
|
||||
for emoji in [Some("👍"), Some("🎉"), None] {
|
||||
let out = jan.react(jan_side, news, emoji).expect("react");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
}
|
||||
assert_eq!(
|
||||
eva.poll().expect("poll"),
|
||||
vec![
|
||||
Event::Reaction {
|
||||
contact: eva_side,
|
||||
to: news,
|
||||
emoji: Some("👍".into())
|
||||
},
|
||||
Event::Reaction {
|
||||
contact: eva_side,
|
||||
to: news,
|
||||
emoji: Some("🎉".into())
|
||||
},
|
||||
Event::Reaction {
|
||||
contact: eva_side,
|
||||
to: news,
|
||||
emoji: None
|
||||
},
|
||||
]
|
||||
);
|
||||
// A family ZWJ sequence (25 bytes) is one emoji, and fits.
|
||||
let family = "👨👩👧👦";
|
||||
assert!(family.len() <= MAX_EMOJI_BYTES);
|
||||
let out = eva
|
||||
.react(eva_side, news, Some(family))
|
||||
.expect("own message");
|
||||
eva.deliver(&out).expect("deliver");
|
||||
let got = jan.poll().expect("poll");
|
||||
assert!(
|
||||
matches!(got.as_slice(), [Event::Reaction { emoji: Some(e), .. }] if e == family),
|
||||
"{got:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reference_to_a_message_that_does_not_exist_or_a_bad_emoji_is_refused_before_sealing() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
eva.send(eva_side, "jedna").expect("send");
|
||||
jan.poll().expect("poll");
|
||||
let first = MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 1,
|
||||
};
|
||||
let stranger = Client::new("Cizí", relay.clone())
|
||||
.expect("stranger")
|
||||
.author();
|
||||
let before = relay.waiting_blobs();
|
||||
for bad in [
|
||||
MessageRef { seq: 2, ..first },
|
||||
MessageRef { seq: 0, ..first },
|
||||
MessageRef {
|
||||
author: jan.author(),
|
||||
seq: 1,
|
||||
},
|
||||
MessageRef {
|
||||
author: stranger,
|
||||
seq: 1,
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
jan.react(jan_side, bad, Some("👍")).err(),
|
||||
Some(ClientError::BadReference),
|
||||
"{bad:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
jan.compose_text(jan_side, "?", Some(bad)).err(),
|
||||
Some(ClientError::BadReference),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
jan.react(jan_side, first, Some(&"a".repeat(MAX_EMOJI_BYTES + 1)))
|
||||
.err(),
|
||||
Some(ClientError::TooLong)
|
||||
);
|
||||
for bad in ["", "👍\n", "\u{7}"] {
|
||||
assert_eq!(
|
||||
jan.react(jan_side, first, Some(bad)).err(),
|
||||
Some(ClientError::BadReference),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(relay.waiting_blobs(), before, "nothing was posted");
|
||||
// A refused reply used no seq: the next text is still Jan's first.
|
||||
jan.send(jan_side, "ok").expect("send");
|
||||
let got = eva.poll().expect("poll");
|
||||
assert!(
|
||||
matches!(got.as_slice(), [Event::Message { seq: 1, .. }]),
|
||||
"{got:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_contacts_reaction_is_dropped() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
eva.send(eva_side, "ahoj").expect("send");
|
||||
jan.poll().expect("poll");
|
||||
let out = jan
|
||||
.react(
|
||||
jan_side,
|
||||
MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 1,
|
||||
},
|
||||
Some("😡"),
|
||||
)
|
||||
.expect("react");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
assert_eq!(eva.poll().expect("poll"), vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_relay_holds_no_emoji_and_no_reply_text() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
eva.send(eva_side, "CANARY-first-text").expect("send");
|
||||
jan.poll().expect("poll");
|
||||
let first = MessageRef {
|
||||
author: eva.author(),
|
||||
seq: 1,
|
||||
};
|
||||
let emoji = "🦜CANARY🦜";
|
||||
let out = jan.react(jan_side, first, Some(emoji)).expect("react");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
let out = jan
|
||||
.compose_text(jan_side, "CANARY-reply-text", Some(first))
|
||||
.expect("reply");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
let stored = relay.everything_stored();
|
||||
for needle in [
|
||||
emoji,
|
||||
"CANARY",
|
||||
"replyTo",
|
||||
"reaction",
|
||||
&eva.author().to_wire(),
|
||||
] {
|
||||
assert!(
|
||||
!contains(&stored, needle.as_bytes()),
|
||||
"{needle} is readable on the relay"
|
||||
);
|
||||
}
|
||||
assert_eq!(eva.poll().expect("poll").len(), 2);
|
||||
}
|
||||
@@ -51,6 +51,7 @@ impl Http {
|
||||
"200" | "201" | "204" => Ok(resp[split + 4..].to_vec()),
|
||||
"404" => Err(TransportError::NotFound),
|
||||
"409" => Err(TransportError::Conflict),
|
||||
"507" => Err(TransportError::Full),
|
||||
_ => Err(TransportError::Failed),
|
||||
}
|
||||
}
|
||||
@@ -98,6 +99,20 @@ impl Transport for Http {
|
||||
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)
|
||||
@@ -115,13 +130,57 @@ impl Transport for Http {
|
||||
serde_json::from_slice(&body).map_err(|_| TransportError::Failed)?;
|
||||
Ok(claimed.key_package.bytes().to_vec())
|
||||
}
|
||||
fn set_push(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
endpoint: Option<&PushEndpoint>,
|
||||
) -> Result<(), TransportError> {
|
||||
let path = format!("/v0/mailboxes/{}/push", id.to_wire());
|
||||
match endpoint {
|
||||
Some(e) => {
|
||||
let body = serde_json::to_vec(&SetPush {
|
||||
endpoint: e.clone(),
|
||||
})
|
||||
.map_err(|_| TransportError::Failed)?;
|
||||
self.call("PUT", &path, Some(fetch), &body, true)
|
||||
}
|
||||
None => self.call("DELETE", &path, Some(fetch), &[], false),
|
||||
}
|
||||
.map(|_| ())
|
||||
}
|
||||
fn create_file(&self, req: &CreateFile) -> Result<(), TransportError> {
|
||||
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
|
||||
self.call("POST", "/v0/files", None, &body, true)
|
||||
.map(|_| ())
|
||||
}
|
||||
fn put_chunk(
|
||||
&self,
|
||||
id: &FileId,
|
||||
upload: &Token,
|
||||
index: u32,
|
||||
chunk: &[u8],
|
||||
) -> Result<(), TransportError> {
|
||||
let path = format!("/v0/files/{}/chunks/{index}", id.to_wire());
|
||||
self.call("PUT", &path, Some(upload), chunk, false)
|
||||
.map(|_| ())
|
||||
}
|
||||
fn get_chunk(&self, id: &FileId, fetch: &Token, index: u32) -> Result<Vec<u8>, TransportError> {
|
||||
let path = format!("/v0/files/{}/chunks/{index}", id.to_wire());
|
||||
self.call("GET", &path, Some(fetch), &[], false)
|
||||
}
|
||||
fn delete_file(&self, id: &FileId, upload: &Token) -> Result<(), TransportError> {
|
||||
let path = format!("/v0/files/{}", id.to_wire());
|
||||
self.call("DELETE", &path, Some(upload), &[], false)
|
||||
.map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the real relay on 127.0.0.1:<free port> with its database in `db`.
|
||||
fn start_relay(db: &std::path::Path) -> SocketAddr {
|
||||
let store = Arc::new(Store::open(db).expect("store"));
|
||||
let clock: Clock = Arc::new(|| 1_794_000_000);
|
||||
let app = router(AppState { store, clock });
|
||||
let app = router(AppState::new(store, clock));
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
@@ -152,6 +211,8 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
|
||||
|
||||
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");
|
||||
@@ -171,6 +232,21 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
|
||||
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");
|
||||
// A reaction (F27) waits with them: its emoji must not be readable either.
|
||||
let emoji = "🦜CANARY🦜";
|
||||
let mine = MessageRef {
|
||||
author: jan.author(),
|
||||
seq: 1,
|
||||
};
|
||||
let out = jan.react(jan_side, mine, Some(emoji)).expect("react");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
// And a poll (F28): its question and options neither.
|
||||
let question = "POLL-QUESTION-CANARY";
|
||||
let options = vec!["OPTION-CANARY-A".to_string(), "OPTION-CANARY-B".to_string()];
|
||||
let out = jan
|
||||
.compose_poll(jan_side, question, &options, false)
|
||||
.expect("poll");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
|
||||
// Snapshot the database while both messages wait, before anyone fetches.
|
||||
let waiting = std::fs::read(&db).expect("db");
|
||||
@@ -178,21 +254,43 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
|
||||
jan.poll().expect("poll"),
|
||||
vec![Event::Message {
|
||||
contact: jan_side,
|
||||
text: canary.into()
|
||||
text: canary.into(),
|
||||
seq: 1,
|
||||
reply_to: None,
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
eva.poll().expect("poll"),
|
||||
vec![Event::Message {
|
||||
contact: eva_side,
|
||||
text: format!("re: {canary}")
|
||||
}]
|
||||
vec![
|
||||
Event::Message {
|
||||
contact: eva_side,
|
||||
text: format!("re: {canary}"),
|
||||
seq: 1,
|
||||
reply_to: None,
|
||||
},
|
||||
Event::Reaction {
|
||||
contact: eva_side,
|
||||
to: mine,
|
||||
emoji: Some(emoji.into()),
|
||||
},
|
||||
Event::Poll {
|
||||
contact: eva_side,
|
||||
seq: 2,
|
||||
question: question.into(),
|
||||
options: options.clone(),
|
||||
multiple: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
let after = std::fs::read(&db).expect("db");
|
||||
|
||||
for snapshot in [&invited, &waiting, &after] {
|
||||
for (what, needle) in [
|
||||
("canary", canary.as_bytes()),
|
||||
("reaction", emoji.as_bytes()),
|
||||
("poll question", question.as_bytes()),
|
||||
("poll option", options[0].as_bytes()),
|
||||
("poll option", options[1].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()),
|
||||
@@ -206,3 +304,117 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
|
||||
// The messages were there, as ciphertext: the database grew while they waited.
|
||||
assert!(waiting.len() >= 4096, "the relay stored something");
|
||||
}
|
||||
|
||||
/// Files (`.agents/features/files.md` §5): a photo through the real relay. Its name, type,
|
||||
/// thumbnail and content are in no byte of the relay's database, before or after the download, and
|
||||
/// every chunk the relay holds is the same size.
|
||||
#[test]
|
||||
fn a_file_goes_through_the_real_relay_which_never_sees_its_name_type_or_content() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let db = dir.path().join("relay.db");
|
||||
let relay = Http(start_relay(&db));
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
eva.set_receipts(false);
|
||||
jan.set_receipts(false);
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
jan.poll().expect("poll");
|
||||
|
||||
// Two chunks and a bit, every one of them full of canaries, so any plaintext would be found.
|
||||
let line = b"FILE-CONTENT-CANARY-7f3a ";
|
||||
let content: Vec<u8> = line
|
||||
.iter()
|
||||
.copied()
|
||||
.cycle()
|
||||
.take(2 * FILE_CHUNK_PLAIN + 999)
|
||||
.collect();
|
||||
let name = "FILENAME-CANARY-Menu.jpg";
|
||||
let mime = "image/x-mime-canary";
|
||||
let mut thumb = vec![0xFF, 0xD8, 0xFF, 0xE0];
|
||||
thumb.extend_from_slice(b"THUMBNAIL-CANARY");
|
||||
let up = jan.start_upload(content.len() as u64).expect("start");
|
||||
jan.upload(&up, &content).expect("upload");
|
||||
let out = jan
|
||||
.compose_file(jan_side, &up, name, mime, Some(&thumb))
|
||||
.expect("compose");
|
||||
jan.deliver(&out).expect("deliver");
|
||||
let waiting = std::fs::read(&db).expect("db");
|
||||
|
||||
let events = eva.poll().expect("poll");
|
||||
let Some(Event::File {
|
||||
file,
|
||||
name: got_name,
|
||||
mime: got_mime,
|
||||
thumb: got_thumb,
|
||||
seq,
|
||||
..
|
||||
}) = events.first().cloned()
|
||||
else {
|
||||
panic!("no file: {events:?}");
|
||||
};
|
||||
assert_eq!((got_name.as_str(), got_mime.as_str(), seq), (name, mime, 1));
|
||||
assert_eq!(got_thumb.as_deref(), Some(thumb.as_slice()));
|
||||
assert_eq!(file.chunks(), 3);
|
||||
assert_eq!(eva.download(&file).expect("download"), content);
|
||||
let after = std::fs::read(&db).expect("db");
|
||||
|
||||
for snapshot in [&waiting, &after] {
|
||||
for (what, needle) in [
|
||||
("file content", &line[..]),
|
||||
("file name", name.as_bytes()),
|
||||
("media type", mime.as_bytes()),
|
||||
("thumbnail", b"THUMBNAIL-CANARY".as_slice()),
|
||||
] {
|
||||
assert!(
|
||||
!contains(snapshot, needle),
|
||||
"{what} is readable in the relay's database"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
waiting.len() >= 3 * FILE_CHUNK_BYTES,
|
||||
"the three chunks were stored"
|
||||
);
|
||||
// The sender deletes it early; the relay answers 404 from then on.
|
||||
jan.delete_file(&up).expect("delete");
|
||||
assert_eq!(
|
||||
eva.get_chunk(&file, 0),
|
||||
Err(ClientError::Transport(TransportError::NotFound))
|
||||
);
|
||||
}
|
||||
|
||||
// Wake-up (`.agents/features/wake-up.md` §2.4): an endpoint per mailbox, set and cleared through the
|
||||
// real relay with the mailbox's fetch token.
|
||||
#[test]
|
||||
fn each_inbox_takes_its_own_push_endpoint_through_the_real_relay() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let db = dir.path().join("relay.db");
|
||||
let relay = Http(start_relay(&db));
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
let (eva_boxes, jan_boxes) = (eva.inboxes(), jan.inboxes());
|
||||
assert_eq!((eva_boxes.len(), jan_boxes.len()), (1, 1));
|
||||
let endpoint = |path: &str| PushEndpoint::parse(&format!("https://push.invalid/{path}"));
|
||||
let a = endpoint("upEvaOnly1").expect("endpoint");
|
||||
eva.set_push(&eva_boxes[0], Some(&a)).expect("set");
|
||||
jan.set_push(
|
||||
&jan_boxes[0],
|
||||
Some(&endpoint("upJanOnly2").expect("endpoint")),
|
||||
)
|
||||
.expect("set");
|
||||
let stored = std::fs::read(&db).expect("db");
|
||||
assert!(contains(&stored, b"upEvaOnly1") && contains(&stored, b"upJanOnly2"));
|
||||
// Not Jan's mailbox: Eva cannot set it.
|
||||
assert_eq!(
|
||||
eva.set_push(&jan_boxes[0], Some(&a)),
|
||||
Err(ClientError::UnknownContact)
|
||||
);
|
||||
eva.set_push(&eva_boxes[0], None).expect("clear");
|
||||
// Nothing is posted after this: a post would make the relay try to wake `push.invalid`, and no
|
||||
// test reaches for the network.
|
||||
}
|
||||
|
||||
@@ -5,10 +5,16 @@ 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 = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
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");
|
||||
@@ -39,7 +45,7 @@ fn texts(events: Vec<Event>) -> Vec<String> {
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::Message { text, .. } => Some(text),
|
||||
Event::Joined { .. } => None,
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -64,8 +70,8 @@ fn both_sides_restart_mid_conversation_and_keep_talking() {
|
||||
#[test]
|
||||
fn an_invite_waiting_survives_a_restart() {
|
||||
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 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");
|
||||
@@ -84,7 +90,7 @@ 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 = Client::new("Petr", relay.clone()).expect("petr");
|
||||
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");
|
||||
@@ -99,8 +105,8 @@ fn a_restored_client_gives_a_new_contact_a_new_id() {
|
||||
#[test]
|
||||
fn the_staged_calls_post_nothing_and_acknowledge_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 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");
|
||||
@@ -137,8 +143,8 @@ fn the_staged_calls_post_nothing_and_acknowledge_nothing() {
|
||||
#[test]
|
||||
fn a_crash_between_receive_and_finish_loses_nothing_and_shows_nothing_twice() {
|
||||
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 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.
|
||||
@@ -168,7 +174,9 @@ fn a_crash_between_receive_and_finish_loses_nothing_and_shows_nothing_twice() {
|
||||
eva.poll().expect("poll"),
|
||||
[Event::Message {
|
||||
contact,
|
||||
text: "funguje to".into()
|
||||
text: "funguje to".into(),
|
||||
seq: 1,
|
||||
reply_to: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -317,6 +325,49 @@ impl Transport for Flaky {
|
||||
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
|
||||
self.inner.create_invite(r)
|
||||
}
|
||||
fn create_file(&self, r: &tabellarius_protocol::CreateFile) -> Result<(), TransportError> {
|
||||
self.inner.create_file(r)
|
||||
}
|
||||
fn put_chunk(
|
||||
&self,
|
||||
id: &tabellarius_protocol::FileId,
|
||||
upload: &tabellarius_protocol::Token,
|
||||
index: u32,
|
||||
chunk: &[u8],
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.put_chunk(id, upload, index, chunk)
|
||||
}
|
||||
fn get_chunk(
|
||||
&self,
|
||||
id: &tabellarius_protocol::FileId,
|
||||
fetch: &tabellarius_protocol::Token,
|
||||
index: u32,
|
||||
) -> Result<Vec<u8>, TransportError> {
|
||||
self.inner.get_chunk(id, fetch, index)
|
||||
}
|
||||
fn delete_file(
|
||||
&self,
|
||||
id: &tabellarius_protocol::FileId,
|
||||
upload: &tabellarius_protocol::Token,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.delete_file(id, upload)
|
||||
}
|
||||
fn set_push(
|
||||
&self,
|
||||
id: &tabellarius_protocol::MailboxId,
|
||||
fetch: &tabellarius_protocol::Token,
|
||||
endpoint: Option<&tabellarius_protocol::PushEndpoint>,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.set_push(id, fetch, endpoint)
|
||||
}
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &tabellarius_protocol::MailboxId,
|
||||
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,
|
||||
@@ -332,8 +383,8 @@ impl Transport for Flaky {
|
||||
fn finish_acknowledges_nothing_when_delivering_fails() {
|
||||
let relay = MemoryTransport::default();
|
||||
let flaky = Flaky::new(&relay);
|
||||
let mut eva = Client::new("Eva", flaky.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
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");
|
||||
|
||||
@@ -362,10 +413,10 @@ fn finish_acknowledges_nothing_when_delivering_fails() {
|
||||
fn a_relay_failing_part_way_returns_what_was_processed() {
|
||||
let relay = MemoryTransport::default();
|
||||
let flaky = Flaky::new(&relay);
|
||||
let mut eva = Client::new("Eva", flaky.clone()).expect("eva");
|
||||
let mut eva = quiet(Client::new("Eva", flaky.clone()).expect("eva"));
|
||||
let mut friends = Vec::new();
|
||||
for name in ["Jan", "Petr"] {
|
||||
let mut friend = Client::new(name, relay.clone()).expect("friend");
|
||||
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));
|
||||
@@ -398,8 +449,8 @@ fn a_relay_failing_part_way_returns_what_was_processed() {
|
||||
#[test]
|
||||
fn a_used_welcome_mailbox_is_no_longer_fetched() {
|
||||
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 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");
|
||||
@@ -415,8 +466,8 @@ fn a_used_welcome_mailbox_is_no_longer_fetched() {
|
||||
#[test]
|
||||
fn a_forgotten_invite_is_no_longer_fetched() {
|
||||
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 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);
|
||||
@@ -439,7 +490,7 @@ fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
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 = Client::new("Petr Zapomenutý", relay.clone()).expect("petr");
|
||||
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 {
|
||||
|
||||
+184
-1
@@ -23,6 +23,19 @@ pub const MAX_BLOBS_PER_FETCH: usize = 100;
|
||||
pub const BLOB_TTL_SECS: i64 = 30 * 24 * 3600;
|
||||
/// An unclaimed invite expires after this many seconds (7 days, `PROTOCOL.md` §4).
|
||||
pub const INVITE_TTL_SECS: i64 = 7 * 24 * 3600;
|
||||
/// The longest push endpoint a mailbox may hold (UnifiedPush's own limit, `wake-up.md` §2.1).
|
||||
pub const MAX_PUSH_ENDPOINT_BYTES: usize = 1000;
|
||||
/// The body of every wake: a constant, so it carries nothing (`PROTOCOL.md` §6).
|
||||
pub const WAKE_BODY: &[u8] = b"wake";
|
||||
/// A mailbox is woken at most once in this many seconds.
|
||||
pub const WAKE_EVERY_SECS: i64 = 60;
|
||||
/// Every file chunk on the wire is exactly this many bytes, the last one too (250 KiB; G41,
|
||||
/// `.agents/features/files.md` §2.1).
|
||||
pub const FILE_CHUNK_BYTES: usize = 256_000;
|
||||
/// The most chunks one file may have: 100 MiB of plaintext at 255 984 bytes a chunk.
|
||||
pub const MAX_FILE_CHUNKS: u32 = 410;
|
||||
/// A file that is not complete this long after it was created is purged (`files.md` §2.3).
|
||||
pub const INCOMPLETE_FILE_TTL_SECS: i64 = 24 * 3600;
|
||||
|
||||
/// Why a value from the wire was refused. Carries no part of the input.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -35,6 +48,8 @@ pub enum ParseError {
|
||||
Scheme,
|
||||
/// More bytes than the protocol allows.
|
||||
TooLarge { max: usize },
|
||||
/// Not a push endpoint the protocol accepts (`wake-up.md` §2.1).
|
||||
Endpoint,
|
||||
}
|
||||
|
||||
impl fmt::Display for ParseError {
|
||||
@@ -46,6 +61,7 @@ impl fmt::Display for ParseError {
|
||||
}
|
||||
ParseError::Scheme => write!(f, "expected 'Bearer <token>'"),
|
||||
ParseError::TooLarge { max } => write!(f, "more than {max} bytes"),
|
||||
ParseError::Endpoint => write!(f, "not an https push endpoint"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,6 +155,17 @@ fixed_bytes!(
|
||||
InviteId,
|
||||
16
|
||||
);
|
||||
fixed_bytes!(
|
||||
/// A file on the relay: 16 random bytes made by its uploader (`PROTOCOL.md` §8, files).
|
||||
FileId,
|
||||
16
|
||||
);
|
||||
fixed_bytes!(
|
||||
/// A message's author: the 16 random bytes in their MLS credential, made on their device, never
|
||||
/// a name. With the author's `seq` it names a message (`PROTOCOL.md` §4, reactions and replies).
|
||||
Author,
|
||||
16
|
||||
);
|
||||
fixed_bytes!(
|
||||
/// SHA-256 of a token, or of a blob when it is acknowledged. The relay stores token hashes only.
|
||||
Sha256Hash,
|
||||
@@ -151,6 +178,20 @@ fixed_bytes!(
|
||||
32
|
||||
);
|
||||
|
||||
fixed_bytes!(
|
||||
/// A file's key: 32 random bytes made for one file, travelling only inside MLS (`PROTOCOL.md`
|
||||
/// §4, `file`). The relay never sees it.
|
||||
FileKey,
|
||||
32
|
||||
);
|
||||
|
||||
// A file key is a secret: never printed.
|
||||
impl fmt::Debug for FileKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("FileKey(..)")
|
||||
}
|
||||
}
|
||||
|
||||
impl Token {
|
||||
/// The hash the relay stores and compares against.
|
||||
pub fn hash(&self) -> Sha256Hash {
|
||||
@@ -184,7 +225,7 @@ macro_rules! debug_as_wire {
|
||||
}
|
||||
)*};
|
||||
}
|
||||
debug_as_wire!(MailboxId, InviteId, Sha256Hash);
|
||||
debug_as_wire!(MailboxId, InviteId, Sha256Hash, Author, FileId);
|
||||
|
||||
/// The SHA-256 of a blob: how its recipient acknowledges it.
|
||||
pub fn blob_hash(blob: &[u8]) -> Sha256Hash {
|
||||
@@ -318,6 +359,43 @@ pub struct VersionInfo {
|
||||
pub relay: String,
|
||||
}
|
||||
|
||||
/// How many chunks a file has: 1 to [`MAX_FILE_CHUNKS`]; anything else does not parse.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct ChunkCount(u32);
|
||||
|
||||
impl ChunkCount {
|
||||
pub fn new(n: u32) -> Result<Self, ParseError> {
|
||||
if (1..=MAX_FILE_CHUNKS).contains(&n) {
|
||||
Ok(Self(n))
|
||||
} else {
|
||||
Err(ParseError::TooLarge {
|
||||
max: MAX_FILE_CHUNKS as usize,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ChunkCount {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
ChunkCount::new(u32::deserialize(d)?).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /v0/files`: the uploader sends hashes of the two tokens it made, and the chunk count.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CreateFile {
|
||||
pub id: FileId,
|
||||
pub upload_token_hash: Sha256Hash,
|
||||
pub fetch_token_hash: Sha256Hash,
|
||||
pub chunks: ChunkCount,
|
||||
}
|
||||
|
||||
/// 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)
|
||||
@@ -327,3 +405,108 @@ pub fn hour_of(unix_secs: i64) -> i64 {
|
||||
pub fn day_of(unix_secs: i64) -> i64 {
|
||||
unix_secs.div_euclid(86_400)
|
||||
}
|
||||
|
||||
/// A push endpoint (`PROTOCOL.md` §6, `.agents/features/wake-up.md` §2.1): a capability URL at the
|
||||
/// push server the mailbox's owner chose. `https://` with a host, no user info, no fragment, printable
|
||||
/// ASCII, at most [`MAX_PUSH_ENDPOINT_BYTES`]; `http://` only to a loopback host, which a relay
|
||||
/// accepts only when its operator allows it (tests).
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct PushEndpoint {
|
||||
url: String,
|
||||
host: String,
|
||||
https: bool,
|
||||
}
|
||||
|
||||
impl PushEndpoint {
|
||||
pub fn parse(text: &str) -> Result<Self, ParseError> {
|
||||
let bad = || ParseError::Endpoint;
|
||||
if text.len() > MAX_PUSH_ENDPOINT_BYTES {
|
||||
return Err(ParseError::TooLarge {
|
||||
max: MAX_PUSH_ENDPOINT_BYTES,
|
||||
});
|
||||
}
|
||||
if !text.bytes().all(|b| (0x21..=0x7e).contains(&b)) || text.contains('#') {
|
||||
return Err(bad());
|
||||
}
|
||||
let (https, rest) = if let Some(r) = text.strip_prefix("https://") {
|
||||
(true, r)
|
||||
} else if let Some(r) = text.strip_prefix("http://") {
|
||||
(false, r)
|
||||
} else {
|
||||
return Err(bad());
|
||||
};
|
||||
let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())];
|
||||
if authority.contains('@') {
|
||||
return Err(bad());
|
||||
}
|
||||
let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
|
||||
let end = v6.find(']').ok_or_else(bad)?;
|
||||
(&v6[..end], &v6[end + 1..])
|
||||
} else {
|
||||
match authority.find(':') {
|
||||
Some(i) => (&authority[..i], &authority[i..]),
|
||||
None => (authority, ""),
|
||||
}
|
||||
};
|
||||
if host.is_empty() || host.contains(['[', ']']) && !authority.starts_with('[') {
|
||||
return Err(bad());
|
||||
}
|
||||
if !port.is_empty() {
|
||||
let digits = port.strip_prefix(':').ok_or_else(bad)?;
|
||||
match digits.parse::<u16>() {
|
||||
Ok(p) if p > 0 && !digits.starts_with('0') => {}
|
||||
_ => return Err(bad()),
|
||||
}
|
||||
}
|
||||
let host = host.to_ascii_lowercase();
|
||||
if !https && !matches!(host.as_str(), "127.0.0.1" | "::1" | "localhost") {
|
||||
return Err(bad());
|
||||
}
|
||||
Ok(Self {
|
||||
url: text.to_string(),
|
||||
host,
|
||||
https,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.url
|
||||
}
|
||||
|
||||
/// The host, lower case, without brackets or port.
|
||||
pub fn host(&self) -> &str {
|
||||
&self.host
|
||||
}
|
||||
|
||||
/// `http://` to a loopback host: only for a relay whose operator allows it.
|
||||
pub fn is_loopback_http(&self) -> bool {
|
||||
!self.https
|
||||
}
|
||||
}
|
||||
|
||||
/// The endpoint is a capability: `Debug` shows its host only.
|
||||
impl fmt::Debug for PushEndpoint {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "PushEndpoint({})", self.host)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for PushEndpoint {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&self.url)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for PushEndpoint {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let text = Cow::<'de, str>::deserialize(d)?;
|
||||
PushEndpoint::parse(&text).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
/// `PUT /v0/mailboxes/{id}/push`: where to wake the mailbox's owner (`PROTOCOL.md` §6).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SetPush {
|
||||
pub endpoint: PushEndpoint,
|
||||
}
|
||||
|
||||
@@ -145,6 +145,7 @@ proptest! {
|
||||
let _ = InviteId::parse(&text);
|
||||
let _ = Sha256Hash::parse(&text);
|
||||
let _ = Token::parse(&text);
|
||||
let _ = Author::parse(&text);
|
||||
let _ = Token::from_bearer(&text);
|
||||
let _ = WireBytes::parse(&text, MAX_BLOB_BYTES);
|
||||
}
|
||||
@@ -172,7 +173,10 @@ proptest! {
|
||||
#[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);
|
||||
prop_assert_eq!(&id.to_wire(), &text);
|
||||
}
|
||||
if let Ok(author) = Author::parse(&text) {
|
||||
prop_assert_eq!(&author.to_wire(), &text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,3 +188,144 @@ proptest! {
|
||||
prop_assert_eq!(back.bytes(), &bytes[..]);
|
||||
}
|
||||
}
|
||||
|
||||
// Wake-up (`.agents/features/wake-up.md` §2.1): the push endpoint a mailbox may hold.
|
||||
#[test]
|
||||
fn a_push_endpoint_is_https_or_loopback_http_and_nothing_else() {
|
||||
for good in [
|
||||
"https://ntfy.sh/upAbCdEf0123456789?up=1",
|
||||
"https://push.example.cz:8443/x",
|
||||
"https://[2001:db8::1]/up",
|
||||
"https://ntfy.sh",
|
||||
] {
|
||||
let e = PushEndpoint::parse(good).unwrap_or_else(|_| panic!("{good}"));
|
||||
assert_eq!(e.as_str(), good);
|
||||
assert!(!e.is_loopback_http());
|
||||
}
|
||||
assert_eq!(
|
||||
PushEndpoint::parse("https://NTFY.sh/a").map(|e| e.host().to_string()),
|
||||
Ok("ntfy.sh".into())
|
||||
);
|
||||
for loopback in [
|
||||
"http://127.0.0.1:9000/up",
|
||||
"http://[::1]:9000/up",
|
||||
"http://localhost/up",
|
||||
] {
|
||||
assert!(PushEndpoint::parse(loopback)
|
||||
.expect("loopback")
|
||||
.is_loopback_http());
|
||||
}
|
||||
for bad in [
|
||||
"",
|
||||
"ntfy.sh/up",
|
||||
"ftp://ntfy.sh/up",
|
||||
"http://ntfy.sh/up",
|
||||
"http://10.0.0.1/up",
|
||||
"https:///up",
|
||||
"https://user:pw@ntfy.sh/up",
|
||||
"https://user@ntfy.sh/up",
|
||||
"https://ntfy.sh/up#frag",
|
||||
"https://ntfy.sh/a b",
|
||||
"https://ntfy.sh/\u{e9}",
|
||||
"https://ntfy.sh:0/up",
|
||||
"https://ntfy.sh:65536/up",
|
||||
"https://ntfy.sh:08/up",
|
||||
"https://ntfy.sh:/up",
|
||||
"https://[::1/up",
|
||||
"https://ntfy]sh/up",
|
||||
] {
|
||||
assert!(PushEndpoint::parse(bad).is_err(), "{bad}");
|
||||
}
|
||||
let long = format!("https://ntfy.sh/{}", "a".repeat(MAX_PUSH_ENDPOINT_BYTES));
|
||||
assert_eq!(
|
||||
PushEndpoint::parse(&long),
|
||||
Err(ParseError::TooLarge {
|
||||
max: MAX_PUSH_ENDPOINT_BYTES
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_push_refuses_unknown_fields_and_bad_endpoints_and_debug_hides_the_path() {
|
||||
let ok: SetPush =
|
||||
serde_json::from_str(r#"{"endpoint":"https://ntfy.sh/upSecret"}"#).expect("json");
|
||||
assert_eq!(ok.endpoint.as_str(), "https://ntfy.sh/upSecret");
|
||||
assert!(!format!("{ok:?}").contains("upSecret"));
|
||||
assert!(serde_json::from_str::<SetPush>(r#"{"endpoint":"http://ntfy.sh/x"}"#).is_err());
|
||||
assert!(
|
||||
serde_json::from_str::<SetPush>(r#"{"endpoint":"https://ntfy.sh/x","extra":1}"#).is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&ok).expect("json"),
|
||||
r#"{"endpoint":"https://ntfy.sh/upSecret"}"#
|
||||
);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn a_push_endpoint_parser_never_panics(text in "\\PC{0,64}") {
|
||||
let _ = PushEndpoint::parse(&text);
|
||||
let _ = PushEndpoint::parse(&format!("https://{text}"));
|
||||
}
|
||||
}
|
||||
|
||||
// Reactions and replies (`.agents/features/reactions-replies.md` §2.1): a message's author.
|
||||
#[test]
|
||||
fn an_author_is_16_bytes_in_22_canonical_characters_and_prints_as_its_wire() {
|
||||
let author = Author::from_bytes([0x5A; 16]);
|
||||
let wire = author.to_wire();
|
||||
assert_eq!(wire.len(), 22);
|
||||
assert_eq!(Author::parse(&wire), Ok(author));
|
||||
assert_eq!(
|
||||
serde_json::to_string(&author).expect("json"),
|
||||
format!("\"{wire}\"")
|
||||
);
|
||||
assert!(Author::parse(&wire[..21]).is_err());
|
||||
assert!(Author::parse(&Token::from_bytes([1; 32]).to_wire()).is_err());
|
||||
let zero = Author::from_bytes([0; 16]).to_wire();
|
||||
assert_eq!(
|
||||
Author::parse(&format!("{}B", &zero[..21])),
|
||||
Err(ParseError::Encoding)
|
||||
);
|
||||
assert_eq!(format!("{author:?}"), format!("Author({wire})"));
|
||||
}
|
||||
|
||||
// Files (`.agents/features/files.md` §2.3).
|
||||
#[test]
|
||||
fn create_file_takes_one_to_410_chunks_and_no_other_field() {
|
||||
let body = |chunks: i64, extra: &str| {
|
||||
format!(
|
||||
r#"{{"id":"{}","uploadTokenHash":"{}","fetchTokenHash":"{}","chunks":{chunks}{extra}}}"#,
|
||||
FileId::from_bytes([1; 16]).to_wire(),
|
||||
Token::from_bytes([2; 32]).hash().to_wire(),
|
||||
Token::from_bytes([3; 32]).hash().to_wire(),
|
||||
)
|
||||
};
|
||||
for ok in [1, 2, i64::from(MAX_FILE_CHUNKS)] {
|
||||
let req: CreateFile = serde_json::from_str(&body(ok, "")).expect("parses");
|
||||
assert_eq!(i64::from(req.chunks.get()), ok);
|
||||
}
|
||||
for bad in [0, -1, i64::from(MAX_FILE_CHUNKS) + 1, 1 << 40] {
|
||||
assert!(
|
||||
serde_json::from_str::<CreateFile>(&body(bad, "")).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
}
|
||||
assert!(serde_json::from_str::<CreateFile>(&body(1, r#","name":"a.jpg""#)).is_err());
|
||||
assert!(serde_json::from_str::<CreateFile>(&body(1, r#","size":5"#)).is_err());
|
||||
assert!(ChunkCount::new(0).is_err() && ChunkCount::new(MAX_FILE_CHUNKS + 1).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_key_is_never_printed_and_a_file_id_prints_as_its_wire() {
|
||||
let key = FileKey::from_bytes([5; 32]);
|
||||
assert_eq!(format!("{key:?}"), "FileKey(..)");
|
||||
assert_eq!(FileKey::parse(&key.to_wire()), Ok(key));
|
||||
let id = FileId::from_bytes([6; 16]);
|
||||
assert_eq!(format!("{id:?}"), format!("FileId({})", id.to_wire()));
|
||||
assert!(FileId::parse(&id.to_wire()[..21]).is_err());
|
||||
// 410 chunks of 255 984 plaintext bytes hold 100 MiB; 409 do not.
|
||||
let plain = FILE_CHUNK_BYTES as u64 - 16;
|
||||
assert!(u64::from(MAX_FILE_CHUNKS) * plain >= 100 * 1024 * 1024);
|
||||
assert!(u64::from(MAX_FILE_CHUNKS - 1) * plain < 100 * 1024 * 1024);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,12 @@ rusqlite = { version = "0.41", features = ["bundled"] }
|
||||
serde = "1"
|
||||
serde_json = "1"
|
||||
subtle = "2"
|
||||
# The join page's Content-Security-Policy names its inline script and style by SHA-256 (base64).
|
||||
sha2 = "0.10"
|
||||
base64 = "0.22"
|
||||
# The wake (`.agents/features/wake-up.md` §2.2): the relay's only outgoing request. rustls with
|
||||
# Mozilla's roots built in; the resolver is the relay's own, which drops every non-global address.
|
||||
ureq = { version = "3", default-features = false, features = ["rustls"] }
|
||||
|
||||
[dev-dependencies]
|
||||
getrandom = "0.3"
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>An invite to a private chat</title>
|
||||
<style>
|
||||
:root { color-scheme: dark light; }
|
||||
body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
|
||||
background: #0d0a0c; color: #f2ece8; font: 17px/1.5 system-ui, sans-serif; }
|
||||
main { max-width: 420px; padding: 32px 24px; text-align: center; }
|
||||
h1 { font-weight: 600; font-size: 26px; line-height: 1.2; margin: 0 0 12px; }
|
||||
p { margin: 0 0 20px; color: #cfc4bf; }
|
||||
.button { display: block; padding: 14px 20px; margin: 8px 0 24px; border-radius: 12px;
|
||||
background: #b3223a; color: #fff; text-decoration: none; font-weight: 600; font-size: 18px; }
|
||||
.small { font-size: 14px; color: #a99d98; }
|
||||
[hidden] { display: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>You're invited to a private chat</h1>
|
||||
<p>Someone who knows you invited you to chat in Amicitia, end to end encrypted.</p>
|
||||
<a id="open" class="button" href="#">Open Amicitia</a>
|
||||
<p id="missing" class="small">Don't have Amicitia yet? Ask the person who invited you how to get it, then tap their message again.</p>
|
||||
<p id="bad" class="small" hidden>This invite link is incomplete. Ask for a new one.</p>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
// The invite is in the fragment, which the browser never sends to this server.
|
||||
var invite = location.hash.slice(1);
|
||||
var open = document.getElementById("open");
|
||||
if (!/^[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/.test(invite)) {
|
||||
open.hidden = true;
|
||||
document.getElementById("missing").hidden = true;
|
||||
document.getElementById("bad").hidden = false;
|
||||
return;
|
||||
}
|
||||
open.href = "amicitia://invite?relay=" + location.origin + "#" + invite;
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+150
-7
@@ -2,7 +2,9 @@
|
||||
//! address, and nothing here writes a request anywhere.
|
||||
|
||||
use crate::store::{Refused, Store};
|
||||
use crate::wake::Waker;
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::rejection::BytesRejection;
|
||||
use axum::extract::{DefaultBodyLimit, Path, State};
|
||||
use axum::http::{header, HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
@@ -11,8 +13,9 @@ 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,
|
||||
CreateFile, CreateInvite, CreateMailbox, FetchedBlobs, FileId, InviteId, MailboxId,
|
||||
RotatePostToken, SetPush, Sha256Hash, Token, VersionInfo, FILE_CHUNK_BYTES, MAX_BLOB_BYTES,
|
||||
VERSION,
|
||||
};
|
||||
|
||||
/// Unix seconds. The server passes the system clock; tests pass their own.
|
||||
@@ -22,6 +25,23 @@ pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
|
||||
pub struct AppState {
|
||||
pub store: Arc<Store>,
|
||||
pub clock: Clock,
|
||||
/// Wakes a mailbox's owner when a blob arrives (`PROTOCOL.md` §6).
|
||||
pub waker: Arc<Waker>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
/// A relay that wakes only global `https://` endpoints: what a relay facing the internet runs.
|
||||
pub fn new(store: Arc<Store>, clock: Clock) -> Self {
|
||||
Self::with_waker(store, clock, Waker::new(false))
|
||||
}
|
||||
|
||||
pub fn with_waker(store: Arc<Store>, clock: Clock, waker: Waker) -> Self {
|
||||
Self {
|
||||
store,
|
||||
clock,
|
||||
waker: Arc::new(waker),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url.
|
||||
@@ -31,15 +51,27 @@ 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));
|
||||
// A chunk is exactly FILE_CHUNK_BYTES; one byte more is refused before it is read.
|
||||
let chunk_routes = Router::new()
|
||||
.route(
|
||||
"/v0/files/{id}/chunks/{index}",
|
||||
put(put_chunk).get(get_chunk),
|
||||
)
|
||||
.layer(DefaultBodyLimit::max(FILE_CHUNK_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/mailboxes/{id}/push", put(set_push).delete(clear_push))
|
||||
.route("/v0/files", post(create_file))
|
||||
.route("/v0/files/{id}", delete(delete_file))
|
||||
.route("/v0/invites", post(create_invite))
|
||||
.route("/v0/invites/{id}", get(claim_invite))
|
||||
.route("/version", get(version))
|
||||
.route("/join", get(crate::join::page))
|
||||
.layer(DefaultBodyLimit::max(MAX_JSON_BYTES))
|
||||
.merge(blob_routes)
|
||||
.merge(chunk_routes)
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
@@ -64,6 +96,11 @@ impl From<Refused> for Status {
|
||||
}
|
||||
}
|
||||
|
||||
/// A body over the route's limit is axum's rejection, which carries a text: a bare 413 instead.
|
||||
fn bare(body: Result<Bytes, BytesRejection>) -> Result<Bytes, Status> {
|
||||
body.map_err(|_| Status(StatusCode::PAYLOAD_TOO_LARGE))
|
||||
}
|
||||
|
||||
/// 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))
|
||||
@@ -83,7 +120,11 @@ fn bearer(headers: &HeaderMap) -> Result<Token, Status> {
|
||||
.ok_or(Status(StatusCode::NOT_FOUND))
|
||||
}
|
||||
|
||||
async fn create_mailbox(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
|
||||
async fn create_mailbox(
|
||||
State(s): State<AppState>,
|
||||
body: Result<Bytes, BytesRejection>,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let body = bare(body)?;
|
||||
let req: CreateMailbox = json(&body)?;
|
||||
s.store.create_mailbox(&req, (s.clock)())?;
|
||||
Ok(StatusCode::CREATED)
|
||||
@@ -93,11 +134,17 @@ async fn post_blob(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
body: Result<Bytes, BytesRejection>,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let body = bare(body)?;
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
s.store.post(&id, &token, &body, (s.clock)())?;
|
||||
let now = (s.clock)();
|
||||
s.store.post(&id, &token, &body, now)?;
|
||||
// Only after the blob is stored under a valid post token; the 201 does not wait for the wake.
|
||||
if let Ok(Some(endpoint)) = s.store.push_endpoint(&id) {
|
||||
s.waker.wake(Arc::clone(&s.store), id, endpoint, now);
|
||||
}
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
@@ -128,8 +175,9 @@ async fn rotate_post_token(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
body: Result<Bytes, BytesRejection>,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let body = bare(body)?;
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
let req: RotatePostToken = json(&body)?;
|
||||
@@ -138,7 +186,102 @@ async fn rotate_post_token(
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn create_invite(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
|
||||
async fn set_push(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
body: Result<Bytes, BytesRejection>,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let body = bare(body)?;
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
let req: SetPush = json(&body)?;
|
||||
if !s.waker.accepts(&req.endpoint) {
|
||||
return Err(Status(StatusCode::BAD_REQUEST));
|
||||
}
|
||||
s.store.set_push(&id, &token, Some(&req.endpoint))?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn clear_push(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
s.store.set_push(&id, &token, None)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// A malformed file id in the path is treated like an unknown one.
|
||||
fn file(id: &str) -> Result<FileId, Status> {
|
||||
FileId::parse(id).map_err(|_| Status(StatusCode::NOT_FOUND))
|
||||
}
|
||||
|
||||
/// A chunk index: decimal digits of a `u32`, no sign, no leading zero. Anything else is a 404.
|
||||
fn chunk_index(text: &str) -> Result<u32, Status> {
|
||||
let canonical = !text.is_empty()
|
||||
&& text.bytes().all(|b| b.is_ascii_digit())
|
||||
&& (text == "0" || !text.starts_with('0'));
|
||||
text.parse::<u32>()
|
||||
.ok()
|
||||
.filter(|_| canonical)
|
||||
.ok_or(Status(StatusCode::NOT_FOUND))
|
||||
}
|
||||
|
||||
async fn create_file(
|
||||
State(s): State<AppState>,
|
||||
body: Result<Bytes, BytesRejection>,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let body = bare(body)?;
|
||||
let req: CreateFile = json(&body)?;
|
||||
s.store.create_file(&req, (s.clock)())?;
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
async fn put_chunk(
|
||||
State(s): State<AppState>,
|
||||
Path((id, index)): Path<(String, String)>,
|
||||
headers: HeaderMap,
|
||||
body: Result<Bytes, BytesRejection>,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let body = bare(body)?;
|
||||
let id = file(&id)?;
|
||||
let index = chunk_index(&index)?;
|
||||
let token = bearer(&headers)?;
|
||||
s.store.put_chunk(&id, &token, index, &body)?;
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
async fn get_chunk(
|
||||
State(s): State<AppState>,
|
||||
Path((id, index)): Path<(String, String)>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, Status> {
|
||||
let id = file(&id)?;
|
||||
let index = chunk_index(&index)?;
|
||||
let token = bearer(&headers)?;
|
||||
let bytes = s.store.get_chunk(&id, &token, index)?;
|
||||
Ok(([(header::CONTENT_TYPE, "application/octet-stream")], bytes).into_response())
|
||||
}
|
||||
|
||||
async fn delete_file(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let id = file(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
s.store.delete_file(&id, &token)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn create_invite(
|
||||
State(s): State<AppState>,
|
||||
body: Result<Bytes, BytesRejection>,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let body = bare(body)?;
|
||||
let req: CreateInvite = json(&body)?;
|
||||
s.store.create_invite(&req, (s.clock)())?;
|
||||
Ok(StatusCode::CREATED)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! `GET /join` (PROTOCOL.md §8, added 2026-11-18): the page an invite link opens in a browser. It
|
||||
//! hands the invite, which sits in the URL's fragment and so never reaches this server, to the app
|
||||
//! as `amicitia://invite?relay=<this origin>#<id>.<secret>`. Static: it reads nothing, stores
|
||||
//! nothing, sets no cookie and loads nothing from anywhere else.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use axum::http::header;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use base64::Engine;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub const PAGE: &str = include_str!("../assets/join.html");
|
||||
|
||||
/// The text between `<tag>` and `</tag>` in the page (one of each), exactly as the browser hashes it.
|
||||
fn inline(tag: &str) -> &'static str {
|
||||
let open = format!("<{tag}>");
|
||||
let close = format!("</{tag}>");
|
||||
let start = PAGE.find(&open).expect("the page has the tag") + open.len();
|
||||
let end = PAGE[start..].find(&close).expect("the tag is closed") + start;
|
||||
&PAGE[start..end]
|
||||
}
|
||||
|
||||
fn hash(text: &str) -> String {
|
||||
let digest = Sha256::digest(text.as_bytes());
|
||||
format!(
|
||||
"'sha256-{}'",
|
||||
base64::engine::general_purpose::STANDARD.encode(digest)
|
||||
)
|
||||
}
|
||||
|
||||
/// Nothing but the page's own script and style, each by its hash: no other script, no image, no
|
||||
/// font, no connection, no frame, no form.
|
||||
pub static CONTENT_SECURITY_POLICY: LazyLock<String> = LazyLock::new(|| {
|
||||
format!(
|
||||
"default-src 'none'; script-src {}; style-src {}; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
|
||||
hash(inline("script")),
|
||||
hash(inline("style"))
|
||||
)
|
||||
});
|
||||
|
||||
pub async fn page() -> Response {
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
|
||||
(
|
||||
header::CONTENT_SECURITY_POLICY,
|
||||
CONTENT_SECURITY_POLICY.as_str(),
|
||||
),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
(header::REFERRER_POLICY, "no-referrer"),
|
||||
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
|
||||
],
|
||||
PAGE,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
+18
-5
@@ -2,7 +2,9 @@
|
||||
//! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request.
|
||||
|
||||
pub mod http;
|
||||
pub mod join;
|
||||
pub mod store;
|
||||
pub mod wake;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
@@ -16,17 +18,20 @@ pub struct Args {
|
||||
pub listen: SocketAddr,
|
||||
pub db: PathBuf,
|
||||
pub limits: store::Limits,
|
||||
/// `--push-loopback`: accept and wake `http://` loopback push endpoints. Tests only.
|
||||
pub push_loopback: bool,
|
||||
}
|
||||
|
||||
/// `--listen <addr:port>`, `--db <path>`, and the relay-wide quotas `--max-bytes`,
|
||||
/// `--max-mailboxes`, `--max-invites` (positive integers). Anything else is refused with a usage
|
||||
/// line.
|
||||
/// `--listen <addr:port>`, `--db <path>`, the relay-wide quotas `--max-bytes`, `--max-mailboxes`,
|
||||
/// `--max-invites`, `--max-files`, `--max-file-bytes` (positive integers), and `--push-loopback`
|
||||
/// (tests). Anything else is refused with a usage line.
|
||||
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
|
||||
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] \
|
||||
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000]";
|
||||
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000] \n [--max-files 10000] [--max-file-bytes 4294967296] [--push-loopback]";
|
||||
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
|
||||
let mut db = PathBuf::from(DEFAULT_DB);
|
||||
let mut limits = store::Limits::default();
|
||||
let mut push_loopback = false;
|
||||
let mut it = args.into_iter();
|
||||
let positive = |v: Option<String>| -> Result<i64, String> {
|
||||
v.and_then(|v| v.parse::<i64>().ok())
|
||||
@@ -38,6 +43,9 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
|
||||
"--max-bytes" => limits.total_bytes = positive(it.next())?,
|
||||
"--max-mailboxes" => limits.mailboxes = positive(it.next())?,
|
||||
"--max-invites" => limits.invites = positive(it.next())?,
|
||||
"--max-files" => limits.files = positive(it.next())?,
|
||||
"--max-file-bytes" => limits.file_bytes = positive(it.next())?,
|
||||
"--push-loopback" => push_loopback = true,
|
||||
"--listen" => {
|
||||
listen = it
|
||||
.next()
|
||||
@@ -53,5 +61,10 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
|
||||
_ => return Err(usage.to_string()),
|
||||
}
|
||||
}
|
||||
Ok(Args { listen, db, limits })
|
||||
Ok(Args {
|
||||
listen,
|
||||
db,
|
||||
limits,
|
||||
push_loopback,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] [--max-bytes N]
|
||||
//! [--max-mailboxes N] [--max-invites N]`
|
||||
//! [--max-mailboxes N] [--max-invites N] [--max-files N] [--max-file-bytes N] [--push-loopback]`
|
||||
//!
|
||||
//! Prints one line at start (version and address) and nothing per request.
|
||||
|
||||
@@ -8,6 +8,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tabellarius_relay::http::{router, AppState, Clock};
|
||||
use tabellarius_relay::parse_args;
|
||||
use tabellarius_relay::store::Store;
|
||||
use tabellarius_relay::wake::Waker;
|
||||
|
||||
fn now() -> i64 {
|
||||
SystemTime::now()
|
||||
@@ -52,7 +53,8 @@ async fn main() {
|
||||
tabellarius_protocol::VERSION
|
||||
);
|
||||
|
||||
// Purge at start and every hour: blobs after 30 days, invites after their expiry.
|
||||
// Purge at start and every hour: blobs and files after 30 days, files not complete after a
|
||||
// day, invites after their expiry.
|
||||
let purger = Arc::clone(&store);
|
||||
tokio::spawn(async move {
|
||||
let mut every_hour = tokio::time::interval(Duration::from_secs(3600));
|
||||
@@ -63,7 +65,11 @@ async fn main() {
|
||||
});
|
||||
|
||||
let clock: Clock = Arc::new(now);
|
||||
let app = router(AppState { store, clock });
|
||||
let app = router(AppState::with_waker(
|
||||
store,
|
||||
clock,
|
||||
Waker::new(args.push_loopback),
|
||||
));
|
||||
let shutdown = async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
};
|
||||
|
||||
+219
-8
@@ -1,6 +1,6 @@
|
||||
//! Every rule of the relay, over SQLite, with the clock passed in.
|
||||
//!
|
||||
//! The database holds exactly `docs/PROTOCOL.md` §5: three tables, and nothing about who connected.
|
||||
//! The database holds exactly `docs/PROTOCOL.md` §5: six 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.
|
||||
|
||||
@@ -9,8 +9,9 @@ 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,
|
||||
blob_hash, day_of, hour_of, BlobBytes, ClaimedInvite, CreateFile, CreateInvite, CreateMailbox,
|
||||
FetchedBlob, FileId, InviteId, KeyPackageBytes, MailboxId, PushEndpoint, Sha256Hash, Token,
|
||||
BLOB_TTL_SECS, FILE_CHUNK_BYTES, INCOMPLETE_FILE_TTL_SECS, INVITE_TTL_SECS,
|
||||
MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES,
|
||||
};
|
||||
|
||||
@@ -35,6 +36,23 @@ CREATE TABLE IF NOT EXISTS invites (
|
||||
key_package BLOB NOT NULL,
|
||||
expiry INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS push (
|
||||
mailbox_id BLOB PRIMARY KEY NOT NULL,
|
||||
endpoint TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS files (
|
||||
id BLOB PRIMARY KEY NOT NULL,
|
||||
upload_hash BLOB NOT NULL,
|
||||
fetch_hash BLOB NOT NULL,
|
||||
chunks INTEGER NOT NULL,
|
||||
uploaded_hour INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS chunks (
|
||||
file_id BLOB NOT NULL,
|
||||
idx INTEGER NOT NULL,
|
||||
ciphertext BLOB NOT NULL,
|
||||
PRIMARY KEY (file_id, idx)
|
||||
);
|
||||
";
|
||||
|
||||
/// Why a request was refused. Deliberately coarse: it says nothing about which part was wrong.
|
||||
@@ -61,6 +79,10 @@ pub struct Limits {
|
||||
pub total_bytes: i64,
|
||||
pub mailboxes: i64,
|
||||
pub invites: i64,
|
||||
/// Files on the relay, complete or not (`.agents/features/files.md` §2.3).
|
||||
pub files: i64,
|
||||
/// Bytes reserved by files: each counts as its chunks times `FILE_CHUNK_BYTES` from creation.
|
||||
pub file_bytes: i64,
|
||||
}
|
||||
|
||||
/// Waiting blobs in one mailbox (`PROTOCOL.md` §8).
|
||||
@@ -76,6 +98,8 @@ impl Default for Limits {
|
||||
total_bytes: 1024 * 1024 * 1024,
|
||||
mailboxes: 100_000,
|
||||
invites: 10_000,
|
||||
files: 10_000,
|
||||
file_bytes: 4 * 1024 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,6 +120,8 @@ pub struct Store {
|
||||
pub struct Purged {
|
||||
pub blobs: usize,
|
||||
pub invites: usize,
|
||||
/// Files removed with their chunks: older than 30 days, or incomplete after 24 hours.
|
||||
pub files: usize,
|
||||
}
|
||||
|
||||
fn same_hash(stored: &[u8], presented: &Sha256Hash) -> bool {
|
||||
@@ -351,14 +377,197 @@ impl Store {
|
||||
})
|
||||
}
|
||||
|
||||
/// Deletes blobs older than 30 days and invites past their expiry.
|
||||
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
|
||||
/// Sets (`Some`) or removes (`None`) the mailbox's push endpoint. Needs the fetch token: only the
|
||||
/// owner says where to be woken (`PROTOCOL.md` §6).
|
||||
pub fn set_push(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
token: &Token,
|
||||
endpoint: Option<&PushEndpoint>,
|
||||
) -> Result<(), Refused> {
|
||||
let conn = self.conn();
|
||||
Self::authorize(&conn, id, token, Column::Fetch)?;
|
||||
match endpoint {
|
||||
Some(e) => conn.execute(
|
||||
"INSERT OR REPLACE INTO push (mailbox_id, endpoint) VALUES (?1, ?2)",
|
||||
params![&id.as_bytes()[..], e.as_str()],
|
||||
)?,
|
||||
None => conn.execute(
|
||||
"DELETE FROM push WHERE mailbox_id = ?1",
|
||||
[&id.as_bytes()[..]],
|
||||
)?,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The endpoint to wake after a blob was stored for this mailbox, if its owner gave one.
|
||||
pub fn push_endpoint(&self, id: &MailboxId) -> Result<Option<String>, Refused> {
|
||||
Ok(self
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT endpoint FROM push WHERE mailbox_id = ?1",
|
||||
[&id.as_bytes()[..]],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
/// The push server said the endpoint is gone: removes it, unless the owner has set another since.
|
||||
pub fn drop_push_if(&self, id: &MailboxId, endpoint: &str) -> Result<(), Refused> {
|
||||
self.conn().execute(
|
||||
"DELETE FROM push WHERE mailbox_id = ?1 AND endpoint = ?2",
|
||||
params![&id.as_bytes()[..], endpoint],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes blobs older than 30 days, invites past their expiry, and files older than 30 days
|
||||
/// or still incomplete 24 hours after they were created, with their chunks.
|
||||
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
|
||||
let mut 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 })
|
||||
let oldest_incomplete = hour_of(now - INCOMPLETE_FILE_TTL_SECS);
|
||||
let tx = conn.transaction()?;
|
||||
let blobs = tx.execute("DELETE FROM blobs WHERE received_hour < ?1", [oldest_kept])?;
|
||||
let invites = tx.execute("DELETE FROM invites WHERE expiry <= ?1", [now])?;
|
||||
let files = tx.execute(
|
||||
"DELETE FROM files WHERE uploaded_hour < ?1
|
||||
OR (uploaded_hour < ?2
|
||||
AND chunks > (SELECT count(*) FROM chunks WHERE chunks.file_id = files.id))",
|
||||
params![oldest_kept, oldest_incomplete],
|
||||
)?;
|
||||
tx.execute(
|
||||
"DELETE FROM chunks WHERE file_id NOT IN (SELECT id FROM files)",
|
||||
[],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(Purged {
|
||||
blobs,
|
||||
invites,
|
||||
files,
|
||||
})
|
||||
}
|
||||
|
||||
/// A new file (`.agents/features/files.md` §2.3): its id, the hashes of the two tokens its
|
||||
/// uploader made, and how many chunks it will have. It counts against the relay's file quota
|
||||
/// at its full size from now on, so an upload under way is never cut off by another.
|
||||
pub fn create_file(&self, req: &CreateFile, now: i64) -> Result<(), Refused> {
|
||||
let conn = self.conn();
|
||||
let (files, chunks): (i64, Option<i64>) =
|
||||
conn.query_row("SELECT count(*), sum(chunks) FROM files", [], |r| {
|
||||
Ok((r.get(0)?, r.get(1)?))
|
||||
})?;
|
||||
let reserved =
|
||||
(chunks.unwrap_or(0) + i64::from(req.chunks.get())) * FILE_CHUNK_BYTES as i64;
|
||||
if files >= self.limits.files || reserved > self.limits.file_bytes {
|
||||
return Err(Refused::Full);
|
||||
}
|
||||
let changed = conn.execute(
|
||||
"INSERT OR IGNORE INTO files (id, upload_hash, fetch_hash, chunks, uploaded_hour)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![
|
||||
&req.id.as_bytes()[..],
|
||||
&req.upload_token_hash.as_bytes()[..],
|
||||
&req.fetch_token_hash.as_bytes()[..],
|
||||
i64::from(req.chunks.get()),
|
||||
hour_of(now)
|
||||
],
|
||||
)?;
|
||||
if changed == 0 {
|
||||
return Err(Refused::Exists);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks a token against a file's upload or fetch hash; returns its chunk count.
|
||||
fn authorize_file(
|
||||
conn: &Connection,
|
||||
id: &FileId,
|
||||
token: &Token,
|
||||
column: Column,
|
||||
) -> Result<i64, Refused> {
|
||||
let sql = match column {
|
||||
Column::Post => "SELECT upload_hash, chunks FROM files WHERE id = ?1",
|
||||
Column::Fetch => "SELECT fetch_hash, chunks FROM files WHERE id = ?1",
|
||||
};
|
||||
let stored: Option<(Vec<u8>, i64)> = conn
|
||||
.query_row(sql, [&id.as_bytes()[..]], |r| Ok((r.get(0)?, r.get(1)?)))
|
||||
.optional()?;
|
||||
// As for mailboxes: an unknown file takes the same path as a wrong token.
|
||||
let (stored, chunks) = stored.unwrap_or_else(|| (vec![0; 32], 0));
|
||||
let known = !stored.iter().all(|b| *b == 0);
|
||||
if known & same_hash(&stored, &token.hash()) {
|
||||
Ok(chunks)
|
||||
} else {
|
||||
Err(Refused::NotFound)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores chunk `index` of a file, with the upload token. The same bytes again are accepted (an
|
||||
/// upload resumed after a crash); other bytes are [`Refused::Exists`]: a chunk never changes.
|
||||
/// An index at or past the file's chunk count is [`Refused::Full`], after the token.
|
||||
pub fn put_chunk(
|
||||
&self,
|
||||
id: &FileId,
|
||||
token: &Token,
|
||||
index: u32,
|
||||
chunk: &[u8],
|
||||
) -> Result<(), Refused> {
|
||||
if chunk.len() != FILE_CHUNK_BYTES {
|
||||
return Err(Refused::TooLarge);
|
||||
}
|
||||
let mut conn = self.conn();
|
||||
let chunks = Self::authorize_file(&conn, id, token, Column::Post)?;
|
||||
if i64::from(index) >= chunks {
|
||||
return Err(Refused::Full);
|
||||
}
|
||||
let tx = conn.transaction()?;
|
||||
let held: Option<Vec<u8>> = tx
|
||||
.query_row(
|
||||
"SELECT ciphertext FROM chunks WHERE file_id = ?1 AND idx = ?2",
|
||||
params![&id.as_bytes()[..], i64::from(index)],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
match held {
|
||||
Some(bytes) if bytes == chunk => return Ok(()),
|
||||
Some(_) => return Err(Refused::Exists),
|
||||
None => {}
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO chunks (file_id, idx, ciphertext) VALUES (?1, ?2, ?3)",
|
||||
params![&id.as_bytes()[..], i64::from(index), chunk],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Chunk `index` of a file, with the fetch token. Not there (yet) = [`Refused::NotFound`].
|
||||
pub fn get_chunk(&self, id: &FileId, token: &Token, index: u32) -> Result<Vec<u8>, Refused> {
|
||||
let conn = self.conn();
|
||||
Self::authorize_file(&conn, id, token, Column::Fetch)?;
|
||||
conn.query_row(
|
||||
"SELECT ciphertext FROM chunks WHERE file_id = ?1 AND idx = ?2",
|
||||
params![&id.as_bytes()[..], i64::from(index)],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?
|
||||
.ok_or(Refused::NotFound)
|
||||
}
|
||||
|
||||
/// The uploader deletes a file and its chunks early, with the upload token.
|
||||
pub fn delete_file(&self, id: &FileId, token: &Token) -> Result<(), Refused> {
|
||||
let mut conn = self.conn();
|
||||
Self::authorize_file(&conn, id, token, Column::Post)?;
|
||||
let tx = conn.transaction()?;
|
||||
tx.execute(
|
||||
"DELETE FROM chunks WHERE file_id = ?1",
|
||||
[&id.as_bytes()[..]],
|
||||
)?;
|
||||
tx.execute("DELETE FROM files WHERE id = ?1", [&id.as_bytes()[..]])?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The live schema: (table, columns) for every table, in name order. For the §5 test.
|
||||
@@ -381,6 +590,8 @@ impl Store {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of a mailbox's (or a file's) two hashes a token is checked against: the one that lets it
|
||||
/// post (or upload), or the one that lets it fetch.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Column {
|
||||
Post,
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
//! The relay's only outgoing request: a wake to a mailbox owner's push endpoint when a blob arrived
|
||||
//! (`docs/PROTOCOL.md` §6, `.agents/features/wake-up.md` §2.2).
|
||||
//!
|
||||
//! The body is a constant; nothing of the mailbox, the blob or its sender goes out. A mailbox is
|
||||
//! woken at most once a minute, remembered in memory only. The endpoint's host is resolved here and
|
||||
//! every address that is not global is dropped before connecting, so a mailbox owner cannot point
|
||||
//! the relay at its own network. Nothing about a wake is printed.
|
||||
|
||||
use crate::store::Store;
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tabellarius_protocol::{MailboxId, PushEndpoint, WAKE_BODY, WAKE_EVERY_SECS};
|
||||
use tokio::sync::Semaphore;
|
||||
use ureq::config::Config;
|
||||
use ureq::http::Uri;
|
||||
use ureq::unversioned::resolver::{DefaultResolver, ResolvedSocketAddrs, Resolver};
|
||||
use ureq::unversioned::transport::{DefaultConnector, NextTimeout};
|
||||
|
||||
/// At most this many wakes are on their way at once; beyond that a wake is dropped.
|
||||
pub const MAX_IN_FLIGHT: usize = 16;
|
||||
/// A wake gives up after this long.
|
||||
pub const WAKE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// The in-memory "woken lately" map is pruned when it reaches this size.
|
||||
const MAX_REMEMBERED: usize = 100_000;
|
||||
|
||||
pub struct Waker {
|
||||
allow_loopback: bool,
|
||||
/// Mailbox → the second it was last woken. Memory only: `PROTOCOL.md` §5 does not change.
|
||||
woken: Mutex<HashMap<MailboxId, i64>>,
|
||||
slots: Arc<Semaphore>,
|
||||
agent: ureq::Agent,
|
||||
}
|
||||
|
||||
/// What a wake came to; the tests read it, the relay only acts on `Gone`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
Delivered,
|
||||
/// 404 or 410: the endpoint no longer exists, so it is removed.
|
||||
Gone,
|
||||
/// Anything else: the network, a refused address, a timeout, another status.
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl Waker {
|
||||
/// `allow_loopback`: `http://` to a loopback host, and loopback addresses, for tests only
|
||||
/// (`--push-loopback`). A relay facing the internet never sets it.
|
||||
pub fn new(allow_loopback: bool) -> Self {
|
||||
let config = Config::builder()
|
||||
.timeout_global(Some(WAKE_TIMEOUT))
|
||||
.max_redirects(0)
|
||||
.http_status_as_error(false)
|
||||
.proxy(None)
|
||||
.build();
|
||||
let agent = ureq::Agent::with_parts(
|
||||
config,
|
||||
DefaultConnector::default(),
|
||||
GlobalOnly { allow_loopback },
|
||||
);
|
||||
Self {
|
||||
allow_loopback,
|
||||
woken: Mutex::new(HashMap::new()),
|
||||
slots: Arc::new(Semaphore::new(MAX_IN_FLIGHT)),
|
||||
agent,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this relay accepts the endpoint at all.
|
||||
pub fn accepts(&self, endpoint: &PushEndpoint) -> bool {
|
||||
!endpoint.is_loopback_http() || self.allow_loopback
|
||||
}
|
||||
|
||||
/// After a blob was stored: wakes the mailbox's owner, unless it was woken in the last minute or
|
||||
/// too many wakes are on their way. Returns at once; the request runs in the background.
|
||||
pub fn wake(&self, store: Arc<Store>, id: MailboxId, endpoint: String, now: i64) -> bool {
|
||||
if !self.due(id, now) {
|
||||
return false;
|
||||
}
|
||||
let Ok(slot) = Arc::clone(&self.slots).try_acquire_owned() else {
|
||||
return false;
|
||||
};
|
||||
let agent = self.agent.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _slot = slot;
|
||||
if send(&agent, &endpoint) == Outcome::Gone {
|
||||
let _ = store.drop_push_if(&id, &endpoint);
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Once a minute per mailbox. A clock that went back counts as due.
|
||||
fn due(&self, id: MailboxId, now: i64) -> bool {
|
||||
let mut woken = self.woken.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(&last) = woken.get(&id) {
|
||||
if (0..WAKE_EVERY_SECS).contains(&(now - last)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if woken.len() >= MAX_REMEMBERED {
|
||||
woken.retain(|_, last| now - *last < WAKE_EVERY_SECS);
|
||||
}
|
||||
woken.insert(id, now);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// One wake: the constant body and nothing else of the relay's.
|
||||
pub fn send(agent: &ureq::Agent, endpoint: &str) -> Outcome {
|
||||
let sent = agent
|
||||
.post(endpoint)
|
||||
.header("TTL", "86400")
|
||||
.header("Urgency", "normal")
|
||||
.header("Content-Type", "application/octet-stream")
|
||||
.send(WAKE_BODY);
|
||||
match sent.map(|r| r.status().as_u16()) {
|
||||
Ok(200..=299) => Outcome::Delivered,
|
||||
Ok(404 | 410) => Outcome::Gone,
|
||||
_ => Outcome::Failed,
|
||||
}
|
||||
}
|
||||
|
||||
/// The system's resolver, with every address that is not global dropped.
|
||||
#[derive(Debug)]
|
||||
struct GlobalOnly {
|
||||
allow_loopback: bool,
|
||||
}
|
||||
|
||||
impl Resolver for GlobalOnly {
|
||||
fn resolve(
|
||||
&self,
|
||||
uri: &Uri,
|
||||
config: &Config,
|
||||
timeout: NextTimeout,
|
||||
) -> Result<ResolvedSocketAddrs, ureq::Error> {
|
||||
let all = DefaultResolver::default().resolve(uri, config, timeout)?;
|
||||
let mut kept = self.empty();
|
||||
for addr in &all {
|
||||
if reachable(addr.ip(), self.allow_loopback) {
|
||||
kept.push(*addr);
|
||||
}
|
||||
}
|
||||
if kept.is_empty() {
|
||||
Err(ureq::Error::HostNotFound)
|
||||
} else {
|
||||
Ok(kept)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the relay may connect to this address: global unicast only (loopback when allowed).
|
||||
pub fn reachable(ip: IpAddr, allow_loopback: bool) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(v4) => v4_reachable(v4, allow_loopback),
|
||||
IpAddr::V6(v6) => {
|
||||
// An IPv4 address in IPv6 clothing is judged as the IPv4 address.
|
||||
if let Some(v4) = v6.to_ipv4_mapped() {
|
||||
return v4_reachable(v4, allow_loopback);
|
||||
}
|
||||
let s = v6.segments();
|
||||
// NAT64 (64:ff9b::/96) reaches the IPv4 address in its last 32 bits.
|
||||
if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
|
||||
let v4 =
|
||||
Ipv4Addr::new((s[6] >> 8) as u8, s[6] as u8, (s[7] >> 8) as u8, s[7] as u8);
|
||||
return v4_reachable(v4, allow_loopback);
|
||||
}
|
||||
v6_reachable(v6, allow_loopback)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn v4_reachable(ip: Ipv4Addr, allow_loopback: bool) -> bool {
|
||||
if ip.is_loopback() {
|
||||
return allow_loopback;
|
||||
}
|
||||
let o = ip.octets();
|
||||
!(o[0] == 0 // "this network"
|
||||
|| ip.is_private() // 10/8, 172.16/12, 192.168/16
|
||||
|| ip.is_link_local() // 169.254/16
|
||||
|| (o[0] == 100 && (o[1] & 0xc0) == 64) // CGNAT 100.64/10
|
||||
|| (o[0] == 192 && o[1] == 0 && o[2] == 0) // IETF 192.0.0/24
|
||||
|| ip.is_documentation()
|
||||
|| (o[0] == 198 && (o[1] & 0xfe) == 18) // benchmarking 198.18/15
|
||||
|| ip.is_multicast()
|
||||
|| o[0] >= 240) // reserved and broadcast
|
||||
}
|
||||
|
||||
fn v6_reachable(ip: Ipv6Addr, allow_loopback: bool) -> bool {
|
||||
if ip.is_loopback() {
|
||||
return allow_loopback;
|
||||
}
|
||||
let s = ip.segments();
|
||||
!(ip.is_unspecified()
|
||||
|| ip.is_multicast()
|
||||
|| s[..6] == [0; 6] // IPv4-compatible ::/96
|
||||
|| (s[0] & 0xfe00) == 0xfc00 // unique local fc00::/7
|
||||
|| (s[0] & 0xffc0) == 0xfe80 // link-local fe80::/10
|
||||
|| (s[0] & 0xffc0) == 0xfec0 // site-local fec0::/10
|
||||
|| (s[0] == 0x2001 && s[1] == 0x0db8) // documentation
|
||||
|| s[0] == 0x2002 // 6to4: an IPv4 address inside
|
||||
|| (s[0] == 0x2001 && s[1] == 0) // Teredo
|
||||
|| (s[0] == 0x0100 && s[1..4] == [0; 3])) // discard-only 100::/64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ok(text: &str) -> bool {
|
||||
reachable(text.parse().expect("an address"), false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_global_addresses_are_reachable() {
|
||||
for global in ["1.1.1.1", "159.69.10.20", "2a01:4f8::1", "64:ff9b::808:808"] {
|
||||
assert!(ok(global), "{global}");
|
||||
}
|
||||
for not in [
|
||||
"127.0.0.1",
|
||||
"10.1.2.3",
|
||||
"172.16.0.1",
|
||||
"192.168.1.1",
|
||||
"169.254.169.254",
|
||||
"100.64.0.1",
|
||||
"0.0.0.0",
|
||||
"192.0.0.8",
|
||||
"192.0.2.1",
|
||||
"198.18.0.1",
|
||||
"224.0.0.1",
|
||||
"255.255.255.255",
|
||||
"::1",
|
||||
"::",
|
||||
"fc00::1",
|
||||
"fd12::1",
|
||||
"fe80::1",
|
||||
"ff02::1",
|
||||
"2001:db8::1",
|
||||
"::ffff:10.0.0.1",
|
||||
"::ffff:127.0.0.1",
|
||||
"::10.0.0.1",
|
||||
"64:ff9b::a00:1",
|
||||
"2002:a00:1::",
|
||||
"2001:0:4136:e378::1",
|
||||
"100::1",
|
||||
] {
|
||||
assert!(!ok(not), "{not}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_only_when_allowed() {
|
||||
assert!(reachable("127.0.0.1".parse().expect("v4"), true));
|
||||
assert!(reachable("::1".parse().expect("v6"), true));
|
||||
assert!(!reachable("10.0.0.1".parse().expect("v4"), true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
//! Files (`.agents/features/files.md` §2.3, `PROTOCOL.md` §8): create, put, get, delete; only the
|
||||
//! upload token puts and deletes, only the fetch token gets; every chunk is the same size; a
|
||||
//! per-file and a relay-wide quota (507); files go after 30 days, incomplete ones after a day.
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{header, Method, Request, StatusCode};
|
||||
use http_body_util::BodyExt;
|
||||
use std::sync::atomic::{AtomicI64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use tabellarius_protocol::*;
|
||||
use tabellarius_relay::http::{router, AppState, Clock};
|
||||
use tabellarius_relay::store::{Limits, Purged, Store};
|
||||
use tower::ServiceExt;
|
||||
|
||||
const T0: i64 = 1_794_000_000;
|
||||
const HOUR: i64 = 3600;
|
||||
const DAY: i64 = 24 * HOUR;
|
||||
|
||||
fn random<const N: usize>() -> [u8; N] {
|
||||
let mut b = [0u8; N];
|
||||
getrandom::fill(&mut b).expect("system randomness");
|
||||
b
|
||||
}
|
||||
|
||||
struct File {
|
||||
id: FileId,
|
||||
upload: Token,
|
||||
fetch: Token,
|
||||
chunks: u32,
|
||||
}
|
||||
|
||||
impl File {
|
||||
fn new(chunks: u32) -> Self {
|
||||
Self {
|
||||
id: FileId::from_bytes(random()),
|
||||
upload: Token::from_bytes(random()),
|
||||
fetch: Token::from_bytes(random()),
|
||||
chunks,
|
||||
}
|
||||
}
|
||||
fn chunk_path(&self, index: u32) -> String {
|
||||
format!("/v0/files/{}/chunks/{index}", self.id.to_wire())
|
||||
}
|
||||
}
|
||||
|
||||
fn chunk(fill: u8) -> Vec<u8> {
|
||||
vec![fill; FILE_CHUNK_BYTES]
|
||||
}
|
||||
|
||||
struct Relay {
|
||||
app: axum::Router,
|
||||
store: Arc<Store>,
|
||||
now: Arc<AtomicI64>,
|
||||
}
|
||||
|
||||
impl Relay {
|
||||
fn with(limits: Limits) -> Self {
|
||||
let store = Arc::new(Store::open_in_memory_with(limits).expect("store"));
|
||||
let now = Arc::new(AtomicI64::new(T0));
|
||||
let n = Arc::clone(&now);
|
||||
let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst));
|
||||
Relay {
|
||||
app: router(AppState::new(Arc::clone(&store), clock)),
|
||||
store,
|
||||
now,
|
||||
}
|
||||
}
|
||||
fn new() -> Self {
|
||||
Self::with(Limits::default())
|
||||
}
|
||||
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 body = resp.into_body().collect().await.expect("body").to_bytes();
|
||||
if !status.is_success() {
|
||||
assert!(body.is_empty(), "a refusal has no body");
|
||||
}
|
||||
(status, body.to_vec())
|
||||
}
|
||||
async fn create(&self, f: &File) -> StatusCode {
|
||||
self.create_json(serde_json::json!({
|
||||
"id": f.id,
|
||||
"uploadTokenHash": f.upload.hash(),
|
||||
"fetchTokenHash": f.fetch.hash(),
|
||||
"chunks": f.chunks,
|
||||
}))
|
||||
.await
|
||||
}
|
||||
async fn create_json(&self, body: serde_json::Value) -> StatusCode {
|
||||
let body = serde_json::to_vec(&body).expect("json");
|
||||
self.call(Method::POST, "/v0/files", None, body).await.0
|
||||
}
|
||||
async fn put(&self, f: &File, index: u32, token: &Token, bytes: Vec<u8>) -> StatusCode {
|
||||
self.call(Method::PUT, &f.chunk_path(index), Some(token), bytes)
|
||||
.await
|
||||
.0
|
||||
}
|
||||
async fn get(&self, f: &File, index: u32, token: &Token) -> (StatusCode, Vec<u8>) {
|
||||
self.call(Method::GET, &f.chunk_path(index), Some(token), Vec::new())
|
||||
.await
|
||||
}
|
||||
async fn delete(&self, f: &File, token: &Token) -> StatusCode {
|
||||
let path = format!("/v0/files/{}", f.id.to_wire());
|
||||
self.call(Method::DELETE, &path, Some(token), Vec::new())
|
||||
.await
|
||||
.0
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_file_is_created_put_fetched_and_deleted() {
|
||||
let relay = Relay::new();
|
||||
let f = File::new(2);
|
||||
assert_eq!(relay.create(&f).await, StatusCode::CREATED);
|
||||
assert_eq!(relay.create(&f).await, StatusCode::CONFLICT);
|
||||
assert_eq!(
|
||||
relay.put(&f, 0, &f.upload, chunk(1)).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
assert_eq!(
|
||||
relay.get(&f, 1, &f.fetch).await.0,
|
||||
StatusCode::NOT_FOUND,
|
||||
"not up yet"
|
||||
);
|
||||
assert_eq!(
|
||||
relay.put(&f, 1, &f.upload, chunk(2)).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
let (status, bytes) = relay.get(&f, 1, &f.fetch).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(bytes, chunk(2));
|
||||
// Fetching deletes nothing, and is not counted anywhere.
|
||||
assert_eq!(relay.get(&f, 1, &f.fetch).await.0, StatusCode::OK);
|
||||
assert_eq!(relay.delete(&f, &f.upload).await, StatusCode::NO_CONTENT);
|
||||
assert_eq!(relay.get(&f, 0, &f.fetch).await.0, StatusCode::NOT_FOUND);
|
||||
assert_eq!(relay.delete(&f, &f.upload).await, StatusCode::NOT_FOUND);
|
||||
assert_eq!(relay.store.purge(T0).expect("purge"), Purged::default());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_the_upload_token_puts_and_deletes_and_only_the_fetch_token_gets() {
|
||||
let relay = Relay::new();
|
||||
let f = File::new(1);
|
||||
let other = File::new(1);
|
||||
relay.create(&f).await;
|
||||
relay.create(&other).await;
|
||||
let stranger = Token::from_bytes(random());
|
||||
for token in [&stranger, &f.fetch, &other.upload] {
|
||||
assert_eq!(
|
||||
relay.put(&f, 0, token, chunk(1)).await,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(relay.delete(&f, token).await, StatusCode::NOT_FOUND);
|
||||
}
|
||||
let (s, _) = relay
|
||||
.call(Method::PUT, &f.chunk_path(0), None, chunk(1))
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND, "no token at all");
|
||||
assert_eq!(
|
||||
relay.put(&f, 0, &f.upload, chunk(1)).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
for token in [&stranger, &f.upload, &other.fetch] {
|
||||
assert_eq!(relay.get(&f, 0, token).await.0, StatusCode::NOT_FOUND);
|
||||
}
|
||||
assert_eq!(relay.get(&f, 0, &f.fetch).await.0, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_chunk_is_exactly_the_chunk_size_and_never_changes() {
|
||||
let relay = Relay::new();
|
||||
let f = File::new(1);
|
||||
relay.create(&f).await;
|
||||
for size in [0, 1, FILE_CHUNK_BYTES - 1] {
|
||||
assert_eq!(
|
||||
relay.put(&f, 0, &f.upload, vec![1; size]).await,
|
||||
StatusCode::PAYLOAD_TOO_LARGE,
|
||||
"{size}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
relay
|
||||
.put(&f, 0, &f.upload, vec![1; FILE_CHUNK_BYTES + 1])
|
||||
.await,
|
||||
StatusCode::PAYLOAD_TOO_LARGE
|
||||
);
|
||||
assert_eq!(
|
||||
relay.put(&f, 0, &f.upload, chunk(1)).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
assert_eq!(
|
||||
relay.put(&f, 0, &f.upload, chunk(1)).await,
|
||||
StatusCode::CREATED,
|
||||
"the same bytes again: an upload resumed"
|
||||
);
|
||||
assert_eq!(
|
||||
relay.put(&f, 0, &f.upload, chunk(2)).await,
|
||||
StatusCode::CONFLICT,
|
||||
"other bytes: refused"
|
||||
);
|
||||
assert_eq!(relay.get(&f, 0, &f.fetch).await.1, chunk(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_file_holds_only_its_declared_chunks_and_at_most_the_protocols() {
|
||||
let relay = Relay::new();
|
||||
let f = File::new(2);
|
||||
relay.create(&f).await;
|
||||
assert_eq!(
|
||||
relay.put(&f, 2, &f.upload, chunk(1)).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE,
|
||||
"the file's quota"
|
||||
);
|
||||
assert_eq!(
|
||||
relay
|
||||
.put(&f, 2, &Token::from_bytes(random()), chunk(1))
|
||||
.await,
|
||||
StatusCode::NOT_FOUND,
|
||||
"a stranger learns nothing about the file from a 507"
|
||||
);
|
||||
for chunks in [0, MAX_FILE_CHUNKS + 1] {
|
||||
assert_eq!(
|
||||
relay.create(&File::new(chunks)).await,
|
||||
StatusCode::BAD_REQUEST,
|
||||
"{chunks}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
relay.create(&File::new(MAX_FILE_CHUNKS)).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
let extra = serde_json::json!({
|
||||
"id": FileId::from_bytes(random()),
|
||||
"uploadTokenHash": Token::from_bytes(random()).hash(),
|
||||
"fetchTokenHash": Token::from_bytes(random()).hash(),
|
||||
"chunks": 1,
|
||||
"name": "Menu.jpg",
|
||||
});
|
||||
assert_eq!(
|
||||
relay.create_json(extra).await,
|
||||
StatusCode::BAD_REQUEST,
|
||||
"no field beyond the four: the relay takes no name"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_malformed_id_or_index_is_a_bare_404() {
|
||||
let relay = Relay::new();
|
||||
let f = File::new(3);
|
||||
relay.create(&f).await;
|
||||
relay.put(&f, 0, &f.upload, chunk(1)).await;
|
||||
let id = f.id.to_wire();
|
||||
for path in [
|
||||
format!("/v0/files/{id}/chunks/00"),
|
||||
format!("/v0/files/{id}/chunks/+0"),
|
||||
format!("/v0/files/{id}/chunks/-1"),
|
||||
format!("/v0/files/{id}/chunks/x"),
|
||||
format!("/v0/files/{id}/chunks/4294967296"),
|
||||
format!("/v0/files/{id}A/chunks/0"),
|
||||
"/v0/files/AAAA/chunks/0".to_string(),
|
||||
] {
|
||||
let (s, _) = relay
|
||||
.call(Method::GET, &path, Some(&f.fetch), Vec::new())
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::NOT_FOUND, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_relay_wide_file_quota_counts_each_file_at_full_size_from_its_creation() {
|
||||
let relay = Relay::with(Limits {
|
||||
files: 3,
|
||||
file_bytes: 5 * FILE_CHUNK_BYTES as i64,
|
||||
..Limits::default()
|
||||
});
|
||||
let a = File::new(3);
|
||||
assert_eq!(relay.create(&a).await, StatusCode::CREATED);
|
||||
assert_eq!(
|
||||
relay.create(&File::new(3)).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE,
|
||||
"a's three chunks are reserved though none is up"
|
||||
);
|
||||
let b = File::new(2);
|
||||
assert_eq!(relay.create(&b).await, StatusCode::CREATED);
|
||||
// a's upload is never cut off by b.
|
||||
for i in 0..3 {
|
||||
assert_eq!(
|
||||
relay.put(&a, i, &a.upload, chunk(1)).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
}
|
||||
assert_eq!(relay.delete(&b, &b.upload).await, StatusCode::NO_CONTENT);
|
||||
assert_eq!(relay.create(&File::new(1)).await, StatusCode::CREATED);
|
||||
assert_eq!(relay.create(&File::new(1)).await, StatusCode::CREATED);
|
||||
assert_eq!(
|
||||
relay.create(&File::new(1)).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE,
|
||||
"the file count"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn files_go_after_30_days_and_incomplete_ones_after_a_day() {
|
||||
let relay = Relay::new();
|
||||
let complete = File::new(1);
|
||||
let incomplete = File::new(2);
|
||||
relay.create(&complete).await;
|
||||
relay.create(&incomplete).await;
|
||||
relay.put(&complete, 0, &complete.upload, chunk(1)).await;
|
||||
relay
|
||||
.put(&incomplete, 0, &incomplete.upload, chunk(2))
|
||||
.await;
|
||||
|
||||
let p = relay.store.purge(T0 + DAY - HOUR).expect("purge");
|
||||
assert_eq!(p.files, 0, "under a day: an upload may still be under way");
|
||||
let p = relay.store.purge(T0 + DAY + HOUR).expect("purge");
|
||||
assert_eq!(p.files, 1);
|
||||
assert_eq!(
|
||||
relay.get(&incomplete, 0, &incomplete.fetch).await.0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(
|
||||
relay
|
||||
.put(&incomplete, 1, &incomplete.upload, chunk(2))
|
||||
.await,
|
||||
StatusCode::NOT_FOUND,
|
||||
"and cannot be finished"
|
||||
);
|
||||
assert_eq!(
|
||||
relay.get(&complete, 0, &complete.fetch).await.0,
|
||||
StatusCode::OK
|
||||
);
|
||||
|
||||
let p = relay.store.purge(T0 + 30 * DAY - HOUR).expect("purge");
|
||||
assert_eq!(p.files, 0, "the complete file within its 30 days");
|
||||
let p = relay.store.purge(T0 + 30 * DAY + HOUR).expect("purge");
|
||||
assert_eq!(p.files, 1);
|
||||
assert_eq!(
|
||||
relay.get(&complete, 0, &complete.fetch).await.0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
relay.now.store(T0 + 31 * DAY, Ordering::SeqCst);
|
||||
assert_eq!(
|
||||
relay.create(&complete).await,
|
||||
StatusCode::CREATED,
|
||||
"the id is free again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_of_a_file_is_left_after_it_is_deleted_or_purged() {
|
||||
let dir = tempfile::tempdir().expect("dir");
|
||||
let path = dir.path().join("relay.db");
|
||||
let store = Store::open(&path).expect("store");
|
||||
let count = || -> (i64, i64) {
|
||||
let conn = rusqlite::Connection::open(&path).expect("open");
|
||||
let n = |t: &str| {
|
||||
conn.query_row(&format!("SELECT count(*) FROM {t}"), [], |r| r.get(0))
|
||||
.expect("count")
|
||||
};
|
||||
(n("files"), n("chunks"))
|
||||
};
|
||||
let deleted = File::new(2);
|
||||
let abandoned = File::new(2);
|
||||
for f in [&deleted, &abandoned] {
|
||||
store
|
||||
.create_file(
|
||||
&CreateFile {
|
||||
id: f.id,
|
||||
upload_token_hash: f.upload.hash(),
|
||||
fetch_token_hash: f.fetch.hash(),
|
||||
chunks: ChunkCount::new(f.chunks).expect("count"),
|
||||
},
|
||||
T0,
|
||||
)
|
||||
.expect("create");
|
||||
store
|
||||
.put_chunk(&f.id, &f.upload, 0, &chunk(3))
|
||||
.expect("chunk");
|
||||
}
|
||||
assert_eq!(count(), (2, 2));
|
||||
store
|
||||
.delete_file(&deleted.id, &deleted.upload)
|
||||
.expect("delete");
|
||||
assert_eq!(count(), (1, 1), "the deleted file's chunks went with it");
|
||||
store.purge(T0 + DAY + HOUR).expect("purge");
|
||||
assert_eq!(count(), (0, 0), "the abandoned one's too");
|
||||
}
|
||||
@@ -44,7 +44,7 @@ impl Relay {
|
||||
fn with(limits: Limits) -> Self {
|
||||
let store = Arc::new(Store::open_in_memory_with(limits).expect("store"));
|
||||
let clock: Clock = Arc::new(|| T0);
|
||||
Relay(router(AppState { store, clock }))
|
||||
Relay(router(AppState::new(store, clock)))
|
||||
}
|
||||
async fn call(
|
||||
&self,
|
||||
@@ -242,6 +242,10 @@ fn the_operator_sets_the_relay_wide_caps() {
|
||||
"7",
|
||||
"--max-invites",
|
||||
"9",
|
||||
"--max-files",
|
||||
"11",
|
||||
"--max-file-bytes",
|
||||
"13",
|
||||
]
|
||||
.map(String::from),
|
||||
)
|
||||
@@ -250,9 +254,11 @@ fn the_operator_sets_the_relay_wide_caps() {
|
||||
(
|
||||
args.limits.total_bytes,
|
||||
args.limits.mailboxes,
|
||||
args.limits.invites
|
||||
args.limits.invites,
|
||||
args.limits.files,
|
||||
args.limits.file_bytes
|
||||
),
|
||||
(5000, 7, 9)
|
||||
(5000, 7, 9, 11, 13)
|
||||
);
|
||||
assert_eq!(
|
||||
args.limits.mailbox_blobs, MAILBOX_BLOBS,
|
||||
@@ -264,6 +270,8 @@ fn the_operator_sets_the_relay_wide_caps() {
|
||||
vec!["--max-bytes", "-5"],
|
||||
vec!["--max-mailboxes", "many"],
|
||||
vec!["--max-invites", "1.5"],
|
||||
vec!["--max-files", "0"],
|
||||
vec!["--max-file-bytes", "-1"],
|
||||
] {
|
||||
assert!(
|
||||
parse_args(bad.iter().map(|s| s.to_string())).is_err(),
|
||||
|
||||
+136
-4
@@ -63,10 +63,7 @@ impl Relay {
|
||||
let now = Arc::new(AtomicI64::new(T0));
|
||||
let n = Arc::clone(&now);
|
||||
let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst));
|
||||
let app = router(AppState {
|
||||
store: Arc::clone(&store),
|
||||
clock,
|
||||
});
|
||||
let app = router(AppState::new(Arc::clone(&store), clock));
|
||||
Self { app, store, now }
|
||||
}
|
||||
fn advance(&self, secs: i64) {
|
||||
@@ -150,6 +147,21 @@ fn schema_is_exactly_protocol_section_5() {
|
||||
"received_hour".into(),
|
||||
],
|
||||
),
|
||||
// Files (`.agents/features/files.md` §2.3): every chunk is the same size, so no size column.
|
||||
(
|
||||
"chunks".into(),
|
||||
vec!["file_id".into(), "idx".into(), "ciphertext".into()],
|
||||
),
|
||||
(
|
||||
"files".into(),
|
||||
vec![
|
||||
"id".into(),
|
||||
"upload_hash".into(),
|
||||
"fetch_hash".into(),
|
||||
"chunks".into(),
|
||||
"uploaded_hour".into(),
|
||||
],
|
||||
),
|
||||
(
|
||||
"invites".into(),
|
||||
vec![
|
||||
@@ -168,6 +180,8 @@ fn schema_is_exactly_protocol_section_5() {
|
||||
"created_day".into(),
|
||||
],
|
||||
),
|
||||
// Wake-up (`.agents/features/wake-up.md` §2.3), only for a mailbox whose owner opted in.
|
||||
("push".into(), vec!["mailbox_id".into(), "endpoint".into()]),
|
||||
];
|
||||
assert_eq!(
|
||||
live, expected,
|
||||
@@ -356,6 +370,20 @@ async fn a_blob_over_256_kib_is_refused() {
|
||||
relay.post(&m, &m.post, &vec![1; MAX_BLOB_BYTES + 1]).await,
|
||||
StatusCode::PAYLOAD_TOO_LARGE
|
||||
);
|
||||
// Over a route's limit, axum's own refusal carries a text; the relay's is bare (§8).
|
||||
let (s, body) = relay
|
||||
.call(
|
||||
Method::POST,
|
||||
&m.blobs_path(),
|
||||
Some(&m.post),
|
||||
vec![1; MAX_BLOB_BYTES + 1],
|
||||
)
|
||||
.await;
|
||||
assert_eq!((s, body.len()), (StatusCode::PAYLOAD_TOO_LARGE, 0));
|
||||
let (s, body) = relay
|
||||
.call(Method::POST, "/v0/mailboxes", None, vec![b' '; 64 * 1024])
|
||||
.await;
|
||||
assert_eq!((s, body.len()), (StatusCode::PAYLOAD_TOO_LARGE, 0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -628,6 +656,15 @@ fn the_relay_listens_on_loopback_unless_told_otherwise() {
|
||||
let args = parse_args(Vec::<String>::new()).expect("defaults");
|
||||
assert_eq!(args.listen.to_string(), DEFAULT_LISTEN);
|
||||
assert!(args.listen.ip().is_loopback());
|
||||
assert!(
|
||||
!args.push_loopback,
|
||||
"loopback push endpoints only when asked for"
|
||||
);
|
||||
assert!(
|
||||
parse_args(["--push-loopback".to_string()])
|
||||
.expect("flag")
|
||||
.push_loopback
|
||||
);
|
||||
assert!(parse_args(["--listen".to_string()]).is_err());
|
||||
assert!(parse_args(["--verbose".to_string()]).is_err());
|
||||
}
|
||||
@@ -741,3 +778,98 @@ async fn no_random_request_breaks_the_relay() {
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /join` (PROTOCOL.md §8, 2026-11-18): a static page that hands the fragment to the app. It
|
||||
/// must load nothing from elsewhere, run nothing but its own script, and keep nothing.
|
||||
#[tokio::test]
|
||||
async fn the_join_page_is_static_and_loads_nothing_from_elsewhere() {
|
||||
use tower::ServiceExt;
|
||||
let relay = Relay::in_memory();
|
||||
let response = relay
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(Request::get("/join").body(Body::empty()).expect("request"))
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let h = response.headers().clone();
|
||||
let get = |name: &str| {
|
||||
h.get(name)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
};
|
||||
assert_eq!(get("content-type"), "text/html; charset=utf-8");
|
||||
assert_eq!(get("cache-control"), "no-store");
|
||||
assert_eq!(get("referrer-policy"), "no-referrer");
|
||||
assert_eq!(get("x-content-type-options"), "nosniff");
|
||||
assert!(h.get("set-cookie").is_none());
|
||||
let csp = get("content-security-policy");
|
||||
assert!(
|
||||
csp.starts_with("default-src 'none'; script-src 'sha256-"),
|
||||
"{csp}"
|
||||
);
|
||||
for part in [
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'",
|
||||
"frame-ancestors 'none'",
|
||||
] {
|
||||
assert!(csp.contains(part), "{csp} lacks {part}");
|
||||
}
|
||||
let body = String::from_utf8(
|
||||
response
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.expect("body")
|
||||
.to_bytes()
|
||||
.to_vec(),
|
||||
)
|
||||
.expect("utf-8");
|
||||
// Nothing loaded from anywhere, and nothing the script could send the fragment with or leave
|
||||
// the page by on its own (a custom scheme must wait for the person's tap).
|
||||
for banned in [
|
||||
"http://",
|
||||
"https://",
|
||||
" src=",
|
||||
"<link",
|
||||
"<img",
|
||||
"<iframe",
|
||||
"@import",
|
||||
"url(",
|
||||
"fetch(",
|
||||
"XMLHttpRequest",
|
||||
"sendBeacon",
|
||||
"WebSocket",
|
||||
"location.href",
|
||||
"location.assign",
|
||||
"location.replace",
|
||||
"window.open",
|
||||
] {
|
||||
assert!(!body.contains(banned), "the page contains {banned:?}");
|
||||
}
|
||||
// One script and one style, both named by the policy's hashes; the invite goes to the app.
|
||||
assert_eq!(body.matches("<script>").count(), 1);
|
||||
assert_eq!(body.matches("<style>").count(), 1);
|
||||
assert!(body.contains("\"amicitia://invite?relay=\" + location.origin + \"#\" + invite"));
|
||||
assert!(body.contains("location.hash"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_join_page_policy_hashes_its_own_script_and_style() {
|
||||
use base64::Engine;
|
||||
use sha2::{Digest, Sha256};
|
||||
let page = tabellarius_relay::join::PAGE;
|
||||
let between = |open: &str, close: &str| {
|
||||
let s = page.find(open).expect("the tag opens") + open.len();
|
||||
&page[s..page[s..].find(close).expect("the tag closes") + s]
|
||||
};
|
||||
let csp = tabellarius_relay::join::CONTENT_SECURITY_POLICY.as_str();
|
||||
for text in [
|
||||
between("<script>", "</script>"),
|
||||
between("<style>", "</style>"),
|
||||
] {
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(text.as_bytes()));
|
||||
assert!(csp.contains(&format!("'sha256-{b64}'")), "{csp}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
//! Wake-up (`docs/PROTOCOL.md` §6, `.agents/features/wake-up.md`): the push routes and the one
|
||||
//! request the relay sends, against a push server on loopback. Tokens and ids are generated per test.
|
||||
|
||||
use axum::body::{Body, Bytes};
|
||||
use axum::http::{header, HeaderMap, Method, Request, StatusCode};
|
||||
use http_body_util::BodyExt;
|
||||
use std::sync::atomic::{AtomicI64, AtomicU16, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tabellarius_protocol::*;
|
||||
use tabellarius_relay::http::{router, AppState, Clock};
|
||||
use tabellarius_relay::store::Store;
|
||||
use tabellarius_relay::wake::Waker;
|
||||
use tower::ServiceExt;
|
||||
|
||||
const T0: i64 = 1_794_000_000;
|
||||
|
||||
fn random<const N: usize>() -> [u8; N] {
|
||||
let mut b = [0u8; N];
|
||||
getrandom::fill(&mut b).expect("system randomness");
|
||||
b
|
||||
}
|
||||
|
||||
struct Mailbox {
|
||||
id: MailboxId,
|
||||
post: Token,
|
||||
fetch: Token,
|
||||
}
|
||||
|
||||
impl Mailbox {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
id: MailboxId::from_bytes(random()),
|
||||
post: Token::from_bytes(random()),
|
||||
fetch: Token::from_bytes(random()),
|
||||
}
|
||||
}
|
||||
fn path(&self, rest: &str) -> String {
|
||||
format!("/v0/mailboxes/{}/{rest}", self.id.to_wire())
|
||||
}
|
||||
}
|
||||
|
||||
/// What reached the push server: path, headers, body.
|
||||
#[derive(Clone)]
|
||||
struct Seen {
|
||||
path: String,
|
||||
headers: HeaderMap,
|
||||
body: Vec<u8>,
|
||||
}
|
||||
|
||||
/// A push server on loopback that records every request and answers with `status`.
|
||||
struct PushServer {
|
||||
port: u16,
|
||||
seen: Arc<Mutex<Vec<Seen>>>,
|
||||
status: Arc<AtomicU16>,
|
||||
}
|
||||
|
||||
impl PushServer {
|
||||
async fn start() -> Self {
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let status = Arc::new(AtomicU16::new(201));
|
||||
let (s, st) = (Arc::clone(&seen), Arc::clone(&status));
|
||||
let app = axum::Router::new().fallback(
|
||||
move |uri: axum::http::Uri, headers: HeaderMap, body: Bytes| {
|
||||
let (s, st) = (Arc::clone(&s), Arc::clone(&st));
|
||||
async move {
|
||||
s.lock().expect("seen").push(Seen {
|
||||
path: uri.to_string(),
|
||||
headers,
|
||||
body: body.to_vec(),
|
||||
});
|
||||
StatusCode::from_u16(st.load(Ordering::SeqCst)).expect("status")
|
||||
}
|
||||
},
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind");
|
||||
let port = listener.local_addr().expect("addr").port();
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
Self { port, seen, status }
|
||||
}
|
||||
fn endpoint(&self, path: &str) -> String {
|
||||
format!("http://127.0.0.1:{}{path}", self.port)
|
||||
}
|
||||
fn seen(&self) -> Vec<Seen> {
|
||||
self.seen.lock().expect("seen").clone()
|
||||
}
|
||||
/// Waits up to 5 s for `n` requests.
|
||||
async fn wait_for(&self, n: usize) -> Vec<Seen> {
|
||||
for _ in 0..100 {
|
||||
if self.seen().len() >= n {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
self.seen()
|
||||
}
|
||||
/// Gives a wake that should not happen a second to show up anyway.
|
||||
async fn quiet(&self) -> Vec<Seen> {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
self.seen()
|
||||
}
|
||||
}
|
||||
|
||||
struct Relay {
|
||||
app: axum::Router,
|
||||
store: Arc<Store>,
|
||||
now: Arc<AtomicI64>,
|
||||
}
|
||||
|
||||
impl Relay {
|
||||
/// `loopback`: the relay was started with `--push-loopback`, as tests must be to reach a local
|
||||
/// push server.
|
||||
fn new(loopback: bool) -> Self {
|
||||
let store = Arc::new(Store::open_in_memory().expect("store"));
|
||||
let now = Arc::new(AtomicI64::new(T0));
|
||||
let n = Arc::clone(&now);
|
||||
let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst));
|
||||
let app = router(AppState::with_waker(
|
||||
Arc::clone(&store),
|
||||
clock,
|
||||
Waker::new(loopback),
|
||||
));
|
||||
Self { app, store, now }
|
||||
}
|
||||
async fn call(
|
||||
&self,
|
||||
method: Method,
|
||||
path: &str,
|
||||
auth: Option<&Token>,
|
||||
body: Vec<u8>,
|
||||
) -> StatusCode {
|
||||
let mut req = Request::builder().method(method).uri(path);
|
||||
if let Some(t) = auth {
|
||||
req = req.header(header::AUTHORIZATION, t.to_bearer());
|
||||
}
|
||||
let resp = self
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(req.body(Body::from(body)).expect("request"))
|
||||
.await
|
||||
.expect("infallible");
|
||||
let status = resp.status();
|
||||
let body = resp.into_body().collect().await.expect("body").to_bytes();
|
||||
assert!(
|
||||
status != StatusCode::NOT_FOUND || body.is_empty(),
|
||||
"a 404 has no body"
|
||||
);
|
||||
status
|
||||
}
|
||||
async fn mailbox(&self) -> Mailbox {
|
||||
let m = Mailbox::new();
|
||||
let body = serde_json::to_vec(&CreateMailbox {
|
||||
id: m.id,
|
||||
post_token_hash: m.post.hash(),
|
||||
fetch_token_hash: m.fetch.hash(),
|
||||
})
|
||||
.expect("json");
|
||||
assert_eq!(
|
||||
self.call(Method::POST, "/v0/mailboxes", None, body).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
m
|
||||
}
|
||||
async fn set_push(&self, m: &Mailbox, token: &Token, endpoint: &str) -> StatusCode {
|
||||
let body = format!(r#"{{"endpoint":"{endpoint}"}}"#).into_bytes();
|
||||
self.call(Method::PUT, &m.path("push"), Some(token), body)
|
||||
.await
|
||||
}
|
||||
async fn clear_push(&self, m: &Mailbox, token: &Token) -> StatusCode {
|
||||
self.call(Method::DELETE, &m.path("push"), Some(token), vec![])
|
||||
.await
|
||||
}
|
||||
async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode {
|
||||
self.call(Method::POST, &m.path("blobs"), Some(token), blob.to_vec())
|
||||
.await
|
||||
}
|
||||
fn advance(&self, secs: i64) {
|
||||
self.now.fetch_add(secs, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn only_the_owner_sets_or_clears_where_to_be_woken() {
|
||||
let relay = Relay::new(true);
|
||||
let push = PushServer::start().await;
|
||||
let m = relay.mailbox().await;
|
||||
let endpoint = push.endpoint("/up/a");
|
||||
// The post token is the contact's: it cannot say where the owner is woken.
|
||||
assert_eq!(
|
||||
relay.set_push(&m, &m.post, &endpoint).await,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(
|
||||
relay.set_push(&Mailbox::new(), &m.fetch, &endpoint).await,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(
|
||||
relay
|
||||
.call(Method::PUT, &m.path("push"), Some(&m.fetch), b"{}".to_vec())
|
||||
.await,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
assert_eq!(
|
||||
relay
|
||||
.set_push(&m, &m.fetch, "http://push.example.cz/up")
|
||||
.await,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
assert_eq!(
|
||||
relay.set_push(&m, &m.fetch, &endpoint).await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
assert_eq!(
|
||||
relay.store.push_endpoint(&m.id).expect("read"),
|
||||
Some(endpoint)
|
||||
);
|
||||
assert_eq!(relay.clear_push(&m, &m.post).await, StatusCode::NOT_FOUND);
|
||||
assert_eq!(relay.clear_push(&m, &m.fetch).await, StatusCode::NO_CONTENT);
|
||||
assert_eq!(relay.store.push_endpoint(&m.id).expect("read"), None);
|
||||
// Clearing what is not there is not an error.
|
||||
assert_eq!(relay.clear_push(&m, &m.fetch).await, StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_relay_facing_the_internet_refuses_loopback_endpoints() {
|
||||
let relay = Relay::new(false);
|
||||
let m = relay.mailbox().await;
|
||||
assert_eq!(
|
||||
relay.set_push(&m, &m.fetch, "http://127.0.0.1:9/up").await,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
assert_eq!(relay.store.push_endpoint(&m.id).expect("read"), None);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_post_wakes_with_a_constant_and_nothing_of_the_mailbox_or_the_blob() {
|
||||
let relay = Relay::new(true);
|
||||
let push = PushServer::start().await;
|
||||
let m = relay.mailbox().await;
|
||||
assert_eq!(
|
||||
relay
|
||||
.set_push(&m, &m.fetch, &push.endpoint("/upToken123?up=1"))
|
||||
.await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
let canary = b"CANARY-wake-7f3a9c";
|
||||
assert_eq!(relay.post(&m, &m.post, canary).await, StatusCode::CREATED);
|
||||
let seen = push.wait_for(1).await;
|
||||
assert_eq!(seen.len(), 1, "one wake");
|
||||
let wake = &seen[0];
|
||||
assert_eq!(wake.path, "/upToken123?up=1");
|
||||
assert_eq!(wake.body, WAKE_BODY);
|
||||
assert_eq!(wake.headers.get("ttl").expect("TTL"), "86400");
|
||||
assert_eq!(wake.headers.get("urgency").expect("Urgency"), "normal");
|
||||
// Nothing of the mailbox, its tokens or the blob, anywhere in the request.
|
||||
let mut everything = wake.path.clone().into_bytes();
|
||||
for (name, value) in &wake.headers {
|
||||
everything.extend_from_slice(name.as_str().as_bytes());
|
||||
everything.extend_from_slice(value.as_bytes());
|
||||
}
|
||||
everything.extend_from_slice(&wake.body);
|
||||
let text = String::from_utf8_lossy(&everything);
|
||||
for secret in [
|
||||
m.id.to_wire(),
|
||||
m.post.to_wire(),
|
||||
m.fetch.to_wire(),
|
||||
blob_hash(canary).to_wire(),
|
||||
] {
|
||||
assert!(!text.contains(&secret), "the wake carries {secret}");
|
||||
}
|
||||
assert!(!text.contains("CANARY"), "the wake carries the blob");
|
||||
assert!(!text.contains("authorization"), "no token goes out");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_mailbox_is_woken_at_most_once_a_minute() {
|
||||
let relay = Relay::new(true);
|
||||
let push = PushServer::start().await;
|
||||
let m = relay.mailbox().await;
|
||||
relay.set_push(&m, &m.fetch, &push.endpoint("/up/a")).await;
|
||||
for _ in 0..3 {
|
||||
assert_eq!(relay.post(&m, &m.post, b"x").await, StatusCode::CREATED);
|
||||
}
|
||||
assert_eq!(push.wait_for(1).await.len(), 1);
|
||||
relay.advance(WAKE_EVERY_SECS - 1);
|
||||
relay.post(&m, &m.post, b"y").await;
|
||||
assert_eq!(push.quiet().await.len(), 1, "within the minute");
|
||||
relay.advance(1);
|
||||
relay.post(&m, &m.post, b"z").await;
|
||||
assert_eq!(push.wait_for(2).await.len(), 2, "after the minute");
|
||||
// Another mailbox has its own minute.
|
||||
let other = relay.mailbox().await;
|
||||
relay
|
||||
.set_push(&other, &other.fetch, &push.endpoint("/up/b"))
|
||||
.await;
|
||||
relay.post(&other, &other.post, b"w").await;
|
||||
let seen = push.wait_for(3).await;
|
||||
assert_eq!(seen.len(), 3);
|
||||
assert_eq!(seen[2].path, "/up/b");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn nothing_wakes_without_a_stored_post_or_without_an_endpoint() {
|
||||
let relay = Relay::new(true);
|
||||
let push = PushServer::start().await;
|
||||
let m = relay.mailbox().await;
|
||||
// No endpoint: a post wakes nobody.
|
||||
relay.post(&m, &m.post, b"before").await;
|
||||
relay.set_push(&m, &m.fetch, &push.endpoint("/up/a")).await;
|
||||
// A refused post wakes nobody: a stranger, or the owner's fetch token.
|
||||
assert_eq!(
|
||||
relay.post(&m, &Token::from_bytes(random()), b"x").await,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(relay.post(&m, &m.fetch, b"x").await, StatusCode::NOT_FOUND);
|
||||
let too_big = vec![0u8; MAX_BLOB_BYTES + 1];
|
||||
assert_ne!(relay.post(&m, &m.post, &too_big).await, StatusCode::CREATED);
|
||||
assert!(push.quiet().await.is_empty());
|
||||
// Cleared: nothing either.
|
||||
relay.clear_push(&m, &m.fetch).await;
|
||||
relay.post(&m, &m.post, b"after").await;
|
||||
assert!(push.quiet().await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_endpoint_the_push_server_says_is_gone_is_removed() {
|
||||
let relay = Relay::new(true);
|
||||
let push = PushServer::start().await;
|
||||
let m = relay.mailbox().await;
|
||||
let endpoint = push.endpoint("/up/a");
|
||||
relay.set_push(&m, &m.fetch, &endpoint).await;
|
||||
// A failure that is not "gone" keeps it.
|
||||
push.status.store(500, Ordering::SeqCst);
|
||||
relay.post(&m, &m.post, b"x").await;
|
||||
push.wait_for(1).await;
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
assert_eq!(
|
||||
relay.store.push_endpoint(&m.id).expect("read"),
|
||||
Some(endpoint)
|
||||
);
|
||||
push.status.store(410, Ordering::SeqCst);
|
||||
relay.advance(WAKE_EVERY_SECS);
|
||||
relay.post(&m, &m.post, b"y").await;
|
||||
push.wait_for(2).await;
|
||||
let mut gone = false;
|
||||
for _ in 0..50 {
|
||||
gone = relay.store.push_endpoint(&m.id).expect("read").is_none();
|
||||
if gone {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
assert!(gone, "410: the endpoint is removed");
|
||||
}
|
||||
|
||||
/// A raw listener that only counts connections: proves whether the relay connected at all.
|
||||
async fn counting_listener() -> (u16, Arc<AtomicUsize>) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind");
|
||||
let port = listener.local_addr().expect("addr").port();
|
||||
let count = Arc::new(AtomicUsize::new(0));
|
||||
let c = Arc::clone(&count);
|
||||
tokio::spawn(async move {
|
||||
while let Ok((conn, _)) = listener.accept().await {
|
||||
c.fetch_add(1, Ordering::SeqCst);
|
||||
drop(conn);
|
||||
}
|
||||
});
|
||||
(port, count)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_https_endpoint_on_a_local_address_is_never_connected_to() {
|
||||
// `https://127.0.0.1` passes the endpoint's syntax, so only the resolver stands in the way.
|
||||
for (loopback, expected) in [(false, 0), (true, 1)] {
|
||||
let relay = Relay::new(loopback);
|
||||
let (port, count) = counting_listener().await;
|
||||
let m = relay.mailbox().await;
|
||||
assert_eq!(
|
||||
relay
|
||||
.set_push(&m, &m.fetch, &format!("https://127.0.0.1:{port}/up"))
|
||||
.await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
relay.post(&m, &m.post, b"x").await;
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
assert_eq!(
|
||||
count.load(Ordering::SeqCst),
|
||||
expected,
|
||||
"with --push-loopback {loopback}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_redirect_from_the_push_server_is_not_followed() {
|
||||
let relay = Relay::new(true);
|
||||
let push = PushServer::start().await;
|
||||
let m = relay.mailbox().await;
|
||||
// The push server answers 303 to a second path on itself: following it would show up there.
|
||||
let target = push.endpoint("/second");
|
||||
let redirecting = axum::Router::new().fallback(move || {
|
||||
let target = target.clone();
|
||||
async move { (StatusCode::SEE_OTHER, [(header::LOCATION, target)]) }
|
||||
});
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind");
|
||||
let port = listener.local_addr().expect("addr").port();
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, redirecting).await;
|
||||
});
|
||||
relay
|
||||
.set_push(&m, &m.fetch, &format!("http://127.0.0.1:{port}/first"))
|
||||
.await;
|
||||
relay.post(&m, &m.post, b"x").await;
|
||||
assert!(push.quiet().await.is_empty(), "the redirect was followed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gone_endpoint_does_not_remove_the_one_set_since() {
|
||||
let store = Store::open_in_memory().expect("store");
|
||||
let m = Mailbox::new();
|
||||
store
|
||||
.create_mailbox(
|
||||
&CreateMailbox {
|
||||
id: m.id,
|
||||
post_token_hash: m.post.hash(),
|
||||
fetch_token_hash: m.fetch.hash(),
|
||||
},
|
||||
T0,
|
||||
)
|
||||
.expect("mailbox");
|
||||
let newer = PushEndpoint::parse("https://push.invalid/newer").expect("endpoint");
|
||||
store.set_push(&m.id, &m.fetch, Some(&newer)).expect("set");
|
||||
store
|
||||
.drop_push_if(&m.id, "https://push.invalid/older")
|
||||
.expect("drop");
|
||||
assert_eq!(
|
||||
store.push_endpoint(&m.id).expect("read").as_deref(),
|
||||
Some("https://push.invalid/newer")
|
||||
);
|
||||
}
|
||||
@@ -38,7 +38,7 @@ Pin `tabellarius` in `flake.lock`, as for any input. Then `nixos-rebuild switch
|
||||
## 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`) |
|
||||
| `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, and with `wake = true` (the default) to global addresses only, for the wakes of `PROTOCOL.md` §6; every non-global range is denied (`IPAddressDeny`). `wake = false`: localhost only |
|
||||
| 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 |
|
||||
|
||||
|
||||
+24
-3
@@ -52,6 +52,18 @@ in
|
||||
description = "Unclaimed invites the relay holds before it answers 507.";
|
||||
};
|
||||
|
||||
wake = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
Wake apps whose owners gave a push endpoint (PROTOCOL.md section 6): the relay may then
|
||||
connect out to global addresses, and only to those; every private, loopback-other-than-Caddy,
|
||||
link-local and reserved range stays denied here as well as in the relay. Names are looked up
|
||||
through the system's resolver (nscd on NixOS), so local sockets are allowed. Off: the relay
|
||||
talks to Caddy on loopback and to nothing else.
|
||||
'';
|
||||
};
|
||||
|
||||
openFirewall = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
@@ -79,10 +91,19 @@ in
|
||||
StateDirectoryMode = "0700";
|
||||
UMask = "0077";
|
||||
|
||||
# It talks to Caddy on loopback and to nothing else, even if it had a bug.
|
||||
IPAddressDeny = "any";
|
||||
# Without wakes it talks to Caddy on loopback and to nothing else, even if it had a bug. With
|
||||
# wakes it may also reach global addresses: the non-global ranges stay denied here, a second
|
||||
# wall behind the relay's own check (crates/relay/src/wake.rs). An address in both lists is
|
||||
# allowed, so localhost (Caddy) stays reachable.
|
||||
IPAddressAllow = "localhost";
|
||||
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
|
||||
IPAddressDeny =
|
||||
if cfg.wake then [
|
||||
"0.0.0.0/8" "10.0.0.0/8" "100.64.0.0/10" "169.254.0.0/16" "172.16.0.0/12"
|
||||
"192.0.0.0/24" "192.0.2.0/24" "192.168.0.0/16" "198.18.0.0/15" "198.51.100.0/24"
|
||||
"203.0.113.0/24" "224.0.0.0/3" "::/96" "::ffff:0:0/96" "64:ff9b::/96" "100::/64"
|
||||
"2001::/32" "2001:db8::/32" "2002::/16" "fc00::/7" "fe80::/10" "fec0::/10" "ff00::/8"
|
||||
] else "any";
|
||||
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ] ++ lib.optional cfg.wake "AF_UNIX";
|
||||
|
||||
CapabilityBoundingSet = "";
|
||||
NoNewPrivileges = true;
|
||||
|
||||
+91
-5
@@ -7,7 +7,7 @@ is a protocol version bump: documented here with its date and reason, and review
|
||||
## 1. Threat model
|
||||
| Adversary | Protected | Not protected |
|
||||
|:--|:--|:--|
|
||||
| **Relay operator** (honest but curious, including us) | message content, names, contact lists, which mailboxes belong to the same person *by content* | IP addresses at connection time and timing — an operator who logs at the network layer can correlate. Reduced by not logging (§5), not prevented. |
|
||||
| **Relay operator** (honest but curious, including us) | message content, names, contact lists, which mailboxes belong to the same person *by content*; a file's name, type, exact size and content | IP addresses at connection time and timing — an operator who logs at the network layer can correlate. Reduced by not logging (§5), not prevented. A file's size rounded up to 250 KiB, when it was uploaded, and each fetch of its chunks as it serves them (§8, files) |
|
||||
| **Network observer** | content (TLS + MLS) | that a device talks to a relay, and when |
|
||||
| **Stranger** | cannot post: no capability token | — |
|
||||
| **Contact who turns hostile** | block = rotate the token; their posts are refused | what they already received |
|
||||
@@ -46,15 +46,59 @@ 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`, `replyTo`? | a message; `seq` counts the sender's messages to this contact from 1. `replyTo` *(2026-11-21)*, when there, names the message it answers |
|
||||
| `reaction` *(2026-11-21)* | `to`, `emoji`? | the sender's reaction to the message `to`: `emoji` (1–32 bytes of UTF-8, no control characters) sets it, replacing their earlier one; absent removes it. No `seq` |
|
||||
| `poll` *(2026-11-22)* | `seq`, `question`, `options`, `multiple` | a message (it shares `seq` with `text`): a question of 1–300 characters and 2–10 different options of 1–100, none blank, no control characters; `multiple` allows several choices in a vote |
|
||||
| `vote` *(2026-11-22)* | `poll`, `choices` | the sender's choices in the poll `poll` names, replacing their earlier ones: indexes into `options`, ascending, each once, at most one unless `multiple`; `[]` takes the vote back. Refused once the poll is closed. No `seq` |
|
||||
| `pollClose` *(2026-11-22)* | `poll`, `ballots` | sent by the poll's author only: the poll is closed, and `ballots` (`{author, choices}`, one per member with a non-empty vote) are **the final votes**, as the author's client had accepted them, so a vote that crossed the close counts nowhere. No `seq` |
|
||||
| `file` *(2026-11-22)* | `seq`, `file`, `fetchToken`, `key`, `name`, `mime`, `size`, `thumb`? | a message (it shares `seq` with `text`): a file on the relay (§8, files). `file` its id, `fetchToken` the capability to get its chunks, `key` its 32-byte key; `name` 1–255 characters without control characters, `/` or `\`; `mime` `type/subtype`, 3–127 printable ASCII bytes; `size` 1 byte to 100 MiB; `thumb`, when there, a JPEG of at most 32 KiB (a receiver drops a thumbnail that is not, and keeps the file). The key, the name, the type and the exact size travel **only here** |
|
||||
| `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 |
|
||||
|
||||
**Naming a message** *(added 2026-11-21, Amicitia F27; `.agents/features/reactions-replies.md`)*:
|
||||
`{"author", "seq"}`, where `author` is the 16 random bytes in the author's MLS credential (unpadded
|
||||
base64url, 22 characters; made on the device, never a name) and `seq` the author's own. A receiver
|
||||
accepts a reference only to a message that exists in that conversation (an author who is one of its
|
||||
two members, a `seq` from 1 up to the last one sent or received); a reaction that names anything
|
||||
else is dropped, and a text keeps its words but loses the reference.
|
||||
|
||||
**Kinds a client does not know** *(2026-11-21)*: one with a `seq` of at least 1 is shown as *update
|
||||
the app to see this message* and counts for receipts; one without is dropped. A known kind with an
|
||||
unknown field is dropped: **new fields go into new kinds**, so that older clients say so instead of
|
||||
dropping a message without a trace.
|
||||
|
||||
**A file's chunks** *(added 2026-11-22, Amicitia F29; `.agents/features/files.md`)*: the file is
|
||||
padded with zeros to whole chunks of 255 984 bytes and each is sealed with ChaCha20-Poly1305 under
|
||||
the file's key in the STREAM construction (the `aead` crate's `StreamBE32`: a zero 7-byte nonce
|
||||
prefix, the chunk's index as a 32-bit big-endian counter, and a last-chunk flag), so every chunk is
|
||||
256 000 bytes and opens only at its own index, and only the last opens as last. A key is made for
|
||||
one file and never reused. A receiver refuses a chunk that does not open, and padding that is not
|
||||
zeros.
|
||||
|
||||
**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 |
|
||||
|:--|:--|
|
||||
| `mailboxes` | id, hash(post token), hash(fetch token), created day |
|
||||
| `blobs` | mailbox id, ciphertext, size, received hour (rounded) |
|
||||
| `invites` | invite id, hash(fetch secret), KeyPackage, expiry |
|
||||
| `push` *(only if the user opts in, G03)* | mailbox id, push endpoint |
|
||||
| `push` *(only if the user opts in, G03; made concrete 2026-11-20)* | mailbox id, push endpoint |
|
||||
| `files` *(2026-11-22, F29)* | file id, hash(upload token), hash(fetch token), chunk count, uploaded hour (rounded) |
|
||||
| `chunks` *(2026-11-22, F29)* | file id, index, ciphertext (always 256 000 bytes) |
|
||||
|
||||
Nothing else. No IP, no user agent, no request log beyond counts. A blob is deleted on acknowledged
|
||||
Nothing else. *(2026-11-22:)* a file has no mailbox, no sender and no recipient, and the relay
|
||||
keeps **no count of fetches**: it sees each one as it serves it. A file is deleted when its
|
||||
uploader deletes it, after **30 days**, or after **24 hours** if not all its chunks have arrived. No IP, no user agent, no request log beyond counts. *(2026-11-20:)* the relay also
|
||||
remembers **in memory only**, never on disk, when it last woke each mailbox (§6), to wake it at most
|
||||
once a minute. A blob is deleted on acknowledged
|
||||
delivery and after **30 days** at the latest *(decided 2026-11-08)*. The reverse proxy in front must also not
|
||||
log; the NixOS module ships configured that way.
|
||||
|
||||
@@ -62,6 +106,17 @@ log; the NixOS module ships configured that way.
|
||||
A notification for a closed app needs a push service. The wake-up carries **no content and no sender**
|
||||
— only "something arrived".
|
||||
- **Android:** UnifiedPush lets the user choose their own distributor; FCM as a fallback.
|
||||
*(Made concrete 2026-11-20, F25b; `.agents/features/wake-up.md`.)* The owner gives the relay one
|
||||
**push endpoint per mailbox** (§8, `PUT …/push`), so the relay cannot link a person's mailboxes by
|
||||
endpoint — it does see the endpoint's **host**, which on a person's own push server links them.
|
||||
When a blob is stored under a valid post token, the relay POSTs the constant body `wake` to the
|
||||
endpoint, at most once a minute per mailbox, with nothing of the mailbox, the blob or its sender.
|
||||
It connects only to **global** addresses (it resolves the host itself and drops loopback,
|
||||
private, link-local, CGNAT, multicast and reserved addresses, IPv4-mapped forms included), follows
|
||||
no redirect, gives up after 10 s, and has at most 16 wakes on their way. A push server's 404 or
|
||||
410 removes the endpoint. The push server learns that the relay woke one of its capability URLs,
|
||||
and when. Not done: Web Push encryption and VAPID (RFC 8291/8292) — the body is a public
|
||||
constant, but a distributor that requires VAPID cannot be used (gap W1).
|
||||
- **iOS:** only the app's publisher can send through Apple's push service, so a self-hosted relay
|
||||
cannot wake an iOS app directly. It would go through a small push gateway run by the publisher,
|
||||
which learns a device token and timing.
|
||||
@@ -71,12 +126,17 @@ The platform facts above are Claude's understanding, to be verified in `.agents/
|
||||
|
||||
## 7. Tests that prove this document
|
||||
- A canary string sent in a message never appears anywhere in the relay's database or logs.
|
||||
- A reaction's emoji and a reply's text never appear in the relay's database (`client/tests/real_relay.rs`, `client/tests/reactions.rs`); a reaction or reply to a message that does not exist in the conversation is refused (`client/tests/reactions.rs`, the client's unit tests).
|
||||
- A poll's question and options never appear in the relay's database (`client/tests/real_relay.rs`); a vote or close that does not fit its poll, a close by anyone but the poll's author, and anything after the close are refused and dropped (`client/tests/polls.rs`, the client's unit tests).
|
||||
- A file's name, type, thumbnail and content never appear in the relay's database, and every chunk it holds is 256 000 bytes (`client/tests/real_relay.rs`, `client/tests/files.rs`); a chunk tampered with, swapped, repeated, cut or from another file is refused (`client/tests/files.rs`, the client's unit tests); only the upload token puts or deletes and only the fetch token gets, a chunk never changes, the quotas answer 507, and files go after 30 days or 24 hours incomplete (`relay/tests/files.rs`).
|
||||
- A post without a valid token is refused; after rotation the old token is refused.
|
||||
- A delivered blob is gone; an undelivered blob is gone after the TTL (clock injected).
|
||||
- A wake carries the constant body and nothing of the mailbox, its tokens or the blob; a mailbox is
|
||||
woken at most once a minute; a non-global address is never connected to (`relay/tests/wake.rs`).
|
||||
- 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
|
||||
## 8. The wire (v0) — approved 2026-11-08, routes added 2026-11-14, quotas 2026-11-16, join page 2026-11-18, push 2026-11-20, files 2026-11-22
|
||||
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.
|
||||
@@ -88,9 +148,16 @@ unknown fields. A blob is at most 256 KiB, and a KeyPackage at most 16 KiB.
|
||||
| `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 |
|
||||
| `PUT /v0/mailboxes/{id}/push` `{endpoint}` *(2026-11-20)* | fetch token | where to wake the owner (§6): `https://`, a host, no user info or fragment, at most 1 000 bytes. 204 |
|
||||
| `DELETE /v0/mailboxes/{id}/push` *(2026-11-20)* | fetch token | no more wakes for this mailbox. 204, also when none was set |
|
||||
| `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 |
|
||||
| `POST /v0/files` `{id, uploadTokenHash, fetchTokenHash, chunks}` *(2026-11-22)* | none | creates a file of `chunks` (1–410) chunks. The uploader sends **hashes** of two tokens it made. 201; 409 if the id is taken; 400 if `chunks` is out of range |
|
||||
| `PUT /v0/files/{id}/chunks/{index}` (exactly 256 000 bytes) *(2026-11-22)* | upload token | stores chunk `index` (decimal, from 0). The same bytes again: 201; other bytes: 409, a chunk never changes; another size: 413 |
|
||||
| `GET /v0/files/{id}/chunks/{index}` *(2026-11-22)* | fetch token | the chunk's bytes; a chunk not there (yet) is 404 |
|
||||
| `DELETE /v0/files/{id}` *(2026-11-22)* | upload token | deletes the file and its chunks. 204 |
|
||||
| `GET /version` | none | the protocol and relay versions |
|
||||
| `GET /join` | none | a static page for an invite link opened in a browser *(added 2026-11-18)* |
|
||||
|
||||
- A wrong token, an unknown id and a malformed id all give the same bare **404**, so nobody can probe
|
||||
what exists.
|
||||
@@ -100,6 +167,25 @@ unknown fields. A blob is at most 256 KiB, and a KeyPackage at most 16 KiB.
|
||||
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.
|
||||
- **Files** *(added 2026-11-22, Amicitia F29, so a chat can carry photos, videos and documents;
|
||||
`.agents/features/files.md`)*: a file holds at most its declared chunks (an index at or past them
|
||||
is 507, checked after the upload token), at most 410 (100 MiB of plaintext). A relay holds at most
|
||||
`--max-files` files (default 10 000) and `--max-file-bytes` (default 4 GiB), each file counted at
|
||||
its full size from its creation so an upload under way is never cut off; over either, `POST` is
|
||||
507. Files have their own quota, apart from blobs, so they cannot starve messages. Only the token
|
||||
whose hash came with `POST` can add, or delete; a stranger who learns a file id can do neither.
|
||||
A relay from before this answers 404 to `POST /v0/files`.
|
||||
- **The join page** *(added 2026-11-18; `.agents/features/join-page.md`)*: an invite can travel as
|
||||
`https://<relay>/join#<invite id>.<secret>`, which messengers make tappable. The browser sends
|
||||
only `GET /join`: the fragment, and so the secret, never reaches the relay, a link preview or a
|
||||
proxy. The page is static (one inline script and style, named by hash in a
|
||||
`Content-Security-Policy` of `default-src 'none'`; `no-store`; `no-referrer`; no cookie) and
|
||||
points its one button at `amicitia://invite?relay=<its origin>#<id>.<secret>`. The relay stores
|
||||
nothing for it and learns only that some address opened the page.
|
||||
- A refusal has no body.
|
||||
- The relay prints no request.
|
||||
- Tests: `crates/relay/tests/relay.rs`, `crates/protocol/tests/wire.rs`.
|
||||
- **Push** *(added 2026-11-20, Amicitia F25b, so a closed Android app hears that something arrived)*:
|
||||
a wrong token or unknown mailbox is §8's bare 404; an endpoint that breaks the rules is 400, and so
|
||||
is `http://` to a loopback host, which only a relay started with `--push-loopback` (tests) accepts.
|
||||
- Tests: `crates/relay/tests/relay.rs`, `crates/relay/tests/wake.rs`, `crates/relay/tests/files.rs`,
|
||||
`crates/protocol/tests/wire.rs`.
|
||||
|
||||
Reference in New Issue
Block a user