Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ccae752d7 | |||
| dff1bec275 | |||
| cfabc97d20 | |||
| 0e6be38280 | |||
| 0fbcb34b53 | |||
| dd576f9feb | |||
| 2a8daa7570 | |||
| 3ac2075ec6 | |||
| 4f78101735 |
@@ -0,0 +1,68 @@
|
||||
# F24 — Block, unblock, and *delivered*
|
||||
|
||||
Analysis, 2026-11-17. Issues Amicitia #52 (F24). It builds on F21/F22a (`client.md`,
|
||||
`client-state.md`). `PROTOCOL.md` §3 already says what block is: *the owner rotates the post token;
|
||||
the old one is refused. The blocked person is not told.* The relay route exists (§8, `PUT
|
||||
…/post-token`); the client never used it.
|
||||
|
||||
## 1. Why and what
|
||||
- **Block:** someone who turns hostile can no longer put anything in your mailbox. Nothing is sent
|
||||
to them, so they are not told. What they posted before the block, and what you already fetched,
|
||||
is dropped and never shown.
|
||||
- **Unblock:** a mistake can be undone. A fresh post token goes to them inside MLS, and their
|
||||
client switches to it, including for what waited in their outbox.
|
||||
- ***Delivered*:** you see when your message reached the other person's app (fetched and saved
|
||||
there). Each text carries a sequence number; the receiving client answers with a **receipt**
|
||||
`upto = n` once it has saved them. **Reciprocal and switchable:** with receipts off, a client
|
||||
neither sends them nor reports the other side's. The cost is said where the switch is: a
|
||||
receipt tells the sender roughly when your app was open.
|
||||
|
||||
## 2. Design
|
||||
### Everything is a staged step
|
||||
F22a's rule holds: nothing reaches the relay before the app has saved. So `Outgoing` grows from
|
||||
"one blob to post" to **one relay operation**: post a blob, or rotate a post token.
|
||||
| Call | Local change | Returned for the app to deliver after saving |
|
||||
|:--|:--|:--|
|
||||
| `block(contact)` | marks the contact blocked | a **rotate** to the hash of a fresh random token, which nobody gets |
|
||||
| `unblock(contact)` | clears the mark | a **rotate** to a new token, then a **post** of `inbox {postToken}` to them, inside MLS |
|
||||
| `compose` | `seq` + 1 for that contact | the text, now with its `seq` |
|
||||
| `receive` | texts from a blocked contact dropped; the highest `seq` received per contact | a **receipt** per contact that sent texts (receipts on, not blocked) |
|
||||
- `deliver` performs either operation. A rotate delivered twice is harmless: the same hash again.
|
||||
- `readdress(&Outgoing)`: a post waiting in an app's outbox carries the token it was sealed with.
|
||||
After an `inbox` payload changed the token, `readdress` swaps in the current one. The sealed
|
||||
blob does not change. Apps call it before delivering from the outbox.
|
||||
- An app learns a message's `seq` from `sent_seq(contact)` right after `compose`.
|
||||
|
||||
### Payloads inside MLS *(documented in `PROTOCOL.md` §4, new: `seq`, `receipt`, `inbox`)*
|
||||
```json
|
||||
{"kind":"hello","mailbox":"…","postToken":"…","name":"…"}
|
||||
{"kind":"text","body":"…","seq":7}
|
||||
{"kind":"receipt","upto":7}
|
||||
{"kind":"inbox","postToken":"…"}
|
||||
```
|
||||
- `inbox` changes only the token for the mailbox we already know: the sender cannot redirect us to
|
||||
another mailbox (F21's *second hello* rule still holds). MLS authenticates that it is theirs.
|
||||
- A `receipt` with `upto` above what we sent is capped to what we sent; it cannot mark the future.
|
||||
- The relay sees none of this: all of it is MLS ciphertext, and a rotate is §8's existing route.
|
||||
|
||||
### What the blocked person can tell
|
||||
Their posts get **404**: the same answer as any wrong token. Their app keeps the message as *not
|
||||
sent yet* and retries. Nothing in the protocol tells them it was a block rather than, say, an
|
||||
expired mailbox. Their client cannot ask. Stated: someone whose messages never leave the outbox
|
||||
may guess.
|
||||
|
||||
## 3. Tests — written first
|
||||
1. Block: the blocked side's next post is refused (404); nothing reaches us; what they posted
|
||||
just before the block, still waiting, is fetched, dropped, never shown, and acknowledged.
|
||||
2. Block works offline: the rotate waits as an `Outgoing`, and after a restart from the snapshot it
|
||||
still applies.
|
||||
3. Unblock: they get the new token, their waiting outbox post is readdressed and arrives, and new
|
||||
texts flow both ways.
|
||||
4. Receipts: Eva sends 3, Jan receives, Eva gets `Delivered{upto: 3}`. Receipts off on Jan: none
|
||||
sent. Off on Eva: Jan's receipts are ignored. A receipt `upto` above what was sent is capped.
|
||||
5. A snapshot from before F24 (no `blocked`, `seq`, `receipts`) still restores, with receipts on.
|
||||
6. `inbox` cannot change the mailbox, only the token.
|
||||
|
||||
Planted bugs: block that also posts something to the blocked person; texts from a blocked contact
|
||||
shown; the rotate done inside `block` (not staged); receipts sent while off; a receipt marking
|
||||
beyond what was sent; `readdress` leaving the old token.
|
||||
@@ -91,6 +91,11 @@ The F21 calls stay, for apps and tests without persistence: `send` = `compose` +
|
||||
relay's 7 days (the library has no clock). Without it an unclaimed invite's mailbox is fetched
|
||||
for ever.
|
||||
|
||||
10. **A forgotten contact leaves nothing behind** (`forget_contact`, added 2026-11-16 for Amicitia's
|
||||
*Remove person*): its name is gone from the snapshot, its MLS group from storage (putting the
|
||||
contact back into the snapshot is refused), and its mailbox is no longer fetched. The other side
|
||||
is not told.
|
||||
|
||||
Planted bugs, for the review: `receive` acknowledges inside the call; `compose` posts; `restore`
|
||||
skips the storage map; `finish` acknowledges before it delivers; a restored client starts
|
||||
`next_contact` at 0, so two contacts share an id.
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# F23 — The relay on a home server: quotas, a NixOS module, TLS
|
||||
|
||||
Analysis, 2026-11-16. Issues T#8 (deploy) and Amicitia #51. The container image of T#8 is left for later: the NixOS module is what the home server runs. It builds on F20 (the relay) and
|
||||
`relay.md` §3–4, which put two things before any relay that faces the internet: **quotas**, and a
|
||||
**reverse proxy that logs no IP address**.
|
||||
|
||||
## 1. Why and what
|
||||
Two people on two machines can only chat through a relay both can reach. Mark's home server is the
|
||||
first one. After F23:
|
||||
- the relay refuses to fill its disk: per-mailbox and relay-wide caps, answered with a bare **507**;
|
||||
- `deploy/nixos/module.nix` runs it on NixOS, listening on loopback only, behind **Caddy** with TLS
|
||||
from Let's Encrypt, and **no access log, no error log with an address in it**;
|
||||
- a NixOS VM test boots that configuration, sends requests through the proxy from a known address,
|
||||
and fails if that address appears anywhere in the journal or under `/var/log`;
|
||||
- Amicitia accepts an `https://` relay address (its own PR).
|
||||
|
||||
## 2. Design
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[app] -->|TLS 443| C[Caddy: TLS, no logs]
|
||||
C -->|HTTP 127.0.0.1:8470| R[tabellarius-relay: systemd, DynamicUser, loopback only]
|
||||
R --> D[(SQLite: PROTOCOL.md section 5)]
|
||||
```
|
||||
### Quotas *(protocol change, §8: a new status)*
|
||||
| Limit | Default | Set by |
|
||||
|:--|:--|:--|
|
||||
| waiting blobs in one mailbox | 1 000 | the protocol |
|
||||
| waiting bytes in one mailbox | 32 MiB | the protocol |
|
||||
| waiting bytes on the relay | 1 GiB | `--max-bytes` |
|
||||
| mailboxes on the relay | 100 000 | `--max-mailboxes` |
|
||||
| unclaimed invites on the relay | 10 000 | `--max-invites` |
|
||||
|
||||
- Over a limit, the relay answers **507 Insufficient Storage**, bare, like every refusal. The
|
||||
per-mailbox caps are checked **after** the post token, so 507 tells nothing to someone without
|
||||
the token. The relay-wide caps say only that the relay is full.
|
||||
- **No identity is needed to count**: nothing new is stored; the counts come from §5's own columns
|
||||
(`size`, the rows). No IP address is kept, not even in memory: rate limits by address would need
|
||||
one. A flood can fill the relay up to its caps; then it refuses, and the operator sees it.
|
||||
- The client already handles it: 507 is a failure, so the message waits in the outbox.
|
||||
- **Mailboxes are never deleted yet** (`relay.md` §4): an abandoned mailbox counts against the
|
||||
100 000 until a protocol version can delete one. Stated.
|
||||
|
||||
### The NixOS module (`deploy/nixos/module.nix`)
|
||||
- `services.tabellarius.enable`, `.domain`, `.maxBytes`, `.maxMailboxes`, `.maxInvites`, `.package`
|
||||
(the flake's own build).
|
||||
- **The relay:** a systemd service with `DynamicUser`, `StateDirectory=tabellarius` (the database),
|
||||
`--listen 127.0.0.1:8470`. Hardened: `ProtectSystem=strict`, `ProtectHome`, `PrivateTmp`,
|
||||
`PrivateDevices`, `NoNewPrivileges`, `MemoryDenyWriteExecute`, `RestrictAddressFamilies=AF_INET
|
||||
AF_INET6`, `SystemCallFilter=@system-service`, and **`IPAddressDeny=any` with
|
||||
`IPAddressAllow=localhost`**: even a bug cannot make it talk to anything but the proxy.
|
||||
- **The proxy:** `services.caddy`, one virtual host, `reverse_proxy 127.0.0.1:8470`. The NixOS
|
||||
module writes an access log per host by default; the host's `logFormat` is set to
|
||||
`output discard`, and Caddy's default logger too. Caddy's own TLS-handshake and proxy errors can
|
||||
name a client address, so no log is the rule; an operator who needs one turns it on and knows
|
||||
why. Headers: none added.
|
||||
- **journald:** the relay prints one line at start. Nothing per request.
|
||||
|
||||
### The VM test (`deploy/nixos/test.nix`, `nix flake check`)
|
||||
Two machines: `server` with the module (TLS from Caddy's internal CA instead of Let's Encrypt), and
|
||||
`client` at a fixed address. The client creates a mailbox, posts, fetches, acknowledges, makes a
|
||||
mistake (a wrong token, a malformed request), and fills a mailbox to its 507. Then the test greps
|
||||
the server's whole journal and `/var/log` for the client's address and fails if it appears.
|
||||
|
||||
**Not run here.** This machine has neither Nix nor WSL. The module and the test are written to be
|
||||
run with `nix flake check` on Linux, and the PR says so. Mark's server is the first real run.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy:** the logs are the risk this feature exists to close. The VM test is its proof, once
|
||||
it runs. The network layer (a router, the ISP) still sees addresses and timing (§1).
|
||||
- **Abuse:** caps bound the disk; they do not stop someone from filling them. Proof of work or
|
||||
invite-only mailbox creation is for a later protocol version.
|
||||
- **Reproducibility:** the module uses the flake's package, so the relay that runs is the one built
|
||||
from this commit (`docs/VERIFY.md`).
|
||||
|
||||
## 4. Tests — written first
|
||||
1. Each cap: the post or create that would cross it gets 507; one under it succeeds; after an
|
||||
acknowledgement (or a purge) there is room again.
|
||||
2. The per-mailbox cap answers 404, not 507, to a wrong token.
|
||||
3. The CLI reads `--max-bytes`, `--max-mailboxes`, `--max-invites`; a bad value is refused.
|
||||
4. The VM test (§2), on Linux.
|
||||
|
||||
Planted bugs: the mailbox cap checked before the token; an acknowledgement not freeing space; the
|
||||
global byte cap ignored; the invite cap counting claimed invites; the CLI option ignored.
|
||||
@@ -0,0 +1,39 @@
|
||||
# The join page — an invite link a messenger can open
|
||||
|
||||
## 1. Why and what
|
||||
Amicitia (the app this relay serves) makes connecting seamless: *Invite Petr* opens the phone's
|
||||
share sheet with a message holding the invite link, and Petr taps it (Amicitia's
|
||||
`.agents/features/seamless-invite.md`). Messengers make `https://` links tappable, not
|
||||
`amicitia://`. So the link is `https://<relay>/join#<invite id>.<secret>`, and the relay serves the
|
||||
page it opens: one button, **Open Amicitia**, that hands the invite to the app.
|
||||
|
||||
## 2. Design
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant B as Browser
|
||||
participant R as Relay
|
||||
participant A as App
|
||||
B->>R: GET /join (the fragment #id.secret is never sent)
|
||||
R-->>B: static page: CSP default-src 'none' + hashes, no-store, no-referrer
|
||||
B->>A: tap → amicitia://invite?relay=<origin>#id.secret
|
||||
```
|
||||
- `crates/relay/assets/join.html`, served by `crates/relay/src/join.rs`. The CSP names the page's
|
||||
only script and style by SHA-256, computed from the page itself at start-up, so an edit to the
|
||||
page cannot run without its hash.
|
||||
- The script checks the fragment's shape (22 + 43 base64url characters) and only then sets the
|
||||
button's target; anything else shows *This invite link is incomplete*.
|
||||
- No automatic redirect: Chrome refuses a custom scheme opened without a tap.
|
||||
|
||||
## 3. Risks
|
||||
- **Privacy:** the relay learns that an address opened `/join` — no more than any client tells it.
|
||||
It stores nothing and prints no request. The secret stays in the fragment. A messenger's link
|
||||
preview fetches `/join` only.
|
||||
- **The page as an attack surface:** static, no input read on the server, no cookie, framing
|
||||
refused, nothing loaded from elsewhere.
|
||||
|
||||
## 4. Verification
|
||||
| Case | How |
|
||||
|:--|:--|
|
||||
| Static, strict headers, nothing external, no cookie | `the_join_page_is_static_and_loads_nothing_from_elsewhere` |
|
||||
| The policy's hashes match the page's script and style | `the_join_page_policy_hashes_its_own_script_and_style` |
|
||||
| The script builds the app link from a good fragment and refuses a bad one | Node, by hand (in the PR); Amicitia's phone test end to end |
|
||||
Generated
+2
@@ -2276,11 +2276,13 @@ name = "tabellarius-relay"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64",
|
||||
"getrandom 0.3.4",
|
||||
"http-body-util",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"subtle",
|
||||
"tabellarius-protocol",
|
||||
"tempfile",
|
||||
|
||||
+276
-38
@@ -106,22 +106,55 @@ pub enum Event {
|
||||
contact: ContactId,
|
||||
text: String,
|
||||
},
|
||||
/// The other side's app has saved our texts up to `upto` (a `seq` from
|
||||
/// [`Client::sent_seq`]). Only while receipts are on ([`Client::set_receipts`]).
|
||||
Delivered {
|
||||
contact: ContactId,
|
||||
upto: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// One blob for the relay, to deliver once the app has saved the snapshot. An app may keep it in
|
||||
/// an outbox and deliver it again after a crash: a second copy is refused by MLS as a replay.
|
||||
/// `Debug` shows neither the post token nor the bytes.
|
||||
/// One operation for the relay, to deliver once the app has saved the snapshot: a blob to post,
|
||||
/// or a post token to rotate (block, unblock). An app may keep it in an outbox and deliver it
|
||||
/// again after a crash: a second post is refused by MLS as a replay, a second rotate changes
|
||||
/// nothing. `Debug` shows no token and no bytes.
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Outgoing {
|
||||
to: MailboxId,
|
||||
post: Token,
|
||||
blob: Bytes,
|
||||
#[serde(transparent)]
|
||||
pub struct Outgoing(Op);
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "camelCase", deny_unknown_fields)]
|
||||
enum Op {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Post {
|
||||
to: MailboxId,
|
||||
post: Token,
|
||||
blob: Bytes,
|
||||
},
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Rotate {
|
||||
mailbox: MailboxId,
|
||||
fetch: Token,
|
||||
post_token_hash: Sha256Hash,
|
||||
},
|
||||
}
|
||||
|
||||
impl Outgoing {
|
||||
fn post(to: MailboxId, post: Token, blob: Vec<u8>) -> Outgoing {
|
||||
Outgoing(Op::Post {
|
||||
to,
|
||||
post,
|
||||
blob: Bytes(blob),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Outgoing {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Outgoing({} bytes)", self.blob.0.len())
|
||||
match &self.0 {
|
||||
Op::Post { blob, .. } => write!(f, "Outgoing({} bytes)", blob.0.len()),
|
||||
Op::Rotate { .. } => f.write_str("Outgoing(rotate)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +171,7 @@ struct Ack {
|
||||
#[derive(Debug)]
|
||||
pub struct Received {
|
||||
pub events: Vec<Event>,
|
||||
/// Our answering `hello`s.
|
||||
/// Our answering `hello`s, and receipts.
|
||||
pub outgoing: Vec<Outgoing>,
|
||||
/// The relay failed part-way: what was fetched before it is here, the rest waits there.
|
||||
pub interrupted: Option<TransportError>,
|
||||
@@ -161,9 +194,13 @@ enum Payload {
|
||||
post_token: Token,
|
||||
name: String,
|
||||
},
|
||||
Text {
|
||||
body: String,
|
||||
},
|
||||
/// `seq` counts this sender's texts to this contact, from 1.
|
||||
Text { body: String, seq: u64 },
|
||||
/// The receiver has saved our texts up to `upto`.
|
||||
Receipt { upto: u64 },
|
||||
/// A new post token for the mailbox the receiver already knows (unblock).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Inbox { post_token: Token },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -189,6 +226,12 @@ struct Contact {
|
||||
outbox: Option<(MailboxId, Token)>,
|
||||
/// The invite this contact came through, on the inviter's side.
|
||||
via: Option<InviteId>,
|
||||
/// Blocked: their mailbox token rotated away; what still arrives from them is dropped.
|
||||
blocked: bool,
|
||||
/// The `seq` of our last text to them.
|
||||
sent_seq: u64,
|
||||
/// The highest `seq` of their texts we have received.
|
||||
received_seq: u64,
|
||||
}
|
||||
|
||||
pub struct Client<T: Transport> {
|
||||
@@ -201,6 +244,8 @@ pub struct Client<T: Transport> {
|
||||
contacts: Vec<Contact>,
|
||||
welcome_boxes: Vec<WelcomeBox>,
|
||||
next_contact: u32,
|
||||
/// Send receipts and report the other side's (reciprocal). On by default.
|
||||
receipts: bool,
|
||||
}
|
||||
|
||||
impl<T: Transport> Client<T> {
|
||||
@@ -230,6 +275,7 @@ impl<T: Transport> Client<T> {
|
||||
contacts: Vec::new(),
|
||||
welcome_boxes: Vec::new(),
|
||||
next_contact: 0,
|
||||
receipts: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -301,6 +347,21 @@ impl<T: Transport> Client<T> {
|
||||
self.welcome_boxes.retain(|w| w.invite != *invite);
|
||||
}
|
||||
|
||||
/// Forgets a contact: its MLS group is deleted from storage, its name and tokens from the
|
||||
/// client, and its mailbox is no longer fetched. The other side is not told, and anything it
|
||||
/// still posts waits on the relay until it expires. Save the snapshot after it. Returns whether
|
||||
/// there was such a contact.
|
||||
pub fn forget_contact(&mut self, contact: ContactId) -> Result<bool, ClientError> {
|
||||
let Some(index) = self.contacts.iter().position(|c| c.id == contact) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let mut c = self.contacts.remove(index);
|
||||
c.group
|
||||
.delete(self.provider.storage())
|
||||
.map_err(|_| ClientError::State)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Step 2, on the other device, staged: claims the KeyPackage (which uses the link up) and
|
||||
/// creates our mailbox, then makes the group. The Welcome and our `hello` come back for the
|
||||
/// app to deliver after saving.
|
||||
@@ -340,16 +401,8 @@ impl<T: Transport> Client<T> {
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?;
|
||||
let out = vec![
|
||||
Outgoing {
|
||||
to: welcome_id,
|
||||
post: welcome_post,
|
||||
blob: Bytes(welcome),
|
||||
},
|
||||
Outgoing {
|
||||
to: welcome_id,
|
||||
post: welcome_post,
|
||||
blob: Bytes(hello),
|
||||
},
|
||||
Outgoing::post(welcome_id, welcome_post, welcome),
|
||||
Outgoing::post(welcome_id, welcome_post, hello),
|
||||
];
|
||||
let id = self.add_contact(group, Some(inbox), None, None);
|
||||
Ok((id, out))
|
||||
@@ -380,6 +433,9 @@ impl<T: Transport> Client<T> {
|
||||
inbox,
|
||||
outbox,
|
||||
via,
|
||||
blocked: false,
|
||||
sent_seq: 0,
|
||||
received_seq: 0,
|
||||
});
|
||||
id
|
||||
}
|
||||
@@ -414,27 +470,118 @@ impl<T: Transport> Client<T> {
|
||||
.find(|c| c.id == contact)
|
||||
.ok_or(ClientError::UnknownContact)?;
|
||||
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||||
let seq = c.sent_seq + 1;
|
||||
let blob = Self::seal(
|
||||
&self.provider,
|
||||
&self.signer,
|
||||
&mut c.group,
|
||||
&Payload::Text {
|
||||
body: text.to_string(),
|
||||
seq,
|
||||
},
|
||||
)?;
|
||||
Ok(Outgoing {
|
||||
to,
|
||||
post,
|
||||
blob: Bytes(blob),
|
||||
})
|
||||
c.sent_seq = seq;
|
||||
Ok(Outgoing::post(to, post, blob))
|
||||
}
|
||||
|
||||
/// Posts one blob to the relay.
|
||||
/// The `seq` of our last text to a contact: right after [`Client::compose`], the one it made.
|
||||
pub fn sent_seq(&self, contact: ContactId) -> Option<u64> {
|
||||
self.contacts
|
||||
.iter()
|
||||
.find(|c| c.id == contact)
|
||||
.map(|c| c.sent_seq)
|
||||
}
|
||||
|
||||
/// Performs one operation on the relay: posts a blob, or rotates a post token.
|
||||
pub fn deliver(&self, out: &Outgoing) -> Result<(), ClientError> {
|
||||
self.transport.post(&out.to, &out.post, &out.blob.0)?;
|
||||
match &out.0 {
|
||||
Op::Post { to, post, blob } => self.transport.post(to, post, &blob.0)?,
|
||||
Op::Rotate {
|
||||
mailbox,
|
||||
fetch,
|
||||
post_token_hash,
|
||||
} => self
|
||||
.transport
|
||||
.rotate_post_token(mailbox, fetch, post_token_hash)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A post waiting in an app's outbox, with the contact's current post token: after an
|
||||
/// unblock on their side, the token it was sealed with is refused. The blob is unchanged.
|
||||
pub fn readdress(&self, out: &Outgoing) -> Outgoing {
|
||||
if let Op::Post { to, blob, .. } = &out.0 {
|
||||
if let Some((_, post)) = self
|
||||
.contacts
|
||||
.iter()
|
||||
.filter_map(|c| c.outbox)
|
||||
.find(|(mailbox, _)| mailbox == to)
|
||||
{
|
||||
return Outgoing::post(*to, post, blob.0.clone());
|
||||
}
|
||||
}
|
||||
out.clone()
|
||||
}
|
||||
|
||||
/// Blocks a contact, staged: they are marked, and their way into our mailbox is closed by a
|
||||
/// rotate to the hash of a fresh token that nobody gets. Nothing is sent to them. Save the
|
||||
/// snapshot, then deliver the result.
|
||||
pub fn block(&mut self, contact: ContactId) -> Result<Outgoing, ClientError> {
|
||||
let token = Token::from_bytes(self.random()?);
|
||||
let c = self
|
||||
.contacts
|
||||
.iter_mut()
|
||||
.find(|c| c.id == contact)
|
||||
.ok_or(ClientError::UnknownContact)?;
|
||||
let inbox = c.inbox.ok_or(ClientError::UnknownContact)?;
|
||||
c.blocked = true;
|
||||
Ok(Outgoing(Op::Rotate {
|
||||
mailbox: inbox.id,
|
||||
fetch: inbox.fetch,
|
||||
post_token_hash: token.hash(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Unblocks, staged: a rotate to a new token, then that token to them inside MLS.
|
||||
pub fn unblock(&mut self, contact: ContactId) -> Result<Vec<Outgoing>, ClientError> {
|
||||
let token = Token::from_bytes(self.random()?);
|
||||
let c = self
|
||||
.contacts
|
||||
.iter_mut()
|
||||
.find(|c| c.id == contact)
|
||||
.ok_or(ClientError::UnknownContact)?;
|
||||
let inbox = c.inbox.ok_or(ClientError::UnknownContact)?;
|
||||
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||||
let blob = Self::seal(
|
||||
&self.provider,
|
||||
&self.signer,
|
||||
&mut c.group,
|
||||
&Payload::Inbox { post_token: token },
|
||||
)?;
|
||||
c.blocked = false;
|
||||
Ok(vec![
|
||||
Outgoing(Op::Rotate {
|
||||
mailbox: inbox.id,
|
||||
fetch: inbox.fetch,
|
||||
post_token_hash: token.hash(),
|
||||
}),
|
||||
Outgoing::post(to, post, blob),
|
||||
])
|
||||
}
|
||||
|
||||
pub fn is_blocked(&self, contact: ContactId) -> bool {
|
||||
self.contacts.iter().any(|c| c.id == contact && c.blocked)
|
||||
}
|
||||
|
||||
/// Receipts on or off: off, we send none and report none of theirs. Save the snapshot after.
|
||||
pub fn set_receipts(&mut self, on: bool) {
|
||||
self.receipts = on;
|
||||
}
|
||||
|
||||
pub fn receipts(&self) -> bool {
|
||||
self.receipts
|
||||
}
|
||||
|
||||
/// [`Client::compose`] and [`Client::deliver`] at once, for use without persistence.
|
||||
pub fn send(&mut self, contact: ContactId, text: &str) -> Result<(), ClientError> {
|
||||
let out = self.compose(contact, text)?;
|
||||
@@ -473,6 +620,11 @@ impl<T: Transport> Client<T> {
|
||||
.iter()
|
||||
.filter_map(|c| c.inbox.map(|m| (m, None))),
|
||||
);
|
||||
let before: Vec<(ContactId, u64)> = self
|
||||
.contacts
|
||||
.iter()
|
||||
.map(|c| (c.id, c.received_seq))
|
||||
.collect();
|
||||
for (mailbox, via) in sources {
|
||||
let blobs = match self.transport.fetch(&mailbox.id, &mailbox.fetch) {
|
||||
Ok(blobs) => blobs,
|
||||
@@ -516,16 +668,31 @@ impl<T: Transport> Client<T> {
|
||||
continue;
|
||||
};
|
||||
c.inbox = Some(inbox);
|
||||
got.outgoing.push(Outgoing {
|
||||
to,
|
||||
post,
|
||||
blob: Bytes(blob),
|
||||
});
|
||||
got.outgoing.push(Outgoing::post(to, post, blob));
|
||||
}
|
||||
Err(ClientError::Transport(e)) => got.interrupted = Some(e),
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
// Receipts, for every contact whose texts arrived now. Delivered by `finish`, so only
|
||||
// after the app has saved the texts.
|
||||
if self.receipts {
|
||||
for (id, was) in before {
|
||||
let Some(c) = self.contacts.iter_mut().find(|c| c.id == id) else {
|
||||
continue;
|
||||
};
|
||||
let Some((to, post)) = c.outbox else { continue };
|
||||
if c.received_seq == was || c.blocked {
|
||||
continue;
|
||||
}
|
||||
let receipt = Payload::Receipt {
|
||||
upto: c.received_seq,
|
||||
};
|
||||
if let Ok(blob) = Self::seal(&self.provider, &self.signer, &mut c.group, &receipt) {
|
||||
got.outgoing.push(Outgoing::post(to, post, blob));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(got)
|
||||
}
|
||||
|
||||
@@ -536,9 +703,16 @@ impl<T: Transport> Client<T> {
|
||||
/// is never fetched. Not before: a snapshot saved between `receive` and `finish` must still
|
||||
/// know the mailbox, so that a restored client fetches its blobs again and acknowledges them.
|
||||
/// Save the snapshot again after `finish`.
|
||||
///
|
||||
/// A post the relay refuses with 404 is skipped: that mailbox's token is gone (we may be
|
||||
/// blocked), and trying again cannot help. Without the skip, one refused receipt would keep
|
||||
/// everything fetched from being acknowledged, for ever.
|
||||
pub fn finish(&mut self, received: &Received) -> Result<(), ClientError> {
|
||||
for out in &received.outgoing {
|
||||
self.deliver(out)?;
|
||||
match self.deliver(out) {
|
||||
Ok(()) | Err(ClientError::Transport(TransportError::NotFound)) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
for ack in &received.acks {
|
||||
self.transport
|
||||
@@ -638,17 +812,42 @@ impl<T: Transport> Client<T> {
|
||||
via: c.via,
|
||||
}))
|
||||
}
|
||||
Payload::Text { body } => {
|
||||
let c = &self.contacts[index];
|
||||
Payload::Text { body, seq } => {
|
||||
let c = &mut self.contacts[index];
|
||||
if c.name.is_none() {
|
||||
// Text before hello: not from a conversation that has been set up.
|
||||
return Err(ClientError::Mls);
|
||||
}
|
||||
if c.blocked {
|
||||
// Posted before the block, or fetched after it: dropped, never shown.
|
||||
return Ok(None);
|
||||
}
|
||||
c.received_seq = c.received_seq.max(seq);
|
||||
Ok(Some(Event::Message {
|
||||
contact: c.id,
|
||||
text: body,
|
||||
}))
|
||||
}
|
||||
Payload::Receipt { upto } => {
|
||||
let c = &self.contacts[index];
|
||||
if !self.receipts || c.name.is_none() || c.blocked {
|
||||
return Ok(None);
|
||||
}
|
||||
// A receipt cannot mark what was never sent.
|
||||
Ok(Some(Event::Delivered {
|
||||
contact: c.id,
|
||||
upto: upto.min(c.sent_seq),
|
||||
}))
|
||||
}
|
||||
Payload::Inbox { post_token } => {
|
||||
let c = &mut self.contacts[index];
|
||||
// Only the token changes: the mailbox stays the one their hello named.
|
||||
let Some((mailbox, _)) = c.outbox else {
|
||||
return Err(ClientError::Mls);
|
||||
};
|
||||
c.outbox = Some((mailbox, post_token));
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -688,4 +887,43 @@ mod tests {
|
||||
assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before);
|
||||
assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan"));
|
||||
}
|
||||
|
||||
/// `inbox` (unblock) changes only the token for the mailbox their hello named.
|
||||
#[test]
|
||||
fn an_inbox_payload_changes_the_token_not_the_mailbox() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
let (mailbox, before) = eva.contacts[0].outbox.expect("outbox");
|
||||
let fresh = Token::from_bytes([5; 32]);
|
||||
let inbox = Payload::Inbox { post_token: fresh };
|
||||
assert_eq!(eva.receive_payload(0, inbox), Ok(None));
|
||||
let (still, after) = eva.contacts[0].outbox.expect("outbox");
|
||||
assert_eq!(still, mailbox);
|
||||
assert_ne!(after.hash(), before.hash());
|
||||
assert_eq!(after.hash(), fresh.hash());
|
||||
}
|
||||
|
||||
/// A receipt cannot mark texts that were never sent.
|
||||
#[test]
|
||||
fn a_receipt_is_capped_at_what_was_sent() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
eva.send(eva.contacts[0].id, "jedna").expect("send");
|
||||
let got = eva.receive_payload(0, Payload::Receipt { upto: 99 });
|
||||
assert_eq!(
|
||||
got,
|
||||
Ok(Some(Event::Delivered {
|
||||
contact: eva.contacts[0].id,
|
||||
upto: 1
|
||||
}))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,17 @@ struct ContactState {
|
||||
inbox: Option<Mailbox>,
|
||||
outbox: Option<(MailboxId, Token)>,
|
||||
via: Option<InviteId>,
|
||||
// F24; absent in older snapshots.
|
||||
#[serde(default)]
|
||||
blocked: bool,
|
||||
#[serde(default)]
|
||||
sent_seq: u64,
|
||||
#[serde(default)]
|
||||
received_seq: u64,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -59,6 +70,8 @@ struct State {
|
||||
contacts: Vec<ContactState>,
|
||||
welcome_boxes: Vec<WelcomeBox>,
|
||||
next_contact: u32,
|
||||
#[serde(default = "yes")]
|
||||
receipts: bool,
|
||||
/// OpenMLS's storage: every key and value, sorted by key so equal states give equal bytes.
|
||||
storage: Vec<(Bytes, Bytes)>,
|
||||
}
|
||||
@@ -91,10 +104,14 @@ impl<T: Transport> Client<T> {
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
blocked: c.blocked,
|
||||
sent_seq: c.sent_seq,
|
||||
received_seq: c.received_seq,
|
||||
})
|
||||
.collect(),
|
||||
welcome_boxes: self.welcome_boxes.clone(),
|
||||
next_contact: self.next_contact,
|
||||
receipts: self.receipts,
|
||||
storage,
|
||||
};
|
||||
serde_json::to_vec(&state).map_err(|_| ClientError::State)
|
||||
@@ -143,6 +160,9 @@ impl<T: Transport> Client<T> {
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
blocked: c.blocked,
|
||||
sent_seq: c.sent_seq,
|
||||
received_seq: c.received_seq,
|
||||
});
|
||||
}
|
||||
Ok(Client {
|
||||
@@ -155,6 +175,7 @@ impl<T: Transport> Client<T> {
|
||||
contacts,
|
||||
welcome_boxes: state.welcome_boxes,
|
||||
next_contact: state.next_contact,
|
||||
receipts: state.receipts,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,13 @@ pub trait Transport {
|
||||
hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError>;
|
||||
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError>;
|
||||
/// Block: the mailbox's post token becomes `new_hash`'s; the old one is refused from now on.
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
new_hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError>;
|
||||
/// The KeyPackage, once.
|
||||
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError>;
|
||||
}
|
||||
@@ -129,6 +136,21 @@ impl Transport for MemoryTransport {
|
||||
}
|
||||
}
|
||||
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
new_hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
match self.boxes().mailboxes.get_mut(id) {
|
||||
Some((post, f, _)) if *f == fetch.hash() => {
|
||||
*post = *new_hash;
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(TransportError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> {
|
||||
let mut b = self.boxes();
|
||||
if b.invites.contains_key(&req.id) {
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Block, unblock and receipts (`.agents/features/block-and-receipts.md` §3). No I/O: runs on the
|
||||
//! Android emulator too.
|
||||
|
||||
use tabellarius_client::*;
|
||||
|
||||
type C = Client<MemoryTransport>;
|
||||
|
||||
fn pair(relay: &MemoryTransport) -> (C, ContactId, C, ContactId) {
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
let Some(Event::Joined {
|
||||
contact: eva_side, ..
|
||||
}) = eva.poll().expect("poll").first().cloned()
|
||||
else {
|
||||
panic!("no join")
|
||||
};
|
||||
jan.poll().expect("poll");
|
||||
(eva, eva_side, jan, jan_side)
|
||||
}
|
||||
|
||||
fn texts(events: &[Event]) -> Vec<String> {
|
||||
events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::Message { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_contact_reaches_us_no_more_and_is_not_told() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
// Jan writes once before the block; it waits on the relay.
|
||||
jan.send(jan_side, "před blokem").expect("send");
|
||||
let waiting = relay.waiting_blobs();
|
||||
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
assert_eq!(
|
||||
relay.waiting_blobs(),
|
||||
waiting,
|
||||
"block posts nothing to anyone"
|
||||
);
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
assert!(eva.is_blocked(eva_side));
|
||||
|
||||
// Jan's next post is refused, the same 404 as any wrong token.
|
||||
assert_eq!(
|
||||
jan.send(jan_side, "po bloku"),
|
||||
Err(ClientError::Transport(TransportError::NotFound))
|
||||
);
|
||||
// What he posted before the block is fetched, dropped, never shown, and acknowledged.
|
||||
let events = eva.poll().expect("poll");
|
||||
assert!(texts(&events).is_empty(), "{events:?}");
|
||||
assert_eq!(relay.waiting_blobs(), 0);
|
||||
// Eva can still write to him: block closes her mailbox, not his. His receipt for it is
|
||||
// refused, and that does not stop his app from acknowledging what it fetched.
|
||||
assert!(jan.receipts());
|
||||
eva.send(eva_side, "jen já tobě").expect("send");
|
||||
assert_eq!(texts(&jan.poll().expect("poll")), ["jen já tobě"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_made_offline_waits_and_survives_a_restart() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
// Staged: nothing reached the relay, so Jan can still post until the rotate is delivered.
|
||||
jan.send(jan_side, "ještě to prošlo")
|
||||
.expect("not blocked on the relay yet");
|
||||
let saved = eva.snapshot().expect("snapshot");
|
||||
let kept = serde_json::to_vec(&rotate).expect("outbox");
|
||||
drop(eva); // the relay was away; the app closes
|
||||
|
||||
let eva = Client::restore(&saved, relay.clone()).expect("restore");
|
||||
assert!(eva.is_blocked(eva_side));
|
||||
let rotate: Outgoing = serde_json::from_slice(&kept).expect("outbox");
|
||||
assert_eq!(format!("{rotate:?}"), "Outgoing(rotate)");
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
eva.deliver(&rotate).expect("a second time changes nothing");
|
||||
assert!(jan.send(jan_side, "x").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unblocking_readdresses_what_waited_and_both_can_talk_again() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
// Jan's app keeps what it could not send in its outbox.
|
||||
let stuck = jan.compose(jan_side, "čekalo to").expect("compose");
|
||||
assert!(jan.deliver(&stuck).is_err());
|
||||
|
||||
for out in eva.unblock(eva_side).expect("unblock") {
|
||||
eva.deliver(&out).expect("deliver");
|
||||
}
|
||||
assert!(!eva.is_blocked(eva_side));
|
||||
jan.poll().expect("Jan receives the new token");
|
||||
// The old token is still refused; readdressed, the same sealed message goes through.
|
||||
assert!(jan.deliver(&stuck).is_err());
|
||||
jan.deliver(&jan.readdress(&stuck)).expect("readdressed");
|
||||
jan.send(jan_side, "a teď nová").expect("send");
|
||||
assert_eq!(
|
||||
texts(&eva.poll().expect("poll")),
|
||||
["čekalo to", "a teď nová"]
|
||||
);
|
||||
eva.send(eva_side, "vítej zpátky").expect("send");
|
||||
assert_eq!(texts(&jan.poll().expect("poll")), ["vítej zpátky"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipts_say_what_arrived_and_only_while_both_want_them() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
for t in ["jedna", "dvě", "tři"] {
|
||||
eva.send(eva_side, t).expect("send");
|
||||
}
|
||||
assert_eq!(eva.sent_seq(eva_side), Some(3));
|
||||
assert_eq!(texts(&jan.poll().expect("poll")).len(), 3);
|
||||
assert!(eva.poll().expect("poll").contains(&Event::Delivered {
|
||||
contact: eva_side,
|
||||
upto: 3
|
||||
}));
|
||||
|
||||
// Jan turns them off: he sends none.
|
||||
jan.set_receipts(false);
|
||||
eva.send(eva_side, "čtyři").expect("send");
|
||||
jan.poll().expect("poll");
|
||||
assert!(!eva
|
||||
.poll()
|
||||
.expect("poll")
|
||||
.iter()
|
||||
.any(|e| matches!(e, Event::Delivered { .. })));
|
||||
|
||||
// Eva turns them off: Jan's are ignored (reciprocal).
|
||||
jan.set_receipts(true);
|
||||
eva.set_receipts(false);
|
||||
eva.send(eva_side, "pět").expect("send");
|
||||
jan.poll().expect("poll");
|
||||
assert!(!eva
|
||||
.poll()
|
||||
.expect("poll")
|
||||
.iter()
|
||||
.any(|e| matches!(e, Event::Delivered { .. })));
|
||||
// And she sends none for Jan's.
|
||||
jan.send(jan_side, "ahoj").expect("send");
|
||||
eva.poll().expect("poll");
|
||||
assert!(!jan
|
||||
.poll()
|
||||
.expect("poll")
|
||||
.iter()
|
||||
.any(|e| matches!(e, Event::Delivered { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_contact_gets_no_receipt() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
jan.send(jan_side, "x").expect("send");
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
eva.poll().expect("poll");
|
||||
assert!(!jan
|
||||
.poll()
|
||||
.expect("poll")
|
||||
.iter()
|
||||
.any(|e| matches!(e, Event::Delivered { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipts_are_kept_across_a_restart_and_default_to_on() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, _jan, _) = pair(&relay);
|
||||
assert!(eva.receipts());
|
||||
eva.set_receipts(false);
|
||||
eva.send(eva_side, "x").expect("send");
|
||||
let saved = eva.snapshot().expect("snapshot");
|
||||
let eva = Client::restore(&saved, relay.clone()).expect("restore");
|
||||
assert!(!eva.receipts());
|
||||
assert_eq!(eva.sent_seq(eva_side), Some(1));
|
||||
|
||||
// A snapshot from before F24 has none of the new fields: it restores, receipts on.
|
||||
let mut old: serde_json::Value = serde_json::from_slice(&saved).expect("json");
|
||||
old.as_object_mut().expect("object").remove("receipts");
|
||||
for c in old["contacts"].as_array_mut().expect("contacts") {
|
||||
let c = c.as_object_mut().expect("contact");
|
||||
for f in ["blocked", "sentSeq", "receivedSeq"] {
|
||||
c.remove(f);
|
||||
}
|
||||
}
|
||||
let old = serde_json::to_vec(&old).expect("json");
|
||||
let eva = Client::restore(&old, relay.clone()).expect("an old snapshot");
|
||||
assert!(eva.receipts());
|
||||
assert!(!eva.is_blocked(eva_side));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_receipt_does_not_keep_the_blocked_side_from_acknowledging() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, _) = pair(&relay);
|
||||
let rotate = eva.block(eva_side).expect("block");
|
||||
eva.deliver(&rotate).expect("rotate");
|
||||
eva.send(eva_side, "jedna").expect("send");
|
||||
eva.send(eva_side, "dvě").expect("send");
|
||||
assert_eq!(texts(&jan.poll().expect("poll")), ["jedna", "dvě"]);
|
||||
assert_eq!(
|
||||
relay.waiting_blobs(),
|
||||
0,
|
||||
"acknowledged, the refused receipt skipped"
|
||||
);
|
||||
assert!(jan.poll().expect("poll").is_empty());
|
||||
}
|
||||
@@ -19,6 +19,9 @@ fn pair(
|
||||
) {
|
||||
let mut eva = Client::new("Eva Nováková", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
// Receipts (F24) have their own tests; here they would only add events and blobs.
|
||||
eva.set_receipts(false);
|
||||
jan.set_receipts(false);
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
let eva_events = eva.poll().expect("eva polls");
|
||||
|
||||
@@ -98,6 +98,20 @@ impl Transport for Http {
|
||||
self.call("DELETE", &path, Some(fetch), &[], false)
|
||||
.map(|_| ())
|
||||
}
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
new_hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
let body = serde_json::to_vec(&RotatePostToken {
|
||||
post_token_hash: *new_hash,
|
||||
})
|
||||
.map_err(|_| TransportError::Failed)?;
|
||||
let path = format!("/v0/mailboxes/{}/post-token", id.to_wire());
|
||||
self.call("PUT", &path, Some(fetch), &body, true)
|
||||
.map(|_| ())
|
||||
}
|
||||
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> {
|
||||
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
|
||||
self.call("POST", "/v0/invites", None, &body, true)
|
||||
@@ -152,6 +166,8 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
|
||||
|
||||
let mut eva = Client::new("Eva Nováková", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan Dvořák", relay.clone()).expect("jan");
|
||||
eva.set_receipts(false);
|
||||
jan.set_receipts(false);
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
// While the invite waits, the relay holds Eva's KeyPackage: it must not carry her name.
|
||||
let invited = std::fs::read(&db).expect("db");
|
||||
|
||||
@@ -5,10 +5,16 @@ use tabellarius_client::*;
|
||||
|
||||
type C = Client<MemoryTransport>;
|
||||
|
||||
/// Receipts off: these tests count events and waiting blobs, and receipts (F24) have their own.
|
||||
fn quiet<T: Transport>(mut c: Client<T>) -> Client<T> {
|
||||
c.set_receipts(false);
|
||||
c
|
||||
}
|
||||
|
||||
/// Pairs Eva (inviter) and Jan through the staged calls, saving nothing. Returns both sides' ids.
|
||||
fn pair(relay: &MemoryTransport) -> (C, ContactId, C, ContactId) {
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
let events = eva.poll().expect("poll");
|
||||
@@ -39,7 +45,7 @@ fn texts(events: Vec<Event>) -> Vec<String> {
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::Message { text, .. } => Some(text),
|
||||
Event::Joined { .. } => None,
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -64,8 +70,8 @@ fn both_sides_restart_mid_conversation_and_keep_talking() {
|
||||
#[test]
|
||||
fn an_invite_waiting_survives_a_restart() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let mut eva = restart(&eva, &relay);
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
@@ -84,7 +90,7 @@ fn a_restored_client_gives_a_new_contact_a_new_id() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (eva, eva_side, _jan, _) = pair(&relay);
|
||||
let mut eva = restart(&eva, &relay);
|
||||
let mut petr = Client::new("Petr", relay.clone()).expect("petr");
|
||||
let mut petr = quiet(Client::new("Petr", relay.clone()).expect("petr"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
petr.accept_invite(&invite).expect("accept");
|
||||
let events = eva.poll().expect("poll");
|
||||
@@ -99,8 +105,8 @@ fn a_restored_client_gives_a_new_contact_a_new_id() {
|
||||
#[test]
|
||||
fn the_staged_calls_post_nothing_and_acknowledge_nothing() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
|
||||
let (jan_side, out) = jan.accept(&invite).expect("accept");
|
||||
@@ -137,8 +143,8 @@ fn the_staged_calls_post_nothing_and_acknowledge_nothing() {
|
||||
#[test]
|
||||
fn a_crash_between_receive_and_finish_loses_nothing_and_shows_nothing_twice() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
// Jan cannot write before Eva's hello gives him her mailbox.
|
||||
@@ -317,6 +323,14 @@ impl Transport for Flaky {
|
||||
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
|
||||
self.inner.create_invite(r)
|
||||
}
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &tabellarius_protocol::MailboxId,
|
||||
fetch: &tabellarius_protocol::Token,
|
||||
new_hash: &tabellarius_protocol::Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.rotate_post_token(id, fetch, new_hash)
|
||||
}
|
||||
fn claim_invite(
|
||||
&self,
|
||||
id: &tabellarius_protocol::InviteId,
|
||||
@@ -332,8 +346,8 @@ impl Transport for Flaky {
|
||||
fn finish_acknowledges_nothing_when_delivering_fails() {
|
||||
let relay = MemoryTransport::default();
|
||||
let flaky = Flaky::new(&relay);
|
||||
let mut eva = Client::new("Eva", flaky.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let mut eva = quiet(Client::new("Eva", flaky.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let jan_side = jan.accept_invite(&invite).expect("accept");
|
||||
|
||||
@@ -362,10 +376,10 @@ fn finish_acknowledges_nothing_when_delivering_fails() {
|
||||
fn a_relay_failing_part_way_returns_what_was_processed() {
|
||||
let relay = MemoryTransport::default();
|
||||
let flaky = Flaky::new(&relay);
|
||||
let mut eva = Client::new("Eva", flaky.clone()).expect("eva");
|
||||
let mut eva = quiet(Client::new("Eva", flaky.clone()).expect("eva"));
|
||||
let mut friends = Vec::new();
|
||||
for name in ["Jan", "Petr"] {
|
||||
let mut friend = Client::new(name, relay.clone()).expect("friend");
|
||||
let mut friend = quiet(Client::new(name, relay.clone()).expect("friend"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let side = friend.accept_invite(&invite).expect("accept");
|
||||
friends.push((friend, side));
|
||||
@@ -398,8 +412,8 @@ fn a_relay_failing_part_way_returns_what_was_processed() {
|
||||
#[test]
|
||||
fn a_used_welcome_mailbox_is_no_longer_fetched() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
@@ -415,8 +429,8 @@ fn a_used_welcome_mailbox_is_no_longer_fetched() {
|
||||
#[test]
|
||||
fn a_forgotten_invite_is_no_longer_fetched() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva"));
|
||||
let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
eva.forget_invite(&invite.id);
|
||||
let mut eva = restart(&eva, &relay);
|
||||
@@ -428,3 +442,61 @@ fn a_forgotten_invite_is_no_longer_fetched() {
|
||||
"the Welcome and hello wait, never fetched"
|
||||
);
|
||||
}
|
||||
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
/// Forgetting a contact leaves no name in the snapshot, stops fetching its mailbox, and survives a
|
||||
/// restart; the other contacts are untouched.
|
||||
#[test]
|
||||
fn a_forgotten_contact_leaves_nothing_behind() {
|
||||
let relay = MemoryTransport::default();
|
||||
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
|
||||
let mut petr = quiet(Client::new("Petr Zapomenutý", relay.clone()).expect("petr"));
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
let petr_side = petr.accept_invite(&invite).expect("accept");
|
||||
let Some(Event::Joined {
|
||||
contact: forgotten, ..
|
||||
}) = eva.poll().expect("poll").first().cloned()
|
||||
else {
|
||||
panic!("no join")
|
||||
};
|
||||
petr.poll().expect("poll");
|
||||
let before: serde_json::Value =
|
||||
serde_json::from_slice(&eva.snapshot().expect("snapshot")).expect("json");
|
||||
assert!(before.to_string().contains("Petr Zapomenutý"));
|
||||
let petr_state = before["contacts"][1].clone();
|
||||
|
||||
assert_eq!(eva.forget_contact(forgotten), Ok(true));
|
||||
assert_eq!(eva.forget_contact(forgotten), Ok(false), "only once");
|
||||
let saved = eva.snapshot().expect("snapshot");
|
||||
assert!(
|
||||
!contains(&saved, "Petr Zapomenutý".as_bytes()),
|
||||
"the name is gone"
|
||||
);
|
||||
// The group's MLS state is gone from storage too: putting the contact back is refused.
|
||||
let mut back: serde_json::Value = serde_json::from_slice(&saved).expect("json");
|
||||
back["contacts"]
|
||||
.as_array_mut()
|
||||
.expect("contacts")
|
||||
.push(petr_state);
|
||||
let back = serde_json::to_vec(&back).expect("json");
|
||||
assert!(matches!(
|
||||
C::restore(&back, relay.clone()),
|
||||
Err(ClientError::State)
|
||||
));
|
||||
let mut eva = Client::restore(&saved, relay.clone()).expect("restore");
|
||||
assert_eq!(eva.contact_name(forgotten), None);
|
||||
|
||||
petr.send(petr_side, "slyšíš mě?")
|
||||
.expect("the relay still takes it");
|
||||
jan.send(jan_side, "já ano").expect("send");
|
||||
assert_eq!(texts(eva.poll().expect("poll")), ["já ano"]);
|
||||
assert_eq!(relay.waiting_blobs(), 1, "Petr's message was never fetched");
|
||||
assert_eq!(
|
||||
eva.compose(forgotten, "x"),
|
||||
Err(ClientError::UnknownContact)
|
||||
);
|
||||
eva.send(eva_side, "Jan still works").expect("send");
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@ rusqlite = { version = "0.41", features = ["bundled"] }
|
||||
serde = "1"
|
||||
serde_json = "1"
|
||||
subtle = "2"
|
||||
# The join page's Content-Security-Policy names its inline script and style by SHA-256 (base64).
|
||||
sha2 = "0.10"
|
||||
base64 = "0.22"
|
||||
|
||||
[dev-dependencies]
|
||||
getrandom = "0.3"
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>An invite to a private chat</title>
|
||||
<style>
|
||||
:root { color-scheme: dark light; }
|
||||
body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
|
||||
background: #0d0a0c; color: #f2ece8; font: 17px/1.5 system-ui, sans-serif; }
|
||||
main { max-width: 420px; padding: 32px 24px; text-align: center; }
|
||||
h1 { font-weight: 600; font-size: 26px; line-height: 1.2; margin: 0 0 12px; }
|
||||
p { margin: 0 0 20px; color: #cfc4bf; }
|
||||
.button { display: block; padding: 14px 20px; margin: 8px 0 24px; border-radius: 12px;
|
||||
background: #b3223a; color: #fff; text-decoration: none; font-weight: 600; font-size: 18px; }
|
||||
.small { font-size: 14px; color: #a99d98; }
|
||||
[hidden] { display: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>You're invited to a private chat</h1>
|
||||
<p>Someone who knows you invited you to chat in Amicitia, end to end encrypted.</p>
|
||||
<a id="open" class="button" href="#">Open Amicitia</a>
|
||||
<p id="missing" class="small">Don't have Amicitia yet? Ask the person who invited you how to get it, then tap their message again.</p>
|
||||
<p id="bad" class="small" hidden>This invite link is incomplete. Ask for a new one.</p>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
// The invite is in the fragment, which the browser never sends to this server.
|
||||
var invite = location.hash.slice(1);
|
||||
var open = document.getElementById("open");
|
||||
if (!/^[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/.test(invite)) {
|
||||
open.hidden = true;
|
||||
document.getElementById("missing").hidden = true;
|
||||
document.getElementById("bad").hidden = false;
|
||||
return;
|
||||
}
|
||||
open.href = "amicitia://invite?relay=" + location.origin + "#" + invite;
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -38,6 +38,7 @@ pub fn router(state: AppState) -> Router {
|
||||
.route("/v0/invites", post(create_invite))
|
||||
.route("/v0/invites/{id}", get(claim_invite))
|
||||
.route("/version", get(version))
|
||||
.route("/join", get(crate::join::page))
|
||||
.layer(DefaultBodyLimit::max(MAX_JSON_BYTES))
|
||||
.merge(blob_routes)
|
||||
.with_state(state)
|
||||
@@ -59,6 +60,7 @@ impl From<Refused> for Status {
|
||||
Refused::Exists => StatusCode::CONFLICT,
|
||||
Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Refused::Full => StatusCode::INSUFFICIENT_STORAGE,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! `GET /join` (PROTOCOL.md §8, added 2026-11-18): the page an invite link opens in a browser. It
|
||||
//! hands the invite, which sits in the URL's fragment and so never reaches this server, to the app
|
||||
//! as `amicitia://invite?relay=<this origin>#<id>.<secret>`. Static: it reads nothing, stores
|
||||
//! nothing, sets no cookie and loads nothing from anywhere else.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use axum::http::header;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use base64::Engine;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub const PAGE: &str = include_str!("../assets/join.html");
|
||||
|
||||
/// The text between `<tag>` and `</tag>` in the page (one of each), exactly as the browser hashes it.
|
||||
fn inline(tag: &str) -> &'static str {
|
||||
let open = format!("<{tag}>");
|
||||
let close = format!("</{tag}>");
|
||||
let start = PAGE.find(&open).expect("the page has the tag") + open.len();
|
||||
let end = PAGE[start..].find(&close).expect("the tag is closed") + start;
|
||||
&PAGE[start..end]
|
||||
}
|
||||
|
||||
fn hash(text: &str) -> String {
|
||||
let digest = Sha256::digest(text.as_bytes());
|
||||
format!(
|
||||
"'sha256-{}'",
|
||||
base64::engine::general_purpose::STANDARD.encode(digest)
|
||||
)
|
||||
}
|
||||
|
||||
/// Nothing but the page's own script and style, each by its hash: no other script, no image, no
|
||||
/// font, no connection, no frame, no form.
|
||||
pub static CONTENT_SECURITY_POLICY: LazyLock<String> = LazyLock::new(|| {
|
||||
format!(
|
||||
"default-src 'none'; script-src {}; style-src {}; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
|
||||
hash(inline("script")),
|
||||
hash(inline("style"))
|
||||
)
|
||||
});
|
||||
|
||||
pub async fn page() -> Response {
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
|
||||
(
|
||||
header::CONTENT_SECURITY_POLICY,
|
||||
CONTENT_SECURITY_POLICY.as_str(),
|
||||
),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
(header::REFERRER_POLICY, "no-referrer"),
|
||||
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
|
||||
],
|
||||
PAGE,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
+17
-3
@@ -2,6 +2,7 @@
|
||||
//! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request.
|
||||
|
||||
pub mod http;
|
||||
pub mod join;
|
||||
pub mod store;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
@@ -15,16 +16,29 @@ pub const DEFAULT_DB: &str = "tabellarius-relay.db";
|
||||
pub struct Args {
|
||||
pub listen: SocketAddr,
|
||||
pub db: PathBuf,
|
||||
pub limits: store::Limits,
|
||||
}
|
||||
|
||||
/// `--listen <addr:port>`, `--db <path>`. Anything else is refused with a usage line.
|
||||
/// `--listen <addr:port>`, `--db <path>`, and the relay-wide quotas `--max-bytes`,
|
||||
/// `--max-mailboxes`, `--max-invites` (positive integers). Anything else is refused with a usage
|
||||
/// line.
|
||||
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
|
||||
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]";
|
||||
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] \
|
||||
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000]";
|
||||
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
|
||||
let mut db = PathBuf::from(DEFAULT_DB);
|
||||
let mut limits = store::Limits::default();
|
||||
let mut it = args.into_iter();
|
||||
let positive = |v: Option<String>| -> Result<i64, String> {
|
||||
v.and_then(|v| v.parse::<i64>().ok())
|
||||
.filter(|&n| n > 0)
|
||||
.ok_or_else(|| usage.to_string())
|
||||
};
|
||||
while let Some(arg) = it.next() {
|
||||
match arg.as_str() {
|
||||
"--max-bytes" => limits.total_bytes = positive(it.next())?,
|
||||
"--max-mailboxes" => limits.mailboxes = positive(it.next())?,
|
||||
"--max-invites" => limits.invites = positive(it.next())?,
|
||||
"--listen" => {
|
||||
listen = it
|
||||
.next()
|
||||
@@ -40,5 +54,5 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
|
||||
_ => return Err(usage.to_string()),
|
||||
}
|
||||
}
|
||||
Ok(Args { listen, db })
|
||||
Ok(Args { listen, db, limits })
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]`
|
||||
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] [--max-bytes N]
|
||||
//! [--max-mailboxes N] [--max-invites N]`
|
||||
//!
|
||||
//! Prints one line at start (version and address) and nothing per request.
|
||||
|
||||
@@ -24,7 +25,7 @@ async fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let store = match Store::open(&args.db) {
|
||||
let store = match Store::open_with(&args.db, args.limits) {
|
||||
Ok(s) => Arc::new(s),
|
||||
Err(_) => {
|
||||
eprintln!(
|
||||
|
||||
@@ -48,6 +48,36 @@ pub enum Refused {
|
||||
TooLarge,
|
||||
/// The database failed; nothing about the request is in the error.
|
||||
Storage,
|
||||
/// A quota is reached (`PROTOCOL.md` §8, 507): the mailbox's, after its token, or the relay's.
|
||||
Full,
|
||||
}
|
||||
|
||||
/// How much the relay holds before it answers [`Refused::Full`]. The per-mailbox caps are the
|
||||
/// protocol's; the relay-wide ones are the operator's (`.agents/features/home-relay.md` §2).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
pub mailbox_blobs: i64,
|
||||
pub mailbox_bytes: i64,
|
||||
pub total_bytes: i64,
|
||||
pub mailboxes: i64,
|
||||
pub invites: i64,
|
||||
}
|
||||
|
||||
/// Waiting blobs in one mailbox (`PROTOCOL.md` §8).
|
||||
pub const MAILBOX_BLOBS: i64 = 1_000;
|
||||
/// Waiting bytes in one mailbox (`PROTOCOL.md` §8).
|
||||
pub const MAILBOX_BYTES: i64 = 32 * 1024 * 1024;
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Limits {
|
||||
mailbox_blobs: MAILBOX_BLOBS,
|
||||
mailbox_bytes: MAILBOX_BYTES,
|
||||
total_bytes: 1024 * 1024 * 1024,
|
||||
mailboxes: 100_000,
|
||||
invites: 10_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<rusqlite::Error> for Refused {
|
||||
@@ -58,6 +88,7 @@ impl From<rusqlite::Error> for Refused {
|
||||
|
||||
pub struct Store {
|
||||
conn: Mutex<Connection>,
|
||||
limits: Limits,
|
||||
}
|
||||
|
||||
/// What a purge removed.
|
||||
@@ -73,23 +104,39 @@ fn same_hash(stored: &[u8], presented: &Sha256Hash) -> bool {
|
||||
|
||||
impl Store {
|
||||
pub fn open(path: &Path) -> Result<Self, rusqlite::Error> {
|
||||
Self::init(Connection::open(path)?)
|
||||
Self::init(Connection::open(path)?, Limits::default())
|
||||
}
|
||||
|
||||
pub fn open_with(path: &Path, limits: Limits) -> Result<Self, rusqlite::Error> {
|
||||
Self::init(Connection::open(path)?, limits)
|
||||
}
|
||||
|
||||
pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
|
||||
Self::init(Connection::open_in_memory()?)
|
||||
Self::init(Connection::open_in_memory()?, Limits::default())
|
||||
}
|
||||
|
||||
fn init(conn: Connection) -> Result<Self, rusqlite::Error> {
|
||||
pub fn open_in_memory_with(limits: Limits) -> Result<Self, rusqlite::Error> {
|
||||
Self::init(Connection::open_in_memory()?, limits)
|
||||
}
|
||||
|
||||
fn init(conn: Connection, limits: Limits) -> Result<Self, rusqlite::Error> {
|
||||
// Deleted rows are overwritten in the file, and there is no -wal copy of anything.
|
||||
conn.pragma_update(None, "secure_delete", "ON")?;
|
||||
conn.pragma_update(None, "journal_mode", "DELETE")?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
Ok(Self {
|
||||
conn: Mutex::new(conn),
|
||||
limits,
|
||||
})
|
||||
}
|
||||
|
||||
/// One number from the database: a count or a sum, 0 for none.
|
||||
fn number(conn: &Connection, sql: &str, args: impl rusqlite::Params) -> Result<i64, Refused> {
|
||||
Ok(conn
|
||||
.query_row(sql, args, |r| r.get::<_, Option<i64>>(0))?
|
||||
.unwrap_or(0))
|
||||
}
|
||||
|
||||
fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
|
||||
// A panic while holding the lock leaves SQLite consistent (every write is one statement or
|
||||
// one transaction), so a poisoned lock is still safe to use.
|
||||
@@ -97,7 +144,11 @@ impl Store {
|
||||
}
|
||||
|
||||
pub fn create_mailbox(&self, req: &CreateMailbox, now: i64) -> Result<(), Refused> {
|
||||
let changed = self.conn().execute(
|
||||
let conn = self.conn();
|
||||
if Self::number(&conn, "SELECT count(*) FROM mailboxes", [])? >= self.limits.mailboxes {
|
||||
return Err(Refused::Full);
|
||||
}
|
||||
let changed = conn.execute(
|
||||
"INSERT OR IGNORE INTO mailboxes (id, post_hash, fetch_hash, created_day)
|
||||
VALUES (?1, ?2, ?3, ?4)",
|
||||
params![
|
||||
@@ -150,6 +201,20 @@ impl Store {
|
||||
}
|
||||
let conn = self.conn();
|
||||
Self::authorize(&conn, id, token, Column::Post)?;
|
||||
// After the token: a stranger learns nothing about this mailbox from a 507.
|
||||
let size = blob.len() as i64;
|
||||
let (count, bytes): (i64, Option<i64>) = conn.query_row(
|
||||
"SELECT count(*), sum(size) FROM blobs WHERE mailbox_id = ?1",
|
||||
[&id.as_bytes()[..]],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
let total = Self::number(&conn, "SELECT sum(size) FROM blobs", [])?;
|
||||
if count >= self.limits.mailbox_blobs
|
||||
|| bytes.unwrap_or(0) + size > self.limits.mailbox_bytes
|
||||
|| total + size > self.limits.total_bytes
|
||||
{
|
||||
return Err(Refused::Full);
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO blobs (mailbox_id, ciphertext, size, received_hour) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![&id.as_bytes()[..], blob, blob.len() as i64, hour_of(now)],
|
||||
@@ -231,7 +296,17 @@ impl Store {
|
||||
pub fn create_invite(&self, req: &CreateInvite, now: i64) -> Result<(), Refused> {
|
||||
// Expiry rounded up to the hour: the exact second the invite was made is not kept.
|
||||
let expiry = (hour_of(now + INVITE_TTL_SECS) + 1) * 3600;
|
||||
let changed = self.conn().execute(
|
||||
let conn = self.conn();
|
||||
// Expired invites wait for the hourly purge; they do not count against new ones.
|
||||
let waiting = Self::number(
|
||||
&conn,
|
||||
"SELECT count(*) FROM invites WHERE expiry > ?1",
|
||||
[now],
|
||||
)?;
|
||||
if waiting >= self.limits.invites {
|
||||
return Err(Refused::Full);
|
||||
}
|
||||
let changed = conn.execute(
|
||||
"INSERT OR IGNORE INTO invites (id, secret_hash, key_package, expiry) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![
|
||||
&req.id.as_bytes()[..],
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
//! Quotas (`.agents/features/home-relay.md` §4, `PROTOCOL.md` §8): over a limit the relay answers a
|
||||
//! bare 507; the per-mailbox caps only after the post token. Small limits, so the tests are quick.
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{header, Method, Request, StatusCode};
|
||||
use http_body_util::BodyExt;
|
||||
use std::sync::Arc;
|
||||
use tabellarius_protocol::*;
|
||||
use tabellarius_relay::http::{router, AppState, Clock};
|
||||
use tabellarius_relay::parse_args;
|
||||
use tabellarius_relay::store::{Limits, Store, MAILBOX_BLOBS, MAILBOX_BYTES};
|
||||
use tower::ServiceExt;
|
||||
|
||||
const T0: i64 = 1_794_000_000;
|
||||
|
||||
fn random<const N: usize>() -> [u8; N] {
|
||||
let mut b = [0u8; N];
|
||||
getrandom::fill(&mut b).expect("system randomness");
|
||||
b
|
||||
}
|
||||
|
||||
struct Mailbox {
|
||||
id: MailboxId,
|
||||
post: Token,
|
||||
fetch: Token,
|
||||
}
|
||||
|
||||
impl Mailbox {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
id: MailboxId::from_bytes(random()),
|
||||
post: Token::from_bytes(random()),
|
||||
fetch: Token::from_bytes(random()),
|
||||
}
|
||||
}
|
||||
fn path(&self) -> String {
|
||||
format!("/v0/mailboxes/{}/blobs", self.id.to_wire())
|
||||
}
|
||||
}
|
||||
|
||||
struct Relay(axum::Router);
|
||||
|
||||
impl Relay {
|
||||
fn with(limits: Limits) -> Self {
|
||||
let store = Arc::new(Store::open_in_memory_with(limits).expect("store"));
|
||||
let clock: Clock = Arc::new(|| T0);
|
||||
Relay(router(AppState { store, clock }))
|
||||
}
|
||||
async fn call(
|
||||
&self,
|
||||
method: Method,
|
||||
path: &str,
|
||||
auth: Option<&Token>,
|
||||
body: Vec<u8>,
|
||||
) -> StatusCode {
|
||||
let mut req = Request::builder().method(method).uri(path);
|
||||
if let Some(t) = auth {
|
||||
req = req.header(header::AUTHORIZATION, t.to_bearer());
|
||||
}
|
||||
let resp = self
|
||||
.0
|
||||
.clone()
|
||||
.oneshot(req.body(Body::from(body)).expect("request"))
|
||||
.await
|
||||
.expect("infallible");
|
||||
let status = resp.status();
|
||||
let body = resp.into_body().collect().await.expect("body").to_bytes();
|
||||
if !status.is_success() {
|
||||
assert!(body.is_empty(), "a refusal has no body");
|
||||
}
|
||||
status
|
||||
}
|
||||
async fn create(&self, m: &Mailbox) -> StatusCode {
|
||||
let body = serde_json::to_vec(&CreateMailbox {
|
||||
id: m.id,
|
||||
post_token_hash: m.post.hash(),
|
||||
fetch_token_hash: m.fetch.hash(),
|
||||
})
|
||||
.expect("json");
|
||||
self.call(Method::POST, "/v0/mailboxes", None, body).await
|
||||
}
|
||||
async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode {
|
||||
self.call(Method::POST, &m.path(), Some(token), blob.to_vec())
|
||||
.await
|
||||
}
|
||||
async fn ack(&self, m: &Mailbox, blob: &[u8]) -> StatusCode {
|
||||
let path = format!("{}/{}", m.path(), blob_hash(blob).to_wire());
|
||||
self.call(Method::DELETE, &path, Some(&m.fetch), vec![])
|
||||
.await
|
||||
}
|
||||
async fn invite(&self) -> (StatusCode, InviteId, Token) {
|
||||
let id = InviteId::from_bytes(random());
|
||||
let secret = Token::from_bytes(random());
|
||||
let body = serde_json::to_vec(&CreateInvite {
|
||||
id,
|
||||
secret_hash: secret.hash(),
|
||||
key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"),
|
||||
})
|
||||
.expect("json");
|
||||
(
|
||||
self.call(Method::POST, "/v0/invites", None, body).await,
|
||||
id,
|
||||
secret,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn small(f: impl FnOnce(&mut Limits)) -> Limits {
|
||||
let mut l = Limits::default();
|
||||
f(&mut l);
|
||||
l
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_protocol_caps_are_the_documented_ones() {
|
||||
assert_eq!(MAILBOX_BLOBS, 1_000);
|
||||
assert_eq!(MAILBOX_BYTES, 32 * 1024 * 1024);
|
||||
let l = Limits::default();
|
||||
assert_eq!(
|
||||
(l.total_bytes, l.mailboxes, l.invites),
|
||||
(1 << 30, 100_000, 10_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_mailbox_holds_a_thousand_blobs_then_says_full_until_one_is_acknowledged() {
|
||||
let relay = Relay::with(Limits::default());
|
||||
let m = Mailbox::new();
|
||||
assert_eq!(relay.create(&m).await, StatusCode::CREATED);
|
||||
for i in 0..MAILBOX_BLOBS {
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &i.to_le_bytes()).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
}
|
||||
let one_more = b"one more";
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, one_more).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE
|
||||
);
|
||||
// A stranger without the token learns nothing: 404, as for any wrong token.
|
||||
let stranger = Token::from_bytes(random());
|
||||
assert_eq!(
|
||||
relay.post(&m, &stranger, one_more).await,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(
|
||||
relay.ack(&m, &0i64.to_le_bytes()).await,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
assert_eq!(relay.post(&m, &m.post, one_more).await, StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_mailbox_holds_at_most_its_bytes() {
|
||||
let relay = Relay::with(small(|l| l.mailbox_bytes = 1000));
|
||||
let m = Mailbox::new();
|
||||
relay.create(&m).await;
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &[1u8; 600]).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &[2u8; 400]).await,
|
||||
StatusCode::CREATED,
|
||||
"exactly at the cap"
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&m, &m.post, &[3u8; 1]).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE
|
||||
);
|
||||
// Another mailbox is not affected.
|
||||
let other = Mailbox::new();
|
||||
relay.create(&other).await;
|
||||
assert_eq!(
|
||||
relay.post(&other, &other.post, &[4u8; 600]).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_relay_holds_at_most_its_bytes_across_mailboxes() {
|
||||
let relay = Relay::with(small(|l| l.total_bytes = 1000));
|
||||
let (a, b) = (Mailbox::new(), Mailbox::new());
|
||||
relay.create(&a).await;
|
||||
relay.create(&b).await;
|
||||
assert_eq!(
|
||||
relay.post(&a, &a.post, &[1u8; 700]).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&b, &b.post, &[2u8; 301]).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE
|
||||
);
|
||||
assert_eq!(
|
||||
relay.post(&b, &b.post, &[2u8; 300]).await,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
assert_eq!(relay.ack(&a, &[1u8; 700]).await, StatusCode::NO_CONTENT);
|
||||
assert_eq!(
|
||||
relay.post(&b, &b.post, &[3u8; 700]).await,
|
||||
StatusCode::CREATED,
|
||||
"room again after an acknowledgement"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_relay_holds_at_most_its_mailboxes() {
|
||||
let relay = Relay::with(small(|l| l.mailboxes = 3));
|
||||
for _ in 0..3 {
|
||||
assert_eq!(relay.create(&Mailbox::new()).await, StatusCode::CREATED);
|
||||
}
|
||||
assert_eq!(
|
||||
relay.create(&Mailbox::new()).await,
|
||||
StatusCode::INSUFFICIENT_STORAGE
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_relay_holds_at_most_its_unclaimed_invites() {
|
||||
let relay = Relay::with(small(|l| l.invites = 2));
|
||||
let (s, id, secret) = relay.invite().await;
|
||||
assert_eq!(s, StatusCode::CREATED);
|
||||
assert_eq!(relay.invite().await.0, StatusCode::CREATED);
|
||||
assert_eq!(relay.invite().await.0, StatusCode::INSUFFICIENT_STORAGE);
|
||||
// A claimed invite is gone and makes room.
|
||||
let path = format!("/v0/invites/{}", id.to_wire());
|
||||
assert_eq!(
|
||||
relay.call(Method::GET, &path, Some(&secret), vec![]).await,
|
||||
StatusCode::OK
|
||||
);
|
||||
assert_eq!(relay.invite().await.0, StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_operator_sets_the_relay_wide_caps() {
|
||||
let args = parse_args(
|
||||
[
|
||||
"--max-bytes",
|
||||
"5000",
|
||||
"--max-mailboxes",
|
||||
"7",
|
||||
"--max-invites",
|
||||
"9",
|
||||
]
|
||||
.map(String::from),
|
||||
)
|
||||
.expect("args");
|
||||
assert_eq!(
|
||||
(
|
||||
args.limits.total_bytes,
|
||||
args.limits.mailboxes,
|
||||
args.limits.invites
|
||||
),
|
||||
(5000, 7, 9)
|
||||
);
|
||||
assert_eq!(
|
||||
args.limits.mailbox_blobs, MAILBOX_BLOBS,
|
||||
"not the operator's"
|
||||
);
|
||||
for bad in [
|
||||
vec!["--max-bytes"],
|
||||
vec!["--max-bytes", "0"],
|
||||
vec!["--max-bytes", "-5"],
|
||||
vec!["--max-mailboxes", "many"],
|
||||
vec!["--max-invites", "1.5"],
|
||||
] {
|
||||
assert!(
|
||||
parse_args(bad.iter().map(|s| s.to_string())).is_err(),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_expired_invite_does_not_count_against_new_ones() {
|
||||
let store = Store::open_in_memory_with(small(|l| l.invites = 1)).expect("store");
|
||||
let invite = || CreateInvite {
|
||||
id: InviteId::from_bytes(random()),
|
||||
secret_hash: Token::from_bytes(random()).hash(),
|
||||
key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"),
|
||||
};
|
||||
store.create_invite(&invite(), T0).expect("first");
|
||||
assert_eq!(
|
||||
store.create_invite(&invite(), T0 + 3600),
|
||||
Err(tabellarius_relay::store::Refused::Full)
|
||||
);
|
||||
// Eight days on, the first has expired, though the hourly purge has not run yet.
|
||||
store
|
||||
.create_invite(&invite(), T0 + 8 * 24 * 3600)
|
||||
.expect("room after the expiry");
|
||||
}
|
||||
@@ -741,3 +741,98 @@ async fn no_random_request_breaks_the_relay() {
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /join` (PROTOCOL.md §8, 2026-11-18): a static page that hands the fragment to the app. It
|
||||
/// must load nothing from elsewhere, run nothing but its own script, and keep nothing.
|
||||
#[tokio::test]
|
||||
async fn the_join_page_is_static_and_loads_nothing_from_elsewhere() {
|
||||
use tower::ServiceExt;
|
||||
let relay = Relay::in_memory();
|
||||
let response = relay
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(Request::get("/join").body(Body::empty()).expect("request"))
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let h = response.headers().clone();
|
||||
let get = |name: &str| {
|
||||
h.get(name)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
};
|
||||
assert_eq!(get("content-type"), "text/html; charset=utf-8");
|
||||
assert_eq!(get("cache-control"), "no-store");
|
||||
assert_eq!(get("referrer-policy"), "no-referrer");
|
||||
assert_eq!(get("x-content-type-options"), "nosniff");
|
||||
assert!(h.get("set-cookie").is_none());
|
||||
let csp = get("content-security-policy");
|
||||
assert!(
|
||||
csp.starts_with("default-src 'none'; script-src 'sha256-"),
|
||||
"{csp}"
|
||||
);
|
||||
for part in [
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'",
|
||||
"frame-ancestors 'none'",
|
||||
] {
|
||||
assert!(csp.contains(part), "{csp} lacks {part}");
|
||||
}
|
||||
let body = String::from_utf8(
|
||||
response
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.expect("body")
|
||||
.to_bytes()
|
||||
.to_vec(),
|
||||
)
|
||||
.expect("utf-8");
|
||||
// Nothing loaded from anywhere, and nothing the script could send the fragment with or leave
|
||||
// the page by on its own (a custom scheme must wait for the person's tap).
|
||||
for banned in [
|
||||
"http://",
|
||||
"https://",
|
||||
" src=",
|
||||
"<link",
|
||||
"<img",
|
||||
"<iframe",
|
||||
"@import",
|
||||
"url(",
|
||||
"fetch(",
|
||||
"XMLHttpRequest",
|
||||
"sendBeacon",
|
||||
"WebSocket",
|
||||
"location.href",
|
||||
"location.assign",
|
||||
"location.replace",
|
||||
"window.open",
|
||||
] {
|
||||
assert!(!body.contains(banned), "the page contains {banned:?}");
|
||||
}
|
||||
// One script and one style, both named by the policy's hashes; the invite goes to the app.
|
||||
assert_eq!(body.matches("<script>").count(), 1);
|
||||
assert_eq!(body.matches("<style>").count(), 1);
|
||||
assert!(body.contains("\"amicitia://invite?relay=\" + location.origin + \"#\" + invite"));
|
||||
assert!(body.contains("location.hash"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_join_page_policy_hashes_its_own_script_and_style() {
|
||||
use base64::Engine;
|
||||
use sha2::{Digest, Sha256};
|
||||
let page = tabellarius_relay::join::PAGE;
|
||||
let between = |open: &str, close: &str| {
|
||||
let s = page.find(open).expect("the tag opens") + open.len();
|
||||
&page[s..page[s..].find(close).expect("the tag closes") + s]
|
||||
};
|
||||
let csp = tabellarius_relay::join::CONTENT_SECURITY_POLICY.as_str();
|
||||
for text in [
|
||||
between("<script>", "</script>"),
|
||||
between("<style>", "</style>"),
|
||||
] {
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(text.as_bytes()));
|
||||
assert!(csp.contains(&format!("'sha256-{b64}'")), "{csp}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Running the relay on NixOS
|
||||
|
||||
The relay listens on `127.0.0.1` only. Caddy sits in front with TLS from Let's Encrypt, and writes
|
||||
no log that holds an address (`.agents/features/home-relay.md`).
|
||||
|
||||
## 1. Before
|
||||
- A DNS name for the relay (an `A` and/or `AAAA` record) pointing at the machine.
|
||||
- Ports **80** and **443** reachable from the internet. 80 is for Let's Encrypt's challenge; Caddy
|
||||
redirects everything else on it to 443.
|
||||
|
||||
## 2. The configuration
|
||||
In the machine's flake:
|
||||
```nix
|
||||
{
|
||||
inputs.tabellarius.url = "git+https://gitea.marek-novak.cz/mnovak/Amicitia-Tabellarius?ref=main";
|
||||
|
||||
outputs = { nixpkgs, tabellarius, ... }: {
|
||||
nixosConfigurations.home = nixpkgs.lib.nixosSystem {
|
||||
system = "x86_64-linux";
|
||||
modules = [
|
||||
tabellarius.nixosModules.default
|
||||
{
|
||||
services.tabellarius = {
|
||||
enable = true;
|
||||
domain = "relay.example.cz";
|
||||
# Optional, the defaults shown:
|
||||
# maxBytes = 1073741824; maxMailboxes = 100000; maxInvites = 10000;
|
||||
};
|
||||
}
|
||||
./configuration.nix
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
Pin `tabellarius` in `flake.lock`, as for any input. Then `nixos-rebuild switch --flake .#home`.
|
||||
|
||||
## 3. What it sets up
|
||||
| Part | What it does |
|
||||
|:--|:--|
|
||||
| `tabellarius.service` | `--listen 127.0.0.1:8470`, its database in `/var/lib/private/tabellarius`, a dynamic user, and a systemd sandbox. It may talk to localhost only (`IPAddressAllow=localhost`) |
|
||||
| Caddy | one virtual host, `reverse_proxy` to the relay. No access log, no error log. `X-Forwarded-For`, `X-Real-IP` and `Forwarded` are removed, so the relay never learns who connected |
|
||||
| Firewall | 80 and 443 open. `logRefusedConnections` off by default: a relay that keeps no address keeps no stranger's either |
|
||||
|
||||
## 4. Check it
|
||||
- From another machine: `curl https://relay.example.cz/version` answers with the versions.
|
||||
- On the server, after some use, the address of the machine you used must appear nowhere:
|
||||
`journalctl -o verbose | grep -F <that address>` and `grep -rF <that address> /var/log` find
|
||||
nothing.
|
||||
- The same check runs automatically in a VM: `nix flake check` in this repository (Linux, KVM).
|
||||
|
||||
> **Not run yet (2026-11-16).** This module and its VM test were written on a machine without Nix
|
||||
> and have never been evaluated. Until `nix flake check` passes on Linux, and the check above is
|
||||
> done on the real server, *Caddy keeps no address* is the design, not a tested fact.
|
||||
|
||||
## 5. In the app
|
||||
Settings → *Your message relay*: `https://relay.example.cz`. Until the app accepts `https://`
|
||||
addresses (Amicitia F23), it takes a loopback address only.
|
||||
|
||||
## 6. What the operator still sees
|
||||
Caddy and the relay keep nothing, but the machine's network still carries the connections while
|
||||
they happen. A router or ISP log, or `tcpdump` on the server, would show addresses and timing
|
||||
(`docs/PROTOCOL.md` §1). Turning Caddy's log on, even for a while, writes addresses. Do it only
|
||||
knowing that.
|
||||
@@ -0,0 +1,142 @@
|
||||
# The Tabellarius relay on NixOS, behind Caddy with TLS, and no log that holds an address
|
||||
# (.agents/features/home-relay.md). Import it from the flake: `tabellarius.nixosModules.default`.
|
||||
#
|
||||
# services.tabellarius = {
|
||||
# enable = true;
|
||||
# domain = "relay.example.cz"; # its DNS name points at this machine; ports 80 and 443 open
|
||||
# };
|
||||
{ self }:
|
||||
{ config, lib, pkgs, ... }:
|
||||
let
|
||||
cfg = config.services.tabellarius;
|
||||
system = pkgs.stdenv.hostPlatform.system;
|
||||
in
|
||||
{
|
||||
options.services.tabellarius = {
|
||||
enable = lib.mkEnableOption "the Tabellarius message relay, behind Caddy with TLS and no logs";
|
||||
|
||||
domain = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
example = "relay.example.cz";
|
||||
description = "The relay's DNS name. Caddy gets its certificate from Let's Encrypt.";
|
||||
};
|
||||
|
||||
package = lib.mkOption {
|
||||
type = lib.types.package;
|
||||
default = self.packages.${system}.default;
|
||||
defaultText = lib.literalExpression "tabellarius.packages.\${system}.default";
|
||||
description = "The relay, built from this flake: the code that runs is the code published.";
|
||||
};
|
||||
|
||||
port = lib.mkOption {
|
||||
type = lib.types.port;
|
||||
default = 8470;
|
||||
description = "The loopback port between Caddy and the relay. Never exposed.";
|
||||
};
|
||||
|
||||
maxBytes = lib.mkOption {
|
||||
type = lib.types.ints.positive;
|
||||
default = 1073741824;
|
||||
description = "Waiting blobs the relay holds, in bytes, before it answers 507 (PROTOCOL.md section 8).";
|
||||
};
|
||||
|
||||
maxMailboxes = lib.mkOption {
|
||||
type = lib.types.ints.positive;
|
||||
default = 100000;
|
||||
description = "Mailboxes the relay holds before it answers 507.";
|
||||
};
|
||||
|
||||
maxInvites = lib.mkOption {
|
||||
type = lib.types.ints.positive;
|
||||
default = 10000;
|
||||
description = "Unclaimed invites the relay holds before it answers 507.";
|
||||
};
|
||||
|
||||
openFirewall = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = "Open ports 80 (the ACME challenge, then a redirect) and 443.";
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
systemd.services.tabellarius = {
|
||||
description = "Tabellarius message relay (loopback only; Caddy in front)";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "network.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = lib.escapeShellArgs [
|
||||
"${cfg.package}/bin/tabellarius-relay"
|
||||
"--listen" "127.0.0.1:${toString cfg.port}"
|
||||
"--db" "/var/lib/tabellarius/relay.db"
|
||||
"--max-bytes" (toString cfg.maxBytes)
|
||||
"--max-mailboxes" (toString cfg.maxMailboxes)
|
||||
"--max-invites" (toString cfg.maxInvites)
|
||||
];
|
||||
Restart = "on-failure";
|
||||
DynamicUser = true;
|
||||
StateDirectory = "tabellarius";
|
||||
StateDirectoryMode = "0700";
|
||||
UMask = "0077";
|
||||
|
||||
# It talks to Caddy on loopback and to nothing else, even if it had a bug.
|
||||
IPAddressDeny = "any";
|
||||
IPAddressAllow = "localhost";
|
||||
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
|
||||
|
||||
CapabilityBoundingSet = "";
|
||||
NoNewPrivileges = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
PrivateTmp = true;
|
||||
PrivateDevices = true;
|
||||
PrivateUsers = true;
|
||||
ProtectHostname = true;
|
||||
ProtectClock = true;
|
||||
ProtectKernelTunables = true;
|
||||
ProtectKernelModules = true;
|
||||
ProtectKernelLogs = true;
|
||||
ProtectControlGroups = true;
|
||||
ProtectProc = "invisible";
|
||||
ProcSubset = "pid";
|
||||
RestrictNamespaces = true;
|
||||
RestrictRealtime = true;
|
||||
RestrictSUIDSGID = true;
|
||||
RemoveIPC = true;
|
||||
LockPersonality = true;
|
||||
MemoryDenyWriteExecute = true;
|
||||
SystemCallArchitectures = "native";
|
||||
SystemCallFilter = [ "@system-service" "~@privileged" ];
|
||||
};
|
||||
};
|
||||
|
||||
services.caddy = {
|
||||
enable = true;
|
||||
# Caddy's own logger: errors about TLS handshakes or upstreams can name a client's address.
|
||||
# No log is the rule; an operator who needs one turns it on for a while, knowing why.
|
||||
logFormat = ''
|
||||
output discard
|
||||
'';
|
||||
virtualHosts.${cfg.domain} = {
|
||||
# The NixOS module writes an access log per host by default; this one writes none.
|
||||
logFormat = ''
|
||||
output discard
|
||||
'';
|
||||
extraConfig = ''
|
||||
reverse_proxy 127.0.0.1:${toString cfg.port} {
|
||||
# The relay never learns who connected: Caddy adds these by default.
|
||||
header_up -X-Forwarded-For
|
||||
header_up -X-Real-IP
|
||||
header_up -Forwarded
|
||||
}
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ 80 443 ];
|
||||
# NixOS logs every refused connection with its source address by default. Those are strangers,
|
||||
# not users, but a relay that keeps no address should not keep theirs either. mkDefault: the
|
||||
# machine's owner can turn it back on.
|
||||
networking.firewall.logRefusedConnections = lib.mkDefault false;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# `nix flake check` (Linux, KVM): two machines. `server` runs the module; `client` talks to it
|
||||
# through Caddy with TLS, does everything the protocol allows and some things it refuses, fills a
|
||||
# mailbox cap to its 507, and then the test fails if the client's address appears anywhere in the
|
||||
# server's journal or under /var/log, or in the relay's database (.agents/features/home-relay.md).
|
||||
{ self, pkgs }:
|
||||
pkgs.testers.runNixOSTest {
|
||||
name = "tabellarius-relay-keeps-no-address";
|
||||
|
||||
nodes.server = { lib, ... }: {
|
||||
imports = [ self.nixosModules.default ];
|
||||
services.tabellarius = {
|
||||
enable = true;
|
||||
domain = "relay.test";
|
||||
maxMailboxes = 3;
|
||||
};
|
||||
# No Let's Encrypt inside a VM: Caddy's own CA instead.
|
||||
services.caddy.virtualHosts."relay.test".extraConfig = lib.mkBefore "tls internal";
|
||||
};
|
||||
|
||||
nodes.client = { pkgs, ... }: {
|
||||
environment.systemPackages = [ pkgs.curl pkgs.python3 ];
|
||||
};
|
||||
|
||||
testScript = ''
|
||||
import base64, hashlib, json, os
|
||||
|
||||
def b64(raw):
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
||||
|
||||
start_all()
|
||||
server.wait_for_unit("tabellarius.service")
|
||||
server.wait_for_unit("caddy.service")
|
||||
server.wait_for_open_port(443)
|
||||
client.wait_for_unit("multi-user.target")
|
||||
|
||||
client_ip = client.succeed("ip -4 -o addr show dev eth1 | awk '{print $4}' | cut -d/ -f1").strip()
|
||||
server_ip = server.succeed("ip -4 -o addr show dev eth1 | awk '{print $4}' | cut -d/ -f1").strip()
|
||||
assert client_ip and server_ip and client_ip != server_ip, (client_ip, server_ip)
|
||||
|
||||
def call(method, path, token=None, body=None, json_body=False):
|
||||
cmd = ["curl", "-sk", "-o", "/dev/null", "-w", "%{http_code}",
|
||||
"--resolve", "relay.test:443:" + server_ip, "-X", method]
|
||||
if token:
|
||||
cmd += ["-H", "Authorization: Bearer " + token]
|
||||
if body is not None:
|
||||
client.succeed("cat > /tmp/body <<'EOF'\n" + body + "\nEOF")
|
||||
client.succeed("truncate -s -1 /tmp/body")
|
||||
cmd += ["--data-binary", "@/tmp/body"]
|
||||
if json_body:
|
||||
cmd += ["-H", "Content-Type: application/json"]
|
||||
cmd.append("https://relay.test" + path)
|
||||
return client.succeed(" ".join("'" + c + "'" for c in cmd)).strip()
|
||||
|
||||
def mailbox():
|
||||
mid, post, fetch = os.urandom(16), os.urandom(32), os.urandom(32)
|
||||
body = json.dumps({"id": b64(mid), "postTokenHash": b64(hashlib.sha256(post).digest()),
|
||||
"fetchTokenHash": b64(hashlib.sha256(fetch).digest())})
|
||||
return b64(mid), b64(post), b64(fetch), body
|
||||
|
||||
assert call("GET", "/version") == "200"
|
||||
mid, post, fetch, body = mailbox()
|
||||
assert call("POST", "/v0/mailboxes", body=body, json_body=True) == "201"
|
||||
blob = "sealed-envelope-for-the-test"
|
||||
assert call("POST", "/v0/mailboxes/" + mid + "/blobs", token=post, body=blob) == "201"
|
||||
assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=fetch) == "200"
|
||||
digest = b64(hashlib.sha256(blob.encode()).digest())
|
||||
assert call("DELETE", "/v0/mailboxes/" + mid + "/blobs/" + digest, token=fetch) == "204"
|
||||
# Refusals: a wrong token, a malformed id, a body that is not JSON.
|
||||
assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=b64(os.urandom(32))) == "404"
|
||||
assert call("GET", "/v0/mailboxes/nonsense/blobs", token=fetch) == "404"
|
||||
assert call("POST", "/v0/mailboxes", body="not json", json_body=True) == "400"
|
||||
# The cap: three mailboxes, then 507.
|
||||
for _ in range(2):
|
||||
assert call("POST", "/v0/mailboxes", body=mailbox()[3], json_body=True) == "201"
|
||||
assert call("POST", "/v0/mailboxes", body=mailbox()[3], json_body=True) == "507"
|
||||
|
||||
# Nowhere on the server: not in the journal, not under /var/log, not in the relay's data.
|
||||
server.succeed("journalctl --sync")
|
||||
server.fail("journalctl --no-pager -o verbose | grep -F '" + client_ip + "'")
|
||||
server.fail("grep -rF '" + client_ip + "' /var/log /var/lib/private/tabellarius")
|
||||
'';
|
||||
}
|
||||
+28
-1
@@ -46,6 +46,19 @@ MLS**. To the relay, the welcome mailbox is an ordinary mailbox.
|
||||
*(Changed 2026-11-14, approved by Mark, from "the invitee replies with their own KeyPackage": the
|
||||
invitee needs no KeyPackage, because it creates the group itself.)*
|
||||
|
||||
### Payloads inside MLS *(added 2026-11-17, F24; `.agents/features/block-and-receipts.md`)*
|
||||
Every MLS application message carries one JSON object. The relay sees none of it.
|
||||
| `kind` | Fields | Meaning |
|
||||
|:--|:--|:--|
|
||||
| `hello` | `mailbox`, `postToken`, `name` | where and how to post to the sender; once per conversation |
|
||||
| `text` | `body`, `seq` | a message; `seq` counts the sender's texts to this contact from 1 |
|
||||
| `receipt` | `upto` | the receiver has saved the sender's texts up to `upto`. Sent only by a client with receipts on; a client with them off also ignores them |
|
||||
| `inbox` | `postToken` | a new post token for the mailbox the receiver already knows (after an unblock). It cannot name another mailbox |
|
||||
|
||||
**Block** (§3) is a rotate of the post token to the hash of a token nobody gets. Nothing is sent to
|
||||
the blocked person: their posts get §8's ordinary 404. What they posted before is fetched and
|
||||
dropped. **Unblock** rotates again and sends the new token in an `inbox` payload.
|
||||
|
||||
## 5. What the relay stores — the complete list
|
||||
| Table | Columns |
|
||||
|:--|:--|
|
||||
@@ -76,7 +89,7 @@ The platform facts above are Claude's understanding, to be verified in `.agents/
|
||||
- Parsers are fuzzed (`cargo fuzz`) for every message type.
|
||||
- Every check in `VERIFY.md` §1 has a CI job or a documented manual procedure.
|
||||
|
||||
## 8. The wire (v0) — approved 2026-11-08, routes added 2026-11-14
|
||||
## 8. The wire (v0) — approved 2026-11-08, routes added 2026-11-14, quotas 2026-11-16, join page 2026-11-18
|
||||
HTTP/1.1 behind TLS (the reverse proxy, F23). Ids and tokens are unpadded base64url of a fixed length
|
||||
with one canonical spelling: ids are 16 bytes, and tokens and hashes are 32. JSON bodies refuse
|
||||
unknown fields. A blob is at most 256 KiB, and a KeyPackage at most 16 KiB.
|
||||
@@ -91,9 +104,23 @@ unknown fields. A blob is at most 256 KiB, and a KeyPackage at most 16 KiB.
|
||||
| `POST /v0/invites` `{id, secretHash, keyPackage}` | none | stores an invite. It expires after 7 days, rounded up to the hour |
|
||||
| `GET /v0/invites/{id}` | invite secret | returns the KeyPackage once, then deletes the invite |
|
||||
| `GET /version` | none | the protocol and relay versions |
|
||||
| `GET /join` | none | a static page for an invite link opened in a browser *(added 2026-11-18)* |
|
||||
|
||||
- A wrong token, an unknown id and a malformed id all give the same bare **404**, so nobody can probe
|
||||
what exists.
|
||||
- **Quotas** *(added 2026-11-16, F23, so a relay can face the internet; `.agents/features/home-relay.md`)*:
|
||||
a mailbox holds at most **1 000 waiting blobs** and **32 MiB**, and a relay at most what its
|
||||
operator sets (by default 1 GiB of blobs, 100 000 mailboxes, 10 000 unclaimed invites). Over a
|
||||
limit the answer is a bare **507**. The per-mailbox caps are checked only after the post token,
|
||||
so a 507 tells a stranger nothing about a mailbox. Nothing new is stored to count: the counts
|
||||
come from §5's own rows and `size`. A client treats 507 like any failure and tries again later.
|
||||
- **The join page** *(added 2026-11-18; `.agents/features/join-page.md`)*: an invite can travel as
|
||||
`https://<relay>/join#<invite id>.<secret>`, which messengers make tappable. The browser sends
|
||||
only `GET /join`: the fragment, and so the secret, never reaches the relay, a link preview or a
|
||||
proxy. The page is static (one inline script and style, named by hash in a
|
||||
`Content-Security-Policy` of `default-src 'none'`; `no-store`; `no-referrer`; no cookie) and
|
||||
points its one button at `amicitia://invite?relay=<its origin>#<id>.<secret>`. The relay stores
|
||||
nothing for it and learns only that some address opened the page.
|
||||
- A refusal has no body.
|
||||
- The relay prints no request.
|
||||
- Tests: `crates/relay/tests/relay.rs`, `crates/protocol/tests/wire.rs`.
|
||||
|
||||
@@ -21,6 +21,13 @@
|
||||
};
|
||||
});
|
||||
|
||||
# The relay on NixOS: loopback only, behind Caddy with TLS and no logs (deploy/nixos).
|
||||
nixosModules.default = import ./deploy/nixos/module.nix { inherit self; };
|
||||
|
||||
# A VM test that the server keeps no client address anywhere (needs Linux and KVM).
|
||||
checks.x86_64-linux.relay-keeps-no-address =
|
||||
import ./deploy/nixos/test.nix { inherit self; pkgs = nixpkgs.legacyPackages.x86_64-linux; };
|
||||
|
||||
devShells = forAll (pkgs: {
|
||||
default = pkgs.mkShell {
|
||||
packages = with pkgs; [ cargo rustc clippy rustfmt ];
|
||||
|
||||
Reference in New Issue
Block a user