Compare commits

...

13 Commits

Author SHA1 Message Date
mnovak 2215e8d431 [client] Calls: merge feature/call-kinds — four MLS kinds and the call key; coturn in the NixOS module; Caddy's global logger mkDefault; v0.3.0; client 87, protocol 21, relay 57; Nix checks green r1grtnrqrb580 (review in PR #28)
ci / check (push) Failing after 45s
2026-12-03 10:05:41 +01:00
mnovak 1b15845c97 [deploy] Calls: the VM test takes uclient's refusal in either of its words
ci / check (pull_request) Failing after 52s
2026-12-03 09:56:20 +01:00
mnovak 3c10691574 [deploy] Calls: the VM test reads uclient's last count, its total 2026-12-03 09:44:50 +01:00
mnovak de1e8219ce [deploy] Calls: the VM test shows turnutils_uclient's output when it fails 2026-12-03 09:43:17 +01:00
mnovak 7c6a1680af [client] Calls: four MLS kinds (call, callAnswer, callIce, callEnd) with the frame key in the offer; coturn in the NixOS module; Caddy's global logger mkDefault; v0.3.0 2026-12-03 09:20:13 +01:00
mnovak cb7cbd4941 [relay] Calls: rustfmt the long-poll and TURN code of v0.2.0 (no change in behaviour) 2026-12-03 09:20:13 +01:00
mnovak 7a2b8252da [relay] Calls: merge feature/calls-relay — long-poll, TURN credentials, wakes every 10 s, v0.2.0; relay 57, client 76, protocol 20; Nix checks green (review in PR #27)
ci / check (push) Failing after 10s
2026-12-03 01:31:05 +01:00
mnovak 09b1ac3ec7 [repo] Calls: version 0.2.0 (the long-poll, TURN credentials, wakes every 10 s)
ci / check (pull_request) Failing after 42s
2026-12-03 00:42:28 +01:00
mnovak 776e4ce39b [relay] Calls: a long-poll on the fetch route, TURN credentials for coturn, wakes every 10 s; the module passes the TURN secret by systemd credential 2026-12-03 00:29:07 +01:00
mnovak 1e2eed8e5b [repo] F23: merge feature/nix-check — the relay's Nix checks on the hub (package and VM test, both green), version 0.1.0, deploy notes (review in PR #26)
ci / check (push) Failing after 13s
2026-12-02 23:51:43 +01:00
mnovak 308e63999b [repo] F23: version 0.1.0 for the first deployed relay; how to deploy it from a tag, check it and roll it back
ci / check (pull_request) Failing after 54s
2026-12-02 23:25:37 +01:00
mnovak f1e1f6e8d8 [repo] F23: the relay's Nix checks on the hub's NixOS runner (package and VM test); the flake's licence is CPAL-1.0 2026-12-02 23:02:06 +01:00
mnovak 60d07a340b [repo] Licence: merge chore/cpal-network-use — CPAL-1.0 section 15, the source on the invite page (review in PR #25)
ci / check (push) Has been cancelled
2026-11-23 00:37:49 +01:00
26 changed files with 2001 additions and 42 deletions
+97
View File
@@ -0,0 +1,97 @@
# Calls, the client's part: four MLS kinds and the call's frame key
Designed 2026-12-03 for Amicitia F36 (`amicitia/.agents/features/calls.md`), after the relay's part
(`calls-relay.md`, v0.2.0). This change adds the call's own messages to the client, plus the coturn server
that `calls-relay.md` §2 designed for the NixOS module.
## 1. Why and what
A call is set up by two apps exchanging an offer, an answer and network candidates (WebRTC's SDP and ICE), and it
ends with one line in the chat (*Call, 23 min* or *Missed call*). These go **inside MLS**, like texts, so the relay
sees only sealed blobs of the usual sizes. The SDP carries each side's DTLS fingerprint, so no TURN server or relay
can sit in the middle of the media's DTLS handshake.
Four kinds (`docs/PROTOCOL.md` §4):
| `kind` | Fields | Meaning |
| :-- | :-- | :-- |
| `call` | `id`, `video`, `sdp`, `key`, `at` | an offer: `id` 16 random bytes made by the caller; `sdp` 1 byte to 16 KiB; `key` the call's 32-byte frame key; `at` the caller's clock in Unix seconds. No `seq` |
| `callAnswer` | `id`, `sdp` | the answer to the receiver's own offer `id`. No `seq` |
| `callIce` | `id`, `candidates` | 0–32 ICE candidates for `id`, each 1–512 bytes without control characters; an empty list says *no more*. No `seq` |
| `callEnd` | `id`, `seq`, `reason`, `seconds` | the call is over: `reason` is `hangUp`, `declined`, `busy`, `missed` or `failed`; `seconds` 0–86 400 it lasted. **A message** (it shares `seq` with `text`): the one line a call leaves |
Only `callEnd` has a `seq`, so an older client shows *update the app* for it and drops the other three without a
trace. Such a client cannot answer, so the caller sees no answer and ends the call as *missed*.
## 2. Design
```mermaid
sequenceDiagram
participant A as caller's client
participant R as relay
participant B as callee's client
A->>A: offer_call(contact, video, sdp, now) → id, key
A->>R: call {id, video, sdp, key, at}
R->>B: (fetched, long-poll)
B->>B: Event::CallOffered: the app rings, if `at` is recent
B->>R: callAnswer {id, sdp} · callIce {id, candidates} (both ways)
R->>A: Event::CallAnswered, Event::CallCandidates
Note over A,B: media over TURN: DTLS-SRTP, each frame sealed under `key` by the app
A->>R: callEnd {id, seq, reason, seconds}
R->>B: Event::CallEnded (the chat's line)
```
- **The frame key travels in the offer.** The F36 design derived it from the MLS exporter. Instead the caller's
client makes 32 random bytes and sends them inside the MLS-sealed `call`. It is equally secret (only the two
members can open the message), it is post-quantum exactly when MLS is, and it does not depend on both sides being
in the same MLS epoch: an exporter key would silently differ if one side had processed a commit the other had not
(a key update, a later move to a post-quantum suite, a second device). `CallKey`'s `Debug` prints nothing.
- **Live calls, in memory only.** The client remembers the calls in progress: their id, contact, whether they are
ours, and whether they have been answered. At most 8, the oldest forgotten first. A restart forgets them, so an
answer or candidates for a call the app no longer knows are dropped; that call has failed anyway.
- `call`: dropped if its id is already live (on either side), if the contact is blocked, or if it is malformed.
- `callAnswer`: accepted only for **our** live offer to **this** contact that has not been answered yet. A second
answer, an answer to their own offer, or an answer from another contact is dropped.
- `callIce`: accepted only for a live call with this contact.
- `callEnd`: always shown if well formed and the contact is not blocked (a missed call must leave its line even
when the offer was never seen); it ends the live call if there is one. Its `seq` counts for receipts.
- **Sending:** `offer_call`, `answer_call` (only for their live, unanswered offer), `call_candidates` (a live call),
`end_call` (any id: an app that restarted mid-call can still say it ended; a live one is forgotten). All return an
`Outgoing`; nothing reaches the network until the app delivers it, as for texts.
- **Clock.** `at` lets the callee's app show an offer fetched hours later as missed instead of ringing. Clocks
differ; the app should ring only when `at` is within a minute or two of its own clock, and otherwise say *missed*.
The client does not judge it.
- **Two calls crossing** (each calls the other at once): both offers are live, with different ids. The client
reports both; the app keeps one (the lower id) and ends the other as `busy`.
- **New error:** `ClientError::BadCall` (an id that is not live where one must be, an SDP or a candidate outside its
limits, too many candidates).
### coturn in the NixOS module (`calls-relay.md` §2, §4.4)
`services.tabellarius.turn` already has `secretFile` and `urls` (v0.2.0). New: `turn.coturn.enable` runs coturn on
the same host with `use-auth-secret` and the same secret file (read by systemd's `LoadCredential`, never in the Nix
store), `realm` = the relay's domain, listening on 3478 UDP and TCP, relay ports 49152–49999, and **no logs**
(`no-stdout-log`, `log-file=/dev/null`, `simple-log`, `no-cli`), `no-multicast-peers`, `denied-peer-ip` for private,
loopback and link-local ranges (so TURN cannot reach the server's own network), and `no-tls`/`no-dtls` (the media
inside is DTLS-SRTP and frame-sealed; the credentials are HMAC-based). It opens those ports in the firewall.
Caddy's global `logFormat` becomes `lib.mkDefault`, so a host that keeps a global error log (as .217 does) sets it
without `mkForce`.
## 3. Risks
- **Privacy surface:** nothing new reaches the relay: four more kinds of sealed blob. The SDP holds the device's
candidate addresses; it travels only inside MLS, and the app asks ICE for relay candidates only (TURN), so it holds
no local or public address of the device. coturn sees both devices' addresses while a call runs (`calls-relay.md`
§3); it writes none to disk (VM test).
- **Events (Amicitia):** none here; *Log this call* is the app's.
- **Offline:** a call to an unreachable relay fails at delivery, like a text.
- **Abuse:** a contact can only ring you if you accepted their invite; a blocked contact's calls are dropped.
## 4. Verification (tests first)
| Case | Kind | Where |
| :-- | :-- | :-- |
| an offer, its answer, candidates both ways and the end go from one client to the other through a relay; both hold the same key | integration | `client/tests/calls.rs` |
| a second `call` for a live id, an answer to their own offer, a second answer, an answer from another contact, candidates for an unknown id are dropped | integration | `client/tests/calls.rs` |
| `callEnd` for a call never seen still arrives, with its `seq`, and counts for receipts | integration | `client/tests/calls.rs` |
| a blocked contact's offer is dropped | integration | `client/tests/calls.rs` |
| sending: an answer, candidates or an SDP outside the rules give `BadCall`; nothing is sealed | integration | `client/tests/calls.rs` |
| an older client (without the kinds) shows `callEnd` as unsupported and drops the rest | unit | `client/src/lib.rs` |
| every new kind is in `KNOWN_KINDS`; a known call kind with an unknown field is dropped | unit | `client/src/lib.rs` |
| `CallKey`'s `Debug` shows no byte | unit | `protocol/src/lib.rs` |
| the call kinds' SDP, candidates and key never reach the relay's database | integration | `client/tests/real_relay.rs` |
| coturn allocates with the relay's credentials and refuses a wrong password; no client address on the server's disk or journal | NixOS VM | `deploy/nixos/test.nix` |
+61
View File
@@ -0,0 +1,61 @@
# Calls, the relay's part: long-poll, TURN credentials, faster wakes
Designed 2026-12-03 for Amicitia F36 (`amicitia/.agents/features/calls.md`). The call's own messages (offer, answer,
ICE, end) are MLS application kinds in the client, a separate change; this one is what the relay must do.
## 1. Why and what
A call must ring within about a second and get through any NAT without either side learning the other's address.
- **Long-poll.** `GET /v0/mailboxes/{id}/blobs?wait=N` (N in seconds, at most 25): if nothing is waiting, the relay
holds the request until a blob arrives for that mailbox or N seconds pass, then answers as today. Without `wait`
nothing changes.
- **TURN credentials.** `POST /v0/mailboxes/{id}/turn` with the mailbox's fetch token answers
`{username, password, ttl, urls}` in the TURN REST API's form (coturn `use-auth-secret`): `username` is
`<expiry>:<random>`, `password` is base64(HMAC-SHA1(secret, username)), valid 10 minutes. The relay and the TURN
server share one secret; a relay started without `--turn-secret-file` answers 404.
- **Wakes every 10 s at most per mailbox** (was 60 s), so a call right after a message still wakes a closed app.
## 2. Design
```mermaid
flowchart LR
c[client] -->|"GET …/blobs?wait=25 (fetch token)"| r[relay]
p[sender] -->|"POST …/blobs (post token)"| r
r -. "in-memory notify, per mailbox" .-> r
c -->|"POST …/turn (fetch token)"| r -->|"username, password, urls"| c
c -->|"TURN allocate (username, password)"| t[coturn]
r -. "shared secret, never sent" .- t
```
- **Arrivals** (`relay/src/arrivals.rs`): a map from mailbox id to a `tokio::sync::Notify`, **in memory only**, an entry
only while someone waits. The waiter registers before it reads the store, so a blob posted between the read and
the wait is never missed. At most 1 024 waiters relay-wide; one more is answered at once, as without `wait`.
The token is checked first: a wrong token is 404 at once, never held.
- **TURN** (`relay/src/turn.rs`): the secret is read once at start from a file (Custos on the server writes it);
never logged, never sent. At most 30 credentials per mailbox per hour, counted in memory (a map pruned as it
grows); one more is 429. The answer names no mailbox. `urls` come from `--turn-url` (repeatable), e.g.
`turn:turn.marek-novak.cz:3478?transport=udp`.
- **The NixOS module** gains `services.tabellarius.turn = { enable; domain; secretFile; }`. Enabled, it also runs
**coturn** with `use-auth-secret`, the same secret, `no-cli`, `no-tcp-relay` off, a relay port range, and **no
log** (`log-file=/dev/null`, `no-stdout-log`, `simple-log`, syslog off), and opens 3478 (UDP and TCP) and the
relay ports. TURN over TLS (5349) is left out: the media inside is DTLS-SRTP and frame-encrypted already, and the
TURN credentials are HMAC-based, never sent in clear.
## 3. Risks
- **Privacy surface.** The relay learns *this mailbox wants TURN now* (it already sees each mailbox's fetches and
their timing), and that a client is online while a long-poll is held. Nothing new is stored (§5 unchanged); the
waiter map and the TURN counters live in memory only, like the wake times (PROTOCOL.md §5). coturn sees both
devices' IP addresses during a call — said to users on the first call (Amicitia `calls.md`); the VM test proves
coturn writes no address to disk.
- **Abuse.** Held connections are capped; TURN credentials are per mailbox, rate-limited and short-lived; coturn
relays only for valid HMAC credentials and denies relaying to private ranges (`denied-peer-ip`).
- **Reproducibility.** One new crate, `sha1` (RustCrypto), for coturn's HMAC-SHA1; `hmac` is already in the tree.
## 4. Tests — written first
1. A long-poll answers within 1 s of a post to its mailbox; with nothing posted it answers empty after `wait`; a
post to *another* mailbox does not wake it; a wrong token is 404 without waiting; `wait` over 25 is held 25 s at
most (clock: real, short waits); the 1 025th waiter is answered at once.
2. TURN: without the secret, 404; with it and a right fetch token, a pair whose password is the HMAC-SHA1 of the
username under the secret and whose expiry is now + 600; a wrong token 404; the 31st in an hour 429; the
relay's database is byte-identical before and after (nothing stored).
3. Wakes: a mailbox is woken again after 10 s, not within them.
4. The NixOS VM test: with `turn.enable`, the client gets credentials from the relay and allocates on coturn with
them (`turnutils_uclient`); a wrong password is refused; afterwards the client's address appears nowhere on the
server's disk or journal.
+29 -3
View File
@@ -52,7 +52,9 @@ flowchart LR
module writes an access log per host by default; the host's `logFormat` is set to 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 `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 name a client address, so no log is the rule; an operator who needs one turns it on and knows
why. Headers: none added. why. Headers: none added. *(2026-12-03)* The default logger is every site's on the machine, so the module sets
it with `lib.mkDefault`: a host that serves other sites may keep a global error log (.217 sets
`"level ERROR"`). Such a log can then hold a client's address in a rare TLS-handshake error for the relay's name.
- **journald:** the relay prints one line at start. Nothing per request. - **journald:** the relay prints one line at start. Nothing per request.
### The VM test (`deploy/nixos/test.nix`, `nix flake check`) ### The VM test (`deploy/nixos/test.nix`, `nix flake check`)
@@ -61,8 +63,32 @@ Two machines: `server` with the module (TLS from Caddy's internal CA instead of
mistake (a wrong token, a malformed request), and fills a mailbox to its 507. Then the test greps 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. 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 on the hub (2026-12-02).** `.fabrica/artifex/nix-check.yaml` builds the package (with the crates' tests) and
run with `nix flake check` on Linux, and the PR says so. Mark's server is the first real run. runs this VM test on Fabrica's NixOS runner. First run r54ed0gn5tcqs at f1e1f6e: package 11 min, VM test 10 min,
both exit 0. Run it again on every change to `deploy/`, `crates/relay` or `flake.nix`, and before every deploy.
### Deploying on the home server (2026-12-02)
The relay is deployed by the server's operator from a **tag** of this repository, never from a branch: the flake
input pins the tag, so the code that runs is the code tagged and published (`docs/VERIFY.md`).
- **The flake input:** `tabellarius.url = "git+https://gitea.marek-novak.cz/mnovak/Amicitia-Tabellarius.git?ref=refs/tags/vX.Y.Z";`
and `imports = [ tabellarius.nixosModules.default ];`.
- **The service:** `services.tabellarius = { enable = true; domain = "<name>"; };` The caps keep their defaults
(1 GiB of waiting blobs, 100 000 mailboxes, 10 000 invites); `wake = true` (UnifiedPush wake-ups, F25b).
- **The proxy:** the module turns on `services.caddy` with one virtual host. On a server whose Caddy is already
the NixOS module, it is one more host in the same Caddy; a server with another proxy on 443 must proxy the
name to `127.0.0.1:8470` itself, with no access log and without `X-Forwarded-For`, `X-Real-IP` and `Forwarded`.
- **DNS and TLS:** one A/AAAA name for the relay. Caddy gets its certificate by HTTP-01, so port 80 must reach it.
- **After deploying:** `curl -s https://<name>/version` answers the relay's version, and `https://<name>/join` serves the join page; `journalctl -u
tabellarius` shows the one start line and nothing per request; no file under `/var/log` names a client.
- **Calls (v0.3.0, `call-kinds.md`):** a secret file outside the store, written by Custos (32 random bytes, base64,
one line), then `turn.secretFile = "<path>"`, `turn.urls = [ "turn:<name>:3478?transport=udp"
"turn:<name>:3478?transport=tcp" ]` and `turn.coturn.enable = true`. coturn runs on the same machine with the
same secret and no log. Behind NAT: `turn.coturn.externalIp = "<public>/<this machine's LAN address>"`, and the
router forwards 3478 (UDP and TCP) and 49152–49999 (UDP) to it. The relay answers `POST /v0/mailboxes/{id}/turn`
only once `secretFile` is set. Check: `systemctl status coturn`, `ss -lun 'sport = :3478'`, and from outside
`turnutils_uclient` with a pair from the relay.
- **Rollback:** point the input at the previous tag and switch. The database (`/var/lib/tabellarius/relay.db`)
keeps only waiting ciphertext; it stays across versions unless `docs/PROTOCOL.md` says otherwise.
## 3. Risks ## 3. Risks
- **Privacy:** the logs are the risk this feature exists to close. The VM test is its proof, once - **Privacy:** the logs are the risk this feature exists to close. The VM test is its proof, once
+16
View File
@@ -0,0 +1,16 @@
# Tabellarius: the relay's Nix checks on the hub's NixOS runner (F23, .agents/features/home-relay.md). By hand only
# (Artifex → nix-check, or the hub's POST /api/runs with pipeline nix-check and a ref), on every branch that touches
# deploy/, crates/relay or flake.nix, and always before the relay is deployed or updated on the server. It builds and
# switches nothing on the server: the package is a sandboxed build (with the crates' tests), the VM test runs in
# its own VMs (a server with the module behind Caddy, a client that uses every route and checks that no client
# address is kept anywhere).
name: nix-check
on:
manual: true
runner: nixos
steps:
- id: package
nix: .#packages.x86_64-linux.default
- id: relay-keeps-no-address
needs: [package]
nix: .#checks.x86_64-linux.relay-keeps-no-address
Generated
+45 -3
View File
@@ -66,6 +66,7 @@ checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [ dependencies = [
"axum-core", "axum-core",
"bytes", "bytes",
"form_urlencoded",
"futures-util", "futures-util",
"http", "http",
"http-body", "http-body",
@@ -81,6 +82,7 @@ dependencies = [
"serde_core", "serde_core",
"serde_json", "serde_json",
"serde_path_to_error", "serde_path_to_error",
"serde_urlencoded",
"sync_wrapper", "sync_wrapper",
"tokio", "tokio",
"tower", "tower",
@@ -684,6 +686,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "form_urlencoded"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
[[package]] [[package]]
name = "futures-core" name = "futures-core"
version = "0.3.34" version = "0.3.34"
@@ -2033,6 +2044,12 @@ dependencies = [
"wait-timeout", "wait-timeout",
] ]
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]] [[package]]
name = "sec1" name = "sec1"
version = "0.7.3" version = "0.7.3"
@@ -2117,6 +2134,29 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "sha1"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]] [[package]]
name = "sha2" name = "sha2"
version = "0.10.9" version = "0.10.9"
@@ -2297,7 +2337,7 @@ checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
[[package]] [[package]]
name = "tabellarius-client" name = "tabellarius-client"
version = "0.0.0" version = "0.3.0"
dependencies = [ dependencies = [
"axum", "axum",
"base64 0.22.1", "base64 0.22.1",
@@ -2318,7 +2358,7 @@ dependencies = [
[[package]] [[package]]
name = "tabellarius-protocol" name = "tabellarius-protocol"
version = "0.0.0" version = "0.3.0"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"proptest", "proptest",
@@ -2329,15 +2369,17 @@ dependencies = [
[[package]] [[package]]
name = "tabellarius-relay" name = "tabellarius-relay"
version = "0.0.0" version = "0.3.0"
dependencies = [ dependencies = [
"axum", "axum",
"base64 0.22.1", "base64 0.22.1",
"getrandom 0.3.4", "getrandom 0.3.4",
"hmac 0.12.1",
"http-body-util", "http-body-util",
"rusqlite", "rusqlite",
"serde", "serde",
"serde_json", "serde_json",
"sha1",
"sha2 0.10.9", "sha2 0.10.9",
"subtle", "subtle",
"tabellarius-protocol", "tabellarius-protocol",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/protocol", "crates/client", "crates/relay"] members = ["crates/protocol", "crates/client", "crates/relay"]
[workspace.package] [workspace.package]
version = "0.0.0" version = "0.3.0"
edition = "2021" edition = "2021"
publish = false publish = false
+473 -2
View File
@@ -24,7 +24,7 @@ pub use files::{
chunks_for, FileRef, FileUpload, FILE_CHUNK_PLAIN, MAX_FILE_BYTES, MAX_FILE_NAME_CHARS, chunks_for, FileRef, FileUpload, FILE_CHUNK_PLAIN, MAX_FILE_BYTES, MAX_FILE_NAME_CHARS,
MAX_MIME_BYTES, MAX_THUMB_BYTES, MAX_MIME_BYTES, MAX_THUMB_BYTES,
}; };
pub use tabellarius_protocol::{FileId, FILE_CHUNK_BYTES, MAX_FILE_CHUNKS}; pub use tabellarius_protocol::{CallId, CallKey, FileId, FILE_CHUNK_BYTES, MAX_FILE_CHUNKS};
mod snapshot; mod snapshot;
pub use snapshot::SNAPSHOT_VERSION; pub use snapshot::SNAPSHOT_VERSION;
@@ -59,8 +59,18 @@ pub const MAX_POLL_OPTIONS: usize = 10;
pub const MAX_OPTION_CHARS: usize = 100; pub const MAX_OPTION_CHARS: usize = 100;
/// The longest poll question, in characters. /// The longest poll question, in characters.
pub const MAX_QUESTION_CHARS: usize = 300; pub const MAX_QUESTION_CHARS: usize = 300;
/// The longest SDP in a call's offer or answer, in bytes (`.agents/features/call-kinds.md`).
pub const MAX_SDP_BYTES: usize = 16 * 1024;
/// The most ICE candidates in one `callIce`.
pub const MAX_CANDIDATES: usize = 32;
/// The longest ICE candidate, in bytes.
pub const MAX_CANDIDATE_BYTES: usize = 512;
/// The longest call a `callEnd` reports, in seconds (a day).
pub const MAX_CALL_SECONDS: u32 = 86_400;
/// How many calls in progress the client remembers, in memory only; the oldest is forgotten first.
pub const MAX_LIVE_CALLS: usize = 8;
/// The payload kinds this client knows; any other kind that carries a `seq` is `Unsupported`. /// The payload kinds this client knows; any other kind that carries a `seq` is `Unsupported`.
const KNOWN_KINDS: [&str; 9] = [ const KNOWN_KINDS: [&str; 13] = [
"hello", "hello",
"text", "text",
"receipt", "receipt",
@@ -70,6 +80,10 @@ const KNOWN_KINDS: [&str; 9] = [
"vote", "vote",
"pollClose", "pollClose",
"file", "file",
"call",
"callAnswer",
"callIce",
"callEnd",
]; ];
const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox"; const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox";
@@ -105,6 +119,10 @@ pub enum ClientError {
FileDamaged, FileDamaged,
/// 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,
/// A call that cannot be sent: an answer to anything but their live, unanswered offer, candidates
/// for a call that is not live, an SDP or a candidate outside its limits, too many candidates, or
/// a `callEnd` over [`MAX_CALL_SECONDS`].
BadCall,
} }
impl From<TransportError> for ClientError { impl From<TransportError> for ClientError {
@@ -201,6 +219,58 @@ pub enum Event {
/// The other side's app has saved our texts up to `upto` (a `seq` from /// 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`]). /// [`Client::sent_seq`]). Only while receipts are on ([`Client::set_receipts`]).
Delivered { contact: ContactId, upto: u64 }, Delivered { contact: ContactId, upto: u64 },
/// The contact rings: an offer with its SDP and the call's frame key. `at` is the caller's clock
/// (Unix seconds): ring only when it is recent, else show the call as missed.
CallOffered {
contact: ContactId,
id: CallId,
video: bool,
sdp: String,
key: CallKey,
at: i64,
},
/// The contact answered our live offer `id`.
CallAnswered {
contact: ContactId,
id: CallId,
sdp: String,
},
/// ICE candidates for the live call `id`; an empty list says there are no more.
CallCandidates {
contact: ContactId,
id: CallId,
candidates: Vec<String>,
},
/// A call is over: the one line it leaves in the chat (a message: `seq` names it, like a text's).
/// Arrives even for an offer this client never saw.
CallEnded {
contact: ContactId,
id: CallId,
seq: u64,
reason: CallEndReason,
seconds: u32,
},
}
/// Why a call ended, as its `callEnd` says.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CallEndReason {
HangUp,
Declined,
Busy,
Missed,
Failed,
}
/// A call in progress, remembered in memory only (`.agents/features/call-kinds.md` §2).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct LiveCall {
contact: ContactId,
id: CallId,
/// We made the offer.
ours: bool,
answered: bool,
} }
/// One operation for the relay, to deliver once the app has saved the snapshot: a blob to post, /// One operation for the relay, to deliver once the app has saved the snapshot: a blob to post,
@@ -380,6 +450,36 @@ enum Payload {
/// A new post token for the mailbox the receiver already knows (unblock). /// A new post token for the mailbox the receiver already knows (unblock).
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Inbox { post_token: Token }, Inbox { post_token: Token },
/// A call's offer (`.agents/features/call-kinds.md`). No `seq`.
Call {
id: CallId,
video: bool,
sdp: String,
key: CallKey,
at: i64,
},
/// The answer to the receiver's offer `id`. No `seq`.
CallAnswer { id: CallId, sdp: String },
/// ICE candidates for `id`; `[]` says no more. No `seq`.
CallIce { id: CallId, candidates: Vec<String> },
/// The call is over: a message, sharing the sender's `seq` with texts.
CallEnd {
id: CallId,
seq: u64,
reason: CallEndReason,
seconds: u32,
},
}
fn sdp_ok(sdp: &str) -> bool {
!sdp.is_empty() && sdp.len() <= MAX_SDP_BYTES
}
fn candidates_ok(candidates: &[String]) -> bool {
candidates.len() <= MAX_CANDIDATES
&& candidates.iter().all(|c| {
!c.is_empty() && c.len() <= MAX_CANDIDATE_BYTES && !c.chars().any(char::is_control)
})
} }
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -427,6 +527,8 @@ pub struct Client<T: Transport> {
next_contact: u32, next_contact: u32,
/// Send receipts and report the other side's (reciprocal). On by default. /// Send receipts and report the other side's (reciprocal). On by default.
receipts: bool, receipts: bool,
/// Calls in progress: in memory only, never in a snapshot.
calls: Vec<LiveCall>,
} }
impl<T: Transport> Client<T> { impl<T: Transport> Client<T> {
@@ -457,6 +559,7 @@ impl<T: Transport> Client<T> {
welcome_boxes: Vec::new(), welcome_boxes: Vec::new(),
next_contact: 0, next_contact: 0,
receipts: true, receipts: true,
calls: Vec::new(),
}) })
} }
@@ -680,6 +783,137 @@ impl<T: Transport> Client<T> {
Ok(Outgoing::post(to, post, blob)) Ok(Outgoing::post(to, post, blob))
} }
/// Seals `payload` for a contact whose `hello` has arrived.
fn seal_for(&mut self, index: usize, payload: &Payload) -> Result<Outgoing, ClientError> {
let c = &mut self.contacts[index];
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let blob = Self::seal(&self.provider, &self.signer, &mut c.group, payload)?;
Ok(Outgoing::post(to, post, blob))
}
fn live_call(&self, contact: ContactId, id: CallId) -> Option<usize> {
self.calls
.iter()
.position(|c| c.contact == contact && c.id == id)
}
fn remember_call(&mut self, call: LiveCall) {
if self.calls.len() >= MAX_LIVE_CALLS {
self.calls.remove(0);
}
self.calls.push(call);
}
/// Rings a contact: a new call's id and frame key, and the offer to deliver. `sdp` is the app's
/// WebRTC offer; `now` its clock in Unix seconds. No network (`.agents/features/call-kinds.md`).
pub fn offer_call(
&mut self,
contact: ContactId,
video: bool,
sdp: &str,
now: i64,
) -> Result<(CallId, CallKey, Outgoing), ClientError> {
if !sdp_ok(sdp) {
return Err(ClientError::BadCall);
}
let index = self.index_of(contact)?;
let id = CallId::from_bytes(self.random()?);
let key = CallKey::from_bytes(self.random()?);
let out = self.seal_for(
index,
&Payload::Call {
id,
video,
sdp: sdp.to_string(),
key,
at: now,
},
)?;
self.remember_call(LiveCall {
contact,
id,
ours: true,
answered: false,
});
Ok((id, key, out))
}
/// Answers the contact's live offer `id`, once ([`ClientError::BadCall`] otherwise).
pub fn answer_call(
&mut self,
contact: ContactId,
id: CallId,
sdp: &str,
) -> Result<Outgoing, ClientError> {
let index = self.index_of(contact)?;
let live = self
.live_call(contact, id)
.filter(|&i| !self.calls[i].ours && !self.calls[i].answered)
.ok_or(ClientError::BadCall)?;
if !sdp_ok(sdp) {
return Err(ClientError::BadCall);
}
let out = self.seal_for(
index,
&Payload::CallAnswer {
id,
sdp: sdp.to_string(),
},
)?;
self.calls[live].answered = true;
Ok(out)
}
/// ICE candidates for the live call `id`, at most [`MAX_CANDIDATES`]; `[]` says no more.
pub fn call_candidates(
&mut self,
contact: ContactId,
id: CallId,
candidates: &[String],
) -> Result<Outgoing, ClientError> {
let index = self.index_of(contact)?;
if self.live_call(contact, id).is_none() || !candidates_ok(candidates) {
return Err(ClientError::BadCall);
}
self.seal_for(
index,
&Payload::CallIce {
id,
candidates: candidates.to_vec(),
},
)
}
/// Ends a call, live or not (an app restarted mid-call can still say so): the chat's line for
/// it, with its `seq`, and the message to deliver. A live call is forgotten.
pub fn end_call(
&mut self,
contact: ContactId,
id: CallId,
reason: CallEndReason,
seconds: u32,
) -> Result<(u64, Outgoing), ClientError> {
if seconds > MAX_CALL_SECONDS {
return Err(ClientError::BadCall);
}
let index = self.index_of(contact)?;
let seq = self.contacts[index].sent_seq + 1;
let out = self.seal_for(
index,
&Payload::CallEnd {
id,
seq,
reason,
seconds,
},
)?;
self.contacts[index].sent_seq = seq;
if let Some(i) = self.live_call(contact, id) {
self.calls.remove(i);
}
Ok((seq, out))
}
/// Our reaction to a message in this conversation: `Some(emoji)` sets it (replacing our /// 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. /// earlier one), `None` removes it. No network: save the snapshot, then deliver.
pub fn react( pub fn react(
@@ -1467,6 +1701,95 @@ impl<T: Transport> Client<T> {
c.outbox = Some((mailbox, post_token)); c.outbox = Some((mailbox, post_token));
Ok(None) Ok(None)
} }
Payload::Call {
id,
video,
sdp,
key,
at,
} => {
let c = &self.contacts[index];
if c.name.is_none() {
return Err(ClientError::Mls);
}
let contact = c.id;
// A second offer under a live id (on either side) is not a new call.
if c.blocked || !sdp_ok(&sdp) || self.calls.iter().any(|l| l.id == id) {
return Ok(None);
}
self.remember_call(LiveCall {
contact,
id,
ours: false,
answered: false,
});
Ok(Some(Event::CallOffered {
contact,
id,
video,
sdp,
key,
at,
}))
}
Payload::CallAnswer { id, sdp } => {
let c = &self.contacts[index];
if c.name.is_none() {
return Err(ClientError::Mls);
}
let contact = c.id;
// Only our own offer to this contact, answered once.
let live = self
.live_call(contact, id)
.filter(|&i| self.calls[i].ours && !self.calls[i].answered);
let (false, Some(live), true) = (c.blocked, live, sdp_ok(&sdp)) else {
return Ok(None);
};
self.calls[live].answered = true;
Ok(Some(Event::CallAnswered { contact, id, sdp }))
}
Payload::CallIce { id, candidates } => {
let c = &self.contacts[index];
if c.name.is_none() {
return Err(ClientError::Mls);
}
let contact = c.id;
if c.blocked || !candidates_ok(&candidates) || self.live_call(contact, id).is_none()
{
return Ok(None);
}
Ok(Some(Event::CallCandidates {
contact,
id,
candidates,
}))
}
Payload::CallEnd {
id,
seq,
reason,
seconds,
} => {
let c = &mut self.contacts[index];
if c.name.is_none() {
return Err(ClientError::Mls);
}
if c.blocked || seq == 0 || seconds > MAX_CALL_SECONDS {
return Ok(None);
}
c.received_seq = c.received_seq.max(seq);
let contact = c.id;
if let Some(i) = self.live_call(contact, id) {
self.calls.remove(i);
}
Ok(Some(Event::CallEnded {
contact,
id,
seq,
reason,
seconds,
}))
}
} }
} }
} }
@@ -2282,6 +2605,133 @@ mod tests {
/// Every kind this client sends is in `KNOWN_KINDS`: a variant left out would arrive as /// Every kind this client sends is in `KNOWN_KINDS`: a variant left out would arrive as
/// *Unsupported* at a client of the same version. /// *Unsupported* at a client of the same version.
// Calls (`.agents/features/call-kinds.md` §2): what a misbehaving or older client could send.
const ID: &str = "AgICAgICAgICAgICAgICAg"; // [2; 16]
const KEY: &str = "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM"; // [3; 32]
fn call_json(kind: &str, rest: &str) -> String {
format!(r#"{{"kind":"{kind}","id":"{ID}"{rest}}}"#)
}
fn offer() -> String {
call_json(
"call",
&format!(r#","video":false,"sdp":"v=0","key":"{KEY}","at":1"#),
)
}
fn receive_all(c: &mut Client<MemoryTransport>) -> Vec<Event> {
c.receive().expect("receive").events
}
#[test]
fn a_second_offer_under_a_live_id_and_answers_that_are_not_to_our_offer_are_dropped() {
let (mut eva, mut jan) = paired();
// Jan rings twice under one id: the second is not a new call.
for _ in 0..2 {
let out = seal_raw(&mut jan, &offer());
jan.deliver(&out).expect("deliver");
}
let got = receive_all(&mut eva);
assert_eq!(got.len(), 1, "{got:?}");
// Jan "answers" his own offer: Eva did not make it, so it is dropped.
let answer = call_json("callAnswer", r#","sdp":"v=0""#);
let out = seal_raw(&mut jan, &answer);
jan.deliver(&out).expect("deliver");
assert!(receive_all(&mut eva).is_empty());
// Eva's own offer, answered twice: the second is dropped.
let (id, _, out) = eva
.offer_call(eva.contacts[0].id, false, "v=0", 1)
.expect("offer");
eva.deliver(&out).expect("deliver");
jan.receive().expect("receive");
let answer = call_json("callAnswer", r#","sdp":"v=0""#).replace(ID, &id.to_wire());
for _ in 0..2 {
let out = seal_raw(&mut jan, &answer);
jan.deliver(&out).expect("deliver");
}
assert_eq!(receive_all(&mut eva).len(), 1);
// An answer from another contact: the live call belongs to someone else.
let (id, _, _) = eva
.offer_call(eva.contacts[0].id, false, "v=0", 1)
.expect("offer");
eva.calls.last_mut().expect("live").contact = ContactId(99);
let answer = call_json("callAnswer", r#","sdp":"v=0""#).replace(ID, &id.to_wire());
let out = seal_raw(&mut jan, &answer);
jan.deliver(&out).expect("deliver");
assert!(receive_all(&mut eva).is_empty());
}
#[test]
fn malformed_call_kinds_are_dropped_and_an_unknown_field_drops_a_known_kind() {
let (mut eva, mut jan) = paired();
let many = format!(r#","candidates":[{}]"#, vec![r#""c""#; 33].join(","));
for json in [
call_json(
"call",
&format!(r#","video":false,"sdp":"","key":"{KEY}","at":1"#),
),
call_json(
"call",
&format!(r#","video":false,"sdp":"v=0","key":"{KEY}","at":1,"x":1"#),
),
call_json("callIce", r#","candidates":["c"]"#), // no live call
call_json("callEnd", r#","seq":0,"reason":"hangUp","seconds":1"#),
call_json("callEnd", r#","seq":1,"reason":"hangUp","seconds":86401"#),
call_json("callEnd", r#","seq":1,"reason":"shrug","seconds":1"#),
] {
let out = seal_raw(&mut jan, &json);
jan.deliver(&out).expect("deliver");
assert!(receive_all(&mut eva).is_empty(), "{json}");
}
let out = seal_raw(&mut jan, &offer());
jan.deliver(&out).expect("deliver");
assert_eq!(receive_all(&mut eva).len(), 1);
for json in [
call_json("callIce", &many),
call_json(
"callIce",
r#","candidates":["a
b"]"#,
),
call_json("callIce", r#","candidates":[""]"#),
] {
let out = seal_raw(&mut jan, &json);
jan.deliver(&out).expect("deliver");
assert!(receive_all(&mut eva).is_empty(), "{json}");
}
}
#[test]
fn only_call_end_carries_a_seq_so_an_older_client_shows_it_and_drops_the_rest() {
for (json, seq) in [
(offer(), None),
(call_json("callAnswer", r#","sdp":"v=0""#), None),
(call_json("callIce", r#","candidates":[]"#), None),
(
call_json("callEnd", r#","seq":5,"reason":"missed","seconds":0"#),
Some(5),
),
] {
let value: serde_json::Value = serde_json::from_str(&json).expect("json");
assert_eq!(
value.get("seq").and_then(serde_json::Value::as_u64),
seq,
"{json}"
);
// What a client without these kinds does with it: the rule for unknown kinds.
let older = json.replace(r#""kind":"call"#, r#""kind":"futureCall"#);
let parsed = parse_payload(older.as_bytes());
match seq {
Some(s) => assert!(
matches!(parsed, Ok(Parsed::Unknown { seq }) if seq == s),
"{older}"
),
None => assert!(parsed.is_err(), "{older}"),
}
}
}
#[test] #[test]
fn every_payload_kind_is_known() { fn every_payload_kind_is_known() {
let to = MessageRef { let to = MessageRef {
@@ -2322,6 +2772,27 @@ mod tests {
}], }],
}, },
their_file(3, "a.jpg", "image/jpeg", 10, Some(JPEG.to_vec())), their_file(3, "a.jpg", "image/jpeg", 10, Some(JPEG.to_vec())),
Payload::Call {
id: CallId::from_bytes([2; 16]),
video: true,
sdp: "v=0".into(),
key: CallKey::from_bytes([3; 32]),
at: 1,
},
Payload::CallAnswer {
id: CallId::from_bytes([2; 16]),
sdp: "v=0".into(),
},
Payload::CallIce {
id: CallId::from_bytes([2; 16]),
candidates: vec![],
},
Payload::CallEnd {
id: CallId::from_bytes([2; 16]),
seq: 4,
reason: CallEndReason::Declined,
seconds: 0,
},
]; ];
assert_eq!(all.len(), KNOWN_KINDS.len()); assert_eq!(all.len(), KNOWN_KINDS.len());
for payload in all { for payload in all {
+1
View File
@@ -188,6 +188,7 @@ impl<T: Transport> Client<T> {
welcome_boxes: state.welcome_boxes, welcome_boxes: state.welcome_boxes,
next_contact: state.next_contact, next_contact: state.next_contact,
receipts: state.receipts, receipts: state.receipts,
calls: Vec::new(),
}) })
} }
} }
+308
View File
@@ -0,0 +1,308 @@
//! Calls: the four MLS kinds and the call's key (`.agents/features/call-kinds.md` §4). No I/O: runs on
//! the Android emulator too.
use tabellarius_client::*;
type C = Client<MemoryTransport>;
const OFFER: &str = "v=0\r\no=- 1 2 IN IP4 0.0.0.0\r\na=fingerprint:sha-256 AA:BB\r\n";
const ANSWER: &str = "v=0\r\no=- 3 4 IN IP4 0.0.0.0\r\na=fingerprint:sha-256 CC:DD\r\n";
const NOW: i64 = 1_767_000_000;
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 candidates(n: usize) -> Vec<String> {
(0..n)
.map(|i| format!("candidate:{i} 1 udp 2 192.0.2.{i} 3478 typ relay raddr 0.0.0.0 rport 0"))
.collect()
}
/// Eva rings Jan: the offer is delivered and fetched.
fn ring(eva: &mut C, eva_side: ContactId, jan: &mut C) -> (CallId, CallKey) {
let (id, key, out) = eva.offer_call(eva_side, true, OFFER, NOW).expect("offer");
eva.deliver(&out).expect("deliver");
let events = jan.poll().expect("poll");
assert!(
events
.iter()
.any(|e| matches!(e, Event::CallOffered { id: got, .. } if *got == id)),
"{events:?}"
);
(id, key)
}
#[test]
fn a_call_is_offered_answered_and_ended_and_both_hold_the_same_key() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
let (id, key, out) = eva.offer_call(eva_side, true, OFFER, NOW).expect("offer");
eva.deliver(&out).expect("deliver");
assert_eq!(
jan.poll().expect("poll"),
vec![Event::CallOffered {
contact: jan_side,
id,
video: true,
sdp: OFFER.to_string(),
key,
at: NOW,
}]
);
let out = jan.answer_call(jan_side, id, ANSWER).expect("answer");
jan.deliver(&out).expect("deliver");
let out = jan
.call_candidates(jan_side, id, &candidates(3))
.expect("ice");
jan.deliver(&out).expect("deliver");
assert_eq!(
eva.poll().expect("poll"),
vec![
Event::CallAnswered {
contact: eva_side,
id,
sdp: ANSWER.to_string()
},
Event::CallCandidates {
contact: eva_side,
id,
candidates: candidates(3)
},
]
);
// Eva's candidates, then an empty list: no more.
for list in [candidates(2), Vec::new()] {
let out = eva.call_candidates(eva_side, id, &list).expect("ice");
eva.deliver(&out).expect("deliver");
}
let got = jan.poll().expect("poll");
assert_eq!(got.len(), 2, "{got:?}");
let (seq, out) = eva
.end_call(eva_side, id, CallEndReason::HangUp, 83)
.expect("end");
assert_eq!(seq, 1, "the call's line is Eva's first message");
eva.deliver(&out).expect("deliver");
assert_eq!(
jan.poll().expect("poll"),
vec![Event::CallEnded {
contact: jan_side,
id,
seq: 1,
reason: CallEndReason::HangUp,
seconds: 83
}]
);
// Over on both sides: nothing more can be said about it.
assert_eq!(
jan.call_candidates(jan_side, id, &candidates(1)).err(),
Some(ClientError::BadCall)
);
assert_eq!(
eva.call_candidates(eva_side, id, &candidates(1)).err(),
Some(ClientError::BadCall)
);
}
#[test]
fn every_call_has_its_own_id_and_key() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, _jan, _) = pair(&relay);
let (a, ka, _) = eva.offer_call(eva_side, false, OFFER, NOW).expect("offer");
let (b, kb, _) = eva.offer_call(eva_side, false, OFFER, NOW).expect("offer");
assert_ne!(a, b);
assert_ne!(ka.as_bytes(), kb.as_bytes());
assert_eq!(format!("{ka:?}"), "CallKey(..)", "a key is never printed");
}
#[test]
fn what_is_not_a_live_call_or_breaks_the_limits_is_refused_before_anything_is_sealed() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
let (id, _) = ring(&mut eva, eva_side, &mut jan);
let other = CallId::from_bytes([7; 16]);
// An answer: only to their live offer, once.
assert_eq!(
eva.answer_call(eva_side, id, ANSWER).err(),
Some(ClientError::BadCall),
"her own offer"
);
assert_eq!(
jan.answer_call(jan_side, other, ANSWER).err(),
Some(ClientError::BadCall),
"no such call"
);
assert_eq!(
jan.answer_call(jan_side, id, "").err(),
Some(ClientError::BadCall),
"an empty SDP"
);
jan.answer_call(jan_side, id, ANSWER).expect("answer");
assert_eq!(
jan.answer_call(jan_side, id, ANSWER).err(),
Some(ClientError::BadCall),
"a second answer"
);
// Offers and candidates within their limits.
let long = "a".repeat(16 * 1024 + 1);
assert_eq!(
eva.offer_call(eva_side, true, &long, NOW).err(),
Some(ClientError::BadCall)
);
assert_eq!(
eva.offer_call(eva_side, true, "", NOW).err(),
Some(ClientError::BadCall)
);
assert_eq!(
jan.call_candidates(jan_side, other, &candidates(1)).err(),
Some(ClientError::BadCall)
);
assert_eq!(
jan.call_candidates(jan_side, id, &candidates(33)).err(),
Some(ClientError::BadCall)
);
for bad in ["", "candidate:1\r\na=evil", &"c".repeat(513)] {
assert_eq!(
jan.call_candidates(jan_side, id, &[bad.to_string()]).err(),
Some(ClientError::BadCall),
"{bad:?}"
);
}
assert_eq!(
eva.end_call(eva_side, id, CallEndReason::HangUp, 86_401)
.err(),
Some(ClientError::BadCall)
);
assert_eq!(
relay.waiting_blobs(),
0,
"nothing refused was sealed or sent"
);
}
#[test]
fn a_missed_call_leaves_its_line_even_when_the_offer_never_arrived_and_receipts_cover_it() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
// The offer is made but never delivered (the relay was away); Eva gives up.
let (id, _, _never) = eva.offer_call(eva_side, false, OFFER, NOW).expect("offer");
let (seq, out) = eva
.end_call(eva_side, id, CallEndReason::Missed, 0)
.expect("end");
eva.deliver(&out).expect("deliver");
assert_eq!(
jan.poll().expect("poll"),
vec![Event::CallEnded {
contact: jan_side,
id,
seq,
reason: CallEndReason::Missed,
seconds: 0
}]
);
assert_eq!(
eva.poll().expect("poll"),
vec![Event::Delivered {
contact: eva_side,
upto: seq
}]
);
}
#[test]
fn a_blocked_contacts_call_does_not_ring() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
let (_, _, out) = jan.offer_call(jan_side, true, OFFER, NOW).expect("offer");
jan.deliver(&out).expect("deliver");
let rotate = eva.block(eva_side).expect("block");
eva.deliver(&rotate).expect("rotate");
let events = eva.poll().expect("poll");
assert!(events.is_empty(), "{events:?}");
}
#[test]
fn a_restart_forgets_live_calls_and_a_call_can_still_be_ended() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
let (id, _) = ring(&mut eva, eva_side, &mut jan);
let saved = eva.snapshot().expect("snapshot");
drop(eva);
let mut eva = Client::restore(&saved, relay.clone()).expect("restore");
let out = jan.answer_call(jan_side, id, ANSWER).expect("answer");
jan.deliver(&out).expect("deliver");
let events = eva.poll().expect("poll");
assert!(
events.is_empty(),
"an answer to a call she no longer knows: {events:?}"
);
let (_, out) = eva
.end_call(eva_side, id, CallEndReason::Failed, 0)
.expect("end after a restart");
eva.deliver(&out).expect("deliver");
assert!(matches!(
jan.poll().expect("poll").as_slice(),
[Event::CallEnded {
reason: CallEndReason::Failed,
..
}]
));
}
#[test]
fn at_most_eight_calls_are_live_and_the_oldest_is_forgotten_first() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
let ids: Vec<CallId> = (0..9)
.map(|_| ring(&mut eva, eva_side, &mut jan).0)
.collect();
assert_eq!(
jan.answer_call(jan_side, ids[0], ANSWER).err(),
Some(ClientError::BadCall)
);
jan.answer_call(jan_side, ids[1], ANSWER)
.expect("the second is still live");
jan.answer_call(jan_side, ids[8], ANSWER)
.expect("the last is live");
}
#[test]
fn the_relay_holds_none_of_a_calls_sdp_candidates_or_key() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, _jan, _) = pair(&relay);
let (id, key, out) = eva.offer_call(eva_side, true, OFFER, NOW).expect("offer");
eva.deliver(&out).expect("deliver");
let out = eva
.call_candidates(eva_side, id, &candidates(4))
.expect("ice");
eva.deliver(&out).expect("deliver");
// Before anyone fetches: both are waiting on the relay, sealed.
let held = relay.everything_stored();
let contains = |needle: &[u8]| held.windows(needle.len()).any(|w| w == needle);
for needle in [
&b"fingerprint"[..],
b"192.0.2.",
b"candidate:",
key.as_bytes(),
id.as_bytes(),
] {
assert!(!contains(needle), "the relay holds {needle:?}");
}
}
+30
View File
@@ -247,6 +247,19 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
.compose_poll(jan_side, question, &options, false) .compose_poll(jan_side, question, &options, false)
.expect("poll"); .expect("poll");
jan.deliver(&out).expect("deliver"); jan.deliver(&out).expect("deliver");
// And a call (`.agents/features/call-kinds.md`): its SDP, candidates, id and key neither.
let sdp = "v=0
a=fingerprint:sha-256 SDP-CANARY
";
let (call, key, out) = jan
.offer_call(jan_side, true, sdp, 1_767_000_000)
.expect("offer");
jan.deliver(&out).expect("deliver");
let candidates = vec!["candidate:1 1 udp 2 203.0.113.77 3478 typ relay".to_string()];
let out = jan
.call_candidates(jan_side, call, &candidates)
.expect("ice");
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");
@@ -280,6 +293,19 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
options: options.clone(), options: options.clone(),
multiple: false, multiple: false,
}, },
Event::CallOffered {
contact: eva_side,
id: call,
video: true,
sdp: sdp.into(),
key,
at: 1_767_000_000,
},
Event::CallCandidates {
contact: eva_side,
id: call,
candidates: candidates.clone(),
},
] ]
); );
let after = std::fs::read(&db).expect("db"); let after = std::fs::read(&db).expect("db");
@@ -294,6 +320,10 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
("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()),
("call SDP", b"SDP-CANARY".as_slice()),
("call candidate", b"203.0.113.77".as_slice()),
("call id", call.as_bytes().as_slice()),
("call key", key.as_bytes().as_slice()),
] { ] {
assert!( assert!(
!contains(snapshot, needle), !contains(snapshot, needle),
+41 -3
View File
@@ -27,8 +27,15 @@ pub const INVITE_TTL_SECS: i64 = 7 * 24 * 3600;
pub const MAX_PUSH_ENDPOINT_BYTES: usize = 1000; pub const MAX_PUSH_ENDPOINT_BYTES: usize = 1000;
/// The body of every wake: a constant, so it carries nothing (`PROTOCOL.md` §6). /// The body of every wake: a constant, so it carries nothing (`PROTOCOL.md` §6).
pub const WAKE_BODY: &[u8] = b"wake"; pub const WAKE_BODY: &[u8] = b"wake";
/// A mailbox is woken at most once in this many seconds. /// A mailbox is woken at most once in this many seconds. 10 since 2026-12-03 (was 60), so a call right after a
pub const WAKE_EVERY_SECS: i64 = 60; /// message still wakes a closed app (`.agents/features/calls-relay.md`).
pub const WAKE_EVERY_SECS: i64 = 10;
/// The longest a fetch with `?wait=` is held when nothing is waiting (`calls-relay.md`).
pub const MAX_WAIT_SECS: u64 = 25;
/// How long a TURN credential from `POST /v0/mailboxes/{id}/turn` is valid.
pub const TURN_TTL_SECS: u32 = 600;
/// TURN credentials one mailbox may get in an hour.
pub const TURN_PER_HOUR: u32 = 30;
/// Every file chunk on the wire is exactly this many bytes, the last one too (250 KiB; G41, /// Every file chunk on the wire is exactly this many bytes, the last one too (250 KiB; G41,
/// `.agents/features/files.md` §2.1). /// `.agents/features/files.md` §2.1).
pub const FILE_CHUNK_BYTES: usize = 256_000; pub const FILE_CHUNK_BYTES: usize = 256_000;
@@ -192,6 +199,26 @@ impl fmt::Debug for FileKey {
} }
} }
fixed_bytes!(
/// A call: 16 random bytes made by the caller, naming the call in its four MLS kinds (`PROTOCOL.md`
/// §4, calls). The relay never sees it.
CallId,
16
);
fixed_bytes!(
/// A call's frame key: 32 random bytes made by the caller for one call, travelling only inside the
/// MLS-sealed offer (`PROTOCOL.md` §4, `call`). The app seals every media frame under it.
CallKey,
32
);
// A call key is a secret: never printed.
impl fmt::Debug for CallKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("CallKey(..)")
}
}
impl Token { impl Token {
/// The hash the relay stores and compares against. /// The hash the relay stores and compares against.
pub fn hash(&self) -> Sha256Hash { pub fn hash(&self) -> Sha256Hash {
@@ -225,7 +252,7 @@ macro_rules! debug_as_wire {
} }
)*}; )*};
} }
debug_as_wire!(MailboxId, InviteId, Sha256Hash, Author, FileId); debug_as_wire!(MailboxId, InviteId, Sha256Hash, Author, FileId, CallId);
/// 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 {
@@ -351,6 +378,17 @@ pub struct ClaimedInvite {
pub key_package: KeyPackageBytes, pub key_package: KeyPackageBytes,
} }
/// `POST /v0/mailboxes/{id}/turn`: a TURN REST API pair for coturn's `use-auth-secret`. `username` is
/// `<expiry>:<random>`, `password` base64(HMAC-SHA1(secret, username)); valid [`TURN_TTL_SECS`]. Names no mailbox.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TurnCredentials {
pub username: String,
pub password: String,
pub ttl: u32,
pub urls: Vec<String>,
}
/// `GET /version`. /// `GET /version`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
+10
View File
@@ -329,3 +329,13 @@ fn a_file_key_is_never_printed_and_a_file_id_prints_as_its_wire() {
assert!(u64::from(MAX_FILE_CHUNKS) * plain >= 100 * 1024 * 1024); assert!(u64::from(MAX_FILE_CHUNKS) * plain >= 100 * 1024 * 1024);
assert!(u64::from(MAX_FILE_CHUNKS - 1) * plain < 100 * 1024 * 1024); assert!(u64::from(MAX_FILE_CHUNKS - 1) * plain < 100 * 1024 * 1024);
} }
#[test]
fn a_call_key_is_never_printed_and_a_call_id_prints_as_its_wire() {
let key = CallKey::from_bytes([5; 32]);
assert_eq!(format!("{key:?}"), "CallKey(..)");
assert_eq!(CallKey::parse(&key.to_wire()), Ok(key));
let id = CallId::from_bytes([6; 16]);
assert_eq!(format!("{id:?}"), format!("CallId({})", id.to_wire()));
assert!(CallId::parse(&id.to_wire()[..21]).is_err());
}
+5 -1
View File
@@ -8,7 +8,7 @@ publish.workspace = true
[dependencies] [dependencies]
tabellarius-protocol = { path = "../protocol" } tabellarius-protocol = { path = "../protocol" }
axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] } axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json", "query"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "signal"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "signal"] }
# Plain SQLite: the relay holds only ciphertext and hashes; nothing in it is readable (PROTOCOL.md §5). # Plain SQLite: the relay holds only ciphertext and hashes; nothing in it is readable (PROTOCOL.md §5).
rusqlite = { version = "0.41", features = ["bundled"] } rusqlite = { version = "0.41", features = ["bundled"] }
@@ -21,6 +21,10 @@ base64 = "0.22"
# The wake (`.agents/features/wake-up.md` §2.2): the relay's only outgoing request. rustls with # 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. # 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"] } ureq = { version = "3", default-features = false, features = ["rustls"] }
# TURN credentials for coturn's REST API (`.agents/features/calls-relay.md`): HMAC-SHA1 is what coturn checks.
hmac = "0.12"
sha1 = "0.10"
getrandom = "0.3"
[dev-dependencies] [dev-dependencies]
getrandom = "0.3" getrandom = "0.3"
+71
View File
@@ -0,0 +1,71 @@
//! The long-poll's waiting room (`.agents/features/calls-relay.md`): who is waiting for which mailbox, in memory
//! only, an entry only while someone waits. Nothing here is ever written to disk or logged.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tabellarius_protocol::MailboxId;
use tokio::sync::Notify;
/// Waiters relay-wide before one more is answered at once.
pub const MAX_WAITERS: usize = 1024;
pub struct Arrivals {
waiting: Mutex<HashMap<MailboxId, (Arc<Notify>, usize)>>,
max: usize,
}
/// One waiter's place; leaving it (drop) removes the entry when nobody else waits for that mailbox.
pub struct Place<'a> {
arrivals: &'a Arrivals,
id: MailboxId,
pub notify: Arc<Notify>,
}
impl Arrivals {
pub fn new(max: usize) -> Self {
Self {
waiting: Mutex::new(HashMap::new()),
max,
}
}
/// A place to wait for `id`, or `None` when the relay already holds `max` waiters.
pub fn enter(&self, id: MailboxId) -> Option<Place<'_>> {
let mut w = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
let total: usize = w.values().map(|(_, n)| n).sum();
if total >= self.max {
return None;
}
let entry = w.entry(id).or_insert_with(|| (Arc::new(Notify::new()), 0));
entry.1 += 1;
Some(Place {
arrivals: self,
id,
notify: Arc::clone(&entry.0),
})
}
/// A blob arrived for `id`: everyone waiting for it is answered.
pub fn arrived(&self, id: &MailboxId) {
let w = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
if let Some((n, _)) = w.get(id) {
n.notify_waiters();
}
}
}
impl Drop for Place<'_> {
fn drop(&mut self) {
let mut w = self
.arrivals
.waiting
.lock()
.unwrap_or_else(|e| e.into_inner());
if let Some(entry) = w.get_mut(&self.id) {
entry.1 -= 1;
if entry.1 == 0 {
w.remove(&self.id);
}
}
}
}
+79 -4
View File
@@ -1,21 +1,24 @@
//! The HTTP face of the store. No logging, no connection info: a handler never sees the client's //! The HTTP face of the store. No logging, no connection info: a handler never sees the client's
//! address, and nothing here writes a request anywhere. //! address, and nothing here writes a request anywhere.
use crate::arrivals::{Arrivals, MAX_WAITERS};
use crate::store::{Refused, Store}; use crate::store::{Refused, Store};
use crate::turn::Turn;
use crate::wake::Waker; use crate::wake::Waker;
use axum::body::Bytes; use axum::body::Bytes;
use axum::extract::rejection::BytesRejection; use axum::extract::rejection::BytesRejection;
use axum::extract::{DefaultBodyLimit, Path, State}; use axum::extract::{DefaultBodyLimit, Path, Query, State};
use axum::http::{header, HeaderMap, StatusCode}; use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response}; use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post, put}; use axum::routing::{delete, get, post, put};
use axum::{Json, Router}; use axum::{Json, Router};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration;
use tabellarius_protocol::{ use tabellarius_protocol::{
CreateFile, CreateInvite, CreateMailbox, FetchedBlobs, FileId, InviteId, MailboxId, CreateFile, CreateInvite, CreateMailbox, FetchedBlobs, FileId, InviteId, MailboxId,
RotatePostToken, SetPush, Sha256Hash, Token, VersionInfo, FILE_CHUNK_BYTES, MAX_BLOB_BYTES, RotatePostToken, SetPush, Sha256Hash, Token, TurnCredentials, VersionInfo, FILE_CHUNK_BYTES,
VERSION, MAX_BLOB_BYTES, MAX_WAIT_SECS, 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.
@@ -27,6 +30,10 @@ pub struct AppState {
pub clock: Clock, pub clock: Clock,
/// Wakes a mailbox's owner when a blob arrives (`PROTOCOL.md` §6). /// Wakes a mailbox's owner when a blob arrives (`PROTOCOL.md` §6).
pub waker: Arc<Waker>, pub waker: Arc<Waker>,
/// Who is long-polling which mailbox, in memory only (`calls-relay.md`).
pub arrivals: Arc<Arrivals>,
/// TURN credentials for calls; `None` when the relay was started without a TURN secret.
pub turn: Option<Arc<Turn>>,
} }
impl AppState { impl AppState {
@@ -40,8 +47,22 @@ impl AppState {
store, store,
clock, clock,
waker: Arc::new(waker), waker: Arc::new(waker),
arrivals: Arc::new(Arrivals::new(MAX_WAITERS)),
turn: None,
} }
} }
/// Hands out TURN credentials under this secret and these URLs (`POST /v0/mailboxes/{id}/turn`).
pub fn with_turn(mut self, turn: Turn) -> Self {
self.turn = Some(Arc::new(turn));
self
}
/// At most `max` long-polls held at once, relay-wide (tests set a small one).
pub fn with_max_waiters(mut self, max: usize) -> Self {
self.arrivals = Arc::new(Arrivals::new(max));
self
}
} }
/// 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.
@@ -63,6 +84,7 @@ pub fn router(state: AppState) -> Router {
.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/mailboxes/{id}/push", put(set_push).delete(clear_push))
.route("/v0/mailboxes/{id}/turn", post(turn_credentials))
.route("/v0/files", post(create_file)) .route("/v0/files", post(create_file))
.route("/v0/files/{id}", delete(delete_file)) .route("/v0/files/{id}", delete(delete_file))
.route("/v0/invites", post(create_invite)) .route("/v0/invites", post(create_invite))
@@ -141,6 +163,8 @@ async fn post_blob(
let token = bearer(&headers)?; let token = bearer(&headers)?;
let now = (s.clock)(); let now = (s.clock)();
s.store.post(&id, &token, &body, now)?; s.store.post(&id, &token, &body, now)?;
// Anyone long-polling this mailbox is answered now.
s.arrivals.arrived(&id);
// Only after the blob is stored under a valid post token; the 201 does not wait for the wake. // 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) { if let Ok(Some(endpoint)) = s.store.push_endpoint(&id) {
s.waker.wake(Arc::clone(&s.store), id, endpoint, now); s.waker.wake(Arc::clone(&s.store), id, endpoint, now);
@@ -148,15 +172,66 @@ async fn post_blob(
Ok(StatusCode::CREATED) Ok(StatusCode::CREATED)
} }
#[derive(serde::Deserialize)]
pub struct Wait {
wait: Option<u64>,
}
/// How long a fetch may be held: `?wait=` in seconds, at most [`MAX_WAIT_SECS`]; none means not at all.
pub fn clamp_wait(wait: Option<u64>) -> Duration {
Duration::from_secs(wait.unwrap_or(0).min(MAX_WAIT_SECS))
}
/// `GET …/blobs[?wait=N]`: the waiting blobs; with `wait` and none waiting, held until one arrives or N seconds
/// pass. The token is checked before anything is held, and the place is taken before the store is read, so a blob
/// posted in between is never missed.
async fn fetch_blobs( async fn fetch_blobs(
State(s): State<AppState>, State(s): State<AppState>,
Path(id): Path<String>, Path(id): Path<String>,
Query(q): Query<Wait>,
headers: HeaderMap, headers: HeaderMap,
) -> Result<Json<FetchedBlobs>, Status> { ) -> Result<Json<FetchedBlobs>, Status> {
let id = mailbox(&id)?; let id = mailbox(&id)?;
let token = bearer(&headers)?; let token = bearer(&headers)?;
let wait = clamp_wait(q.wait);
let place = if wait.is_zero() {
None
} else {
s.arrivals.enter(id)
};
let Some(place) = place else {
return Ok(Json(FetchedBlobs {
blobs: s.store.fetch(&id, &token)?,
}));
};
let notified = place.notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
let blobs = s.store.fetch(&id, &token)?; let blobs = s.store.fetch(&id, &token)?;
Ok(Json(FetchedBlobs { blobs })) if !blobs.is_empty() {
return Ok(Json(FetchedBlobs { blobs }));
}
let _ = tokio::time::timeout(wait, notified).await;
// The place is left when this returns.
Ok(Json(FetchedBlobs {
blobs: s.store.fetch(&id, &token)?,
}))
}
/// `POST …/turn` with the fetch token: a TURN REST pair (`calls-relay.md`). 404 without a TURN secret or with a
/// wrong token, 429 over [`tabellarius_protocol::TURN_PER_HOUR`]. Nothing is stored.
async fn turn_credentials(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
) -> Result<Json<TurnCredentials>, Status> {
let turn = s.turn.as_ref().ok_or(Status(StatusCode::NOT_FOUND))?;
let id = mailbox(&id)?;
let token = bearer(&headers)?;
s.store.authorize_fetch(&id, &token)?;
turn.credentials(id, (s.clock)())
.map(Json)
.ok_or(Status(StatusCode::TOO_MANY_REQUESTS))
} }
async fn acknowledge( async fn acknowledge(
+28 -1
View File
@@ -1,9 +1,11 @@
//! The Tabellarius relay: holds ciphertext addressed to a mailbox until its owner fetches and //! The Tabellarius relay: holds ciphertext addressed to a mailbox until its owner fetches and
//! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request. //! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request.
pub mod arrivals;
pub mod http; pub mod http;
pub mod join; pub mod join;
pub mod store; pub mod store;
pub mod turn;
pub mod wake; pub mod wake;
use std::net::SocketAddr; use std::net::SocketAddr;
@@ -20,6 +22,10 @@ pub struct Args {
pub limits: store::Limits, pub limits: store::Limits,
/// `--push-loopback`: accept and wake `http://` loopback push endpoints. Tests only. /// `--push-loopback`: accept and wake `http://` loopback push endpoints. Tests only.
pub push_loopback: bool, pub push_loopback: bool,
/// `--turn-secret-file <path>`: the secret shared with the TURN server (calls); none means no TURN route.
pub turn_secret_file: Option<PathBuf>,
/// `--turn-url <url>` (repeatable): the TURN servers named in each credential.
pub turn_urls: Vec<String>,
} }
/// `--listen <addr:port>`, `--db <path>`, the relay-wide quotas `--max-bytes`, `--max-mailboxes`, /// `--listen <addr:port>`, `--db <path>`, the relay-wide quotas `--max-bytes`, `--max-mailboxes`,
@@ -27,11 +33,13 @@ pub struct Args {
/// (tests). Anything else is refused with a usage line. /// (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 [--max-files 10000] [--max-file-bytes 4294967296] [--push-loopback]"; [--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000] \n [--max-files 10000] [--max-file-bytes 4294967296] [--push-loopback] [--turn-secret-file <path> --turn-url <turn:host:port?transport=udp> ...]";
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 limits = store::Limits::default();
let mut push_loopback = false; let mut push_loopback = false;
let mut turn_secret_file = None;
let mut turn_urls = Vec::new();
let mut it = args.into_iter(); let mut it = args.into_iter();
let positive = |v: Option<String>| -> Result<i64, String> { let positive = |v: Option<String>| -> Result<i64, String> {
v.and_then(|v| v.parse::<i64>().ok()) v.and_then(|v| v.parse::<i64>().ok())
@@ -46,6 +54,19 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
"--max-files" => limits.files = positive(it.next())?, "--max-files" => limits.files = positive(it.next())?,
"--max-file-bytes" => limits.file_bytes = positive(it.next())?, "--max-file-bytes" => limits.file_bytes = positive(it.next())?,
"--push-loopback" => push_loopback = true, "--push-loopback" => push_loopback = true,
"--turn-secret-file" => {
turn_secret_file = Some(
it.next()
.map(PathBuf::from)
.ok_or_else(|| usage.to_string())?,
)
}
"--turn-url" => {
let url = it
.next()
.filter(|u| u.starts_with("turn:") || u.starts_with("turns:"));
turn_urls.push(url.ok_or_else(|| usage.to_string())?);
}
"--listen" => { "--listen" => {
listen = it listen = it
.next() .next()
@@ -61,10 +82,16 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
_ => return Err(usage.to_string()), _ => return Err(usage.to_string()),
} }
} }
// A secret without a URL, or URLs without a secret, is a mistake in the deployment.
if turn_secret_file.is_some() != !turn_urls.is_empty() {
return Err(usage.to_string());
}
Ok(Args { Ok(Args {
listen, listen,
db, db,
limits, limits,
push_loopback, push_loopback,
turn_secret_file,
turn_urls,
}) })
} }
+16 -5
View File
@@ -65,11 +65,22 @@ async fn main() {
}); });
let clock: Clock = Arc::new(now); let clock: Clock = Arc::new(now);
let app = router(AppState::with_waker( let mut state = AppState::with_waker(store, clock, Waker::new(args.push_loopback));
store, if let Some(path) = &args.turn_secret_file {
clock, // Read once; trailing whitespace from an editor or `echo` is not part of the secret. Never printed.
Waker::new(args.push_loopback), let secret = match std::fs::read(path) {
)); Ok(bytes) if !bytes.trim_ascii().is_empty() => bytes.trim_ascii().to_vec(),
_ => {
eprintln!("tabellarius-relay: cannot read the TURN secret file");
std::process::exit(2);
}
};
state = state.with_turn(tabellarius_relay::turn::Turn::new(
secret,
args.turn_urls.clone(),
));
}
let app = router(state);
let shutdown = async { let shutdown = async {
let _ = tokio::signal::ctrl_c().await; let _ = tokio::signal::ctrl_c().await;
}; };
+6
View File
@@ -273,6 +273,12 @@ impl Store {
Ok(out) Ok(out)
} }
/// Checks the fetch token and nothing else (TURN credentials, `calls-relay.md`). Reads, writes nothing.
pub fn authorize_fetch(&self, id: &MailboxId, token: &Token) -> Result<(), Refused> {
let conn = self.conn();
Self::authorize(&conn, id, token, Column::Fetch)
}
/// Deletes this mailbox's blob whose SHA-256 is `hash`. Unknown hash = [`Refused::NotFound`]. /// Deletes this mailbox's blob whose SHA-256 is `hash`. Unknown hash = [`Refused::NotFound`].
pub fn acknowledge( pub fn acknowledge(
&self, &self,
+64
View File
@@ -0,0 +1,64 @@
//! TURN credentials for calls (`.agents/features/calls-relay.md`): coturn's REST API pair under a secret the relay
//! and the TURN server share. The secret is never logged or sent; the counters live in memory only.
use base64::Engine as _;
use hmac::{Hmac, Mac};
use sha1::Sha1;
use std::collections::HashMap;
use std::sync::Mutex;
use tabellarius_protocol::{MailboxId, TurnCredentials, TURN_PER_HOUR, TURN_TTL_SECS};
/// How many mailboxes' hourly counts are remembered before the old ones are pruned.
const MAX_COUNTED: usize = 100_000;
pub struct Turn {
secret: Vec<u8>,
urls: Vec<String>,
/// Per mailbox: the hour's start and how many credentials it got in it.
counts: Mutex<HashMap<MailboxId, (i64, u32)>>,
}
impl Turn {
pub fn new(secret: Vec<u8>, urls: Vec<String>) -> Self {
Self {
secret,
urls,
counts: Mutex::new(HashMap::new()),
}
}
/// A fresh pair for `id` at `now`, or `None` when it had [`TURN_PER_HOUR`] this hour.
pub fn credentials(&self, id: MailboxId, now: i64) -> Option<TurnCredentials> {
{
let mut c = self.counts.lock().unwrap_or_else(|e| e.into_inner());
if c.len() >= MAX_COUNTED {
c.retain(|_, (start, _)| now - *start < 3600);
}
let entry = c.entry(id).or_insert((now, 0));
if !(0..3600).contains(&(now - entry.0)) {
*entry = (now, 0);
}
if entry.1 >= TURN_PER_HOUR {
return None;
}
entry.1 += 1;
}
let mut nonce = [0u8; 16];
getrandom::fill(&mut nonce).ok()?;
let username = format!(
"{}:{}",
now + i64::from(TURN_TTL_SECS),
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(nonce)
);
let mut mac = Hmac::<Sha1>::new_from_slice(&self.secret).ok()?;
mac.update(username.as_bytes());
let password =
base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes());
Some(TurnCredentials {
username,
password,
ttl: TURN_TTL_SECS,
urls: self.urls.clone(),
})
}
}
+404
View File
@@ -0,0 +1,404 @@
//! What the relay does for calls (`.agents/features/calls-relay.md`): the long-poll on the fetch route, short-lived
//! TURN credentials, and nothing of either stored. Tokens, ids and the TURN secret are generated per test.
use axum::body::Body;
use axum::http::{header, Method, Request, StatusCode};
use base64::Engine as _;
use hmac::{Hmac, Mac};
use http_body_util::BodyExt;
use sha1::Sha1;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tabellarius_protocol::*;
use tabellarius_relay::http::{router, AppState, Clock};
use tabellarius_relay::store::Store;
use tabellarius_relay::turn::Turn;
use tower::ServiceExt;
const T0: i64 = 1_796_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,
}
struct Relay {
app: axum::Router,
_store: Arc<Store>,
now: Arc<AtomicI64>,
}
impl Relay {
fn new(turn: Option<Turn>, max_waiters: usize) -> 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 mut state = AppState::new(Arc::clone(&store), clock).with_max_waiters(max_waiters);
if let Some(t) = turn {
state = state.with_turn(t);
}
Self {
app: router(state),
_store: store,
now,
}
}
async fn call(
&self,
method: Method,
path: &str,
auth: Option<&Token>,
body: Vec<u8>,
) -> (StatusCode, Vec<u8>) {
let mut req = Request::builder().method(method).uri(path);
if let Some(t) = auth {
req = req.header(header::AUTHORIZATION, t.to_bearer());
}
let resp = self
.app
.clone()
.oneshot(req.body(Body::from(body)).expect("request"))
.await
.expect("infallible");
let status = resp.status();
let bytes = resp
.into_body()
.collect()
.await
.expect("body")
.to_bytes()
.to_vec();
(status, bytes)
}
async fn mailbox(&self) -> Mailbox {
let m = Mailbox {
id: MailboxId::from_bytes(random()),
post: Token::from_bytes(random()),
fetch: Token::from_bytes(random()),
};
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.0,
StatusCode::CREATED
);
m
}
async fn post(&self, m: &Mailbox, bytes: &[u8]) -> StatusCode {
self.call(
Method::POST,
&format!("/v0/mailboxes/{}/blobs", m.id.to_wire()),
Some(&m.post),
bytes.to_vec(),
)
.await
.0
}
async fn fetch(&self, m: &Mailbox, token: &Token, wait: Option<u64>) -> (StatusCode, usize) {
let q = wait.map(|w| format!("?wait={w}")).unwrap_or_default();
let (status, body) = self
.call(
Method::GET,
&format!("/v0/mailboxes/{}/blobs{q}", m.id.to_wire()),
Some(token),
vec![],
)
.await;
let n = if status == StatusCode::OK {
serde_json::from_slice::<FetchedBlobs>(&body)
.expect("json")
.blobs
.len()
} else {
0
};
(status, n)
}
async fn turn(&self, m: &Mailbox, token: &Token) -> (StatusCode, Vec<u8>) {
self.call(
Method::POST,
&format!("/v0/mailboxes/{}/turn", m.id.to_wire()),
Some(token),
vec![],
)
.await
}
}
// --- the long-poll ---
#[tokio::test(flavor = "multi_thread")]
async fn a_long_poll_answers_as_soon_as_a_blob_arrives() {
let relay = Arc::new(Relay::new(None, 1024));
let m = Arc::new(relay.mailbox().await);
let (r, mm) = (Arc::clone(&relay), Arc::clone(&m));
let started = Instant::now();
let waiting = tokio::spawn(async move { r.fetch(&mm, &mm.fetch, Some(25)).await });
tokio::time::sleep(Duration::from_millis(300)).await;
assert!(
!waiting.is_finished(),
"nothing waiting, so the request is held"
);
assert_eq!(relay.post(&m, b"ring").await, StatusCode::CREATED);
let (status, n) = waiting.await.expect("task");
assert_eq!((status, n), (StatusCode::OK, 1));
assert!(
started.elapsed() < Duration::from_secs(2),
"answered on arrival, not after the wait: {:?}",
started.elapsed()
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_long_poll_with_nothing_arriving_answers_empty_after_the_wait() {
let relay = Relay::new(None, 1024);
let m = relay.mailbox().await;
let started = Instant::now();
assert_eq!(
relay.fetch(&m, &m.fetch, Some(1)).await,
(StatusCode::OK, 0)
);
let took = started.elapsed();
assert!(
took >= Duration::from_millis(900) && took < Duration::from_secs(3),
"held about a second: {took:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_post_to_another_mailbox_does_not_end_the_wait() {
let relay = Arc::new(Relay::new(None, 1024));
let (a, b) = (Arc::new(relay.mailbox().await), relay.mailbox().await);
let (r, aa) = (Arc::clone(&relay), Arc::clone(&a));
let waiting = tokio::spawn(async move { r.fetch(&aa, &aa.fetch, Some(2)).await });
tokio::time::sleep(Duration::from_millis(200)).await;
relay.post(&b, b"not for a").await;
tokio::time::sleep(Duration::from_millis(500)).await;
assert!(!waiting.is_finished(), "b's blob must not wake a's waiter");
assert_eq!(waiting.await.expect("task"), (StatusCode::OK, 0));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_waiting_blob_is_answered_at_once_and_a_wrong_token_is_never_held() {
let relay = Relay::new(None, 1024);
let m = relay.mailbox().await;
relay.post(&m, b"already here").await;
let started = Instant::now();
assert_eq!(
relay.fetch(&m, &m.fetch, Some(25)).await,
(StatusCode::OK, 1)
);
assert_eq!(
relay.fetch(&m, &m.post, Some(25)).await.0,
StatusCode::NOT_FOUND,
"the post token cannot fetch"
);
assert!(
started.elapsed() < Duration::from_secs(1),
"neither was held"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_wait_longer_than_the_limit_is_held_the_limit_at_most() {
assert_eq!(MAX_WAIT_SECS, 25);
assert_eq!(
tabellarius_relay::http::clamp_wait(Some(3600)),
Duration::from_secs(25)
);
assert_eq!(
tabellarius_relay::http::clamp_wait(Some(5)),
Duration::from_secs(5)
);
assert_eq!(tabellarius_relay::http::clamp_wait(None), Duration::ZERO);
}
#[tokio::test(flavor = "multi_thread")]
async fn over_the_cap_a_long_poll_is_answered_at_once() {
let relay = Arc::new(Relay::new(None, 1));
let m = Arc::new(relay.mailbox().await);
let (r, mm) = (Arc::clone(&relay), Arc::clone(&m));
let first = tokio::spawn(async move { r.fetch(&mm, &mm.fetch, Some(2)).await });
tokio::time::sleep(Duration::from_millis(200)).await;
let started = Instant::now();
assert_eq!(
relay.fetch(&m, &m.fetch, Some(25)).await,
(StatusCode::OK, 0)
);
assert!(
started.elapsed() < Duration::from_millis(500),
"the second waiter is over the cap"
);
assert_eq!(first.await.expect("task"), (StatusCode::OK, 0));
}
// --- TURN credentials ---
fn turn() -> (Turn, Vec<u8>) {
let secret = random::<32>().to_vec();
(
Turn::new(
secret.clone(),
vec![
"turn:turn.test:3478?transport=udp".into(),
"turn:turn.test:3478?transport=tcp".into(),
],
),
secret,
)
}
#[tokio::test(flavor = "multi_thread")]
async fn without_a_turn_secret_there_is_no_turn_route() {
let relay = Relay::new(None, 1024);
let m = relay.mailbox().await;
assert_eq!(relay.turn(&m, &m.fetch).await.0, StatusCode::NOT_FOUND);
}
#[tokio::test(flavor = "multi_thread")]
async fn turn_credentials_are_coturns_rest_pair_valid_ten_minutes() {
let (t, secret) = turn();
let relay = Relay::new(Some(t), 1024);
let m = relay.mailbox().await;
let (status, body) = relay.turn(&m, &m.fetch).await;
assert_eq!(status, StatusCode::OK);
let c: TurnCredentials = serde_json::from_slice(&body).expect("json");
let (expiry, rand) = c.username.split_once(':').expect("expiry:random");
assert_eq!(
expiry.parse::<i64>().expect("number"),
T0 + TURN_TTL_SECS as i64
);
assert!(rand.len() >= 16, "a random part, no mailbox in it");
assert!(
!c.username.contains(&m.id.to_wire())
&& !String::from_utf8_lossy(&body).contains(&m.id.to_wire())
);
let mut mac = Hmac::<Sha1>::new_from_slice(&secret).expect("key");
mac.update(c.username.as_bytes());
assert_eq!(
c.password,
base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes())
);
assert_eq!(c.ttl, TURN_TTL_SECS);
assert_eq!(c.urls.len(), 2);
// Two requests give two different usernames.
let again: TurnCredentials =
serde_json::from_slice(&relay.turn(&m, &m.fetch).await.1).expect("json");
assert_ne!(again.username, c.username);
}
#[tokio::test(flavor = "multi_thread")]
async fn only_the_fetch_token_gets_turn_credentials_and_only_thirty_an_hour() {
let (t, _) = turn();
let relay = Relay::new(Some(t), 1024);
let m = relay.mailbox().await;
assert_eq!(relay.turn(&m, &m.post).await.0, StatusCode::NOT_FOUND);
assert_eq!(
relay.turn(&m, &Token::from_bytes(random())).await.0,
StatusCode::NOT_FOUND
);
for i in 0..TURN_PER_HOUR {
assert_eq!(
relay.turn(&m, &m.fetch).await.0,
StatusCode::OK,
"credential {i}"
);
}
assert_eq!(
relay.turn(&m, &m.fetch).await.0,
StatusCode::TOO_MANY_REQUESTS
);
relay.now.fetch_add(3600, Ordering::SeqCst);
assert_eq!(
relay.turn(&m, &m.fetch).await.0,
StatusCode::OK,
"a new hour"
);
// Another mailbox has its own count.
let other = relay.mailbox().await;
assert_eq!(relay.turn(&other, &other.fetch).await.0, StatusCode::OK);
}
#[tokio::test(flavor = "multi_thread")]
async fn turn_credentials_and_long_polls_store_nothing() {
let dir = tempfile::tempdir().expect("dir");
let path = dir.path().join("relay.db");
let (t, secret) = turn();
let store = Arc::new(Store::open(&path).expect("store"));
let clock: Clock = Arc::new(|| T0);
let app = router(AppState::new(Arc::clone(&store), clock).with_turn(t));
let relay = Relay {
app,
_store: store,
now: Arc::new(AtomicI64::new(T0)),
};
let m = relay.mailbox().await;
let before = std::fs::read(&path).expect("db");
let (_, body) = relay.turn(&m, &m.fetch).await;
let c: TurnCredentials = serde_json::from_slice(&body).expect("json");
relay.fetch(&m, &m.fetch, Some(1)).await;
drop(relay);
let after = std::fs::read(&path).expect("db");
assert_eq!(before, after, "the database did not change");
for needle in [c.username.as_bytes(), c.password.as_bytes(), &secret[..]] {
assert!(
!after.windows(needle.len()).any(|w| w == needle),
"nothing of the TURN pair or the secret on disk"
);
}
}
#[test]
fn the_turn_flags_come_together_or_not_at_all() {
use tabellarius_relay::parse_args;
let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
let a = parse_args(s(&[
"--turn-secret-file",
"/run/turn",
"--turn-url",
"turn:t.test:3478?transport=udp",
"--turn-url",
"turn:t.test:3478?transport=tcp",
]))
.expect("valid");
assert_eq!(
a.turn_secret_file.as_deref(),
Some(std::path::Path::new("/run/turn"))
);
assert_eq!(a.turn_urls.len(), 2);
assert!(
parse_args(s(&["--turn-secret-file", "/run/turn"])).is_err(),
"a secret without a URL"
);
assert!(
parse_args(s(&["--turn-url", "turn:t.test:3478"])).is_err(),
"a URL without a secret"
);
assert!(
parse_args(s(&[
"--turn-secret-file",
"/run/turn",
"--turn-url",
"https://t.test"
]))
.is_err(),
"not a TURN URL"
);
assert!(parse_args(s(&[]))
.expect("defaults")
.turn_secret_file
.is_none());
}
+4 -1
View File
@@ -861,7 +861,10 @@ async fn the_join_page_is_static_and_loads_nothing_from_elsewhere() {
"Copyright (c) 2026 Marek Novák", "Copyright (c) 2026 Marek Novák",
"Source (CPAL-1.0): gitea.marek-novak.cz/mnovak/Amicitia-Tabellarius", "Source (CPAL-1.0): gitea.marek-novak.cz/mnovak/Amicitia-Tabellarius",
] { ] {
assert!(body.contains(credit), "the page lacks the credit {credit:?}"); assert!(
body.contains(credit),
"the page lacks the credit {credit:?}"
);
} }
} }
+5 -3
View File
@@ -277,7 +277,9 @@ async fn a_post_wakes_with_a_constant_and_nothing_of_the_mailbox_or_the_blob() {
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn a_mailbox_is_woken_at_most_once_a_minute() { async fn a_mailbox_is_woken_at_most_once_every_ten_seconds() {
// Ten since 2026-12-03, so a call right after a message still wakes a closed app (calls-relay.md).
assert_eq!(WAKE_EVERY_SECS, 10);
let relay = Relay::new(true); let relay = Relay::new(true);
let push = PushServer::start().await; let push = PushServer::start().await;
let m = relay.mailbox().await; let m = relay.mailbox().await;
@@ -288,10 +290,10 @@ async fn a_mailbox_is_woken_at_most_once_a_minute() {
assert_eq!(push.wait_for(1).await.len(), 1); assert_eq!(push.wait_for(1).await.len(), 1);
relay.advance(WAKE_EVERY_SECS - 1); relay.advance(WAKE_EVERY_SECS - 1);
relay.post(&m, &m.post, b"y").await; relay.post(&m, &m.post, b"y").await;
assert_eq!(push.quiet().await.len(), 1, "within the minute"); assert_eq!(push.quiet().await.len(), 1, "within the ten seconds");
relay.advance(1); relay.advance(1);
relay.post(&m, &m.post, b"z").await; relay.post(&m, &m.post, b"z").await;
assert_eq!(push.wait_for(2).await.len(), 2, "after the minute"); assert_eq!(push.wait_for(2).await.len(), 2, "after them");
// Another mailbox has its own minute. // Another mailbox has its own minute.
let other = relay.mailbox().await; let other = relay.mailbox().await;
relay relay
+119 -4
View File
@@ -4,12 +4,27 @@
# services.tabellarius = { # services.tabellarius = {
# enable = true; # enable = true;
# domain = "relay.example.cz"; # its DNS name points at this machine; ports 80 and 443 open # domain = "relay.example.cz"; # its DNS name points at this machine; ports 80 and 443 open
# # Calls (optional): TURN credentials from the relay, coturn on this machine with the same secret.
# # turn.secretFile = "/run/secrets/tabellarius-turn"; # outside the Nix store
# # turn.urls = [ "turn:relay.example.cz:3478?transport=udp" "turn:relay.example.cz:3478?transport=tcp" ];
# # turn.coturn.enable = true;
# }; # };
{ self }: { self }:
{ config, lib, pkgs, ... }: { config, lib, pkgs, ... }:
let let
cfg = config.services.tabellarius; cfg = config.services.tabellarius;
system = pkgs.stdenv.hostPlatform.system; system = pkgs.stdenv.hostPlatform.system;
coturn = cfg.turn.coturn;
# Peers TURN may never relay to: private, loopback, link-local, shared, documentation and reserved ranges, so a
# call cannot be turned into a way into the server's own network (call-kinds.md section 2).
deniedPeers = [
"0.0.0.0-0.255.255.255" "10.0.0.0-10.255.255.255" "100.64.0.0-100.127.255.255" "127.0.0.0-127.255.255.255"
"169.254.0.0-169.254.255.255" "172.16.0.0-172.31.255.255" "192.0.0.0-192.0.0.255" "192.0.2.0-192.0.2.255"
"192.168.0.0-192.168.255.255" "198.18.0.0-198.19.255.255" "198.51.100.0-198.51.100.255"
"203.0.113.0-203.0.113.255" "224.0.0.0-255.255.255.255"
"::1" "::ffff:0:0-::ffff:ffff:ffff" "64:ff9b::-64:ff9b::ffff:ffff" "fc00::-fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
"fe80::-febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff" "ff00::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
];
in in
{ {
options.services.tabellarius = { options.services.tabellarius = {
@@ -64,6 +79,61 @@ in
''; '';
}; };
turn = {
secretFile = lib.mkOption {
# A string, not a path: a path would copy the secret into the world-readable Nix store.
type = lib.types.nullOr lib.types.str;
default = null;
description = ''
The secret the relay shares with the TURN server for calls (coturn `use-auth-secret`), as a file outside
the Nix store (e.g. written by Custos). Null: no TURN route (`POST /v0/mailboxes/{id}/turn` is 404).
'';
};
urls = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "turn:turn.example.org:3478?transport=udp" "turn:turn.example.org:3478?transport=tcp" ];
description = "The TURN servers named in each credential. Required with `secretFile`.";
};
coturn = {
enable = lib.mkEnableOption ''
coturn on this machine, for calls, with the relay's TURN secret (`use-auth-secret`), no logs, and no
relaying to private or reserved addresses. Needs `turn.secretFile`. Opens 3478 (UDP and TCP) and the relay
ports (UDP) when `openFirewall` is on'';
realm = lib.mkOption {
type = lib.types.str;
default = cfg.domain;
defaultText = lib.literalExpression "config.services.tabellarius.domain";
description = "coturn's realm.";
};
minPort = lib.mkOption {
type = lib.types.port;
default = 49152;
description = "The first UDP port coturn relays media on.";
};
maxPort = lib.mkOption {
type = lib.types.port;
default = 49999;
description = "The last UDP port coturn relays media on.";
};
externalIp = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "198.51.100.7/192.168.1.10";
description = ''
Behind NAT: the public address, then `/` and this machine's own (coturn `external-ip`). The router
forwards 3478 (UDP and TCP) and the relay ports (UDP) to this machine.
'';
};
allowedPeerIps = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "192.168.1.0-192.168.1.255" ];
description = "Ranges coturn may relay to although they are denied by default (a test network). Leave empty.";
};
};
};
openFirewall = lib.mkOption { openFirewall = lib.mkOption {
type = lib.types.bool; type = lib.types.bool;
default = true; default = true;
@@ -72,6 +142,17 @@ in
}; };
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
assertions = [
{
assertion = (cfg.turn.secretFile == null) == (cfg.turn.urls == [ ]);
message = "services.tabellarius.turn: secretFile and urls come together, or neither.";
}
{
assertion = coturn.enable -> cfg.turn.secretFile != null;
message = "services.tabellarius.turn.coturn needs turn.secretFile: coturn and the relay share it.";
}
];
systemd.services.tabellarius = { systemd.services.tabellarius = {
description = "Tabellarius message relay (loopback only; Caddy in front)"; description = "Tabellarius message relay (loopback only; Caddy in front)";
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
@@ -84,7 +165,11 @@ in
"--max-bytes" (toString cfg.maxBytes) "--max-bytes" (toString cfg.maxBytes)
"--max-mailboxes" (toString cfg.maxMailboxes) "--max-mailboxes" (toString cfg.maxMailboxes)
"--max-invites" (toString cfg.maxInvites) "--max-invites" (toString cfg.maxInvites)
]; ] + lib.optionalString (cfg.turn.secretFile != null) (" " + lib.escapeShellArgs (
# systemd hands the secret to the DynamicUser under its credentials directory (%d); it is never in the store.
[ "--turn-secret-file" "%d/turn-secret" ] ++ lib.concatMap (u: [ "--turn-url" u ]) cfg.turn.urls
));
LoadCredential = lib.mkIf (cfg.turn.secretFile != null) [ "turn-secret:${toString cfg.turn.secretFile}" ];
Restart = "on-failure"; Restart = "on-failure";
DynamicUser = true; DynamicUser = true;
StateDirectory = "tabellarius"; StateDirectory = "tabellarius";
@@ -134,8 +219,9 @@ in
services.caddy = { services.caddy = {
enable = true; enable = true;
# Caddy's own logger: errors about TLS handshakes or upstreams can name a client's address. # 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. # No log is the rule; an operator who needs one turns it on for a while, knowing why. mkDefault: it is the
logFormat = '' # logger of every site on the machine, so a host that serves others may keep errors (home-relay.md).
logFormat = lib.mkDefault ''
output discard output discard
''; '';
virtualHosts.${cfg.domain} = { virtualHosts.${cfg.domain} = {
@@ -154,7 +240,36 @@ in
}; };
}; };
networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ 80 443 ]; # TURN for calls (call-kinds.md section 2): the relay's secret reaches coturn as a systemd credential, read by
# its start script into /run/coturn (0700); never the Nix store. No log: coturn's sessions name both devices'
# addresses. TLS and DTLS are off: the media inside is DTLS-SRTP and frame-sealed, and the credentials are HMACs.
services.coturn = lib.mkIf coturn.enable {
enable = true;
realm = coturn.realm;
use-auth-secret = true;
static-auth-secret-file = "/run/credentials/coturn.service/turn-secret";
listening-port = 3478;
min-port = coturn.minPort;
max-port = coturn.maxPort;
no-cli = true;
no-tls = true;
no-dtls = true;
no-tcp-relay = true;
extraConfig = lib.concatStringsSep "\n" (
[ "no-stdout-log" "log-file=/dev/null" "simple-log" "no-multicast-peers" ]
++ map (r: "denied-peer-ip=${r}") deniedPeers
++ map (r: "allowed-peer-ip=${r}") coturn.allowedPeerIps
++ lib.optional (coturn.externalIp != null) "external-ip=${coturn.externalIp}"
);
};
systemd.services.coturn.serviceConfig.LoadCredential =
lib.mkIf coturn.enable [ "turn-secret:${toString cfg.turn.secretFile}" ];
networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall ([ 80 443 ] ++ lib.optional coturn.enable 3478);
networking.firewall.allowedUDPPorts = lib.mkIf (cfg.openFirewall && coturn.enable) [ 3478 ];
networking.firewall.allowedUDPPortRanges = lib.mkIf (cfg.openFirewall && coturn.enable) [
{ from = coturn.minPort; to = coturn.maxPort; }
];
# NixOS logs every refused connection with its source address by default. Those are strangers, # 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 # not users, but a relay that keeps no address should not keep theirs either. mkDefault: the
# machine's owner can turn it back on. # machine's owner can turn it back on.
+60 -5
View File
@@ -1,28 +1,49 @@
# `nix flake check` (Linux, KVM): two machines. `server` runs the module; `client` talks to it # `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 # 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 # mailbox cap to its 507, relays a call's packets through coturn with credentials from the relay, and then
# server's journal or under /var/log, or in the relay's database (.agents/features/home-relay.md). # the test fails if the client's address appears anywhere in the server's journal, under /var/log, in the
# relay's database or where coturn runs (.agents/features/home-relay.md, call-kinds.md).
{ self, pkgs }: { self, pkgs }:
pkgs.testers.runNixOSTest { pkgs.testers.runNixOSTest {
name = "tabellarius-relay-keeps-no-address"; name = "tabellarius-relay-keeps-no-address";
nodes.server = { lib, ... }: { nodes.server = { config, lib, ... }: {
imports = [ self.nixosModules.default ]; imports = [ self.nixosModules.default ];
services.tabellarius = { services.tabellarius = {
enable = true; enable = true;
domain = "relay.test"; domain = "relay.test";
maxMailboxes = 3; maxMailboxes = 3;
# Calls (calls-relay.md): the TURN route, with a secret made at boot, never in the repository or the store.
turn.secretFile = "/run/turn-test/secret";
turn.urls = [ "turn:relay.test:3478?transport=udp" ];
# coturn with the same secret. The test network is private, so the client's range is let through here;
# every other private range stays denied.
turn.coturn.enable = true;
turn.coturn.allowedPeerIps = [ "192.168.1.0-192.168.1.255" ];
};
# The VM's first NIC is QEMU's user network, which every node shares as 10.0.2.15: coturn listens and relays on
# the test network only.
services.coturn.listening-ips = [ config.networking.primaryIPAddress ];
services.coturn.relay-ips = [ config.networking.primaryIPAddress ];
systemd.services.turn-test-secret = {
wantedBy = [ "tabellarius.service" "coturn.service" ];
before = [ "tabellarius.service" "coturn.service" ];
serviceConfig.Type = "oneshot";
script = "install -d -m 0700 /run/turn-test && head -c 32 /dev/urandom | base64 > /run/turn-test/secret";
}; };
# No Let's Encrypt inside a VM: Caddy's own CA instead. # No Let's Encrypt inside a VM: Caddy's own CA instead.
services.caddy.virtualHosts."relay.test".extraConfig = lib.mkBefore "tls internal"; services.caddy.virtualHosts."relay.test".extraConfig = lib.mkBefore "tls internal";
}; };
nodes.client = { pkgs, ... }: { nodes.client = { pkgs, ... }: {
environment.systemPackages = [ pkgs.curl pkgs.python3 ]; # coturn for its test tools: turnutils_uclient (a TURN client) and turnutils_peer (the far end).
environment.systemPackages = [ pkgs.curl pkgs.python3 pkgs.coturn ];
# The peer answers the relayed packets on 3480/udp.
networking.firewall.enable = false;
}; };
testScript = '' testScript = ''
import base64, hashlib, json, os import base64, hashlib, json, os, re
def b64(raw): def b64(raw):
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
@@ -30,7 +51,10 @@ pkgs.testers.runNixOSTest {
start_all() start_all()
server.wait_for_unit("tabellarius.service") server.wait_for_unit("tabellarius.service")
server.wait_for_unit("caddy.service") server.wait_for_unit("caddy.service")
server.wait_for_unit("coturn.service")
server.wait_for_open_port(443) server.wait_for_open_port(443)
# coturn listens on the test network only, not on localhost, which is where wait_for_open_port looks.
server.wait_until_succeeds("ss -Hltn 'sport = :3478' | grep -q .")
client.wait_for_unit("multi-user.target") 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() client_ip = client.succeed("ip -4 -o addr show dev eth1 | awk '{print $4}' | cut -d/ -f1").strip()
@@ -65,6 +89,31 @@ pkgs.testers.runNixOSTest {
assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=fetch) == "200" assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=fetch) == "200"
digest = b64(hashlib.sha256(blob.encode()).digest()) digest = b64(hashlib.sha256(blob.encode()).digest())
assert call("DELETE", "/v0/mailboxes/" + mid + "/blobs/" + digest, token=fetch) == "204" assert call("DELETE", "/v0/mailboxes/" + mid + "/blobs/" + digest, token=fetch) == "204"
# Calls: TURN credentials for the fetch token only; a long-poll with nothing arriving answers after its wait.
assert call("POST", "/v0/mailboxes/" + mid + "/turn", token=fetch) == "200"
assert call("POST", "/v0/mailboxes/" + mid + "/turn", token=post) == "404"
creds = json.loads(client.succeed(
"curl -sk --resolve relay.test:443:" + server_ip + " -X POST -H 'Authorization: Bearer " + fetch + "'"
+ " https://relay.test/v0/mailboxes/" + mid + "/turn"))
assert creds["urls"] == ["turn:relay.test:3478?transport=udp"], creds
# coturn relays a call's packets for those credentials, to a peer on the client, and refuses a wrong password.
client.succeed("turnutils_peer -L " + client_ip + " -p 3480 >/dev/null 2>&1 &")
client.succeed("sleep 1")
uclient = ("timeout 60 turnutils_uclient -n 10 -m 1 -l 120 -e " + client_ip + " -r 3480 -u '"
+ creds["username"] + "' -w '{}' " + server_ip)
out = client.succeed(uclient.format(creds["password"]) + " 2>&1")
print(out)
# uclient prints its counts while it runs and once more at the end: the last one is the total.
received = re.findall(r"tot_recv_msgs=(\d+)", out)
# The output goes into the message: Nix keeps only the last lines of a failed test's log.
assert received and int(received[-1]) > 0, "no packet came back through coturn: " + out[-2500:]
refused = client.fail(uclient.format(b64(os.urandom(20))) + " 2>&1")
# The same command with the right password just worked, so the refusal is the password's. uclient says so as
# `error 401`, or, when it keeps answering the challenge, `Cannot complete Allocation`.
assert "error 401" in refused or "Cannot complete Allocation" in refused, (
"a wrong password was not refused: " + refused[-2500:])
assert call("GET", "/v0/mailboxes/" + mid + "/blobs?wait=1", token=fetch) == "200"
# Refusals: a wrong token, a malformed id, a body that is not JSON. # 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/" + mid + "/blobs", token=b64(os.urandom(32))) == "404"
assert call("GET", "/v0/mailboxes/nonsense/blobs", token=fetch) == "404" assert call("GET", "/v0/mailboxes/nonsense/blobs", token=fetch) == "404"
@@ -78,5 +127,11 @@ pkgs.testers.runNixOSTest {
server.succeed("journalctl --sync") server.succeed("journalctl --sync")
server.fail("journalctl --no-pager -o verbose | grep -F '" + client_ip + "'") server.fail("journalctl --no-pager -o verbose | grep -F '" + client_ip + "'")
server.fail("grep -rF '" + client_ip + "' /var/log /var/lib/private/tabellarius") server.fail("grep -rF '" + client_ip + "' /var/log /var/lib/private/tabellarius")
# Nor where coturn runs: its config and pid in /run, any temporary file.
# -s: a missing directory must not turn a match into exit 2, which `fail` would accept.
server.fail("grep -rsF '" + client_ip + "' /run/coturn /run/turnserver /tmp /var/tmp")
# The TURN secret reached the relay through systemd's credentials, never its database.
secret = server.succeed("cat /run/turn-test/secret").strip()
server.fail("grep -rF '" + secret + "' /var/lib/private/tabellarius /var/log")
''; '';
} }
+27 -5
View File
@@ -59,6 +59,17 @@ Every MLS application message carries one JSON object. The relay sees none of it
| `file` *(2026-11-22)* | `seq`, `file`, `fetchToken`, `key`, `name`, `mime`, `size`, `thumb`? | a message (it shares `seq` with `text`): a file on the relay (§8, files). `file` its id, `fetchToken` the capability to get its chunks, `key` its 32-byte key; `name` 1–255 characters without control characters, `/` or `\`; `mime` `type/subtype`, 3–127 printable ASCII bytes; `size` 1 byte to 100 MiB; `thumb`, when there, a JPEG of at most 32 KiB (a receiver drops a thumbnail that is not, and keeps the file). The key, the name, the type and the exact size travel **only here** | | `file` *(2026-11-22)* | `seq`, `file`, `fetchToken`, `key`, `name`, `mime`, `size`, `thumb`? | a message (it shares `seq` with `text`): a file on the relay (§8, files). `file` its id, `fetchToken` the capability to get its chunks, `key` its 32-byte key; `name` 1–255 characters without control characters, `/` or `\`; `mime` `type/subtype`, 3–127 printable ASCII bytes; `size` 1 byte to 100 MiB; `thumb`, when there, a JPEG of at most 32 KiB (a receiver drops a thumbnail that is not, and keeps the file). The key, the name, the type and the exact size travel **only here** |
| `receipt` | `upto` | the receiver has saved the sender's texts up to `upto`. Sent only by a client with receipts on; a client with them off also ignores them | | `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 | | `inbox` | `postToken` | a new post token for the mailbox the receiver already knows (after an unblock). It cannot name another mailbox |
| `call` *(2026-12-03, calls)* | `id`, `video`, `sdp`, `key`, `at` | an offer: `id` 16 random bytes made by the caller; `sdp` the WebRTC offer, 1 byte to 16 KiB; `key` the call's 32-byte frame key, made for one call, travelling **only here**; `at` the caller's clock in Unix seconds (a receiver rings only when it is recent). Dropped if its `id` is already live. No `seq` |
| `callAnswer` *(2026-12-03)* | `id`, `sdp` | the answer to the receiver's own live offer `id`, once; any other is dropped. No `seq` |
| `callIce` *(2026-12-03)* | `id`, `candidates` | 0–32 ICE candidates for the live call `id`, each 1–512 bytes without control characters; `[]` says no more. No `seq` |
| `callEnd` *(2026-12-03)* | `id`, `seq`, `reason`, `seconds` | a message (it shares `seq` with `text`): the call `id` is over, `reason` one of `hangUp`, `declined`, `busy`, `missed`, `failed`, after `seconds` (0–86 400). Shown even for an offer the receiver never saw, so a missed call leaves its line |
**Calls** *(added 2026-12-03, Amicitia F36; `.agents/features/call-kinds.md`)*: the four kinds set up a
WebRTC call between the two members. The SDP carries each side's DTLS fingerprint, so neither the
relay nor a TURN server can stand in the middle of the media's handshake; the app also seals every
media frame under `key`. A client keeps the calls in progress in memory only (at most 8); after a
restart an answer or candidates for a call it no longer knows are dropped. Only `callEnd` has a
`seq`, so a client without these kinds shows it as *update the app* and drops the other three.
**Naming a message** *(added 2026-11-21, Amicitia F27; `.agents/features/reactions-replies.md`)*: **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 `{"author", "seq"}`, where `author` is the 16 random bytes in the author's MLS credential (unpadded
@@ -98,7 +109,8 @@ Nothing else. *(2026-11-22:)* a file has no mailbox, no sender and no recipient,
keeps **no count of fetches**: it sees each one as it serves it. A file is deleted when its keeps **no count of fetches**: it sees each one as it serves it. A file is deleted when its
uploader deletes it, after **30 days**, or after **24 hours** if not all its chunks have arrived. No IP, no user agent, no request log beyond counts. *(2026-11-20:)* the relay also uploader deletes it, after **30 days**, or after **24 hours** if not all its chunks have arrived. No IP, no user agent, no request log beyond counts. *(2026-11-20:)* the relay also
remembers **in memory only**, never on disk, when it last woke each mailbox (§6), to wake it at most 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 once every 10 seconds. *(2026-12-03, calls:)* also in memory only, never on disk: which mailboxes have a long-poll
waiting right now, and how many TURN credentials each mailbox got this hour (§8). 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.
@@ -110,7 +122,8 @@ A notification for a closed app needs a push service. The wake-up carries **no c
**push endpoint per mailbox** (§8, `PUT …/push`), so the relay cannot link a person's mailboxes by **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. 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 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. endpoint, at most once every 10 seconds per mailbox *(60 until 2026-12-03; lowered so a call right after a
message still wakes a closed app)*, with nothing of the mailbox, the blob or its sender.
It connects only to **global** addresses (it resolves the host itself and drops loopback, 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 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 no redirect, gives up after 10 s, and has at most 16 wakes on their way. A push server's 404 or
@@ -132,11 +145,19 @@ The platform facts above are Claude's understanding, to be verified in `.agents/
- 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 - 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`). woken at most once every 10 seconds; a non-global address is never connected to (`relay/tests/wake.rs`).
- *(2026-12-03)* A long-poll is answered as soon as a blob arrives for its mailbox, and only then or after its
wait; a wrong token is never held; TURN credentials are coturn's REST pair, name no mailbox, are limited per
hour, and neither they nor the TURN secret reach the database (`relay/tests/calls.rs`).
- *(2026-12-03)* A call's SDP, candidates, id and key never appear in the relay's database
(`client/tests/real_relay.rs`, `client/tests/calls.rs`); an answer to anything but the receiver's own live
offer, a second offer under a live id, candidates for a call that is not live and a blocked contact's call are
dropped (`client/tests/calls.rs`, the client's unit tests). coturn relays only for the relay's credentials and
writes no client address anywhere on the server (`deploy/nixos/test.nix`).
- 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, quotas 2026-11-16, join page 2026-11-18, push 2026-11-20, files 2026-11-22 ## 8. The wire (v0) — approved 2026-11-08, routes added 2026-11-14, quotas 2026-11-16, join page 2026-11-18, push 2026-11-20, files 2026-11-22, calls 2026-12-03
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.
@@ -145,7 +166,8 @@ unknown fields. A blob is at most 256 KiB, and a KeyPackage at most 16 KiB.
|:--|:--|:--| |:--|:--|:--|
| `POST /v0/mailboxes` `{id, postTokenHash, fetchTokenHash}` | none | creates a mailbox. The owner sends **hashes**, so the relay never holds a token | | `POST /v0/mailboxes` `{id, postTokenHash, fetchTokenHash}` | none | creates a mailbox. The owner sends **hashes**, so the relay never holds a token |
| `POST /v0/mailboxes/{id}/blobs` (bytes) | post token | stores the blob with its size and the hour it arrived | | `POST /v0/mailboxes/{id}/blobs` (bytes) | post token | stores the blob with its size and the hour it arrived |
| `GET /v0/mailboxes/{id}/blobs` | fetch token | the waiting blobs, oldest first, at most 100. Fetching deletes nothing | | `GET /v0/mailboxes/{id}/blobs[?wait=N]` | fetch token | the waiting blobs, oldest first, at most 100. Fetching deletes nothing. *(2026-12-03)* With `wait` (seconds, at most 25) and nothing waiting, the request is held until a blob arrives for this mailbox or `wait` passes. At most 1 024 held relay-wide; over that, answered at once. A held request tells the relay the client is online, as each fetch already does |
| `POST /v0/mailboxes/{id}/turn` *(2026-12-03)* | fetch token | `{username, password, ttl, urls}`: a TURN REST API pair (coturn `use-auth-secret`) for a call, valid 600 s; `username` is `<expiry>:<random>`, `password` base64(HMAC-SHA1(secret, username)). 30 per mailbox per hour, then 429. 404 on a relay without a TURN server. Stores 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 | | `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 |
+1 -1
View File
@@ -13,7 +13,7 @@
packages = forAll (pkgs: { packages = forAll (pkgs: {
default = pkgs.rustPlatform.buildRustPackage { default = pkgs.rustPlatform.buildRustPackage {
pname = "tabellarius"; pname = "tabellarius";
version = "0.0.0"; version = "0.3.0";
src = pkgs.lib.cleanSource ./.; src = pkgs.lib.cleanSource ./.;
cargoLock.lockFile = ./Cargo.lock; cargoLock.lockFile = ./Cargo.lock;
doCheck = true; doCheck = true;