Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| abb0a87471 | |||
| 9d9d63c02b | |||
| 1d7f08927d | |||
| f852b1a6d1 | |||
| f075fae0e3 | |||
| 1ccae752d7 | |||
| dff1bec275 | |||
| cfabc97d20 | |||
| 0e6be38280 | |||
| 0fbcb34b53 | |||
| dd576f9feb | |||
| 2a8daa7570 | |||
| 3ac2075ec6 | |||
| 4f78101735 |
@@ -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.
|
||||||
@@ -91,6 +91,11 @@ The F21 calls stay, for apps and tests without persistence: `send` = `compose` +
|
|||||||
relay's 7 days (the library has no clock). Without it an unclaimed invite's mailbox is fetched
|
relay's 7 days (the library has no clock). Without it an unclaimed invite's mailbox is fetched
|
||||||
for ever.
|
for ever.
|
||||||
|
|
||||||
|
10. **A forgotten contact leaves nothing behind** (`forget_contact`, added 2026-11-16 for Amicitia's
|
||||||
|
*Remove person*): its name is gone from the snapshot, its MLS group from storage (putting the
|
||||||
|
contact back into the snapshot is refused), and its mailbox is no longer fetched. The other side
|
||||||
|
is not told.
|
||||||
|
|
||||||
Planted bugs, for the review: `receive` acknowledges inside the call; `compose` posts; `restore`
|
Planted bugs, for the review: `receive` acknowledges inside the call; `compose` posts; `restore`
|
||||||
skips the storage map; `finish` acknowledges before it delivers; a restored client starts
|
skips the storage map; `finish` acknowledges before it delivers; a restored client starts
|
||||||
`next_contact` at 0, so two contacts share an id.
|
`next_contact` at 0, so two contacts share an id.
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# F23 — The relay on a home server: quotas, a NixOS module, TLS
|
||||||
|
|
||||||
|
Analysis, 2026-11-16. Issues T#8 (deploy) and Amicitia #51. The container image of T#8 is left for later: the NixOS module is what the home server runs. It builds on F20 (the relay) and
|
||||||
|
`relay.md` §3–4, which put two things before any relay that faces the internet: **quotas**, and a
|
||||||
|
**reverse proxy that logs no IP address**.
|
||||||
|
|
||||||
|
## 1. Why and what
|
||||||
|
Two people on two machines can only chat through a relay both can reach. Mark's home server is the
|
||||||
|
first one. After F23:
|
||||||
|
- the relay refuses to fill its disk: per-mailbox and relay-wide caps, answered with a bare **507**;
|
||||||
|
- `deploy/nixos/module.nix` runs it on NixOS, listening on loopback only, behind **Caddy** with TLS
|
||||||
|
from Let's Encrypt, and **no access log, no error log with an address in it**;
|
||||||
|
- a NixOS VM test boots that configuration, sends requests through the proxy from a known address,
|
||||||
|
and fails if that address appears anywhere in the journal or under `/var/log`;
|
||||||
|
- Amicitia accepts an `https://` relay address (its own PR).
|
||||||
|
|
||||||
|
## 2. Design
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
A[app] -->|TLS 443| C[Caddy: TLS, no logs]
|
||||||
|
C -->|HTTP 127.0.0.1:8470| R[tabellarius-relay: systemd, DynamicUser, loopback only]
|
||||||
|
R --> D[(SQLite: PROTOCOL.md section 5)]
|
||||||
|
```
|
||||||
|
### Quotas *(protocol change, §8: a new status)*
|
||||||
|
| Limit | Default | Set by |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| waiting blobs in one mailbox | 1 000 | the protocol |
|
||||||
|
| waiting bytes in one mailbox | 32 MiB | the protocol |
|
||||||
|
| waiting bytes on the relay | 1 GiB | `--max-bytes` |
|
||||||
|
| mailboxes on the relay | 100 000 | `--max-mailboxes` |
|
||||||
|
| unclaimed invites on the relay | 10 000 | `--max-invites` |
|
||||||
|
|
||||||
|
- Over a limit, the relay answers **507 Insufficient Storage**, bare, like every refusal. The
|
||||||
|
per-mailbox caps are checked **after** the post token, so 507 tells nothing to someone without
|
||||||
|
the token. The relay-wide caps say only that the relay is full.
|
||||||
|
- **No identity is needed to count**: nothing new is stored; the counts come from §5's own columns
|
||||||
|
(`size`, the rows). No IP address is kept, not even in memory: rate limits by address would need
|
||||||
|
one. A flood can fill the relay up to its caps; then it refuses, and the operator sees it.
|
||||||
|
- The client already handles it: 507 is a failure, so the message waits in the outbox.
|
||||||
|
- **Mailboxes are never deleted yet** (`relay.md` §4): an abandoned mailbox counts against the
|
||||||
|
100 000 until a protocol version can delete one. Stated.
|
||||||
|
|
||||||
|
### The NixOS module (`deploy/nixos/module.nix`)
|
||||||
|
- `services.tabellarius.enable`, `.domain`, `.maxBytes`, `.maxMailboxes`, `.maxInvites`, `.package`
|
||||||
|
(the flake's own build).
|
||||||
|
- **The relay:** a systemd service with `DynamicUser`, `StateDirectory=tabellarius` (the database),
|
||||||
|
`--listen 127.0.0.1:8470`. Hardened: `ProtectSystem=strict`, `ProtectHome`, `PrivateTmp`,
|
||||||
|
`PrivateDevices`, `NoNewPrivileges`, `MemoryDenyWriteExecute`, `RestrictAddressFamilies=AF_INET
|
||||||
|
AF_INET6`, `SystemCallFilter=@system-service`, and **`IPAddressDeny=any` with
|
||||||
|
`IPAddressAllow=localhost`**: even a bug cannot make it talk to anything but the proxy.
|
||||||
|
- **The proxy:** `services.caddy`, one virtual host, `reverse_proxy 127.0.0.1:8470`. The NixOS
|
||||||
|
module writes an access log per host by default; the host's `logFormat` is set to
|
||||||
|
`output discard`, and Caddy's default logger too. Caddy's own TLS-handshake and proxy errors can
|
||||||
|
name a client address, so no log is the rule; an operator who needs one turns it on and knows
|
||||||
|
why. Headers: none added.
|
||||||
|
- **journald:** the relay prints one line at start. Nothing per request.
|
||||||
|
|
||||||
|
### The VM test (`deploy/nixos/test.nix`, `nix flake check`)
|
||||||
|
Two machines: `server` with the module (TLS from Caddy's internal CA instead of Let's Encrypt), and
|
||||||
|
`client` at a fixed address. The client creates a mailbox, posts, fetches, acknowledges, makes a
|
||||||
|
mistake (a wrong token, a malformed request), and fills a mailbox to its 507. Then the test greps
|
||||||
|
the server's whole journal and `/var/log` for the client's address and fails if it appears.
|
||||||
|
|
||||||
|
**Not run here.** This machine has neither Nix nor WSL. The module and the test are written to be
|
||||||
|
run with `nix flake check` on Linux, and the PR says so. Mark's server is the first real run.
|
||||||
|
|
||||||
|
## 3. Risks
|
||||||
|
- **Privacy:** the logs are the risk this feature exists to close. The VM test is its proof, once
|
||||||
|
it runs. The network layer (a router, the ISP) still sees addresses and timing (§1).
|
||||||
|
- **Abuse:** caps bound the disk; they do not stop someone from filling them. Proof of work or
|
||||||
|
invite-only mailbox creation is for a later protocol version.
|
||||||
|
- **Reproducibility:** the module uses the flake's package, so the relay that runs is the one built
|
||||||
|
from this commit (`docs/VERIFY.md`).
|
||||||
|
|
||||||
|
## 4. Tests — written first
|
||||||
|
1. Each cap: the post or create that would cross it gets 507; one under it succeeds; after an
|
||||||
|
acknowledgement (or a purge) there is room again.
|
||||||
|
2. The per-mailbox cap answers 404, not 507, to a wrong token.
|
||||||
|
3. The CLI reads `--max-bytes`, `--max-mailboxes`, `--max-invites`; a bad value is refused.
|
||||||
|
4. The VM test (§2), on Linux.
|
||||||
|
|
||||||
|
Planted bugs: the mailbox cap checked before the token; an acknowledgement not freeing space; the
|
||||||
|
global byte cap ignored; the invite cap counting claimed invites; the CLI option ignored.
|
||||||
@@ -0,0 +1,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,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
+190
-10
@@ -118,6 +118,12 @@ version = "0.22.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "base64"
|
||||||
|
version = "0.23.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "base64ct"
|
name = "base64ct"
|
||||||
version = "1.8.3"
|
version = "1.8.3"
|
||||||
@@ -617,7 +623,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"windows-sys",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1389,7 +1395,7 @@ checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"wasi",
|
"wasi",
|
||||||
"windows-sys",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1908,6 +1914,20 @@ dependencies = [
|
|||||||
"subtle",
|
"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]]
|
[[package]]
|
||||||
name = "rsqlite-vfs"
|
name = "rsqlite-vfs"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
@@ -1957,7 +1977,42 @@ dependencies = [
|
|||||||
"errno",
|
"errno",
|
||||||
"libc",
|
"libc",
|
||||||
"linux-raw-sys",
|
"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]]
|
[[package]]
|
||||||
@@ -2167,7 +2222,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"windows-sys",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2198,9 +2253,9 @@ checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sqlite-wasm-rs"
|
name = "sqlite-wasm-rs"
|
||||||
version = "0.6.3"
|
version = "0.6.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867"
|
checksum = "36bd8e29bf08189a005b2df1df99823aa0861cabe9044e5f31ed54ca292ee618"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cc",
|
"cc",
|
||||||
"rsqlite-vfs",
|
"rsqlite-vfs",
|
||||||
@@ -2245,7 +2300,7 @@ name = "tabellarius-client"
|
|||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
"base64",
|
"base64 0.22.1",
|
||||||
"hkdf 0.12.4",
|
"hkdf 0.12.4",
|
||||||
"openmls",
|
"openmls",
|
||||||
"openmls_basic_credential",
|
"openmls_basic_credential",
|
||||||
@@ -2264,7 +2319,7 @@ dependencies = [
|
|||||||
name = "tabellarius-protocol"
|
name = "tabellarius-protocol"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64",
|
"base64 0.22.1",
|
||||||
"proptest",
|
"proptest",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -2276,16 +2331,19 @@ name = "tabellarius-relay"
|
|||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum",
|
"axum",
|
||||||
|
"base64 0.22.1",
|
||||||
"getrandom 0.3.4",
|
"getrandom 0.3.4",
|
||||||
"http-body-util",
|
"http-body-util",
|
||||||
"rusqlite",
|
"rusqlite",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2 0.10.9",
|
||||||
"subtle",
|
"subtle",
|
||||||
"tabellarius-protocol",
|
"tabellarius-protocol",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tower",
|
"tower",
|
||||||
|
"ureq",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2298,7 +2356,7 @@ dependencies = [
|
|||||||
"getrandom 0.4.3",
|
"getrandom 0.4.3",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"rustix",
|
"rustix",
|
||||||
"windows-sys",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2356,7 +2414,7 @@ dependencies = [
|
|||||||
"signal-hook-registry",
|
"signal-hook-registry",
|
||||||
"socket2",
|
"socket2",
|
||||||
"tokio-macros",
|
"tokio-macros",
|
||||||
"windows-sys",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2455,6 +2513,46 @@ dependencies = [
|
|||||||
"subtle",
|
"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]]
|
[[package]]
|
||||||
name = "uuid"
|
name = "uuid"
|
||||||
version = "1.29.2"
|
version = "1.29.2"
|
||||||
@@ -2546,12 +2644,30 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"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]]
|
[[package]]
|
||||||
name = "windows-link"
|
name = "windows-link"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
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]]
|
[[package]]
|
||||||
name = "windows-sys"
|
name = "windows-sys"
|
||||||
version = "0.61.2"
|
version = "0.61.2"
|
||||||
@@ -2561,6 +2677,70 @@ dependencies = [
|
|||||||
"windows-link",
|
"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]]
|
[[package]]
|
||||||
name = "winnow"
|
name = "winnow"
|
||||||
version = "1.0.5"
|
version = "1.0.5"
|
||||||
|
|||||||
+756
-45
@@ -32,8 +32,8 @@ use sha2::Sha256;
|
|||||||
use snapshot::Bytes;
|
use snapshot::Bytes;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use tabellarius_protocol::{
|
use tabellarius_protocol::{
|
||||||
blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, Sha256Hash,
|
blob_hash, Author, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId,
|
||||||
Token, MAX_BLOB_BYTES,
|
PushEndpoint, Sha256Hash, Token, MAX_BLOB_BYTES,
|
||||||
};
|
};
|
||||||
pub use transport::{MemoryTransport, Transport, TransportError};
|
pub use transport::{MemoryTransport, Transport, TransportError};
|
||||||
|
|
||||||
@@ -43,6 +43,10 @@ pub const CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_
|
|||||||
pub const MAX_NAME_CHARS: usize = 64;
|
pub const MAX_NAME_CHARS: usize = 64;
|
||||||
/// The longest text message, in bytes; well under a blob's limit once encrypted.
|
/// The longest text message, in bytes; well under a blob's limit once encrypted.
|
||||||
pub const MAX_TEXT_BYTES: usize = 64 * 1024;
|
pub const MAX_TEXT_BYTES: usize = 64 * 1024;
|
||||||
|
/// The longest reaction, in bytes of UTF-8: the longest emoji ZWJ sequences are 28.
|
||||||
|
pub const MAX_EMOJI_BYTES: usize = 32;
|
||||||
|
/// The payload kinds this client knows; any other kind that carries a `seq` is `Unsupported`.
|
||||||
|
const KNOWN_KINDS: [&str; 5] = ["hello", "text", "receipt", "inbox", "reaction"];
|
||||||
|
|
||||||
const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox";
|
const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox";
|
||||||
const WELCOME_POST_LABEL: &[u8] = b"tabellarius v0 welcome mailbox post";
|
const WELCOME_POST_LABEL: &[u8] = b"tabellarius v0 welcome mailbox post";
|
||||||
@@ -59,6 +63,9 @@ pub enum ClientError {
|
|||||||
TooLong,
|
TooLong,
|
||||||
/// No such contact, or a contact whose mailbox is not known yet.
|
/// No such contact, or a contact whose mailbox is not known yet.
|
||||||
UnknownContact,
|
UnknownContact,
|
||||||
|
/// A reply or reaction to a message that does not exist in this conversation, or an emoji
|
||||||
|
/// that is empty or has a control character.
|
||||||
|
BadReference,
|
||||||
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
|
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
|
||||||
State,
|
State,
|
||||||
}
|
}
|
||||||
@@ -102,26 +109,71 @@ pub enum Event {
|
|||||||
name: String,
|
name: String,
|
||||||
via: Option<InviteId>,
|
via: Option<InviteId>,
|
||||||
},
|
},
|
||||||
|
/// A text. `seq` is the author's own count; with the contact's [`Client::contact_author`] it
|
||||||
|
/// names the message, for replies and reactions. `reply_to` is a message this one answers,
|
||||||
|
/// checked to exist in this conversation (a reference that does not is left out).
|
||||||
Message {
|
Message {
|
||||||
contact: ContactId,
|
contact: ContactId,
|
||||||
text: String,
|
text: String,
|
||||||
|
seq: u64,
|
||||||
|
reply_to: Option<MessageRef>,
|
||||||
|
},
|
||||||
|
/// The contact's reaction to a message in this conversation: set (replacing their earlier one)
|
||||||
|
/// or, with `emoji` `None`, removed.
|
||||||
|
Reaction {
|
||||||
|
contact: ContactId,
|
||||||
|
to: MessageRef,
|
||||||
|
emoji: Option<String>,
|
||||||
|
},
|
||||||
|
/// A message of a kind this client does not know (a newer app's). Show that something arrived
|
||||||
|
/// that needs an update; its `seq` counts like a text's.
|
||||||
|
Unsupported { contact: ContactId, seq: u64 },
|
||||||
|
/// The other side's app has saved our texts up to `upto` (a `seq` from
|
||||||
|
/// [`Client::sent_seq`]). Only while receipts are on ([`Client::set_receipts`]).
|
||||||
|
Delivered { contact: ContactId, upto: u64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One operation for the relay, to deliver once the app has saved the snapshot: a blob to post,
|
||||||
|
/// or a post token to rotate (block, unblock). An app may keep it in an outbox and deliver it
|
||||||
|
/// again after a crash: a second post is refused by MLS as a replay, a second rotate changes
|
||||||
|
/// nothing. `Debug` shows no token and no bytes.
|
||||||
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(transparent)]
|
||||||
|
pub struct Outgoing(Op);
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "op", rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
enum Op {
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
Post {
|
||||||
|
to: MailboxId,
|
||||||
|
post: Token,
|
||||||
|
blob: Bytes,
|
||||||
|
},
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
Rotate {
|
||||||
|
mailbox: MailboxId,
|
||||||
|
fetch: Token,
|
||||||
|
post_token_hash: Sha256Hash,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One blob for the relay, to deliver once the app has saved the snapshot. An app may keep it in
|
impl Outgoing {
|
||||||
/// an outbox and deliver it again after a crash: a second copy is refused by MLS as a replay.
|
fn post(to: MailboxId, post: Token, blob: Vec<u8>) -> Outgoing {
|
||||||
/// `Debug` shows neither the post token nor the bytes.
|
Outgoing(Op::Post {
|
||||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
to,
|
||||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
post,
|
||||||
pub struct Outgoing {
|
blob: Bytes(blob),
|
||||||
to: MailboxId,
|
})
|
||||||
post: Token,
|
}
|
||||||
blob: Bytes,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for Outgoing {
|
impl fmt::Debug for Outgoing {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
write!(f, "Outgoing({} bytes)", self.blob.0.len())
|
match &self.0 {
|
||||||
|
Op::Post { blob, .. } => write!(f, "Outgoing({} bytes)", blob.0.len()),
|
||||||
|
Op::Rotate { .. } => f.write_str("Outgoing(rotate)"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +190,7 @@ struct Ack {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Received {
|
pub struct Received {
|
||||||
pub events: Vec<Event>,
|
pub events: Vec<Event>,
|
||||||
/// Our answering `hello`s.
|
/// Our answering `hello`s, and receipts.
|
||||||
pub outgoing: Vec<Outgoing>,
|
pub outgoing: Vec<Outgoing>,
|
||||||
/// The relay failed part-way: what was fetched before it is here, the rest waits there.
|
/// The relay failed part-way: what was fetched before it is here, the rest waits there.
|
||||||
pub interrupted: Option<TransportError>,
|
pub interrupted: Option<TransportError>,
|
||||||
@@ -151,6 +203,14 @@ impl fmt::Debug for Ack {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A message in a conversation, named by its author and the author's own `seq` (`PROTOCOL.md` §4).
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct MessageRef {
|
||||||
|
pub author: Author,
|
||||||
|
pub seq: u64,
|
||||||
|
}
|
||||||
|
|
||||||
/// The JSON inside an MLS application message. The relay never sees it.
|
/// The JSON inside an MLS application message. The relay never sees it.
|
||||||
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
|
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
|
||||||
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
|
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
|
||||||
@@ -161,9 +221,27 @@ enum Payload {
|
|||||||
post_token: Token,
|
post_token: Token,
|
||||||
name: String,
|
name: String,
|
||||||
},
|
},
|
||||||
|
/// `seq` counts this sender's messages to this contact, from 1. `replyTo`, when there, names
|
||||||
|
/// the message this one answers; absent, the JSON is a text's from before replies.
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
Text {
|
Text {
|
||||||
body: String,
|
body: String,
|
||||||
|
seq: u64,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
reply_to: Option<MessageRef>,
|
||||||
},
|
},
|
||||||
|
/// The sender's reaction to a message: `emoji` sets it, absent removes it. No `seq`: not a
|
||||||
|
/// message, so it is not replied to, reacted to or covered by a receipt.
|
||||||
|
Reaction {
|
||||||
|
to: MessageRef,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
emoji: Option<String>,
|
||||||
|
},
|
||||||
|
/// The receiver has saved our texts up to `upto`.
|
||||||
|
Receipt { upto: u64 },
|
||||||
|
/// A new post token for the mailbox the receiver already knows (unblock).
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
Inbox { post_token: Token },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
@@ -189,6 +267,12 @@ struct Contact {
|
|||||||
outbox: Option<(MailboxId, Token)>,
|
outbox: Option<(MailboxId, Token)>,
|
||||||
/// The invite this contact came through, on the inviter's side.
|
/// The invite this contact came through, on the inviter's side.
|
||||||
via: Option<InviteId>,
|
via: Option<InviteId>,
|
||||||
|
/// Blocked: their mailbox token rotated away; what still arrives from them is dropped.
|
||||||
|
blocked: bool,
|
||||||
|
/// The `seq` of our last text to them.
|
||||||
|
sent_seq: u64,
|
||||||
|
/// The highest `seq` of their texts we have received.
|
||||||
|
received_seq: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Client<T: Transport> {
|
pub struct Client<T: Transport> {
|
||||||
@@ -201,6 +285,8 @@ pub struct Client<T: Transport> {
|
|||||||
contacts: Vec<Contact>,
|
contacts: Vec<Contact>,
|
||||||
welcome_boxes: Vec<WelcomeBox>,
|
welcome_boxes: Vec<WelcomeBox>,
|
||||||
next_contact: u32,
|
next_contact: u32,
|
||||||
|
/// Send receipts and report the other side's (reciprocal). On by default.
|
||||||
|
receipts: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Transport> Client<T> {
|
impl<T: Transport> Client<T> {
|
||||||
@@ -230,6 +316,7 @@ impl<T: Transport> Client<T> {
|
|||||||
contacts: Vec::new(),
|
contacts: Vec::new(),
|
||||||
welcome_boxes: Vec::new(),
|
welcome_boxes: Vec::new(),
|
||||||
next_contact: 0,
|
next_contact: 0,
|
||||||
|
receipts: true,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,6 +388,21 @@ impl<T: Transport> Client<T> {
|
|||||||
self.welcome_boxes.retain(|w| w.invite != *invite);
|
self.welcome_boxes.retain(|w| w.invite != *invite);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Forgets a contact: its MLS group is deleted from storage, its name and tokens from the
|
||||||
|
/// client, and its mailbox is no longer fetched. The other side is not told, and anything it
|
||||||
|
/// still posts waits on the relay until it expires. Save the snapshot after it. Returns whether
|
||||||
|
/// there was such a contact.
|
||||||
|
pub fn forget_contact(&mut self, contact: ContactId) -> Result<bool, ClientError> {
|
||||||
|
let Some(index) = self.contacts.iter().position(|c| c.id == contact) else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
let mut c = self.contacts.remove(index);
|
||||||
|
c.group
|
||||||
|
.delete(self.provider.storage())
|
||||||
|
.map_err(|_| ClientError::State)?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
/// Step 2, on the other device, staged: claims the KeyPackage (which uses the link up) and
|
/// Step 2, on the other device, staged: claims the KeyPackage (which uses the link up) and
|
||||||
/// creates our mailbox, then makes the group. The Welcome and our `hello` come back for the
|
/// creates our mailbox, then makes the group. The Welcome and our `hello` come back for the
|
||||||
/// app to deliver after saving.
|
/// app to deliver after saving.
|
||||||
@@ -340,16 +442,8 @@ impl<T: Transport> Client<T> {
|
|||||||
.map_err(|_| ClientError::Mls)?;
|
.map_err(|_| ClientError::Mls)?;
|
||||||
let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?;
|
let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?;
|
||||||
let out = vec![
|
let out = vec![
|
||||||
Outgoing {
|
Outgoing::post(welcome_id, welcome_post, welcome),
|
||||||
to: welcome_id,
|
Outgoing::post(welcome_id, welcome_post, hello),
|
||||||
post: welcome_post,
|
|
||||||
blob: Bytes(welcome),
|
|
||||||
},
|
|
||||||
Outgoing {
|
|
||||||
to: welcome_id,
|
|
||||||
post: welcome_post,
|
|
||||||
blob: Bytes(hello),
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
let id = self.add_contact(group, Some(inbox), None, None);
|
let id = self.add_contact(group, Some(inbox), None, None);
|
||||||
Ok((id, out))
|
Ok((id, out))
|
||||||
@@ -380,6 +474,9 @@ impl<T: Transport> Client<T> {
|
|||||||
inbox,
|
inbox,
|
||||||
outbox,
|
outbox,
|
||||||
via,
|
via,
|
||||||
|
blocked: false,
|
||||||
|
sent_seq: 0,
|
||||||
|
received_seq: 0,
|
||||||
});
|
});
|
||||||
id
|
id
|
||||||
}
|
}
|
||||||
@@ -405,36 +502,248 @@ impl<T: Transport> Client<T> {
|
|||||||
/// Encrypts text for a contact whose `hello` has arrived. No network: save the snapshot, then
|
/// Encrypts text for a contact whose `hello` has arrived. No network: save the snapshot, then
|
||||||
/// [`Client::deliver`] the result.
|
/// [`Client::deliver`] the result.
|
||||||
pub fn compose(&mut self, contact: ContactId, text: &str) -> Result<Outgoing, ClientError> {
|
pub fn compose(&mut self, contact: ContactId, text: &str) -> Result<Outgoing, ClientError> {
|
||||||
|
self.compose_text(contact, text, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Client::compose`], answering `reply_to`: a message in this conversation, ours or theirs,
|
||||||
|
/// that exists ([`ClientError::BadReference`] otherwise).
|
||||||
|
pub fn compose_text(
|
||||||
|
&mut self,
|
||||||
|
contact: ContactId,
|
||||||
|
text: &str,
|
||||||
|
reply_to: Option<MessageRef>,
|
||||||
|
) -> Result<Outgoing, ClientError> {
|
||||||
if text.len() > MAX_TEXT_BYTES {
|
if text.len() > MAX_TEXT_BYTES {
|
||||||
return Err(ClientError::TooLong);
|
return Err(ClientError::TooLong);
|
||||||
}
|
}
|
||||||
let c = self
|
let index = self.index_of(contact)?;
|
||||||
.contacts
|
if let Some(r) = &reply_to {
|
||||||
.iter_mut()
|
if !self.names_a_message(index, r) {
|
||||||
.find(|c| c.id == contact)
|
return Err(ClientError::BadReference);
|
||||||
.ok_or(ClientError::UnknownContact)?;
|
}
|
||||||
|
}
|
||||||
|
let c = &mut self.contacts[index];
|
||||||
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||||||
|
let seq = c.sent_seq + 1;
|
||||||
let blob = Self::seal(
|
let blob = Self::seal(
|
||||||
&self.provider,
|
&self.provider,
|
||||||
&self.signer,
|
&self.signer,
|
||||||
&mut c.group,
|
&mut c.group,
|
||||||
&Payload::Text {
|
&Payload::Text {
|
||||||
body: text.to_string(),
|
body: text.to_string(),
|
||||||
|
seq,
|
||||||
|
reply_to,
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
Ok(Outgoing {
|
c.sent_seq = seq;
|
||||||
to,
|
Ok(Outgoing::post(to, post, blob))
|
||||||
post,
|
|
||||||
blob: Bytes(blob),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Posts one blob to the relay.
|
/// Our reaction to a message in this conversation: `Some(emoji)` sets it (replacing our
|
||||||
|
/// earlier one), `None` removes it. No network: save the snapshot, then deliver.
|
||||||
|
pub fn react(
|
||||||
|
&mut self,
|
||||||
|
contact: ContactId,
|
||||||
|
to: MessageRef,
|
||||||
|
emoji: Option<&str>,
|
||||||
|
) -> Result<Outgoing, ClientError> {
|
||||||
|
if let Some(e) = emoji {
|
||||||
|
if e.len() > MAX_EMOJI_BYTES {
|
||||||
|
return Err(ClientError::TooLong);
|
||||||
|
}
|
||||||
|
if !emoji_ok(e) {
|
||||||
|
return Err(ClientError::BadReference);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let index = self.index_of(contact)?;
|
||||||
|
if !self.names_a_message(index, &to) {
|
||||||
|
return Err(ClientError::BadReference);
|
||||||
|
}
|
||||||
|
let c = &mut self.contacts[index];
|
||||||
|
let (out_to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||||||
|
let blob = Self::seal(
|
||||||
|
&self.provider,
|
||||||
|
&self.signer,
|
||||||
|
&mut c.group,
|
||||||
|
&Payload::Reaction {
|
||||||
|
to,
|
||||||
|
emoji: emoji.map(str::to_string),
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
Ok(Outgoing::post(out_to, post, blob))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Our author name: the 16 bytes in our credential. With a `seq` it names our messages.
|
||||||
|
pub fn author(&self) -> Author {
|
||||||
|
author_of(&self.identity).unwrap_or_else(|| Author::from_bytes([0; 16]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The contact's author name, read from the conversation's other MLS member.
|
||||||
|
pub fn contact_author(&self, contact: ContactId) -> Option<Author> {
|
||||||
|
let index = self.index_of(contact).ok()?;
|
||||||
|
self.peer_author(index)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn index_of(&self, contact: ContactId) -> Result<usize, ClientError> {
|
||||||
|
self.contacts
|
||||||
|
.iter()
|
||||||
|
.position(|c| c.id == contact)
|
||||||
|
.ok_or(ClientError::UnknownContact)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn peer_author(&self, index: usize) -> Option<Author> {
|
||||||
|
self.contacts[index]
|
||||||
|
.group
|
||||||
|
.members()
|
||||||
|
.filter_map(|m| BasicCredential::try_from(m.credential).ok())
|
||||||
|
.map(|c| c.identity().to_vec())
|
||||||
|
.find(|id| id != &self.identity)
|
||||||
|
.and_then(|id| author_of(&id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `r` names a message that exists in this conversation: ours up to our last `seq`,
|
||||||
|
/// theirs up to the highest `seq` received from them.
|
||||||
|
fn names_a_message(&self, index: usize, r: &MessageRef) -> bool {
|
||||||
|
let c = &self.contacts[index];
|
||||||
|
if r.seq == 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if r.author.as_bytes()[..] == self.identity[..] {
|
||||||
|
r.seq <= c.sent_seq
|
||||||
|
} else if self.peer_author(index) == Some(r.author) {
|
||||||
|
r.seq <= c.received_seq
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `seq` of our last text to a contact: right after [`Client::compose`], the one it made.
|
||||||
|
pub fn sent_seq(&self, contact: ContactId) -> Option<u64> {
|
||||||
|
self.contacts
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.id == contact)
|
||||||
|
.map(|c| c.sent_seq)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Performs one operation on the relay: posts a blob, or rotates a post token.
|
||||||
pub fn deliver(&self, out: &Outgoing) -> Result<(), ClientError> {
|
pub fn deliver(&self, out: &Outgoing) -> Result<(), ClientError> {
|
||||||
self.transport.post(&out.to, &out.post, &out.blob.0)?;
|
match &out.0 {
|
||||||
|
Op::Post { to, post, blob } => self.transport.post(to, post, &blob.0)?,
|
||||||
|
Op::Rotate {
|
||||||
|
mailbox,
|
||||||
|
fetch,
|
||||||
|
post_token_hash,
|
||||||
|
} => self
|
||||||
|
.transport
|
||||||
|
.rotate_post_token(mailbox, fetch, post_token_hash)?,
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A post waiting in an app's outbox, with the contact's current post token: after an
|
||||||
|
/// unblock on their side, the token it was sealed with is refused. The blob is unchanged.
|
||||||
|
pub fn readdress(&self, out: &Outgoing) -> Outgoing {
|
||||||
|
if let Op::Post { to, blob, .. } = &out.0 {
|
||||||
|
if let Some((_, post)) = self
|
||||||
|
.contacts
|
||||||
|
.iter()
|
||||||
|
.filter_map(|c| c.outbox)
|
||||||
|
.find(|(mailbox, _)| mailbox == to)
|
||||||
|
{
|
||||||
|
return Outgoing::post(*to, post, blob.0.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The mailboxes this client fetches: each contact's inbox (a blocked contact's too, which
|
||||||
|
/// nothing reaches) and each open invite's welcome mailbox. For wake-ups (`PROTOCOL.md` §6): an
|
||||||
|
/// app registers one push endpoint per mailbox, so the relay cannot link them by endpoint.
|
||||||
|
pub fn inboxes(&self) -> Vec<MailboxId> {
|
||||||
|
self.contacts
|
||||||
|
.iter()
|
||||||
|
.filter_map(|c| c.inbox.map(|m| m.id))
|
||||||
|
.chain(self.welcome_boxes.iter().map(|w| w.mailbox.id))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the relay wakes us when this mailbox receives (`Some`), or nowhere (`None`). Only a
|
||||||
|
/// mailbox from [`Client::inboxes`]; another is [`ClientError::UnknownContact`].
|
||||||
|
pub fn set_push(
|
||||||
|
&self,
|
||||||
|
mailbox: &MailboxId,
|
||||||
|
endpoint: Option<&PushEndpoint>,
|
||||||
|
) -> Result<(), ClientError> {
|
||||||
|
let fetch = self
|
||||||
|
.contacts
|
||||||
|
.iter()
|
||||||
|
.filter_map(|c| c.inbox)
|
||||||
|
.chain(self.welcome_boxes.iter().map(|w| w.mailbox))
|
||||||
|
.find(|m| m.id == *mailbox)
|
||||||
|
.ok_or(ClientError::UnknownContact)?
|
||||||
|
.fetch;
|
||||||
|
Ok(self.transport.set_push(mailbox, &fetch, endpoint)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Blocks a contact, staged: they are marked, and their way into our mailbox is closed by a
|
||||||
|
/// rotate to the hash of a fresh token that nobody gets. Nothing is sent to them. Save the
|
||||||
|
/// snapshot, then deliver the result.
|
||||||
|
pub fn block(&mut self, contact: ContactId) -> Result<Outgoing, ClientError> {
|
||||||
|
let token = Token::from_bytes(self.random()?);
|
||||||
|
let c = self
|
||||||
|
.contacts
|
||||||
|
.iter_mut()
|
||||||
|
.find(|c| c.id == contact)
|
||||||
|
.ok_or(ClientError::UnknownContact)?;
|
||||||
|
let inbox = c.inbox.ok_or(ClientError::UnknownContact)?;
|
||||||
|
c.blocked = true;
|
||||||
|
Ok(Outgoing(Op::Rotate {
|
||||||
|
mailbox: inbox.id,
|
||||||
|
fetch: inbox.fetch,
|
||||||
|
post_token_hash: token.hash(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unblocks, staged: a rotate to a new token, then that token to them inside MLS.
|
||||||
|
pub fn unblock(&mut self, contact: ContactId) -> Result<Vec<Outgoing>, ClientError> {
|
||||||
|
let token = Token::from_bytes(self.random()?);
|
||||||
|
let c = self
|
||||||
|
.contacts
|
||||||
|
.iter_mut()
|
||||||
|
.find(|c| c.id == contact)
|
||||||
|
.ok_or(ClientError::UnknownContact)?;
|
||||||
|
let inbox = c.inbox.ok_or(ClientError::UnknownContact)?;
|
||||||
|
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||||||
|
let blob = Self::seal(
|
||||||
|
&self.provider,
|
||||||
|
&self.signer,
|
||||||
|
&mut c.group,
|
||||||
|
&Payload::Inbox { post_token: token },
|
||||||
|
)?;
|
||||||
|
c.blocked = false;
|
||||||
|
Ok(vec![
|
||||||
|
Outgoing(Op::Rotate {
|
||||||
|
mailbox: inbox.id,
|
||||||
|
fetch: inbox.fetch,
|
||||||
|
post_token_hash: token.hash(),
|
||||||
|
}),
|
||||||
|
Outgoing::post(to, post, blob),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_blocked(&self, contact: ContactId) -> bool {
|
||||||
|
self.contacts.iter().any(|c| c.id == contact && c.blocked)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Receipts on or off: off, we send none and report none of theirs. Save the snapshot after.
|
||||||
|
pub fn set_receipts(&mut self, on: bool) {
|
||||||
|
self.receipts = on;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn receipts(&self) -> bool {
|
||||||
|
self.receipts
|
||||||
|
}
|
||||||
|
|
||||||
/// [`Client::compose`] and [`Client::deliver`] at once, for use without persistence.
|
/// [`Client::compose`] and [`Client::deliver`] at once, for use without persistence.
|
||||||
pub fn send(&mut self, contact: ContactId, text: &str) -> Result<(), ClientError> {
|
pub fn send(&mut self, contact: ContactId, text: &str) -> Result<(), ClientError> {
|
||||||
let out = self.compose(contact, text)?;
|
let out = self.compose(contact, text)?;
|
||||||
@@ -473,6 +782,11 @@ impl<T: Transport> Client<T> {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter_map(|c| c.inbox.map(|m| (m, None))),
|
.filter_map(|c| c.inbox.map(|m| (m, None))),
|
||||||
);
|
);
|
||||||
|
let before: Vec<(ContactId, u64)> = self
|
||||||
|
.contacts
|
||||||
|
.iter()
|
||||||
|
.map(|c| (c.id, c.received_seq))
|
||||||
|
.collect();
|
||||||
for (mailbox, via) in sources {
|
for (mailbox, via) in sources {
|
||||||
let blobs = match self.transport.fetch(&mailbox.id, &mailbox.fetch) {
|
let blobs = match self.transport.fetch(&mailbox.id, &mailbox.fetch) {
|
||||||
Ok(blobs) => blobs,
|
Ok(blobs) => blobs,
|
||||||
@@ -516,16 +830,31 @@ impl<T: Transport> Client<T> {
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
c.inbox = Some(inbox);
|
c.inbox = Some(inbox);
|
||||||
got.outgoing.push(Outgoing {
|
got.outgoing.push(Outgoing::post(to, post, blob));
|
||||||
to,
|
|
||||||
post,
|
|
||||||
blob: Bytes(blob),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
Err(ClientError::Transport(e)) => got.interrupted = Some(e),
|
Err(ClientError::Transport(e)) => got.interrupted = Some(e),
|
||||||
Err(_) => continue,
|
Err(_) => continue,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Receipts, for every contact whose texts arrived now. Delivered by `finish`, so only
|
||||||
|
// after the app has saved the texts.
|
||||||
|
if self.receipts {
|
||||||
|
for (id, was) in before {
|
||||||
|
let Some(c) = self.contacts.iter_mut().find(|c| c.id == id) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some((to, post)) = c.outbox else { continue };
|
||||||
|
if c.received_seq == was || c.blocked {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let receipt = Payload::Receipt {
|
||||||
|
upto: c.received_seq,
|
||||||
|
};
|
||||||
|
if let Ok(blob) = Self::seal(&self.provider, &self.signer, &mut c.group, &receipt) {
|
||||||
|
got.outgoing.push(Outgoing::post(to, post, blob));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(got)
|
Ok(got)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -536,9 +865,16 @@ impl<T: Transport> Client<T> {
|
|||||||
/// is never fetched. Not before: a snapshot saved between `receive` and `finish` must still
|
/// is never fetched. Not before: a snapshot saved between `receive` and `finish` must still
|
||||||
/// know the mailbox, so that a restored client fetches its blobs again and acknowledges them.
|
/// know the mailbox, so that a restored client fetches its blobs again and acknowledges them.
|
||||||
/// Save the snapshot again after `finish`.
|
/// Save the snapshot again after `finish`.
|
||||||
|
///
|
||||||
|
/// A post the relay refuses with 404 is skipped: that mailbox's token is gone (we may be
|
||||||
|
/// blocked), and trying again cannot help. Without the skip, one refused receipt would keep
|
||||||
|
/// everything fetched from being acknowledged, for ever.
|
||||||
pub fn finish(&mut self, received: &Received) -> Result<(), ClientError> {
|
pub fn finish(&mut self, received: &Received) -> Result<(), ClientError> {
|
||||||
for out in &received.outgoing {
|
for out in &received.outgoing {
|
||||||
self.deliver(out)?;
|
match self.deliver(out) {
|
||||||
|
Ok(()) | Err(ClientError::Transport(TransportError::NotFound)) => {}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for ack in &received.acks {
|
for ack in &received.acks {
|
||||||
self.transport
|
self.transport
|
||||||
@@ -607,9 +943,10 @@ impl<T: Transport> Client<T> {
|
|||||||
else {
|
else {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
let payload: Payload =
|
match parse_payload(&app.into_bytes())? {
|
||||||
serde_json::from_slice(&app.into_bytes()).map_err(|_| ClientError::Mls)?;
|
Parsed::Known(payload) => self.receive_payload(index, payload),
|
||||||
self.receive_payload(index, payload)
|
Parsed::Unknown { seq } => self.receive_unknown(index, seq),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ => Err(ClientError::Mls),
|
_ => Err(ClientError::Mls),
|
||||||
}
|
}
|
||||||
@@ -638,21 +975,122 @@ impl<T: Transport> Client<T> {
|
|||||||
via: c.via,
|
via: c.via,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
Payload::Text { body } => {
|
Payload::Text {
|
||||||
|
body,
|
||||||
|
seq,
|
||||||
|
reply_to,
|
||||||
|
} => {
|
||||||
let c = &self.contacts[index];
|
let c = &self.contacts[index];
|
||||||
if c.name.is_none() {
|
if c.name.is_none() {
|
||||||
// Text before hello: not from a conversation that has been set up.
|
// Text before hello: not from a conversation that has been set up.
|
||||||
return Err(ClientError::Mls);
|
return Err(ClientError::Mls);
|
||||||
}
|
}
|
||||||
|
if c.blocked {
|
||||||
|
// Posted before the block, or fetched after it: dropped, never shown.
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
// Checked before this text counts, so a text cannot answer itself. The words are
|
||||||
|
// real even when the reference is not: the text stays, the reference goes.
|
||||||
|
let reply_to = reply_to.filter(|r| self.names_a_message(index, r));
|
||||||
|
let c = &mut self.contacts[index];
|
||||||
|
c.received_seq = c.received_seq.max(seq);
|
||||||
Ok(Some(Event::Message {
|
Ok(Some(Event::Message {
|
||||||
contact: c.id,
|
contact: c.id,
|
||||||
text: body,
|
text: body,
|
||||||
|
seq,
|
||||||
|
reply_to,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
Payload::Reaction { to, emoji } => {
|
||||||
|
let c = &self.contacts[index];
|
||||||
|
if c.name.is_none() {
|
||||||
|
return Err(ClientError::Mls);
|
||||||
|
}
|
||||||
|
let emoji_bad = emoji
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|e| e.len() > MAX_EMOJI_BYTES || !emoji_ok(e));
|
||||||
|
if c.blocked || emoji_bad || !self.names_a_message(index, &to) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
Ok(Some(Event::Reaction {
|
||||||
|
contact: c.id,
|
||||||
|
to,
|
||||||
|
emoji,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Payload::Receipt { upto } => {
|
||||||
|
let c = &self.contacts[index];
|
||||||
|
if !self.receipts || c.name.is_none() || c.blocked {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
// A receipt cannot mark what was never sent.
|
||||||
|
Ok(Some(Event::Delivered {
|
||||||
|
contact: c.id,
|
||||||
|
upto: upto.min(c.sent_seq),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Payload::Inbox { post_token } => {
|
||||||
|
let c = &mut self.contacts[index];
|
||||||
|
// Only the token changes: the mailbox stays the one their hello named.
|
||||||
|
let Some((mailbox, _)) = c.outbox else {
|
||||||
|
return Err(ClientError::Mls);
|
||||||
|
};
|
||||||
|
c.outbox = Some((mailbox, post_token));
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<T: Transport> Client<T> {
|
||||||
|
/// A payload of a kind this client does not know, with a `seq`: a newer app's message.
|
||||||
|
fn receive_unknown(&mut self, index: usize, seq: u64) -> Result<Option<Event>, ClientError> {
|
||||||
|
let c = &mut self.contacts[index];
|
||||||
|
if c.name.is_none() {
|
||||||
|
return Err(ClientError::Mls);
|
||||||
|
}
|
||||||
|
if c.blocked {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
c.received_seq = c.received_seq.max(seq);
|
||||||
|
Ok(Some(Event::Unsupported { contact: c.id, seq }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Parsed {
|
||||||
|
Known(Payload),
|
||||||
|
Unknown { seq: u64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A payload of a known kind must parse exactly (`deny_unknown_fields`); one of an unknown kind is
|
||||||
|
/// `Unknown` when it carries a `seq` of at least 1, and refused otherwise.
|
||||||
|
fn parse_payload(bytes: &[u8]) -> Result<Parsed, ClientError> {
|
||||||
|
let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| ClientError::Mls)?;
|
||||||
|
let kind = value
|
||||||
|
.get("kind")
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.ok_or(ClientError::Mls)?;
|
||||||
|
if KNOWN_KINDS.contains(&kind) {
|
||||||
|
return serde_json::from_value(value)
|
||||||
|
.map(Parsed::Known)
|
||||||
|
.map_err(|_| ClientError::Mls);
|
||||||
|
}
|
||||||
|
match value.get("seq").and_then(serde_json::Value::as_u64) {
|
||||||
|
Some(seq) if seq >= 1 => Ok(Parsed::Unknown { seq }),
|
||||||
|
_ => Err(ClientError::Mls),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An emoji as the wire allows it: not empty, no control characters (the length is checked apart,
|
||||||
|
/// as [`ClientError::TooLong`]).
|
||||||
|
fn emoji_ok(emoji: &str) -> bool {
|
||||||
|
!emoji.is_empty() && !emoji.chars().any(char::is_control)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn author_of(identity: &[u8]) -> Option<Author> {
|
||||||
|
<[u8; 16]>::try_from(identity).ok().map(Author::from_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
fn credential_with_key(identity: &[u8], signer: &SignatureKeyPair) -> CredentialWithKey {
|
fn credential_with_key(identity: &[u8], signer: &SignatureKeyPair) -> CredentialWithKey {
|
||||||
CredentialWithKey {
|
CredentialWithKey {
|
||||||
credential: BasicCredential::new(identity.to_vec()).into(),
|
credential: BasicCredential::new(identity.to_vec()).into(),
|
||||||
@@ -688,4 +1126,277 @@ mod tests {
|
|||||||
assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before);
|
assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before);
|
||||||
assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan"));
|
assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `inbox` (unblock) changes only the token for the mailbox their hello named.
|
||||||
|
#[test]
|
||||||
|
fn an_inbox_payload_changes_the_token_not_the_mailbox() {
|
||||||
|
let relay = MemoryTransport::default();
|
||||||
|
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||||
|
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||||
|
let invite = eva.create_invite().expect("invite");
|
||||||
|
jan.accept_invite(&invite).expect("accept");
|
||||||
|
eva.poll().expect("poll");
|
||||||
|
let (mailbox, before) = eva.contacts[0].outbox.expect("outbox");
|
||||||
|
let fresh = Token::from_bytes([5; 32]);
|
||||||
|
let inbox = Payload::Inbox { post_token: fresh };
|
||||||
|
assert_eq!(eva.receive_payload(0, inbox), Ok(None));
|
||||||
|
let (still, after) = eva.contacts[0].outbox.expect("outbox");
|
||||||
|
assert_eq!(still, mailbox);
|
||||||
|
assert_ne!(after.hash(), before.hash());
|
||||||
|
assert_eq!(after.hash(), fresh.hash());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A receipt cannot mark texts that were never sent.
|
||||||
|
#[test]
|
||||||
|
fn a_receipt_is_capped_at_what_was_sent() {
|
||||||
|
let relay = MemoryTransport::default();
|
||||||
|
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||||
|
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||||
|
let invite = eva.create_invite().expect("invite");
|
||||||
|
jan.accept_invite(&invite).expect("accept");
|
||||||
|
eva.poll().expect("poll");
|
||||||
|
eva.send(eva.contacts[0].id, "jedna").expect("send");
|
||||||
|
let got = eva.receive_payload(0, Payload::Receipt { upto: 99 });
|
||||||
|
assert_eq!(
|
||||||
|
got,
|
||||||
|
Ok(Some(Event::Delivered {
|
||||||
|
contact: eva.contacts[0].id,
|
||||||
|
upto: 1
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reactions and replies (`.agents/features/reactions-replies.md` §2.2).
|
||||||
|
fn paired() -> (Client<MemoryTransport>, Client<MemoryTransport>) {
|
||||||
|
let relay = MemoryTransport::default();
|
||||||
|
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");
|
||||||
|
jan.accept_invite(&invite).expect("accept");
|
||||||
|
eva.poll().expect("poll");
|
||||||
|
jan.poll().expect("poll");
|
||||||
|
(eva, jan)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seals any JSON for the first contact, as a newer or misbehaving client could.
|
||||||
|
fn seal_raw(c: &mut Client<MemoryTransport>, json: &str) -> Outgoing {
|
||||||
|
let contact = &mut c.contacts[0];
|
||||||
|
let (to, post) = contact.outbox.expect("outbox");
|
||||||
|
let blob = contact
|
||||||
|
.group
|
||||||
|
.create_message(&c.provider, &c.signer, json.as_bytes())
|
||||||
|
.expect("seal")
|
||||||
|
.tls_serialize_detached()
|
||||||
|
.expect("bytes");
|
||||||
|
Outgoing::post(to, post, blob)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_text_without_a_reply_is_the_old_json_and_a_removal_has_no_emoji_key() {
|
||||||
|
let text = Payload::Text {
|
||||||
|
body: "x".into(),
|
||||||
|
seq: 1,
|
||||||
|
reply_to: None,
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_string(&text).expect("json"),
|
||||||
|
r#"{"kind":"text","body":"x","seq":1}"#
|
||||||
|
);
|
||||||
|
let to = MessageRef {
|
||||||
|
author: Author::from_bytes([0; 16]),
|
||||||
|
seq: 3,
|
||||||
|
};
|
||||||
|
let removal = Payload::Reaction { to, emoji: None };
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_string(&removal).expect("json"),
|
||||||
|
r#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":3}}"#
|
||||||
|
);
|
||||||
|
let reply = Payload::Text {
|
||||||
|
body: "y".into(),
|
||||||
|
seq: 2,
|
||||||
|
reply_to: Some(to),
|
||||||
|
};
|
||||||
|
assert!(serde_json::to_string(&reply)
|
||||||
|
.expect("json")
|
||||||
|
.contains(r#""replyTo":{"author":"#));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unknown_kind_needs_a_seq_and_a_known_kind_must_parse_exactly() {
|
||||||
|
assert!(matches!(
|
||||||
|
parse_payload(br#"{"kind":"poll","seq":4,"question":"?"}"#),
|
||||||
|
Ok(Parsed::Unknown { seq: 4 })
|
||||||
|
));
|
||||||
|
for bad in [
|
||||||
|
&br#"{"kind":"poll","question":"?"}"#[..],
|
||||||
|
br#"{"kind":"poll","seq":0}"#,
|
||||||
|
br#"{"kind":"poll","seq":-1}"#,
|
||||||
|
br#"{"kind":"poll","seq":"4"}"#,
|
||||||
|
br#"{"seq":4}"#,
|
||||||
|
br#"{"kind":"text","body":"x","seq":1,"mentions":[]}"#,
|
||||||
|
br#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"emoji":"x","extra":1}"#,
|
||||||
|
br#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1,"x":1}}"#,
|
||||||
|
b"not json",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
parse_payload(bad).is_err(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(bad)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_reaction_that_names_no_message_here_or_carries_a_bad_emoji_is_dropped() {
|
||||||
|
let (mut eva, mut jan) = paired();
|
||||||
|
eva.send(eva.contacts[0].id, "jedna").expect("send");
|
||||||
|
jan.poll().expect("poll");
|
||||||
|
let first = MessageRef {
|
||||||
|
author: eva.author(),
|
||||||
|
seq: 1,
|
||||||
|
};
|
||||||
|
let stranger = Author::from_bytes([7; 16]);
|
||||||
|
let reaction = |to: MessageRef, emoji: Option<&str>| Payload::Reaction {
|
||||||
|
to,
|
||||||
|
emoji: emoji.map(str::to_string),
|
||||||
|
};
|
||||||
|
let long = "😀".repeat(9);
|
||||||
|
for payload in [
|
||||||
|
reaction(MessageRef { seq: 2, ..first }, Some("👍")),
|
||||||
|
reaction(MessageRef { seq: 0, ..first }, Some("👍")),
|
||||||
|
reaction(
|
||||||
|
MessageRef {
|
||||||
|
author: stranger,
|
||||||
|
seq: 1,
|
||||||
|
},
|
||||||
|
Some("👍"),
|
||||||
|
),
|
||||||
|
// Eva's view: a reaction from Jan to Jan's message 1, which never came.
|
||||||
|
reaction(
|
||||||
|
MessageRef {
|
||||||
|
author: jan.author(),
|
||||||
|
seq: 1,
|
||||||
|
},
|
||||||
|
Some("👍"),
|
||||||
|
),
|
||||||
|
reaction(first, Some("")),
|
||||||
|
reaction(first, Some("a\u{0}")),
|
||||||
|
reaction(first, Some(&long)),
|
||||||
|
] {
|
||||||
|
assert_eq!(eva.receive_payload(0, payload), Ok(None));
|
||||||
|
}
|
||||||
|
assert!(matches!(
|
||||||
|
eva.receive_payload(0, reaction(first, Some("👍"))),
|
||||||
|
Ok(Some(Event::Reaction { .. }))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_text_whose_reference_names_nothing_here_is_shown_without_it() {
|
||||||
|
let (mut eva, _jan) = paired();
|
||||||
|
let text = |seq, reply_to| Payload::Text {
|
||||||
|
body: "words".into(),
|
||||||
|
seq,
|
||||||
|
reply_to,
|
||||||
|
};
|
||||||
|
// Their first text answering their own first text: itself.
|
||||||
|
let itself = MessageRef {
|
||||||
|
author: eva.peer_author(0).expect("author"),
|
||||||
|
seq: 1,
|
||||||
|
};
|
||||||
|
let got = eva.receive_payload(0, text(1, Some(itself)));
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
&got,
|
||||||
|
Ok(Some(Event::Message {
|
||||||
|
reply_to: None,
|
||||||
|
seq: 1,
|
||||||
|
..
|
||||||
|
}))
|
||||||
|
),
|
||||||
|
"{got:?}"
|
||||||
|
);
|
||||||
|
// Now it exists: their second text may answer it.
|
||||||
|
let got = eva.receive_payload(0, text(2, Some(itself)));
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
&got,
|
||||||
|
Ok(Some(Event::Message {
|
||||||
|
reply_to: Some(_),
|
||||||
|
..
|
||||||
|
}))
|
||||||
|
),
|
||||||
|
"{got:?}"
|
||||||
|
);
|
||||||
|
let ours = MessageRef {
|
||||||
|
author: eva.author(),
|
||||||
|
seq: 1,
|
||||||
|
};
|
||||||
|
let got = eva.receive_payload(0, text(3, Some(ours)));
|
||||||
|
assert!(
|
||||||
|
matches!(&got, Ok(Some(Event::Message { reply_to: None, text, .. })) if text == "words"),
|
||||||
|
"we sent nothing yet: {got:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_newer_apps_message_is_unsupported_and_counts_for_receipts() {
|
||||||
|
let (mut eva, mut jan) = paired();
|
||||||
|
eva.set_receipts(true);
|
||||||
|
let out = seal_raw(&mut jan, r#"{"kind":"poll","seq":1,"question":"Pivo?"}"#);
|
||||||
|
jan.deliver(&out).expect("deliver");
|
||||||
|
let out = seal_raw(&mut jan, r#"{"kind":"poll","question":"no seq"}"#);
|
||||||
|
jan.deliver(&out).expect("deliver");
|
||||||
|
let got = eva.receive().expect("receive");
|
||||||
|
assert_eq!(
|
||||||
|
got.events,
|
||||||
|
vec![Event::Unsupported {
|
||||||
|
contact: eva.contacts[0].id,
|
||||||
|
seq: 1
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
assert_eq!(eva.contacts[0].received_seq, 1);
|
||||||
|
assert_eq!(got.outgoing.len(), 1, "a receipt for it");
|
||||||
|
// From a blocked contact: dropped.
|
||||||
|
eva.contacts[0].blocked = true;
|
||||||
|
assert_eq!(eva.receive_unknown(0, 2), Ok(None));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every kind this client sends is in `KNOWN_KINDS`: a variant left out would arrive as
|
||||||
|
/// *Unsupported* at a client of the same version.
|
||||||
|
#[test]
|
||||||
|
fn every_payload_kind_is_known() {
|
||||||
|
let to = MessageRef {
|
||||||
|
author: Author::from_bytes([1; 16]),
|
||||||
|
seq: 1,
|
||||||
|
};
|
||||||
|
let all = [
|
||||||
|
Payload::Hello {
|
||||||
|
mailbox: MailboxId::from_bytes([0; 16]),
|
||||||
|
post_token: Token::from_bytes([0; 32]),
|
||||||
|
name: "x".into(),
|
||||||
|
},
|
||||||
|
Payload::Text {
|
||||||
|
body: "x".into(),
|
||||||
|
seq: 1,
|
||||||
|
reply_to: None,
|
||||||
|
},
|
||||||
|
Payload::Receipt { upto: 1 },
|
||||||
|
Payload::Inbox {
|
||||||
|
post_token: Token::from_bytes([0; 32]),
|
||||||
|
},
|
||||||
|
Payload::Reaction { to, emoji: None },
|
||||||
|
];
|
||||||
|
assert_eq!(all.len(), KNOWN_KINDS.len());
|
||||||
|
for payload in all {
|
||||||
|
let json = serde_json::to_vec(&payload).expect("json");
|
||||||
|
assert!(
|
||||||
|
matches!(parse_payload(&json), Ok(Parsed::Known(p)) if p == payload),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&json)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,6 +47,17 @@ struct ContactState {
|
|||||||
inbox: Option<Mailbox>,
|
inbox: Option<Mailbox>,
|
||||||
outbox: Option<(MailboxId, Token)>,
|
outbox: Option<(MailboxId, Token)>,
|
||||||
via: Option<InviteId>,
|
via: Option<InviteId>,
|
||||||
|
// F24; absent in older snapshots.
|
||||||
|
#[serde(default)]
|
||||||
|
blocked: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
sent_seq: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
received_seq: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn yes() -> bool {
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
@@ -59,6 +70,8 @@ struct State {
|
|||||||
contacts: Vec<ContactState>,
|
contacts: Vec<ContactState>,
|
||||||
welcome_boxes: Vec<WelcomeBox>,
|
welcome_boxes: Vec<WelcomeBox>,
|
||||||
next_contact: u32,
|
next_contact: u32,
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
receipts: bool,
|
||||||
/// OpenMLS's storage: every key and value, sorted by key so equal states give equal bytes.
|
/// OpenMLS's storage: every key and value, sorted by key so equal states give equal bytes.
|
||||||
storage: Vec<(Bytes, Bytes)>,
|
storage: Vec<(Bytes, Bytes)>,
|
||||||
}
|
}
|
||||||
@@ -91,10 +104,14 @@ impl<T: Transport> Client<T> {
|
|||||||
inbox: c.inbox,
|
inbox: c.inbox,
|
||||||
outbox: c.outbox,
|
outbox: c.outbox,
|
||||||
via: c.via,
|
via: c.via,
|
||||||
|
blocked: c.blocked,
|
||||||
|
sent_seq: c.sent_seq,
|
||||||
|
received_seq: c.received_seq,
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
welcome_boxes: self.welcome_boxes.clone(),
|
welcome_boxes: self.welcome_boxes.clone(),
|
||||||
next_contact: self.next_contact,
|
next_contact: self.next_contact,
|
||||||
|
receipts: self.receipts,
|
||||||
storage,
|
storage,
|
||||||
};
|
};
|
||||||
serde_json::to_vec(&state).map_err(|_| ClientError::State)
|
serde_json::to_vec(&state).map_err(|_| ClientError::State)
|
||||||
@@ -143,6 +160,9 @@ impl<T: Transport> Client<T> {
|
|||||||
inbox: c.inbox,
|
inbox: c.inbox,
|
||||||
outbox: c.outbox,
|
outbox: c.outbox,
|
||||||
via: c.via,
|
via: c.via,
|
||||||
|
blocked: c.blocked,
|
||||||
|
sent_seq: c.sent_seq,
|
||||||
|
received_seq: c.received_seq,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Ok(Client {
|
Ok(Client {
|
||||||
@@ -155,6 +175,7 @@ impl<T: Transport> Client<T> {
|
|||||||
contacts,
|
contacts,
|
||||||
welcome_boxes: state.welcome_boxes,
|
welcome_boxes: state.welcome_boxes,
|
||||||
next_contact: state.next_contact,
|
next_contact: state.next_contact,
|
||||||
|
receipts: state.receipts,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use tabellarius_protocol::{
|
use tabellarius_protocol::{
|
||||||
blob_hash, CreateInvite, CreateMailbox, InviteId, MailboxId, Sha256Hash, Token,
|
blob_hash, CreateInvite, CreateMailbox, InviteId, MailboxId, PushEndpoint, Sha256Hash, Token,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Why the relay said no. Carries nothing of the request.
|
/// Why the relay said no. Carries nothing of the request.
|
||||||
@@ -32,14 +32,30 @@ pub trait Transport {
|
|||||||
hash: &Sha256Hash,
|
hash: &Sha256Hash,
|
||||||
) -> Result<(), TransportError>;
|
) -> Result<(), TransportError>;
|
||||||
fn create_invite(&self, req: &CreateInvite) -> 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.
|
/// The KeyPackage, once.
|
||||||
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError>;
|
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError>;
|
||||||
|
/// Where the relay wakes the mailbox's owner when a blob arrives (`Some`), or nowhere (`None`).
|
||||||
|
/// `PROTOCOL.md` §6, `.agents/features/wake-up.md`.
|
||||||
|
fn set_push(
|
||||||
|
&self,
|
||||||
|
id: &MailboxId,
|
||||||
|
fetch: &Token,
|
||||||
|
endpoint: Option<&PushEndpoint>,
|
||||||
|
) -> Result<(), TransportError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Boxes {
|
struct Boxes {
|
||||||
mailboxes: HashMap<MailboxId, (Sha256Hash, Sha256Hash, Vec<Vec<u8>>)>,
|
mailboxes: HashMap<MailboxId, (Sha256Hash, Sha256Hash, Vec<Vec<u8>>)>,
|
||||||
invites: HashMap<InviteId, (Sha256Hash, Vec<u8>)>,
|
invites: HashMap<InviteId, (Sha256Hash, Vec<u8>)>,
|
||||||
|
push: HashMap<MailboxId, PushEndpoint>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An in-memory relay with the same rules as the real one (no expiry: there is no clock here).
|
/// An in-memory relay with the same rules as the real one (no expiry: there is no clock here).
|
||||||
@@ -61,7 +77,12 @@ impl MemoryTransport {
|
|||||||
.sum()
|
.sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every byte the relay holds, for privacy tests: ids, hashes, blobs and KeyPackages.
|
/// The push endpoint a mailbox holds, if any.
|
||||||
|
pub fn push_endpoint(&self, id: &MailboxId) -> Option<String> {
|
||||||
|
self.boxes().push.get(id).map(|e| e.as_str().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every byte the relay holds, for privacy tests: ids, hashes, blobs, KeyPackages, endpoints.
|
||||||
pub fn everything_stored(&self) -> Vec<u8> {
|
pub fn everything_stored(&self) -> Vec<u8> {
|
||||||
let b = self.boxes();
|
let b = self.boxes();
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
@@ -76,6 +97,10 @@ impl MemoryTransport {
|
|||||||
out.extend_from_slice(hash.as_bytes());
|
out.extend_from_slice(hash.as_bytes());
|
||||||
out.extend_from_slice(kp);
|
out.extend_from_slice(kp);
|
||||||
}
|
}
|
||||||
|
for (id, endpoint) in &b.push {
|
||||||
|
out.extend_from_slice(id.as_bytes());
|
||||||
|
out.extend_from_slice(endpoint.as_str().as_bytes());
|
||||||
|
}
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,6 +154,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> {
|
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> {
|
||||||
let mut b = self.boxes();
|
let mut b = self.boxes();
|
||||||
if b.invites.contains_key(&req.id) {
|
if b.invites.contains_key(&req.id) {
|
||||||
@@ -150,4 +190,22 @@ impl Transport for MemoryTransport {
|
|||||||
_ => Err(TransportError::NotFound),
|
_ => 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(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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());
|
||||||
|
}
|
||||||
@@ -19,6 +19,9 @@ fn pair(
|
|||||||
) {
|
) {
|
||||||
let mut eva = Client::new("Eva Nováková", relay.clone()).expect("eva");
|
let mut eva = Client::new("Eva Nováková", relay.clone()).expect("eva");
|
||||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
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 invite = eva.create_invite().expect("invite");
|
||||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||||
let eva_events = eva.poll().expect("eva polls");
|
let eva_events = eva.poll().expect("eva polls");
|
||||||
@@ -56,11 +59,15 @@ fn two_people_pair_through_an_invite_and_talk_both_ways() {
|
|||||||
vec![
|
vec![
|
||||||
Event::Message {
|
Event::Message {
|
||||||
contact: jan_side,
|
contact: jan_side,
|
||||||
text: "Ahoj Jane, pivo ve čtvrtek?".into()
|
text: "Ahoj Jane, pivo ve čtvrtek?".into(),
|
||||||
|
seq: 1,
|
||||||
|
reply_to: None,
|
||||||
},
|
},
|
||||||
Event::Message {
|
Event::Message {
|
||||||
contact: jan_side,
|
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"),
|
eva.poll().expect("poll"),
|
||||||
vec![Event::Message {
|
vec![Event::Message {
|
||||||
contact: eva_side,
|
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
|
// 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"),
|
eva.poll().expect("poll"),
|
||||||
vec![Event::Message {
|
vec![Event::Message {
|
||||||
contact: eva_side,
|
contact: eva_side,
|
||||||
text: "still here".into()
|
text: "still here".into(),
|
||||||
|
seq: 1,
|
||||||
|
reply_to: None,
|
||||||
}]
|
}]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -98,6 +98,20 @@ impl Transport for Http {
|
|||||||
self.call("DELETE", &path, Some(fetch), &[], false)
|
self.call("DELETE", &path, Some(fetch), &[], false)
|
||||||
.map(|_| ())
|
.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> {
|
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> {
|
||||||
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
|
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
|
||||||
self.call("POST", "/v0/invites", None, &body, true)
|
self.call("POST", "/v0/invites", None, &body, true)
|
||||||
@@ -115,13 +129,32 @@ impl Transport for Http {
|
|||||||
serde_json::from_slice(&body).map_err(|_| TransportError::Failed)?;
|
serde_json::from_slice(&body).map_err(|_| TransportError::Failed)?;
|
||||||
Ok(claimed.key_package.bytes().to_vec())
|
Ok(claimed.key_package.bytes().to_vec())
|
||||||
}
|
}
|
||||||
|
fn set_push(
|
||||||
|
&self,
|
||||||
|
id: &MailboxId,
|
||||||
|
fetch: &Token,
|
||||||
|
endpoint: Option<&PushEndpoint>,
|
||||||
|
) -> Result<(), TransportError> {
|
||||||
|
let path = format!("/v0/mailboxes/{}/push", id.to_wire());
|
||||||
|
match endpoint {
|
||||||
|
Some(e) => {
|
||||||
|
let body = serde_json::to_vec(&SetPush {
|
||||||
|
endpoint: e.clone(),
|
||||||
|
})
|
||||||
|
.map_err(|_| TransportError::Failed)?;
|
||||||
|
self.call("PUT", &path, Some(fetch), &body, true)
|
||||||
|
}
|
||||||
|
None => self.call("DELETE", &path, Some(fetch), &[], false),
|
||||||
|
}
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts the real relay on 127.0.0.1:<free port> with its database in `db`.
|
/// Starts the real relay on 127.0.0.1:<free port> with its database in `db`.
|
||||||
fn start_relay(db: &std::path::Path) -> SocketAddr {
|
fn start_relay(db: &std::path::Path) -> SocketAddr {
|
||||||
let store = Arc::new(Store::open(db).expect("store"));
|
let store = Arc::new(Store::open(db).expect("store"));
|
||||||
let clock: Clock = Arc::new(|| 1_794_000_000);
|
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();
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
let rt = tokio::runtime::Builder::new_current_thread()
|
let rt = tokio::runtime::Builder::new_current_thread()
|
||||||
@@ -152,6 +185,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 eva = Client::new("Eva Nováková", relay.clone()).expect("eva");
|
||||||
let mut jan = Client::new("Jan Dvořák", relay.clone()).expect("jan");
|
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");
|
let invite = eva.create_invite().expect("invite");
|
||||||
// While the invite waits, the relay holds Eva's KeyPackage: it must not carry her name.
|
// While the invite waits, the relay holds Eva's KeyPackage: it must not carry her name.
|
||||||
let invited = std::fs::read(&db).expect("db");
|
let invited = std::fs::read(&db).expect("db");
|
||||||
@@ -171,6 +206,14 @@ 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";
|
let canary = "CANARY-relay-test-4b2e-never-in-the-database";
|
||||||
eva.send(eva_side, canary).expect("send");
|
eva.send(eva_side, canary).expect("send");
|
||||||
jan.send(jan_side, &format!("re: {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");
|
||||||
|
|
||||||
// Snapshot the database while both messages wait, before anyone fetches.
|
// Snapshot the database while both messages wait, before anyone fetches.
|
||||||
let waiting = std::fs::read(&db).expect("db");
|
let waiting = std::fs::read(&db).expect("db");
|
||||||
@@ -178,21 +221,33 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
|
|||||||
jan.poll().expect("poll"),
|
jan.poll().expect("poll"),
|
||||||
vec![Event::Message {
|
vec![Event::Message {
|
||||||
contact: jan_side,
|
contact: jan_side,
|
||||||
text: canary.into()
|
text: canary.into(),
|
||||||
|
seq: 1,
|
||||||
|
reply_to: None,
|
||||||
}]
|
}]
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eva.poll().expect("poll"),
|
eva.poll().expect("poll"),
|
||||||
vec![Event::Message {
|
vec![
|
||||||
contact: eva_side,
|
Event::Message {
|
||||||
text: format!("re: {canary}")
|
contact: eva_side,
|
||||||
}]
|
text: format!("re: {canary}"),
|
||||||
|
seq: 1,
|
||||||
|
reply_to: None,
|
||||||
|
},
|
||||||
|
Event::Reaction {
|
||||||
|
contact: eva_side,
|
||||||
|
to: mine,
|
||||||
|
emoji: Some(emoji.into()),
|
||||||
|
},
|
||||||
|
]
|
||||||
);
|
);
|
||||||
let after = std::fs::read(&db).expect("db");
|
let after = std::fs::read(&db).expect("db");
|
||||||
|
|
||||||
for snapshot in [&invited, &waiting, &after] {
|
for snapshot in [&invited, &waiting, &after] {
|
||||||
for (what, needle) in [
|
for (what, needle) in [
|
||||||
("canary", canary.as_bytes()),
|
("canary", canary.as_bytes()),
|
||||||
|
("reaction", emoji.as_bytes()),
|
||||||
("inviter's name", "Eva Nováková".as_bytes()),
|
("inviter's name", "Eva Nováková".as_bytes()),
|
||||||
("invitee's name", "Jan Dvořák".as_bytes()),
|
("invitee's name", "Jan Dvořák".as_bytes()),
|
||||||
("invite secret", invite.secret.as_bytes().as_slice()),
|
("invite secret", invite.secret.as_bytes().as_slice()),
|
||||||
@@ -206,3 +261,37 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
|
|||||||
// The messages were there, as ciphertext: the database grew while they waited.
|
// The messages were there, as ciphertext: the database grew while they waited.
|
||||||
assert!(waiting.len() >= 4096, "the relay stored something");
|
assert!(waiting.len() >= 4096, "the relay stored something");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Wake-up (`.agents/features/wake-up.md` §2.4): an endpoint per mailbox, set and cleared through the
|
||||||
|
// real relay with the mailbox's fetch token.
|
||||||
|
#[test]
|
||||||
|
fn each_inbox_takes_its_own_push_endpoint_through_the_real_relay() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let db = dir.path().join("relay.db");
|
||||||
|
let relay = Http(start_relay(&db));
|
||||||
|
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||||
|
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||||
|
let invite = eva.create_invite().expect("invite");
|
||||||
|
jan.accept_invite(&invite).expect("accept");
|
||||||
|
eva.poll().expect("poll");
|
||||||
|
let (eva_boxes, jan_boxes) = (eva.inboxes(), jan.inboxes());
|
||||||
|
assert_eq!((eva_boxes.len(), jan_boxes.len()), (1, 1));
|
||||||
|
let endpoint = |path: &str| PushEndpoint::parse(&format!("https://push.invalid/{path}"));
|
||||||
|
let a = endpoint("upEvaOnly1").expect("endpoint");
|
||||||
|
eva.set_push(&eva_boxes[0], Some(&a)).expect("set");
|
||||||
|
jan.set_push(
|
||||||
|
&jan_boxes[0],
|
||||||
|
Some(&endpoint("upJanOnly2").expect("endpoint")),
|
||||||
|
)
|
||||||
|
.expect("set");
|
||||||
|
let stored = std::fs::read(&db).expect("db");
|
||||||
|
assert!(contains(&stored, b"upEvaOnly1") && contains(&stored, b"upJanOnly2"));
|
||||||
|
// Not Jan's mailbox: Eva cannot set it.
|
||||||
|
assert_eq!(
|
||||||
|
eva.set_push(&jan_boxes[0], Some(&a)),
|
||||||
|
Err(ClientError::UnknownContact)
|
||||||
|
);
|
||||||
|
eva.set_push(&eva_boxes[0], None).expect("clear");
|
||||||
|
// Nothing is posted after this: a post would make the relay try to wake `push.invalid`, and no
|
||||||
|
// test reaches for the network.
|
||||||
|
}
|
||||||
|
|||||||
+101
-19
@@ -5,10 +5,16 @@ use tabellarius_client::*;
|
|||||||
|
|
||||||
type C = Client<MemoryTransport>;
|
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.
|
/// Pairs Eva (inviter) and Jan through the staged calls, saving nothing. Returns both sides' ids.
|
||||||
fn pair(relay: &MemoryTransport) -> (C, ContactId, C, ContactId) {
|
fn pair(relay: &MemoryTransport) -> (C, ContactId, C, ContactId) {
|
||||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||||
let invite = eva.create_invite().expect("invite");
|
let invite = eva.create_invite().expect("invite");
|
||||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||||
let events = eva.poll().expect("poll");
|
let events = eva.poll().expect("poll");
|
||||||
@@ -39,7 +45,7 @@ fn texts(events: Vec<Event>) -> Vec<String> {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|e| match e {
|
.filter_map(|e| match e {
|
||||||
Event::Message { text, .. } => Some(text),
|
Event::Message { text, .. } => Some(text),
|
||||||
Event::Joined { .. } => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -64,8 +70,8 @@ fn both_sides_restart_mid_conversation_and_keep_talking() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn an_invite_waiting_survives_a_restart() {
|
fn an_invite_waiting_survives_a_restart() {
|
||||||
let relay = MemoryTransport::default();
|
let relay = MemoryTransport::default();
|
||||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||||
let invite = eva.create_invite().expect("invite");
|
let invite = eva.create_invite().expect("invite");
|
||||||
let mut eva = restart(&eva, &relay);
|
let mut eva = restart(&eva, &relay);
|
||||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
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 relay = MemoryTransport::default();
|
||||||
let (eva, eva_side, _jan, _) = pair(&relay);
|
let (eva, eva_side, _jan, _) = pair(&relay);
|
||||||
let mut eva = restart(&eva, &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");
|
let invite = eva.create_invite().expect("invite");
|
||||||
petr.accept_invite(&invite).expect("accept");
|
petr.accept_invite(&invite).expect("accept");
|
||||||
let events = eva.poll().expect("poll");
|
let events = eva.poll().expect("poll");
|
||||||
@@ -99,8 +105,8 @@ fn a_restored_client_gives_a_new_contact_a_new_id() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn the_staged_calls_post_nothing_and_acknowledge_nothing() {
|
fn the_staged_calls_post_nothing_and_acknowledge_nothing() {
|
||||||
let relay = MemoryTransport::default();
|
let relay = MemoryTransport::default();
|
||||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||||
let invite = eva.create_invite().expect("invite");
|
let invite = eva.create_invite().expect("invite");
|
||||||
|
|
||||||
let (jan_side, out) = jan.accept(&invite).expect("accept");
|
let (jan_side, out) = jan.accept(&invite).expect("accept");
|
||||||
@@ -137,8 +143,8 @@ fn the_staged_calls_post_nothing_and_acknowledge_nothing() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn a_crash_between_receive_and_finish_loses_nothing_and_shows_nothing_twice() {
|
fn a_crash_between_receive_and_finish_loses_nothing_and_shows_nothing_twice() {
|
||||||
let relay = MemoryTransport::default();
|
let relay = MemoryTransport::default();
|
||||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||||
let invite = eva.create_invite().expect("invite");
|
let invite = eva.create_invite().expect("invite");
|
||||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||||
// Jan cannot write before Eva's hello gives him her mailbox.
|
// 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"),
|
eva.poll().expect("poll"),
|
||||||
[Event::Message {
|
[Event::Message {
|
||||||
contact,
|
contact,
|
||||||
text: "funguje to".into()
|
text: "funguje to".into(),
|
||||||
|
seq: 1,
|
||||||
|
reply_to: None,
|
||||||
}]
|
}]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -317,6 +325,22 @@ impl Transport for Flaky {
|
|||||||
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
|
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
|
||||||
self.inner.create_invite(r)
|
self.inner.create_invite(r)
|
||||||
}
|
}
|
||||||
|
fn set_push(
|
||||||
|
&self,
|
||||||
|
id: &tabellarius_protocol::MailboxId,
|
||||||
|
fetch: &tabellarius_protocol::Token,
|
||||||
|
endpoint: Option<&tabellarius_protocol::PushEndpoint>,
|
||||||
|
) -> Result<(), TransportError> {
|
||||||
|
self.inner.set_push(id, fetch, endpoint)
|
||||||
|
}
|
||||||
|
fn rotate_post_token(
|
||||||
|
&self,
|
||||||
|
id: &tabellarius_protocol::MailboxId,
|
||||||
|
fetch: &tabellarius_protocol::Token,
|
||||||
|
new_hash: &tabellarius_protocol::Sha256Hash,
|
||||||
|
) -> Result<(), TransportError> {
|
||||||
|
self.inner.rotate_post_token(id, fetch, new_hash)
|
||||||
|
}
|
||||||
fn claim_invite(
|
fn claim_invite(
|
||||||
&self,
|
&self,
|
||||||
id: &tabellarius_protocol::InviteId,
|
id: &tabellarius_protocol::InviteId,
|
||||||
@@ -332,8 +356,8 @@ impl Transport for Flaky {
|
|||||||
fn finish_acknowledges_nothing_when_delivering_fails() {
|
fn finish_acknowledges_nothing_when_delivering_fails() {
|
||||||
let relay = MemoryTransport::default();
|
let relay = MemoryTransport::default();
|
||||||
let flaky = Flaky::new(&relay);
|
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 jan = Client::new("Jan", relay.clone()).expect("jan");
|
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||||
let invite = eva.create_invite().expect("invite");
|
let invite = eva.create_invite().expect("invite");
|
||||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||||
|
|
||||||
@@ -362,10 +386,10 @@ fn finish_acknowledges_nothing_when_delivering_fails() {
|
|||||||
fn a_relay_failing_part_way_returns_what_was_processed() {
|
fn a_relay_failing_part_way_returns_what_was_processed() {
|
||||||
let relay = MemoryTransport::default();
|
let relay = MemoryTransport::default();
|
||||||
let flaky = Flaky::new(&relay);
|
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();
|
let mut friends = Vec::new();
|
||||||
for name in ["Jan", "Petr"] {
|
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 invite = eva.create_invite().expect("invite");
|
||||||
let side = friend.accept_invite(&invite).expect("accept");
|
let side = friend.accept_invite(&invite).expect("accept");
|
||||||
friends.push((friend, side));
|
friends.push((friend, side));
|
||||||
@@ -398,8 +422,8 @@ fn a_relay_failing_part_way_returns_what_was_processed() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn a_used_welcome_mailbox_is_no_longer_fetched() {
|
fn a_used_welcome_mailbox_is_no_longer_fetched() {
|
||||||
let relay = MemoryTransport::default();
|
let relay = MemoryTransport::default();
|
||||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||||
let invite = eva.create_invite().expect("invite");
|
let invite = eva.create_invite().expect("invite");
|
||||||
jan.accept_invite(&invite).expect("accept");
|
jan.accept_invite(&invite).expect("accept");
|
||||||
eva.poll().expect("poll");
|
eva.poll().expect("poll");
|
||||||
@@ -415,8 +439,8 @@ fn a_used_welcome_mailbox_is_no_longer_fetched() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn a_forgotten_invite_is_no_longer_fetched() {
|
fn a_forgotten_invite_is_no_longer_fetched() {
|
||||||
let relay = MemoryTransport::default();
|
let relay = MemoryTransport::default();
|
||||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||||
let invite = eva.create_invite().expect("invite");
|
let invite = eva.create_invite().expect("invite");
|
||||||
eva.forget_invite(&invite.id);
|
eva.forget_invite(&invite.id);
|
||||||
let mut eva = restart(&eva, &relay);
|
let mut eva = restart(&eva, &relay);
|
||||||
@@ -428,3 +452,61 @@ fn a_forgotten_invite_is_no_longer_fetched() {
|
|||||||
"the Welcome and hello wait, never fetched"
|
"the Welcome and hello wait, never fetched"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||||
|
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forgetting a contact leaves no name in the snapshot, stops fetching its mailbox, and survives a
|
||||||
|
/// restart; the other contacts are untouched.
|
||||||
|
#[test]
|
||||||
|
fn a_forgotten_contact_leaves_nothing_behind() {
|
||||||
|
let relay = MemoryTransport::default();
|
||||||
|
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||||
|
let mut petr = quiet(Client::new("Petr Zapomenutý", relay.clone()).expect("petr"));
|
||||||
|
let invite = eva.create_invite().expect("invite");
|
||||||
|
let petr_side = petr.accept_invite(&invite).expect("accept");
|
||||||
|
let Some(Event::Joined {
|
||||||
|
contact: forgotten, ..
|
||||||
|
}) = eva.poll().expect("poll").first().cloned()
|
||||||
|
else {
|
||||||
|
panic!("no join")
|
||||||
|
};
|
||||||
|
petr.poll().expect("poll");
|
||||||
|
let before: serde_json::Value =
|
||||||
|
serde_json::from_slice(&eva.snapshot().expect("snapshot")).expect("json");
|
||||||
|
assert!(before.to_string().contains("Petr Zapomenutý"));
|
||||||
|
let petr_state = before["contacts"][1].clone();
|
||||||
|
|
||||||
|
assert_eq!(eva.forget_contact(forgotten), Ok(true));
|
||||||
|
assert_eq!(eva.forget_contact(forgotten), Ok(false), "only once");
|
||||||
|
let saved = eva.snapshot().expect("snapshot");
|
||||||
|
assert!(
|
||||||
|
!contains(&saved, "Petr Zapomenutý".as_bytes()),
|
||||||
|
"the name is gone"
|
||||||
|
);
|
||||||
|
// The group's MLS state is gone from storage too: putting the contact back is refused.
|
||||||
|
let mut back: serde_json::Value = serde_json::from_slice(&saved).expect("json");
|
||||||
|
back["contacts"]
|
||||||
|
.as_array_mut()
|
||||||
|
.expect("contacts")
|
||||||
|
.push(petr_state);
|
||||||
|
let back = serde_json::to_vec(&back).expect("json");
|
||||||
|
assert!(matches!(
|
||||||
|
C::restore(&back, relay.clone()),
|
||||||
|
Err(ClientError::State)
|
||||||
|
));
|
||||||
|
let mut eva = Client::restore(&saved, relay.clone()).expect("restore");
|
||||||
|
assert_eq!(eva.contact_name(forgotten), None);
|
||||||
|
|
||||||
|
petr.send(petr_side, "slyšíš mě?")
|
||||||
|
.expect("the relay still takes it");
|
||||||
|
jan.send(jan_side, "já ano").expect("send");
|
||||||
|
assert_eq!(texts(eva.poll().expect("poll")), ["já ano"]);
|
||||||
|
assert_eq!(relay.waiting_blobs(), 1, "Petr's message was never fetched");
|
||||||
|
assert_eq!(
|
||||||
|
eva.compose(forgotten, "x"),
|
||||||
|
Err(ClientError::UnknownContact)
|
||||||
|
);
|
||||||
|
eva.send(eva_side, "Jan still works").expect("send");
|
||||||
|
}
|
||||||
|
|||||||
+121
-1
@@ -23,6 +23,12 @@ pub const MAX_BLOBS_PER_FETCH: usize = 100;
|
|||||||
pub const BLOB_TTL_SECS: i64 = 30 * 24 * 3600;
|
pub const BLOB_TTL_SECS: i64 = 30 * 24 * 3600;
|
||||||
/// An unclaimed invite expires after this many seconds (7 days, `PROTOCOL.md` §4).
|
/// An unclaimed invite expires after this many seconds (7 days, `PROTOCOL.md` §4).
|
||||||
pub const INVITE_TTL_SECS: i64 = 7 * 24 * 3600;
|
pub const INVITE_TTL_SECS: i64 = 7 * 24 * 3600;
|
||||||
|
/// The longest push endpoint a mailbox may hold (UnifiedPush's own limit, `wake-up.md` §2.1).
|
||||||
|
pub const MAX_PUSH_ENDPOINT_BYTES: usize = 1000;
|
||||||
|
/// The body of every wake: a constant, so it carries nothing (`PROTOCOL.md` §6).
|
||||||
|
pub const WAKE_BODY: &[u8] = b"wake";
|
||||||
|
/// A mailbox is woken at most once in this many seconds.
|
||||||
|
pub const WAKE_EVERY_SECS: i64 = 60;
|
||||||
|
|
||||||
/// Why a value from the wire was refused. Carries no part of the input.
|
/// Why a value from the wire was refused. Carries no part of the input.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -35,6 +41,8 @@ pub enum ParseError {
|
|||||||
Scheme,
|
Scheme,
|
||||||
/// More bytes than the protocol allows.
|
/// More bytes than the protocol allows.
|
||||||
TooLarge { max: usize },
|
TooLarge { max: usize },
|
||||||
|
/// Not a push endpoint the protocol accepts (`wake-up.md` §2.1).
|
||||||
|
Endpoint,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for ParseError {
|
impl fmt::Display for ParseError {
|
||||||
@@ -46,6 +54,7 @@ impl fmt::Display for ParseError {
|
|||||||
}
|
}
|
||||||
ParseError::Scheme => write!(f, "expected 'Bearer <token>'"),
|
ParseError::Scheme => write!(f, "expected 'Bearer <token>'"),
|
||||||
ParseError::TooLarge { max } => write!(f, "more than {max} bytes"),
|
ParseError::TooLarge { max } => write!(f, "more than {max} bytes"),
|
||||||
|
ParseError::Endpoint => write!(f, "not an https push endpoint"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,6 +148,12 @@ fixed_bytes!(
|
|||||||
InviteId,
|
InviteId,
|
||||||
16
|
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!(
|
fixed_bytes!(
|
||||||
/// SHA-256 of a token, or of a blob when it is acknowledged. The relay stores token hashes only.
|
/// SHA-256 of a token, or of a blob when it is acknowledged. The relay stores token hashes only.
|
||||||
Sha256Hash,
|
Sha256Hash,
|
||||||
@@ -184,7 +199,7 @@ macro_rules! debug_as_wire {
|
|||||||
}
|
}
|
||||||
)*};
|
)*};
|
||||||
}
|
}
|
||||||
debug_as_wire!(MailboxId, InviteId, Sha256Hash);
|
debug_as_wire!(MailboxId, InviteId, Sha256Hash, Author);
|
||||||
|
|
||||||
/// The SHA-256 of a blob: how its recipient acknowledges it.
|
/// The SHA-256 of a blob: how its recipient acknowledges it.
|
||||||
pub fn blob_hash(blob: &[u8]) -> Sha256Hash {
|
pub fn blob_hash(blob: &[u8]) -> Sha256Hash {
|
||||||
@@ -327,3 +342,108 @@ pub fn hour_of(unix_secs: i64) -> i64 {
|
|||||||
pub fn day_of(unix_secs: i64) -> i64 {
|
pub fn day_of(unix_secs: i64) -> i64 {
|
||||||
unix_secs.div_euclid(86_400)
|
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 _ = InviteId::parse(&text);
|
||||||
let _ = Sha256Hash::parse(&text);
|
let _ = Sha256Hash::parse(&text);
|
||||||
let _ = Token::parse(&text);
|
let _ = Token::parse(&text);
|
||||||
|
let _ = Author::parse(&text);
|
||||||
let _ = Token::from_bearer(&text);
|
let _ = Token::from_bearer(&text);
|
||||||
let _ = WireBytes::parse(&text, MAX_BLOB_BYTES);
|
let _ = WireBytes::parse(&text, MAX_BLOB_BYTES);
|
||||||
}
|
}
|
||||||
@@ -172,7 +173,10 @@ proptest! {
|
|||||||
#[test]
|
#[test]
|
||||||
fn whatever_parses_has_one_spelling(text in "[A-Za-z0-9_-]{22}") {
|
fn whatever_parses_has_one_spelling(text in "[A-Za-z0-9_-]{22}") {
|
||||||
if let Ok(id) = MailboxId::parse(&text) {
|
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,104 @@ proptest! {
|
|||||||
prop_assert_eq!(back.bytes(), &bytes[..]);
|
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})"));
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,6 +15,12 @@ rusqlite = { version = "0.41", features = ["bundled"] }
|
|||||||
serde = "1"
|
serde = "1"
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
subtle = "2"
|
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]
|
[dev-dependencies]
|
||||||
getrandom = "0.3"
|
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>
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
//! address, and nothing here writes a request anywhere.
|
//! address, and nothing here writes a request anywhere.
|
||||||
|
|
||||||
use crate::store::{Refused, Store};
|
use crate::store::{Refused, Store};
|
||||||
|
use crate::wake::Waker;
|
||||||
use axum::body::Bytes;
|
use axum::body::Bytes;
|
||||||
use axum::extract::{DefaultBodyLimit, Path, State};
|
use axum::extract::{DefaultBodyLimit, Path, State};
|
||||||
use axum::http::{header, HeaderMap, StatusCode};
|
use axum::http::{header, HeaderMap, StatusCode};
|
||||||
@@ -11,8 +12,8 @@ use axum::{Json, Router};
|
|||||||
use serde::de::DeserializeOwned;
|
use serde::de::DeserializeOwned;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tabellarius_protocol::{
|
use tabellarius_protocol::{
|
||||||
CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, Sha256Hash,
|
CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, SetPush,
|
||||||
Token, VersionInfo, MAX_BLOB_BYTES, VERSION,
|
Sha256Hash, Token, VersionInfo, MAX_BLOB_BYTES, VERSION,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Unix seconds. The server passes the system clock; tests pass their own.
|
/// Unix seconds. The server passes the system clock; tests pass their own.
|
||||||
@@ -22,6 +23,23 @@ pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
|
|||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub store: Arc<Store>,
|
pub store: Arc<Store>,
|
||||||
pub clock: Clock,
|
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.
|
/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url.
|
||||||
@@ -35,9 +53,11 @@ pub fn router(state: AppState) -> Router {
|
|||||||
.route("/v0/mailboxes", post(create_mailbox))
|
.route("/v0/mailboxes", post(create_mailbox))
|
||||||
.route("/v0/mailboxes/{id}/blobs/{hash}", delete(acknowledge))
|
.route("/v0/mailboxes/{id}/blobs/{hash}", delete(acknowledge))
|
||||||
.route("/v0/mailboxes/{id}/post-token", put(rotate_post_token))
|
.route("/v0/mailboxes/{id}/post-token", put(rotate_post_token))
|
||||||
|
.route("/v0/mailboxes/{id}/push", put(set_push).delete(clear_push))
|
||||||
.route("/v0/invites", post(create_invite))
|
.route("/v0/invites", post(create_invite))
|
||||||
.route("/v0/invites/{id}", get(claim_invite))
|
.route("/v0/invites/{id}", get(claim_invite))
|
||||||
.route("/version", get(version))
|
.route("/version", get(version))
|
||||||
|
.route("/join", get(crate::join::page))
|
||||||
.layer(DefaultBodyLimit::max(MAX_JSON_BYTES))
|
.layer(DefaultBodyLimit::max(MAX_JSON_BYTES))
|
||||||
.merge(blob_routes)
|
.merge(blob_routes)
|
||||||
.with_state(state)
|
.with_state(state)
|
||||||
@@ -59,6 +79,7 @@ impl From<Refused> for Status {
|
|||||||
Refused::Exists => StatusCode::CONFLICT,
|
Refused::Exists => StatusCode::CONFLICT,
|
||||||
Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR,
|
Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Refused::Full => StatusCode::INSUFFICIENT_STORAGE,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -96,7 +117,12 @@ async fn post_blob(
|
|||||||
) -> Result<StatusCode, Status> {
|
) -> Result<StatusCode, Status> {
|
||||||
let id = mailbox(&id)?;
|
let id = mailbox(&id)?;
|
||||||
let token = bearer(&headers)?;
|
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)
|
Ok(StatusCode::CREATED)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,6 +163,33 @@ async fn rotate_post_token(
|
|||||||
Ok(StatusCode::NO_CONTENT)
|
Ok(StatusCode::NO_CONTENT)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn set_push(
|
||||||
|
State(s): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
body: Bytes,
|
||||||
|
) -> Result<StatusCode, Status> {
|
||||||
|
let id = mailbox(&id)?;
|
||||||
|
let token = bearer(&headers)?;
|
||||||
|
let req: SetPush = json(&body)?;
|
||||||
|
if !s.waker.accepts(&req.endpoint) {
|
||||||
|
return Err(Status(StatusCode::BAD_REQUEST));
|
||||||
|
}
|
||||||
|
s.store.set_push(&id, &token, Some(&req.endpoint))?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn clear_push(
|
||||||
|
State(s): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<StatusCode, Status> {
|
||||||
|
let id = mailbox(&id)?;
|
||||||
|
let token = bearer(&headers)?;
|
||||||
|
s.store.set_push(&id, &token, None)?;
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
|
|
||||||
async fn create_invite(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
|
async fn create_invite(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
|
||||||
let req: CreateInvite = json(&body)?;
|
let req: CreateInvite = json(&body)?;
|
||||||
s.store.create_invite(&req, (s.clock)())?;
|
s.store.create_invite(&req, (s.clock)())?;
|
||||||
|
|||||||
@@ -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()
|
||||||
|
}
|
||||||
+27
-3
@@ -2,7 +2,9 @@
|
|||||||
//! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request.
|
//! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request.
|
||||||
|
|
||||||
pub mod http;
|
pub mod http;
|
||||||
|
pub mod join;
|
||||||
pub mod store;
|
pub mod store;
|
||||||
|
pub mod wake;
|
||||||
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@@ -15,16 +17,33 @@ pub const DEFAULT_DB: &str = "tabellarius-relay.db";
|
|||||||
pub struct Args {
|
pub struct Args {
|
||||||
pub listen: SocketAddr,
|
pub listen: SocketAddr,
|
||||||
pub db: PathBuf,
|
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>`. Anything else is refused with a usage line.
|
/// `--listen <addr:port>`, `--db <path>`, and the relay-wide quotas `--max-bytes`,
|
||||||
|
/// `--max-mailboxes`, `--max-invites` (positive integers), and `--push-loopback` (tests). Anything else is refused with a usage
|
||||||
|
/// line.
|
||||||
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
|
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
|
||||||
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]";
|
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] \
|
||||||
|
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000] \n [--push-loopback]";
|
||||||
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
|
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
|
||||||
let mut db = PathBuf::from(DEFAULT_DB);
|
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 mut it = args.into_iter();
|
||||||
|
let positive = |v: Option<String>| -> Result<i64, String> {
|
||||||
|
v.and_then(|v| v.parse::<i64>().ok())
|
||||||
|
.filter(|&n| n > 0)
|
||||||
|
.ok_or_else(|| usage.to_string())
|
||||||
|
};
|
||||||
while let Some(arg) = it.next() {
|
while let Some(arg) = it.next() {
|
||||||
match arg.as_str() {
|
match arg.as_str() {
|
||||||
|
"--max-bytes" => limits.total_bytes = positive(it.next())?,
|
||||||
|
"--max-mailboxes" => limits.mailboxes = positive(it.next())?,
|
||||||
|
"--max-invites" => limits.invites = positive(it.next())?,
|
||||||
|
"--push-loopback" => push_loopback = true,
|
||||||
"--listen" => {
|
"--listen" => {
|
||||||
listen = it
|
listen = it
|
||||||
.next()
|
.next()
|
||||||
@@ -40,5 +59,10 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
|
|||||||
_ => return Err(usage.to_string()),
|
_ => return Err(usage.to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Args { listen, db })
|
Ok(Args {
|
||||||
|
listen,
|
||||||
|
db,
|
||||||
|
limits,
|
||||||
|
push_loopback,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]`
|
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] [--max-bytes N]
|
||||||
|
//! [--max-mailboxes N] [--max-invites N] [--push-loopback]`
|
||||||
//!
|
//!
|
||||||
//! Prints one line at start (version and address) and nothing per request.
|
//! Prints one line at start (version and address) and nothing per request.
|
||||||
|
|
||||||
@@ -7,6 +8,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
|||||||
use tabellarius_relay::http::{router, AppState, Clock};
|
use tabellarius_relay::http::{router, AppState, Clock};
|
||||||
use tabellarius_relay::parse_args;
|
use tabellarius_relay::parse_args;
|
||||||
use tabellarius_relay::store::Store;
|
use tabellarius_relay::store::Store;
|
||||||
|
use tabellarius_relay::wake::Waker;
|
||||||
|
|
||||||
fn now() -> i64 {
|
fn now() -> i64 {
|
||||||
SystemTime::now()
|
SystemTime::now()
|
||||||
@@ -24,7 +26,7 @@ async fn main() {
|
|||||||
std::process::exit(2);
|
std::process::exit(2);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let store = match Store::open(&args.db) {
|
let store = match Store::open_with(&args.db, args.limits) {
|
||||||
Ok(s) => Arc::new(s),
|
Ok(s) => Arc::new(s),
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
@@ -62,7 +64,11 @@ async fn main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let clock: Clock = Arc::new(now);
|
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 shutdown = async {
|
||||||
let _ = tokio::signal::ctrl_c().await;
|
let _ = tokio::signal::ctrl_c().await;
|
||||||
};
|
};
|
||||||
|
|||||||
+131
-8
@@ -1,6 +1,6 @@
|
|||||||
//! Every rule of the relay, over SQLite, with the clock passed in.
|
//! Every rule of the relay, over SQLite, with the clock passed in.
|
||||||
//!
|
//!
|
||||||
//! The database holds exactly `docs/PROTOCOL.md` §5: three tables, and nothing about who connected.
|
//! The database holds exactly `docs/PROTOCOL.md` §5: four tables, and nothing about who connected.
|
||||||
//! A wrong token and an unknown id give the same [`Refused::NotFound`], so nobody can probe which
|
//! A wrong token and an unknown id give the same [`Refused::NotFound`], so nobody can probe which
|
||||||
//! mailboxes or invites exist.
|
//! mailboxes or invites exist.
|
||||||
|
|
||||||
@@ -10,8 +10,8 @@ use std::sync::Mutex;
|
|||||||
use subtle::ConstantTimeEq;
|
use subtle::ConstantTimeEq;
|
||||||
use tabellarius_protocol::{
|
use tabellarius_protocol::{
|
||||||
blob_hash, day_of, hour_of, BlobBytes, ClaimedInvite, CreateInvite, CreateMailbox, FetchedBlob,
|
blob_hash, day_of, hour_of, BlobBytes, ClaimedInvite, CreateInvite, CreateMailbox, FetchedBlob,
|
||||||
InviteId, KeyPackageBytes, MailboxId, Sha256Hash, Token, BLOB_TTL_SECS, INVITE_TTL_SECS,
|
InviteId, KeyPackageBytes, MailboxId, PushEndpoint, Sha256Hash, Token, BLOB_TTL_SECS,
|
||||||
MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES,
|
INVITE_TTL_SECS, MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The schema, and nothing else (`PROTOCOL.md` §5). A column added here is a protocol change.
|
/// The schema, and nothing else (`PROTOCOL.md` §5). A column added here is a protocol change.
|
||||||
@@ -35,6 +35,10 @@ CREATE TABLE IF NOT EXISTS invites (
|
|||||||
key_package BLOB NOT NULL,
|
key_package BLOB NOT NULL,
|
||||||
expiry INTEGER NOT NULL
|
expiry INTEGER NOT NULL
|
||||||
);
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS push (
|
||||||
|
mailbox_id BLOB PRIMARY KEY NOT NULL,
|
||||||
|
endpoint TEXT NOT NULL
|
||||||
|
);
|
||||||
";
|
";
|
||||||
|
|
||||||
/// Why a request was refused. Deliberately coarse: it says nothing about which part was wrong.
|
/// Why a request was refused. Deliberately coarse: it says nothing about which part was wrong.
|
||||||
@@ -48,6 +52,36 @@ pub enum Refused {
|
|||||||
TooLarge,
|
TooLarge,
|
||||||
/// The database failed; nothing about the request is in the error.
|
/// The database failed; nothing about the request is in the error.
|
||||||
Storage,
|
Storage,
|
||||||
|
/// A quota is reached (`PROTOCOL.md` §8, 507): the mailbox's, after its token, or the relay's.
|
||||||
|
Full,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much the relay holds before it answers [`Refused::Full`]. The per-mailbox caps are the
|
||||||
|
/// protocol's; the relay-wide ones are the operator's (`.agents/features/home-relay.md` §2).
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Limits {
|
||||||
|
pub mailbox_blobs: i64,
|
||||||
|
pub mailbox_bytes: i64,
|
||||||
|
pub total_bytes: i64,
|
||||||
|
pub mailboxes: i64,
|
||||||
|
pub invites: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Waiting blobs in one mailbox (`PROTOCOL.md` §8).
|
||||||
|
pub const MAILBOX_BLOBS: i64 = 1_000;
|
||||||
|
/// Waiting bytes in one mailbox (`PROTOCOL.md` §8).
|
||||||
|
pub const MAILBOX_BYTES: i64 = 32 * 1024 * 1024;
|
||||||
|
|
||||||
|
impl Default for Limits {
|
||||||
|
fn default() -> Self {
|
||||||
|
Limits {
|
||||||
|
mailbox_blobs: MAILBOX_BLOBS,
|
||||||
|
mailbox_bytes: MAILBOX_BYTES,
|
||||||
|
total_bytes: 1024 * 1024 * 1024,
|
||||||
|
mailboxes: 100_000,
|
||||||
|
invites: 10_000,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<rusqlite::Error> for Refused {
|
impl From<rusqlite::Error> for Refused {
|
||||||
@@ -58,6 +92,7 @@ impl From<rusqlite::Error> for Refused {
|
|||||||
|
|
||||||
pub struct Store {
|
pub struct Store {
|
||||||
conn: Mutex<Connection>,
|
conn: Mutex<Connection>,
|
||||||
|
limits: Limits,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a purge removed.
|
/// What a purge removed.
|
||||||
@@ -73,23 +108,39 @@ fn same_hash(stored: &[u8], presented: &Sha256Hash) -> bool {
|
|||||||
|
|
||||||
impl Store {
|
impl Store {
|
||||||
pub fn open(path: &Path) -> Result<Self, rusqlite::Error> {
|
pub fn open(path: &Path) -> Result<Self, rusqlite::Error> {
|
||||||
Self::init(Connection::open(path)?)
|
Self::init(Connection::open(path)?, Limits::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open_with(path: &Path, limits: Limits) -> Result<Self, rusqlite::Error> {
|
||||||
|
Self::init(Connection::open(path)?, limits)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
|
pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
|
||||||
Self::init(Connection::open_in_memory()?)
|
Self::init(Connection::open_in_memory()?, Limits::default())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn init(conn: Connection) -> Result<Self, rusqlite::Error> {
|
pub fn open_in_memory_with(limits: Limits) -> Result<Self, rusqlite::Error> {
|
||||||
|
Self::init(Connection::open_in_memory()?, limits)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init(conn: Connection, limits: Limits) -> Result<Self, rusqlite::Error> {
|
||||||
// Deleted rows are overwritten in the file, and there is no -wal copy of anything.
|
// Deleted rows are overwritten in the file, and there is no -wal copy of anything.
|
||||||
conn.pragma_update(None, "secure_delete", "ON")?;
|
conn.pragma_update(None, "secure_delete", "ON")?;
|
||||||
conn.pragma_update(None, "journal_mode", "DELETE")?;
|
conn.pragma_update(None, "journal_mode", "DELETE")?;
|
||||||
conn.execute_batch(SCHEMA)?;
|
conn.execute_batch(SCHEMA)?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
conn: Mutex::new(conn),
|
conn: Mutex::new(conn),
|
||||||
|
limits,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One number from the database: a count or a sum, 0 for none.
|
||||||
|
fn number(conn: &Connection, sql: &str, args: impl rusqlite::Params) -> Result<i64, Refused> {
|
||||||
|
Ok(conn
|
||||||
|
.query_row(sql, args, |r| r.get::<_, Option<i64>>(0))?
|
||||||
|
.unwrap_or(0))
|
||||||
|
}
|
||||||
|
|
||||||
fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
|
fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
|
||||||
// A panic while holding the lock leaves SQLite consistent (every write is one statement or
|
// A panic while holding the lock leaves SQLite consistent (every write is one statement or
|
||||||
// one transaction), so a poisoned lock is still safe to use.
|
// one transaction), so a poisoned lock is still safe to use.
|
||||||
@@ -97,7 +148,11 @@ impl Store {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_mailbox(&self, req: &CreateMailbox, now: i64) -> Result<(), Refused> {
|
pub fn create_mailbox(&self, req: &CreateMailbox, now: i64) -> Result<(), Refused> {
|
||||||
let changed = self.conn().execute(
|
let conn = self.conn();
|
||||||
|
if Self::number(&conn, "SELECT count(*) FROM mailboxes", [])? >= self.limits.mailboxes {
|
||||||
|
return Err(Refused::Full);
|
||||||
|
}
|
||||||
|
let changed = conn.execute(
|
||||||
"INSERT OR IGNORE INTO mailboxes (id, post_hash, fetch_hash, created_day)
|
"INSERT OR IGNORE INTO mailboxes (id, post_hash, fetch_hash, created_day)
|
||||||
VALUES (?1, ?2, ?3, ?4)",
|
VALUES (?1, ?2, ?3, ?4)",
|
||||||
params![
|
params![
|
||||||
@@ -150,6 +205,20 @@ impl Store {
|
|||||||
}
|
}
|
||||||
let conn = self.conn();
|
let conn = self.conn();
|
||||||
Self::authorize(&conn, id, token, Column::Post)?;
|
Self::authorize(&conn, id, token, Column::Post)?;
|
||||||
|
// After the token: a stranger learns nothing about this mailbox from a 507.
|
||||||
|
let size = blob.len() as i64;
|
||||||
|
let (count, bytes): (i64, Option<i64>) = conn.query_row(
|
||||||
|
"SELECT count(*), sum(size) FROM blobs WHERE mailbox_id = ?1",
|
||||||
|
[&id.as_bytes()[..]],
|
||||||
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||||
|
)?;
|
||||||
|
let total = Self::number(&conn, "SELECT sum(size) FROM blobs", [])?;
|
||||||
|
if count >= self.limits.mailbox_blobs
|
||||||
|
|| bytes.unwrap_or(0) + size > self.limits.mailbox_bytes
|
||||||
|
|| total + size > self.limits.total_bytes
|
||||||
|
{
|
||||||
|
return Err(Refused::Full);
|
||||||
|
}
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT INTO blobs (mailbox_id, ciphertext, size, received_hour) VALUES (?1, ?2, ?3, ?4)",
|
"INSERT INTO blobs (mailbox_id, ciphertext, size, received_hour) VALUES (?1, ?2, ?3, ?4)",
|
||||||
params![&id.as_bytes()[..], blob, blob.len() as i64, hour_of(now)],
|
params![&id.as_bytes()[..], blob, blob.len() as i64, hour_of(now)],
|
||||||
@@ -231,7 +300,17 @@ impl Store {
|
|||||||
pub fn create_invite(&self, req: &CreateInvite, now: i64) -> Result<(), Refused> {
|
pub fn create_invite(&self, req: &CreateInvite, now: i64) -> Result<(), Refused> {
|
||||||
// Expiry rounded up to the hour: the exact second the invite was made is not kept.
|
// Expiry rounded up to the hour: the exact second the invite was made is not kept.
|
||||||
let expiry = (hour_of(now + INVITE_TTL_SECS) + 1) * 3600;
|
let expiry = (hour_of(now + INVITE_TTL_SECS) + 1) * 3600;
|
||||||
let changed = self.conn().execute(
|
let conn = self.conn();
|
||||||
|
// Expired invites wait for the hourly purge; they do not count against new ones.
|
||||||
|
let waiting = Self::number(
|
||||||
|
&conn,
|
||||||
|
"SELECT count(*) FROM invites WHERE expiry > ?1",
|
||||||
|
[now],
|
||||||
|
)?;
|
||||||
|
if waiting >= self.limits.invites {
|
||||||
|
return Err(Refused::Full);
|
||||||
|
}
|
||||||
|
let changed = conn.execute(
|
||||||
"INSERT OR IGNORE INTO invites (id, secret_hash, key_package, expiry) VALUES (?1, ?2, ?3, ?4)",
|
"INSERT OR IGNORE INTO invites (id, secret_hash, key_package, expiry) VALUES (?1, ?2, ?3, ?4)",
|
||||||
params![
|
params![
|
||||||
&req.id.as_bytes()[..],
|
&req.id.as_bytes()[..],
|
||||||
@@ -276,6 +355,50 @@ impl Store {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sets (`Some`) or removes (`None`) the mailbox's push endpoint. Needs the fetch token: only the
|
||||||
|
/// owner says where to be woken (`PROTOCOL.md` §6).
|
||||||
|
pub fn set_push(
|
||||||
|
&self,
|
||||||
|
id: &MailboxId,
|
||||||
|
token: &Token,
|
||||||
|
endpoint: Option<&PushEndpoint>,
|
||||||
|
) -> Result<(), Refused> {
|
||||||
|
let conn = self.conn();
|
||||||
|
Self::authorize(&conn, id, token, Column::Fetch)?;
|
||||||
|
match endpoint {
|
||||||
|
Some(e) => conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO push (mailbox_id, endpoint) VALUES (?1, ?2)",
|
||||||
|
params![&id.as_bytes()[..], e.as_str()],
|
||||||
|
)?,
|
||||||
|
None => conn.execute(
|
||||||
|
"DELETE FROM push WHERE mailbox_id = ?1",
|
||||||
|
[&id.as_bytes()[..]],
|
||||||
|
)?,
|
||||||
|
};
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The endpoint to wake after a blob was stored for this mailbox, if its owner gave one.
|
||||||
|
pub fn push_endpoint(&self, id: &MailboxId) -> Result<Option<String>, Refused> {
|
||||||
|
Ok(self
|
||||||
|
.conn()
|
||||||
|
.query_row(
|
||||||
|
"SELECT endpoint FROM push WHERE mailbox_id = ?1",
|
||||||
|
[&id.as_bytes()[..]],
|
||||||
|
|r| r.get(0),
|
||||||
|
)
|
||||||
|
.optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The push server said the endpoint is gone: removes it, unless the owner has set another since.
|
||||||
|
pub fn drop_push_if(&self, id: &MailboxId, endpoint: &str) -> Result<(), Refused> {
|
||||||
|
self.conn().execute(
|
||||||
|
"DELETE FROM push WHERE mailbox_id = ?1 AND endpoint = ?2",
|
||||||
|
params![&id.as_bytes()[..], endpoint],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Deletes blobs older than 30 days and invites past their expiry.
|
/// Deletes blobs older than 30 days and invites past their expiry.
|
||||||
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
|
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
|
||||||
let conn = self.conn();
|
let conn = self.conn();
|
||||||
|
|||||||
@@ -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,292 @@
|
|||||||
|
//! Quotas (`.agents/features/home-relay.md` §4, `PROTOCOL.md` §8): over a limit the relay answers a
|
||||||
|
//! bare 507; the per-mailbox caps only after the post token. Small limits, so the tests are quick.
|
||||||
|
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::http::{header, Method, Request, StatusCode};
|
||||||
|
use http_body_util::BodyExt;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tabellarius_protocol::*;
|
||||||
|
use tabellarius_relay::http::{router, AppState, Clock};
|
||||||
|
use tabellarius_relay::parse_args;
|
||||||
|
use tabellarius_relay::store::{Limits, Store, MAILBOX_BLOBS, MAILBOX_BYTES};
|
||||||
|
use tower::ServiceExt;
|
||||||
|
|
||||||
|
const T0: i64 = 1_794_000_000;
|
||||||
|
|
||||||
|
fn random<const N: usize>() -> [u8; N] {
|
||||||
|
let mut b = [0u8; N];
|
||||||
|
getrandom::fill(&mut b).expect("system randomness");
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Mailbox {
|
||||||
|
id: MailboxId,
|
||||||
|
post: Token,
|
||||||
|
fetch: Token,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mailbox {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
id: MailboxId::from_bytes(random()),
|
||||||
|
post: Token::from_bytes(random()),
|
||||||
|
fetch: Token::from_bytes(random()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn path(&self) -> String {
|
||||||
|
format!("/v0/mailboxes/{}/blobs", self.id.to_wire())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Relay(axum::Router);
|
||||||
|
|
||||||
|
impl Relay {
|
||||||
|
fn with(limits: Limits) -> Self {
|
||||||
|
let store = Arc::new(Store::open_in_memory_with(limits).expect("store"));
|
||||||
|
let clock: Clock = Arc::new(|| T0);
|
||||||
|
Relay(router(AppState::new(store, clock)))
|
||||||
|
}
|
||||||
|
async fn call(
|
||||||
|
&self,
|
||||||
|
method: Method,
|
||||||
|
path: &str,
|
||||||
|
auth: Option<&Token>,
|
||||||
|
body: Vec<u8>,
|
||||||
|
) -> StatusCode {
|
||||||
|
let mut req = Request::builder().method(method).uri(path);
|
||||||
|
if let Some(t) = auth {
|
||||||
|
req = req.header(header::AUTHORIZATION, t.to_bearer());
|
||||||
|
}
|
||||||
|
let resp = self
|
||||||
|
.0
|
||||||
|
.clone()
|
||||||
|
.oneshot(req.body(Body::from(body)).expect("request"))
|
||||||
|
.await
|
||||||
|
.expect("infallible");
|
||||||
|
let status = resp.status();
|
||||||
|
let body = resp.into_body().collect().await.expect("body").to_bytes();
|
||||||
|
if !status.is_success() {
|
||||||
|
assert!(body.is_empty(), "a refusal has no body");
|
||||||
|
}
|
||||||
|
status
|
||||||
|
}
|
||||||
|
async fn create(&self, m: &Mailbox) -> StatusCode {
|
||||||
|
let body = serde_json::to_vec(&CreateMailbox {
|
||||||
|
id: m.id,
|
||||||
|
post_token_hash: m.post.hash(),
|
||||||
|
fetch_token_hash: m.fetch.hash(),
|
||||||
|
})
|
||||||
|
.expect("json");
|
||||||
|
self.call(Method::POST, "/v0/mailboxes", None, body).await
|
||||||
|
}
|
||||||
|
async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode {
|
||||||
|
self.call(Method::POST, &m.path(), Some(token), blob.to_vec())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
async fn ack(&self, m: &Mailbox, blob: &[u8]) -> StatusCode {
|
||||||
|
let path = format!("{}/{}", m.path(), blob_hash(blob).to_wire());
|
||||||
|
self.call(Method::DELETE, &path, Some(&m.fetch), vec![])
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
async fn invite(&self) -> (StatusCode, InviteId, Token) {
|
||||||
|
let id = InviteId::from_bytes(random());
|
||||||
|
let secret = Token::from_bytes(random());
|
||||||
|
let body = serde_json::to_vec(&CreateInvite {
|
||||||
|
id,
|
||||||
|
secret_hash: secret.hash(),
|
||||||
|
key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"),
|
||||||
|
})
|
||||||
|
.expect("json");
|
||||||
|
(
|
||||||
|
self.call(Method::POST, "/v0/invites", None, body).await,
|
||||||
|
id,
|
||||||
|
secret,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn small(f: impl FnOnce(&mut Limits)) -> Limits {
|
||||||
|
let mut l = Limits::default();
|
||||||
|
f(&mut l);
|
||||||
|
l
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_protocol_caps_are_the_documented_ones() {
|
||||||
|
assert_eq!(MAILBOX_BLOBS, 1_000);
|
||||||
|
assert_eq!(MAILBOX_BYTES, 32 * 1024 * 1024);
|
||||||
|
let l = Limits::default();
|
||||||
|
assert_eq!(
|
||||||
|
(l.total_bytes, l.mailboxes, l.invites),
|
||||||
|
(1 << 30, 100_000, 10_000)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_mailbox_holds_a_thousand_blobs_then_says_full_until_one_is_acknowledged() {
|
||||||
|
let relay = Relay::with(Limits::default());
|
||||||
|
let m = Mailbox::new();
|
||||||
|
assert_eq!(relay.create(&m).await, StatusCode::CREATED);
|
||||||
|
for i in 0..MAILBOX_BLOBS {
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&m, &m.post, &i.to_le_bytes()).await,
|
||||||
|
StatusCode::CREATED
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let one_more = b"one more";
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&m, &m.post, one_more).await,
|
||||||
|
StatusCode::INSUFFICIENT_STORAGE
|
||||||
|
);
|
||||||
|
// A stranger without the token learns nothing: 404, as for any wrong token.
|
||||||
|
let stranger = Token::from_bytes(random());
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&m, &stranger, one_more).await,
|
||||||
|
StatusCode::NOT_FOUND
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
relay.ack(&m, &0i64.to_le_bytes()).await,
|
||||||
|
StatusCode::NO_CONTENT
|
||||||
|
);
|
||||||
|
assert_eq!(relay.post(&m, &m.post, one_more).await, StatusCode::CREATED);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_mailbox_holds_at_most_its_bytes() {
|
||||||
|
let relay = Relay::with(small(|l| l.mailbox_bytes = 1000));
|
||||||
|
let m = Mailbox::new();
|
||||||
|
relay.create(&m).await;
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&m, &m.post, &[1u8; 600]).await,
|
||||||
|
StatusCode::CREATED
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&m, &m.post, &[2u8; 400]).await,
|
||||||
|
StatusCode::CREATED,
|
||||||
|
"exactly at the cap"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&m, &m.post, &[3u8; 1]).await,
|
||||||
|
StatusCode::INSUFFICIENT_STORAGE
|
||||||
|
);
|
||||||
|
// Another mailbox is not affected.
|
||||||
|
let other = Mailbox::new();
|
||||||
|
relay.create(&other).await;
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&other, &other.post, &[4u8; 600]).await,
|
||||||
|
StatusCode::CREATED
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_relay_holds_at_most_its_bytes_across_mailboxes() {
|
||||||
|
let relay = Relay::with(small(|l| l.total_bytes = 1000));
|
||||||
|
let (a, b) = (Mailbox::new(), Mailbox::new());
|
||||||
|
relay.create(&a).await;
|
||||||
|
relay.create(&b).await;
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&a, &a.post, &[1u8; 700]).await,
|
||||||
|
StatusCode::CREATED
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&b, &b.post, &[2u8; 301]).await,
|
||||||
|
StatusCode::INSUFFICIENT_STORAGE
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&b, &b.post, &[2u8; 300]).await,
|
||||||
|
StatusCode::CREATED
|
||||||
|
);
|
||||||
|
assert_eq!(relay.ack(&a, &[1u8; 700]).await, StatusCode::NO_CONTENT);
|
||||||
|
assert_eq!(
|
||||||
|
relay.post(&b, &b.post, &[3u8; 700]).await,
|
||||||
|
StatusCode::CREATED,
|
||||||
|
"room again after an acknowledgement"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_relay_holds_at_most_its_mailboxes() {
|
||||||
|
let relay = Relay::with(small(|l| l.mailboxes = 3));
|
||||||
|
for _ in 0..3 {
|
||||||
|
assert_eq!(relay.create(&Mailbox::new()).await, StatusCode::CREATED);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
relay.create(&Mailbox::new()).await,
|
||||||
|
StatusCode::INSUFFICIENT_STORAGE
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_relay_holds_at_most_its_unclaimed_invites() {
|
||||||
|
let relay = Relay::with(small(|l| l.invites = 2));
|
||||||
|
let (s, id, secret) = relay.invite().await;
|
||||||
|
assert_eq!(s, StatusCode::CREATED);
|
||||||
|
assert_eq!(relay.invite().await.0, StatusCode::CREATED);
|
||||||
|
assert_eq!(relay.invite().await.0, StatusCode::INSUFFICIENT_STORAGE);
|
||||||
|
// A claimed invite is gone and makes room.
|
||||||
|
let path = format!("/v0/invites/{}", id.to_wire());
|
||||||
|
assert_eq!(
|
||||||
|
relay.call(Method::GET, &path, Some(&secret), vec![]).await,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
assert_eq!(relay.invite().await.0, StatusCode::CREATED);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_operator_sets_the_relay_wide_caps() {
|
||||||
|
let args = parse_args(
|
||||||
|
[
|
||||||
|
"--max-bytes",
|
||||||
|
"5000",
|
||||||
|
"--max-mailboxes",
|
||||||
|
"7",
|
||||||
|
"--max-invites",
|
||||||
|
"9",
|
||||||
|
]
|
||||||
|
.map(String::from),
|
||||||
|
)
|
||||||
|
.expect("args");
|
||||||
|
assert_eq!(
|
||||||
|
(
|
||||||
|
args.limits.total_bytes,
|
||||||
|
args.limits.mailboxes,
|
||||||
|
args.limits.invites
|
||||||
|
),
|
||||||
|
(5000, 7, 9)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
args.limits.mailbox_blobs, MAILBOX_BLOBS,
|
||||||
|
"not the operator's"
|
||||||
|
);
|
||||||
|
for bad in [
|
||||||
|
vec!["--max-bytes"],
|
||||||
|
vec!["--max-bytes", "0"],
|
||||||
|
vec!["--max-bytes", "-5"],
|
||||||
|
vec!["--max-mailboxes", "many"],
|
||||||
|
vec!["--max-invites", "1.5"],
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
parse_args(bad.iter().map(|s| s.to_string())).is_err(),
|
||||||
|
"{bad:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_expired_invite_does_not_count_against_new_ones() {
|
||||||
|
let store = Store::open_in_memory_with(small(|l| l.invites = 1)).expect("store");
|
||||||
|
let invite = || CreateInvite {
|
||||||
|
id: InviteId::from_bytes(random()),
|
||||||
|
secret_hash: Token::from_bytes(random()).hash(),
|
||||||
|
key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"),
|
||||||
|
};
|
||||||
|
store.create_invite(&invite(), T0).expect("first");
|
||||||
|
assert_eq!(
|
||||||
|
store.create_invite(&invite(), T0 + 3600),
|
||||||
|
Err(tabellarius_relay::store::Refused::Full)
|
||||||
|
);
|
||||||
|
// Eight days on, the first has expired, though the hourly purge has not run yet.
|
||||||
|
store
|
||||||
|
.create_invite(&invite(), T0 + 8 * 24 * 3600)
|
||||||
|
.expect("room after the expiry");
|
||||||
|
}
|
||||||
+107
-4
@@ -63,10 +63,7 @@ impl Relay {
|
|||||||
let now = Arc::new(AtomicI64::new(T0));
|
let now = Arc::new(AtomicI64::new(T0));
|
||||||
let n = Arc::clone(&now);
|
let n = Arc::clone(&now);
|
||||||
let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst));
|
let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst));
|
||||||
let app = router(AppState {
|
let app = router(AppState::new(Arc::clone(&store), clock));
|
||||||
store: Arc::clone(&store),
|
|
||||||
clock,
|
|
||||||
});
|
|
||||||
Self { app, store, now }
|
Self { app, store, now }
|
||||||
}
|
}
|
||||||
fn advance(&self, secs: i64) {
|
fn advance(&self, secs: i64) {
|
||||||
@@ -168,6 +165,8 @@ fn schema_is_exactly_protocol_section_5() {
|
|||||||
"created_day".into(),
|
"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!(
|
assert_eq!(
|
||||||
live, expected,
|
live, expected,
|
||||||
@@ -628,6 +627,15 @@ fn the_relay_listens_on_loopback_unless_told_otherwise() {
|
|||||||
let args = parse_args(Vec::<String>::new()).expect("defaults");
|
let args = parse_args(Vec::<String>::new()).expect("defaults");
|
||||||
assert_eq!(args.listen.to_string(), DEFAULT_LISTEN);
|
assert_eq!(args.listen.to_string(), DEFAULT_LISTEN);
|
||||||
assert!(args.listen.ip().is_loopback());
|
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(["--listen".to_string()]).is_err());
|
||||||
assert!(parse_args(["--verbose".to_string()]).is_err());
|
assert!(parse_args(["--verbose".to_string()]).is_err());
|
||||||
}
|
}
|
||||||
@@ -741,3 +749,98 @@ async fn no_random_request_breaks_the_relay() {
|
|||||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
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")
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# Running the relay on NixOS
|
||||||
|
|
||||||
|
The relay listens on `127.0.0.1` only. Caddy sits in front with TLS from Let's Encrypt, and writes
|
||||||
|
no log that holds an address (`.agents/features/home-relay.md`).
|
||||||
|
|
||||||
|
## 1. Before
|
||||||
|
- A DNS name for the relay (an `A` and/or `AAAA` record) pointing at the machine.
|
||||||
|
- Ports **80** and **443** reachable from the internet. 80 is for Let's Encrypt's challenge; Caddy
|
||||||
|
redirects everything else on it to 443.
|
||||||
|
|
||||||
|
## 2. The configuration
|
||||||
|
In the machine's flake:
|
||||||
|
```nix
|
||||||
|
{
|
||||||
|
inputs.tabellarius.url = "git+https://gitea.marek-novak.cz/mnovak/Amicitia-Tabellarius?ref=main";
|
||||||
|
|
||||||
|
outputs = { nixpkgs, tabellarius, ... }: {
|
||||||
|
nixosConfigurations.home = nixpkgs.lib.nixosSystem {
|
||||||
|
system = "x86_64-linux";
|
||||||
|
modules = [
|
||||||
|
tabellarius.nixosModules.default
|
||||||
|
{
|
||||||
|
services.tabellarius = {
|
||||||
|
enable = true;
|
||||||
|
domain = "relay.example.cz";
|
||||||
|
# Optional, the defaults shown:
|
||||||
|
# maxBytes = 1073741824; maxMailboxes = 100000; maxInvites = 10000;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
./configuration.nix
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Pin `tabellarius` in `flake.lock`, as for any input. Then `nixos-rebuild switch --flake .#home`.
|
||||||
|
|
||||||
|
## 3. What it sets up
|
||||||
|
| Part | What it does |
|
||||||
|
|:--|:--|
|
||||||
|
| `tabellarius.service` | `--listen 127.0.0.1:8470`, its database in `/var/lib/private/tabellarius`, a dynamic user, and a systemd sandbox. It may talk to localhost, 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 |
|
||||||
|
|
||||||
|
## 4. Check it
|
||||||
|
- From another machine: `curl https://relay.example.cz/version` answers with the versions.
|
||||||
|
- On the server, after some use, the address of the machine you used must appear nowhere:
|
||||||
|
`journalctl -o verbose | grep -F <that address>` and `grep -rF <that address> /var/log` find
|
||||||
|
nothing.
|
||||||
|
- The same check runs automatically in a VM: `nix flake check` in this repository (Linux, KVM).
|
||||||
|
|
||||||
|
> **Not run yet (2026-11-16).** This module and its VM test were written on a machine without Nix
|
||||||
|
> and have never been evaluated. Until `nix flake check` passes on Linux, and the check above is
|
||||||
|
> done on the real server, *Caddy keeps no address* is the design, not a tested fact.
|
||||||
|
|
||||||
|
## 5. In the app
|
||||||
|
Settings → *Your message relay*: `https://relay.example.cz`. Until the app accepts `https://`
|
||||||
|
addresses (Amicitia F23), it takes a loopback address only.
|
||||||
|
|
||||||
|
## 6. What the operator still sees
|
||||||
|
Caddy and the relay keep nothing, but the machine's network still carries the connections while
|
||||||
|
they happen. A router or ISP log, or `tcpdump` on the server, would show addresses and timing
|
||||||
|
(`docs/PROTOCOL.md` §1). Turning Caddy's log on, even for a while, writes addresses. Do it only
|
||||||
|
knowing that.
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
# The Tabellarius relay on NixOS, behind Caddy with TLS, and no log that holds an address
|
||||||
|
# (.agents/features/home-relay.md). Import it from the flake: `tabellarius.nixosModules.default`.
|
||||||
|
#
|
||||||
|
# services.tabellarius = {
|
||||||
|
# enable = true;
|
||||||
|
# domain = "relay.example.cz"; # its DNS name points at this machine; ports 80 and 443 open
|
||||||
|
# };
|
||||||
|
{ self }:
|
||||||
|
{ config, lib, pkgs, ... }:
|
||||||
|
let
|
||||||
|
cfg = config.services.tabellarius;
|
||||||
|
system = pkgs.stdenv.hostPlatform.system;
|
||||||
|
in
|
||||||
|
{
|
||||||
|
options.services.tabellarius = {
|
||||||
|
enable = lib.mkEnableOption "the Tabellarius message relay, behind Caddy with TLS and no logs";
|
||||||
|
|
||||||
|
domain = lib.mkOption {
|
||||||
|
type = lib.types.str;
|
||||||
|
example = "relay.example.cz";
|
||||||
|
description = "The relay's DNS name. Caddy gets its certificate from Let's Encrypt.";
|
||||||
|
};
|
||||||
|
|
||||||
|
package = lib.mkOption {
|
||||||
|
type = lib.types.package;
|
||||||
|
default = self.packages.${system}.default;
|
||||||
|
defaultText = lib.literalExpression "tabellarius.packages.\${system}.default";
|
||||||
|
description = "The relay, built from this flake: the code that runs is the code published.";
|
||||||
|
};
|
||||||
|
|
||||||
|
port = lib.mkOption {
|
||||||
|
type = lib.types.port;
|
||||||
|
default = 8470;
|
||||||
|
description = "The loopback port between Caddy and the relay. Never exposed.";
|
||||||
|
};
|
||||||
|
|
||||||
|
maxBytes = lib.mkOption {
|
||||||
|
type = lib.types.ints.positive;
|
||||||
|
default = 1073741824;
|
||||||
|
description = "Waiting blobs the relay holds, in bytes, before it answers 507 (PROTOCOL.md section 8).";
|
||||||
|
};
|
||||||
|
|
||||||
|
maxMailboxes = lib.mkOption {
|
||||||
|
type = lib.types.ints.positive;
|
||||||
|
default = 100000;
|
||||||
|
description = "Mailboxes the relay holds before it answers 507.";
|
||||||
|
};
|
||||||
|
|
||||||
|
maxInvites = lib.mkOption {
|
||||||
|
type = lib.types.ints.positive;
|
||||||
|
default = 10000;
|
||||||
|
description = "Unclaimed invites the relay holds before it answers 507.";
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
description = "Open ports 80 (the ACME challenge, then a redirect) and 443.";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
config = lib.mkIf cfg.enable {
|
||||||
|
systemd.services.tabellarius = {
|
||||||
|
description = "Tabellarius message relay (loopback only; Caddy in front)";
|
||||||
|
wantedBy = [ "multi-user.target" ];
|
||||||
|
after = [ "network.target" ];
|
||||||
|
serviceConfig = {
|
||||||
|
ExecStart = lib.escapeShellArgs [
|
||||||
|
"${cfg.package}/bin/tabellarius-relay"
|
||||||
|
"--listen" "127.0.0.1:${toString cfg.port}"
|
||||||
|
"--db" "/var/lib/tabellarius/relay.db"
|
||||||
|
"--max-bytes" (toString cfg.maxBytes)
|
||||||
|
"--max-mailboxes" (toString cfg.maxMailboxes)
|
||||||
|
"--max-invites" (toString cfg.maxInvites)
|
||||||
|
];
|
||||||
|
Restart = "on-failure";
|
||||||
|
DynamicUser = true;
|
||||||
|
StateDirectory = "tabellarius";
|
||||||
|
StateDirectoryMode = "0700";
|
||||||
|
UMask = "0077";
|
||||||
|
|
||||||
|
# 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";
|
||||||
|
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;
|
||||||
|
ProtectSystem = "strict";
|
||||||
|
ProtectHome = true;
|
||||||
|
PrivateTmp = true;
|
||||||
|
PrivateDevices = true;
|
||||||
|
PrivateUsers = true;
|
||||||
|
ProtectHostname = true;
|
||||||
|
ProtectClock = true;
|
||||||
|
ProtectKernelTunables = true;
|
||||||
|
ProtectKernelModules = true;
|
||||||
|
ProtectKernelLogs = true;
|
||||||
|
ProtectControlGroups = true;
|
||||||
|
ProtectProc = "invisible";
|
||||||
|
ProcSubset = "pid";
|
||||||
|
RestrictNamespaces = true;
|
||||||
|
RestrictRealtime = true;
|
||||||
|
RestrictSUIDSGID = true;
|
||||||
|
RemoveIPC = true;
|
||||||
|
LockPersonality = true;
|
||||||
|
MemoryDenyWriteExecute = true;
|
||||||
|
SystemCallArchitectures = "native";
|
||||||
|
SystemCallFilter = [ "@system-service" "~@privileged" ];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
services.caddy = {
|
||||||
|
enable = true;
|
||||||
|
# Caddy's own logger: errors about TLS handshakes or upstreams can name a client's address.
|
||||||
|
# No log is the rule; an operator who needs one turns it on for a while, knowing why.
|
||||||
|
logFormat = ''
|
||||||
|
output discard
|
||||||
|
'';
|
||||||
|
virtualHosts.${cfg.domain} = {
|
||||||
|
# The NixOS module writes an access log per host by default; this one writes none.
|
||||||
|
logFormat = ''
|
||||||
|
output discard
|
||||||
|
'';
|
||||||
|
extraConfig = ''
|
||||||
|
reverse_proxy 127.0.0.1:${toString cfg.port} {
|
||||||
|
# The relay never learns who connected: Caddy adds these by default.
|
||||||
|
header_up -X-Forwarded-For
|
||||||
|
header_up -X-Real-IP
|
||||||
|
header_up -Forwarded
|
||||||
|
}
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ 80 443 ];
|
||||||
|
# NixOS logs every refused connection with its source address by default. Those are strangers,
|
||||||
|
# not users, but a relay that keeps no address should not keep theirs either. mkDefault: the
|
||||||
|
# machine's owner can turn it back on.
|
||||||
|
networking.firewall.logRefusedConnections = lib.mkDefault false;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# `nix flake check` (Linux, KVM): two machines. `server` runs the module; `client` talks to it
|
||||||
|
# through Caddy with TLS, does everything the protocol allows and some things it refuses, fills a
|
||||||
|
# mailbox cap to its 507, and then the test fails if the client's address appears anywhere in the
|
||||||
|
# server's journal or under /var/log, or in the relay's database (.agents/features/home-relay.md).
|
||||||
|
{ self, pkgs }:
|
||||||
|
pkgs.testers.runNixOSTest {
|
||||||
|
name = "tabellarius-relay-keeps-no-address";
|
||||||
|
|
||||||
|
nodes.server = { lib, ... }: {
|
||||||
|
imports = [ self.nixosModules.default ];
|
||||||
|
services.tabellarius = {
|
||||||
|
enable = true;
|
||||||
|
domain = "relay.test";
|
||||||
|
maxMailboxes = 3;
|
||||||
|
};
|
||||||
|
# No Let's Encrypt inside a VM: Caddy's own CA instead.
|
||||||
|
services.caddy.virtualHosts."relay.test".extraConfig = lib.mkBefore "tls internal";
|
||||||
|
};
|
||||||
|
|
||||||
|
nodes.client = { pkgs, ... }: {
|
||||||
|
environment.systemPackages = [ pkgs.curl pkgs.python3 ];
|
||||||
|
};
|
||||||
|
|
||||||
|
testScript = ''
|
||||||
|
import base64, hashlib, json, os
|
||||||
|
|
||||||
|
def b64(raw):
|
||||||
|
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
||||||
|
|
||||||
|
start_all()
|
||||||
|
server.wait_for_unit("tabellarius.service")
|
||||||
|
server.wait_for_unit("caddy.service")
|
||||||
|
server.wait_for_open_port(443)
|
||||||
|
client.wait_for_unit("multi-user.target")
|
||||||
|
|
||||||
|
client_ip = client.succeed("ip -4 -o addr show dev eth1 | awk '{print $4}' | cut -d/ -f1").strip()
|
||||||
|
server_ip = server.succeed("ip -4 -o addr show dev eth1 | awk '{print $4}' | cut -d/ -f1").strip()
|
||||||
|
assert client_ip and server_ip and client_ip != server_ip, (client_ip, server_ip)
|
||||||
|
|
||||||
|
def call(method, path, token=None, body=None, json_body=False):
|
||||||
|
cmd = ["curl", "-sk", "-o", "/dev/null", "-w", "%{http_code}",
|
||||||
|
"--resolve", "relay.test:443:" + server_ip, "-X", method]
|
||||||
|
if token:
|
||||||
|
cmd += ["-H", "Authorization: Bearer " + token]
|
||||||
|
if body is not None:
|
||||||
|
client.succeed("cat > /tmp/body <<'EOF'\n" + body + "\nEOF")
|
||||||
|
client.succeed("truncate -s -1 /tmp/body")
|
||||||
|
cmd += ["--data-binary", "@/tmp/body"]
|
||||||
|
if json_body:
|
||||||
|
cmd += ["-H", "Content-Type: application/json"]
|
||||||
|
cmd.append("https://relay.test" + path)
|
||||||
|
return client.succeed(" ".join("'" + c + "'" for c in cmd)).strip()
|
||||||
|
|
||||||
|
def mailbox():
|
||||||
|
mid, post, fetch = os.urandom(16), os.urandom(32), os.urandom(32)
|
||||||
|
body = json.dumps({"id": b64(mid), "postTokenHash": b64(hashlib.sha256(post).digest()),
|
||||||
|
"fetchTokenHash": b64(hashlib.sha256(fetch).digest())})
|
||||||
|
return b64(mid), b64(post), b64(fetch), body
|
||||||
|
|
||||||
|
assert call("GET", "/version") == "200"
|
||||||
|
mid, post, fetch, body = mailbox()
|
||||||
|
assert call("POST", "/v0/mailboxes", body=body, json_body=True) == "201"
|
||||||
|
blob = "sealed-envelope-for-the-test"
|
||||||
|
assert call("POST", "/v0/mailboxes/" + mid + "/blobs", token=post, body=blob) == "201"
|
||||||
|
assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=fetch) == "200"
|
||||||
|
digest = b64(hashlib.sha256(blob.encode()).digest())
|
||||||
|
assert call("DELETE", "/v0/mailboxes/" + mid + "/blobs/" + digest, token=fetch) == "204"
|
||||||
|
# Refusals: a wrong token, a malformed id, a body that is not JSON.
|
||||||
|
assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=b64(os.urandom(32))) == "404"
|
||||||
|
assert call("GET", "/v0/mailboxes/nonsense/blobs", token=fetch) == "404"
|
||||||
|
assert call("POST", "/v0/mailboxes", body="not json", json_body=True) == "400"
|
||||||
|
# The cap: three mailboxes, then 507.
|
||||||
|
for _ in range(2):
|
||||||
|
assert call("POST", "/v0/mailboxes", body=mailbox()[3], json_body=True) == "201"
|
||||||
|
assert call("POST", "/v0/mailboxes", body=mailbox()[3], json_body=True) == "507"
|
||||||
|
|
||||||
|
# Nowhere on the server: not in the journal, not under /var/log, not in the relay's data.
|
||||||
|
server.succeed("journalctl --sync")
|
||||||
|
server.fail("journalctl --no-pager -o verbose | grep -F '" + client_ip + "'")
|
||||||
|
server.fail("grep -rF '" + client_ip + "' /var/log /var/lib/private/tabellarius")
|
||||||
|
'';
|
||||||
|
}
|
||||||
+65
-4
@@ -46,15 +46,43 @@ 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
|
*(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.)*
|
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` |
|
||||||
|
| `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.
|
||||||
|
|
||||||
|
**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
|
## 5. What the relay stores — the complete list
|
||||||
| Table | Columns |
|
| Table | Columns |
|
||||||
|:--|:--|
|
|:--|:--|
|
||||||
| `mailboxes` | id, hash(post token), hash(fetch token), created day |
|
| `mailboxes` | id, hash(post token), hash(fetch token), created day |
|
||||||
| `blobs` | mailbox id, ciphertext, size, received hour (rounded) |
|
| `blobs` | mailbox id, ciphertext, size, received hour (rounded) |
|
||||||
| `invites` | invite id, hash(fetch secret), KeyPackage, expiry |
|
| `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 |
|
||||||
|
|
||||||
Nothing else. No IP, no user agent, no request log beyond counts. A blob is deleted on acknowledged
|
Nothing else. 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
|
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.
|
log; the NixOS module ships configured that way.
|
||||||
|
|
||||||
@@ -62,6 +90,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**
|
A notification for a closed app needs a push service. The wake-up carries **no content and no sender**
|
||||||
— only "something arrived".
|
— only "something arrived".
|
||||||
- **Android:** UnifiedPush lets the user choose their own distributor; FCM as a fallback.
|
- **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
|
- **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,
|
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.
|
which learns a device token and timing.
|
||||||
@@ -71,12 +110,15 @@ The platform facts above are Claude's understanding, to be verified in `.agents/
|
|||||||
|
|
||||||
## 7. Tests that prove this document
|
## 7. Tests that prove this document
|
||||||
- A canary string sent in a message never appears anywhere in the relay's database or logs.
|
- 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 post without a valid token is refused; after rotation the old token is refused.
|
- 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 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.
|
- Parsers are fuzzed (`cargo fuzz`) for every message type.
|
||||||
- Every check in `VERIFY.md` §1 has a CI job or a documented manual procedure.
|
- 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
|
## 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
|
||||||
HTTP/1.1 behind TLS (the reverse proxy, F23). Ids and tokens are unpadded base64url of a fixed length
|
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
|
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.
|
unknown fields. A blob is at most 256 KiB, and a KeyPackage at most 16 KiB.
|
||||||
@@ -88,12 +130,31 @@ 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 |
|
| `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 |
|
| `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}/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 |
|
| `POST /v0/invites` `{id, secretHash, keyPackage}` | none | stores an invite. It expires after 7 days, rounded up to the hour |
|
||||||
| `GET /v0/invites/{id}` | invite secret | returns the KeyPackage once, then deletes the invite |
|
| `GET /v0/invites/{id}` | invite secret | returns the KeyPackage once, then deletes the invite |
|
||||||
| `GET /version` | none | the protocol and relay versions |
|
| `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
|
- A wrong token, an unknown id and a malformed id all give the same bare **404**, so nobody can probe
|
||||||
what exists.
|
what exists.
|
||||||
|
- **Quotas** *(added 2026-11-16, F23, so a relay can face the internet; `.agents/features/home-relay.md`)*:
|
||||||
|
a mailbox holds at most **1 000 waiting blobs** and **32 MiB**, and a relay at most what its
|
||||||
|
operator sets (by default 1 GiB of blobs, 100 000 mailboxes, 10 000 unclaimed invites). Over a
|
||||||
|
limit the answer is a bare **507**. The per-mailbox caps are checked only after the post token,
|
||||||
|
so a 507 tells a stranger nothing about a mailbox. Nothing new is stored to count: the counts
|
||||||
|
come from §5's own rows and `size`. A client treats 507 like any failure and tries again later.
|
||||||
|
- **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.
|
- A refusal has no body.
|
||||||
- The relay prints no request.
|
- 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/protocol/tests/wire.rs`.
|
||||||
|
|||||||
@@ -21,6 +21,13 @@
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
# The relay on NixOS: loopback only, behind Caddy with TLS and no logs (deploy/nixos).
|
||||||
|
nixosModules.default = import ./deploy/nixos/module.nix { inherit self; };
|
||||||
|
|
||||||
|
# A VM test that the server keeps no client address anywhere (needs Linux and KVM).
|
||||||
|
checks.x86_64-linux.relay-keeps-no-address =
|
||||||
|
import ./deploy/nixos/test.nix { inherit self; pkgs = nixpkgs.legacyPackages.x86_64-linux; };
|
||||||
|
|
||||||
devShells = forAll (pkgs: {
|
devShells = forAll (pkgs: {
|
||||||
default = pkgs.mkShell {
|
default = pkgs.mkShell {
|
||||||
packages = with pkgs; [ cargo rustc clippy rustfmt ];
|
packages = with pkgs; [ cargo rustc clippy rustfmt ];
|
||||||
|
|||||||
Reference in New Issue
Block a user