Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c45b008e97 |
||
| cf77116143 | |||
|
|
7f3ef8c3fc |
||
| 1c998e9472 | |||
|
|
3620e4f38f |
||
| 4e8d8c0f25 | |||
|
|
69a15fe909 |
||
| 14fccd5396 | |||
|
|
34c257dab5 |
18 changed files with 2903 additions and 18 deletions
36
README.md
36
README.md
|
|
@ -3,7 +3,7 @@
|
||||||
Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti).
|
Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti).
|
||||||
No hosted server. Identity is a public key; the onion is only a locator.
|
No hosted server. Identity is a public key; the onion is only a locator.
|
||||||
|
|
||||||
**v0.2.1** — Linux TUI + Android SDK/APK. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Unreachable chat peers go to a **local outbox** (device-only retry queue — no relay); file transfer and payment frames still fail closed. Optional Monero payments: `/pay` invoices (receive), `/tip` payments (send), and a full in-app wallet create/import (`F6` wallet screen, `/wallet create`, `/wallet import`). Arti onion services are still experimental. The whole store is encrypted at rest with SQLCipher; message bodies add a row-bound AEAD layer on top.
|
**v0.2.1** — Linux TUI + Android SDK/APK. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion, and every chat message is ratcheted inside that session. Unreachable chat peers go to a **local outbox** (device-only retry queue — no relay); file transfer and payment frames still fail closed. Optional Monero payments: `/pay` invoices (receive), `/tip` payments (send), and a full in-app wallet create/import (`F6` wallet screen, `/wallet create`, `/wallet import`). Arti onion services are still experimental. The whole store is encrypted at rest with SQLCipher; message bodies add a row-bound AEAD layer on top.
|
||||||
|
|
||||||
You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion.
|
You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion.
|
||||||
|
|
||||||
|
|
@ -185,6 +185,40 @@ Still **fail closed** (no queue, no retry):
|
||||||
- Arti cannot publish the onion (no C-tor fallback)
|
- Arti cannot publish the onion (no C-tor fallback)
|
||||||
- no DHT, no name server, no hosted chat server
|
- no DHT, no name server, no hosted chat server
|
||||||
|
|
||||||
|
## Chat ratchet (per friend, on device)
|
||||||
|
|
||||||
|
Chat is ratcheted on top of the Noise session: each chat send is
|
||||||
|
Double-Ratchet encrypted first, and the resulting `rat ` frame is what the
|
||||||
|
one-shot Noise session carries. Forward secrecy is per chain, and a snapshot of
|
||||||
|
one side's state stops reading the conversation at the next DH ratchet step.
|
||||||
|
The wire format and the honest limits are in
|
||||||
|
[docs/PROTOCOL.md](docs/PROTOCOL.md) and
|
||||||
|
[docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
|
||||||
|
|
||||||
|
- Per-friend state lives in the encrypted store (`ratchet_sessions`, one row per
|
||||||
|
friend). Nothing about it is transmitted, so the "no relay, no server queue"
|
||||||
|
rule is unchanged.
|
||||||
|
- Message numbers, ratchet keys and chain state ride *inside* the Noise
|
||||||
|
ciphertext; there is nothing new to observe on the wire.
|
||||||
|
- **Only chat is ratcheted.** `loc`, `prf`, `inv`, `rcp`, `tip` and file chunks
|
||||||
|
keep the one-shot Noise shape.
|
||||||
|
- Out-of-order delivery works (bounded skipped keys: 2000 per chain jump, 2000
|
||||||
|
stored, oldest-first eviction; a used key is deleted, so a replay fails
|
||||||
|
closed). A queued chat message re-sends the *same* `rat ` frame, so an outbox
|
||||||
|
retry never burns a second chain key.
|
||||||
|
- `/wipe` clears chat, payments and outbox rows but **keeps** the ratchet state
|
||||||
|
(roster and identity stay), so chat continues on the same epoch. `/wipe-all`
|
||||||
|
removes the data dir and the state with it.
|
||||||
|
- **Session reset.** There is no `/reset` command and no in-band reset in
|
||||||
|
v0.2.1. The state is dropped automatically when the friend's prekey changes —
|
||||||
|
i.e. when you `F3`-paste a refreshed invite — and the next chat frame
|
||||||
|
bootstraps a fresh epoch. That re-paste is the only recovery path today.
|
||||||
|
- **Desync today is quiet.** An inbound `rat ` frame that does not authenticate
|
||||||
|
is logged as `rat dropped (<reason>)` on stderr and dropped: no chat row, no
|
||||||
|
TUI marker, nothing stored. A send-side failure surfaces as the usual
|
||||||
|
`send failed: …` status note. There is no in-app "ratchet desynced" banner
|
||||||
|
yet, so a desync is diagnosed from the terminal the app was started in.
|
||||||
|
|
||||||
## File transfer
|
## File transfer
|
||||||
|
|
||||||
`/file /path` sends a local file to the selected friend. Both must be online.
|
`/file /path` sends a local file to the selected friend. Both must be online.
|
||||||
|
|
|
||||||
|
|
@ -1061,6 +1061,7 @@ mod tests {
|
||||||
friend_pk: vec![0xaa; 32],
|
friend_pk: vec![0xaa; 32],
|
||||||
message_id: 42,
|
message_id: 42,
|
||||||
body: b"hello".to_vec(),
|
body: b"hello".to_vec(),
|
||||||
|
payload: None,
|
||||||
attempts,
|
attempts,
|
||||||
next_attempt_at: 1_700_000_045,
|
next_attempt_at: 1_700_000_045,
|
||||||
created_at: 1_700_000_000,
|
created_at: 1_700_000_000,
|
||||||
|
|
|
||||||
232
docs/PROTOCOL.md
232
docs/PROTOCOL.md
|
|
@ -142,14 +142,21 @@ After decrypt, classify the plaintext:
|
||||||
| `rcp ` | Monero receipt claim | drop |
|
| `rcp ` | Monero receipt claim | drop |
|
||||||
| `png ` | ping (reserved) | drop |
|
| `png ` | ping (reserved) | drop |
|
||||||
| `fil ` | file chunk | drop |
|
| `fil ` | file chunk | drop |
|
||||||
|
| `rat ` | Double Ratchet chat frame (see Ratchet) | drop |
|
||||||
| `[a-z][a-z][a-z] ` | unknown typed frame | **drop** (not chat) |
|
| `[a-z][a-z][a-z] ` | unknown typed frame | **drop** (not chat) |
|
||||||
| anything else | chat | store as a chat line |
|
| anything else | chat | store as a chat line |
|
||||||
|
|
||||||
|
`rat ` is classified before the `[a-z]{3} ` catch-all, so a peer that does not
|
||||||
|
implement the ratchet drops a chat frame instead of rendering ciphertext as a
|
||||||
|
chat line. Older builds that stored `rat `-prefixed bytes as chat are obsolete;
|
||||||
|
upgrade both sides.
|
||||||
|
|
||||||
A peer that does not implement a typed prefix MUST still drop
|
A peer that does not implement a typed prefix MUST still drop
|
||||||
`[a-z]{3}<space>…` rather than render it as chat. Mixed-version 0.1.2 clients
|
`[a-z]{3}<space>…` rather than render it as chat. Mixed-version 0.1.2 clients
|
||||||
that stored those as chat are obsolete; upgrade both sides.
|
that stored those as chat are obsolete; upgrade both sides.
|
||||||
|
|
||||||
Chat MUST NOT begin with three lowercase ASCII letters and a space.
|
Chat MUST NOT begin with three lowercase ASCII letters and a space. (Inside a
|
||||||
|
`rat ` frame the plaintext is a chat line and is not re-classified.)
|
||||||
|
|
||||||
Hex on the wire is lowercase on encode; decode accepts either case. No `0x`
|
Hex on the wire is lowercase on encode; decode accepts either case. No `0x`
|
||||||
prefix.
|
prefix.
|
||||||
|
|
@ -303,6 +310,11 @@ is a chat line `[file] name (N bytes)`, never the raw frame.
|
||||||
|
|
||||||
### Chat
|
### Chat
|
||||||
|
|
||||||
|
A chat send is ratcheted: the wire form of a chat message is a `rat ` frame
|
||||||
|
(see “Ratchet (v1 chat layer)”), and the plaintext inside that frame is the chat
|
||||||
|
line below. A bare chat frame with no typed prefix is still accepted inbound as
|
||||||
|
a chat line (v0.2.1 peers), but MUST NOT be emitted.
|
||||||
|
|
||||||
UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the
|
UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the
|
||||||
implementation does not drop the row). Control and bidi formatting
|
implementation does not drop the row). Control and bidi formatting
|
||||||
characters are stripped at ingest and at render: C0 0x00–0x1F except
|
characters are stripped at ingest and at render: C0 0x00–0x1F except
|
||||||
|
|
@ -312,6 +324,221 @@ so emoji sequences stay intact. `fil ` filenames must not contain
|
||||||
those characters (tab and newline included). Displayed as a line.
|
those characters (tab and newline included). Displayed as a line.
|
||||||
No length limit beyond the frame cap.
|
No length limit beyond the frame cap.
|
||||||
|
|
||||||
|
## Ratchet (v1 chat layer)
|
||||||
|
|
||||||
|
Chat is the only application payload that is ratcheted. A chat send is
|
||||||
|
Double-Ratchet encrypted first, and the resulting `rat ` frame is the
|
||||||
|
application plaintext that a normal one-shot Noise session carries (handshake,
|
||||||
|
one application frame, close — see Transport). Nothing else changes about the
|
||||||
|
session.
|
||||||
|
|
||||||
|
The ratchet header is **inside** the Noise transport message, never in clear on
|
||||||
|
the wire. That is a deliberate divergence from the shape this layer came from:
|
||||||
|
the plan assumed a plaintext header (`dh_pub || N || PN`) ahead of the
|
||||||
|
ciphertext, which was rejected because a plaintext header would hand an observer
|
||||||
|
per-message counters and ratchet-key changes for no benefit — the Noise session
|
||||||
|
already hides the frame, so the header is authenticated as AEAD associated data
|
||||||
|
instead.
|
||||||
|
|
||||||
|
### Frame
|
||||||
|
|
||||||
|
```
|
||||||
|
"rat " 4 bytes (0x72 0x61 0x74 0x20)
|
||||||
|
version 1 byte 0x01
|
||||||
|
header 40 bytes dh_pub[32] || N uint32 BE || PN uint32 BE
|
||||||
|
nonce 12 bytes random, per message
|
||||||
|
ciphertext n+16 ChaCha20-Poly1305 ciphertext || tag
|
||||||
|
```
|
||||||
|
|
||||||
|
- `dh_pub` — the sender's current ratchet public key (X25519, 32 bytes).
|
||||||
|
- `N` — the index of this message in the sender's current sending chain,
|
||||||
|
counting from 0.
|
||||||
|
- `PN` — how many messages the sender sent in its *previous* sending chain.
|
||||||
|
- Associated data is the 40-byte header, exactly as serialized above
|
||||||
|
(`dh_pub || N as u32 BE || PN as u32 BE`). A tampered `dh_pub`, `N` or `PN`
|
||||||
|
therefore fails closed.
|
||||||
|
- The ChaCha20-Poly1305 key is the message key from `KDF_CK`. The 12-byte nonce
|
||||||
|
is random per message, not a chain counter.
|
||||||
|
- Minimum frame (empty plaintext) is 73 bytes: 5 + 40 + 12 + 16.
|
||||||
|
- A receiver MUST reject a frame without the `rat ` prefix, a version other than
|
||||||
|
`0x01`, or less than 73 bytes.
|
||||||
|
- The frame must fit the Noise body cap (65535 bytes, including the 16-byte
|
||||||
|
Poly1305 tag), so a `rat ` frame is at most 65519 bytes.
|
||||||
|
|
||||||
|
Because the header rides inside Noise, an observer sees one opaque ciphertext
|
||||||
|
per message: no message counts, no ratchet keys, and nothing that marks a first
|
||||||
|
message of a chain versus a later one.
|
||||||
|
|
||||||
|
### KDFs
|
||||||
|
|
||||||
|
Signal's constructions, unchanged:
|
||||||
|
|
||||||
|
```
|
||||||
|
KDF_RK(root, dh_out):
|
||||||
|
okm = HKDF-SHA256(salt = root, ikm = dh_out,
|
||||||
|
info = "onionwire-ratchet-v1-kdfrk", L = 64)
|
||||||
|
new_root = okm[0..32]
|
||||||
|
chain_key = okm[32..64]
|
||||||
|
|
||||||
|
KDF_CK(chain_key):
|
||||||
|
message_key = HMAC-SHA256(chain_key, 0x01)
|
||||||
|
next_chain_key = HMAC-SHA256(chain_key, 0x02)
|
||||||
|
```
|
||||||
|
|
||||||
|
`HKDF` is RFC 5869 with SHA-256 (`hkdf` 0.12), `HMAC` is SHA-256 (`hmac`
|
||||||
|
0.12). Each side of an epoch derives its chains from one shared DH output with
|
||||||
|
`KDF_RK` called **twice**:
|
||||||
|
|
||||||
|
```
|
||||||
|
epoch_chains(root, shared) -> (new_root, ck_lo, ck_hi):
|
||||||
|
(root1, ck_lo) = KDF_RK(root, shared)
|
||||||
|
(root2, ck_hi) = KDF_RK(root1, shared)
|
||||||
|
new_root = root2
|
||||||
|
```
|
||||||
|
|
||||||
|
`lo` is the lexicographically lower of the pair's two ratchet public keys and
|
||||||
|
`hi` the higher, comparing the 32 raw bytes. The chain a peer sends on is
|
||||||
|
`ck_lo` if `sender_pub <= receiver_pub`, else `ck_hi`; the receiving chain is the
|
||||||
|
other one. The epoch's chains are a pure function of the *unordered* pair, and
|
||||||
|
the second `KDF_RK` call's root is the epoch's new root.
|
||||||
|
|
||||||
|
### Bootstrap
|
||||||
|
|
||||||
|
The bootstrap epoch is derived, never exchanged: the Noise handshake is frozen
|
||||||
|
and carries no payload, so there is no wire field to hand over an initial
|
||||||
|
ratchet public key. Both peers instead derive it from key material they already
|
||||||
|
have from the invite/roster (identity pubkey and signed prekey):
|
||||||
|
|
||||||
|
```
|
||||||
|
shared = X25519(my_prekey_sk, peer_prekey_pk) // 32 bytes
|
||||||
|
hk = HKDF-SHA256(salt = "onionwire-ratchet-v1-bootstrap",
|
||||||
|
ikm = shared)
|
||||||
|
root_key = hk.expand("root", 32)
|
||||||
|
my_secret = hk.expand("ratchet-key" || my_identity_pk, 32)
|
||||||
|
peer_secret = hk.expand("ratchet-key" || peer_identity_pk, 32)
|
||||||
|
|
||||||
|
state = bootstrap(root_key, my_keypair(my_secret), X25519_pub(peer_secret))
|
||||||
|
```
|
||||||
|
|
||||||
|
`HKDF.expand` above is the RFC 5869 expand step (no second extract). The two
|
||||||
|
identity public keys are public (invite/roster), so either peer computes its own
|
||||||
|
secrets and the peer's, and both agree with no new wire field. Then:
|
||||||
|
|
||||||
|
```
|
||||||
|
shared = DH(my_secret, remote_pub)
|
||||||
|
(new_root, ck_lo, ck_hi) = epoch_chains(root_key, shared)
|
||||||
|
send_ck = chain_for(my_pub, remote_pub) // ck_lo or ck_hi
|
||||||
|
recv_ck = chain_for(remote_pub, my_pub)
|
||||||
|
send_n = recv_n = 0, PN = 0, established = false
|
||||||
|
```
|
||||||
|
|
||||||
|
Fresh entropy enters at the first DH ratchet step; the bootstrap epoch itself is
|
||||||
|
prekey-bound (see [THREAT_MODEL.md](THREAT_MODEL.md)).
|
||||||
|
|
||||||
|
**Convergence when both peers send first.** Either peer may send immediately on
|
||||||
|
the bootstrap epoch, so two peers can each build a sending chain before either
|
||||||
|
has received anything. Because the epoch's two chains come from the unordered
|
||||||
|
pair, both derive both directions and each sends on its own, with no
|
||||||
|
initiator/responder role. The only tie-break needed is for the *first* rotation:
|
||||||
|
the peer whose ratchet public key is lexicographically lower rotates — but only
|
||||||
|
after it has received a bootstrap-epoch frame (see `established` below); the
|
||||||
|
other adopts that new key as a normal DH step and only then rotates. From the
|
||||||
|
second epoch on, every rotation is a reply to an adopted key, so no tie-break is
|
||||||
|
needed and the ratchet alternates.
|
||||||
|
|
||||||
|
**Why it stays in lockstep.** A DH ratchet step happens only on a frame whose
|
||||||
|
`dh_pub` has not been adopted yet, and the side that steps is the side that
|
||||||
|
receives. A peer cannot rotate twice without having received the other side's
|
||||||
|
rotation first, so at most one rotation is ever in flight, and both peers feed
|
||||||
|
`KDF_RK` the same `(root, dh)` pairs in the same causal order.
|
||||||
|
|
||||||
|
### Receiving
|
||||||
|
|
||||||
|
On a decrypted `rat ` frame (the outer Noise session has already been verified,
|
||||||
|
so the peer identity is pinned):
|
||||||
|
|
||||||
|
1. Parse; reject bad prefix, version or a frame under 73 bytes.
|
||||||
|
2. If `(dh_pub, N)` is in the skipped-key store: open with that key, **delete it**
|
||||||
|
from the store, deliver. A replay of the same frame then fails closed because
|
||||||
|
the key is gone.
|
||||||
|
3. Else if `dh_pub` equals the adopted remote ratchet public key, this is the
|
||||||
|
current receiving chain:
|
||||||
|
- `N < recv_n` → reject (message key already used).
|
||||||
|
- `N - recv_n > MAX_SKIP` → reject.
|
||||||
|
- Derive message keys for `recv_n .. N` into the skipped store, derive the
|
||||||
|
key for `N`, open, set `recv_n = N + 1`.
|
||||||
|
- On the *first* frame received in this state (`established == false`): set
|
||||||
|
`established`, and if `my_pub < remote_pub`, rotate the sending chain
|
||||||
|
(fresh keypair; `epoch_chains(root, DH(new_secret, remote_pub))`; new
|
||||||
|
sending chain for `new_pub → remote_pub`; `PN = old send_n`; `send_n = 0`).
|
||||||
|
The receiving chain is untouched.
|
||||||
|
4. Else it is a ratchet key not adopted yet: run a full DH ratchet step.
|
||||||
|
|
||||||
|
### DH ratchet step
|
||||||
|
|
||||||
|
On a frame whose `dh_pub` differs from the adopted remote public key:
|
||||||
|
|
||||||
|
1. **Retire the current receiving chain.** `PN` is how many messages the peer
|
||||||
|
sent in it, so:
|
||||||
|
- `PN < recv_n` → reject (used message key).
|
||||||
|
- `PN - recv_n > MAX_SKIP` → reject.
|
||||||
|
- Derive `recv_n .. PN` into the skipped store, tagged with the retired
|
||||||
|
remote public key, so stragglers of the old chain still decrypt.
|
||||||
|
2. **Receiving half of the step**, on the pair `(my current secret, frame.dh_pub)`:
|
||||||
|
`shared = DH(my_secret, frame.dh_pub)`,
|
||||||
|
`(root_a, ck_lo, ck_hi) = epoch_chains(root, shared)`,
|
||||||
|
`recv_ck = chain_for(frame.dh_pub, my_pub)`, then open the frame with this
|
||||||
|
chain exactly as in step 3 above (it must be within `MAX_SKIP` of index 0).
|
||||||
|
3. **Sending half:** generate a fresh ratchet keypair,
|
||||||
|
`shared = DH(new_secret, frame.dh_pub)`,
|
||||||
|
`(root, ck_lo, ck_hi) = epoch_chains(root_a, shared)`,
|
||||||
|
`send_ck = chain_for(new_pub, frame.dh_pub)`, `remote_pub = frame.dh_pub`,
|
||||||
|
`PN = old send_n`, `send_n = 0`, `established = true`.
|
||||||
|
4. The frame is opened with the *new* receiving chain's message key. If the AEAD
|
||||||
|
open fails, nothing is applied: the state must be byte-identical to before
|
||||||
|
the frame.
|
||||||
|
|
||||||
|
The next frame this side sends therefore carries the new `dh_pub`, which is what
|
||||||
|
lets the peer step too.
|
||||||
|
|
||||||
|
### Bounds and replay
|
||||||
|
|
||||||
|
- `MAX_SKIP = 2000`. Checked on both jumps: `N - recv_n` on the current chain
|
||||||
|
and `PN - recv_n` while retiring one. `jump == 2000` is accepted,
|
||||||
|
`jump == 2001` is rejected (`MaxSkipExceeded`) and leaves the state untouched.
|
||||||
|
- `MAX_SKIPPED_KEYS = 2000` stored message keys. When the store is at the cap,
|
||||||
|
inserting a new key evicts the **oldest-inserted** entry first — insertion
|
||||||
|
order, not `N` order.
|
||||||
|
- A skipped key is removed the moment it decrypts a frame, so a replayed frame
|
||||||
|
fails closed (`UsedMessageKey` or an AEAD failure).
|
||||||
|
- Every bound is validated before any state mutation. A rejected or tampered
|
||||||
|
frame must leave the state byte-identical.
|
||||||
|
|
||||||
|
### State at rest
|
||||||
|
|
||||||
|
`ratchet_sessions` in the SQLCipher store: one row per friend
|
||||||
|
(`friend_id` primary key, `FOREIGN KEY` → `friends.id` `ON DELETE CASCADE`,
|
||||||
|
`state BLOB NOT NULL`, `updated_at`). The blob is version byte `0x01` followed by
|
||||||
|
the implementation's serialized `RatchetState` (root, keypairs, both chain keys
|
||||||
|
and counters, `established`, and the skipped-key store). The state is
|
||||||
|
device-local: it is **never** transmitted, and its layout is not part of this
|
||||||
|
wire protocol. The store is encrypted as a whole, so the blob is ciphertext on
|
||||||
|
disk.
|
||||||
|
|
||||||
|
### Not ratcheted
|
||||||
|
|
||||||
|
`loc `, `prf `, `inv `, `rcp `, `tip `, `png ` and `fil ` frames — and every
|
||||||
|
file chunk — keep the one-shot Noise shape: one handshake per application frame,
|
||||||
|
no ratchet, no persistent session. Only chat is ratcheted.
|
||||||
|
|
||||||
|
### Prekey change resets the epoch
|
||||||
|
|
||||||
|
A peer whose prekey changes invalidates the bootstrap epoch on both sides, and
|
||||||
|
the stale state is dropped locally, so the next chat frame starts a fresh
|
||||||
|
bootstrap epoch. Frames sent under the dropped epoch are not readable
|
||||||
|
afterwards. There is no key-confirmation exchange and no in-band reset command;
|
||||||
|
the new invite is the signal.
|
||||||
|
|
||||||
## Invite (out of band)
|
## Invite (out of band)
|
||||||
|
|
||||||
Not a QR graphic. A single ASCII string, max 4096 characters:
|
Not a QR graphic. A single ASCII string, max 4096 characters:
|
||||||
|
|
@ -353,3 +580,6 @@ path”). They are out of scope, not postponed.
|
||||||
- Frame `version` 1 and invite `onionwire:v1` are this document.
|
- Frame `version` 1 and invite `onionwire:v1` are this document.
|
||||||
- A new handshake prologue or a new invite scheme is a breaking change.
|
- A new handshake prologue or a new invite scheme is a breaking change.
|
||||||
- New typed prefixes (`xyz `) are backward compatible if old peers drop them.
|
- New typed prefixes (`xyz `) are backward compatible if old peers drop them.
|
||||||
|
- The `rat ` frame has its own version byte (`0x01`). A different ratchet frame
|
||||||
|
layout or a different KDF is a breaking change for chat only: peers that
|
||||||
|
disagree cannot read each other's chat, and every other frame keeps working.
|
||||||
|
|
|
||||||
|
|
@ -23,8 +23,9 @@ A 32-byte key is derived from the store passphrase with Argon2id (same params as
|
||||||
identity backup) over a per-install 16-byte salt in `store_salt`, and handed to
|
identity backup) over a per-install 16-byte salt in `store_salt`, and handed to
|
||||||
SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) — no second KDF pass over it.
|
SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) — no second KDF pass over it.
|
||||||
The key is the first statement after open, so the file header, schema, identity
|
The key is the first statement after open, so the file header, schema, identity
|
||||||
secret key, friend public keys, locators, profiles and payment rows are all
|
secret key, friend public keys, locators, profiles, payment rows and the
|
||||||
ciphertext on disk. There is no `identity_sk`-on-disk problem to work around
|
per-friend ratchet session blobs (`ratchet_sessions`) are all ciphertext on
|
||||||
|
disk. There is no `identity_sk`-on-disk problem to work around
|
||||||
because `identity_sk` is inside the encrypted file. A wrong or empty passphrase
|
because `identity_sk` is inside the encrypted file. A wrong or empty passphrase
|
||||||
fails closed before any write; an encrypted store whose `store_salt` is missing
|
fails closed before any write; an encrypted store whose `store_salt` is missing
|
||||||
refuses to open instead of guessing.
|
refuses to open instead of guessing.
|
||||||
|
|
@ -65,6 +66,72 @@ A chat send to an unreachable onion is written to an `outbox` row next to its `m
|
||||||
|
|
||||||
The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever.
|
The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever.
|
||||||
|
|
||||||
|
## Chat is ratcheted on top of the one-shot Noise session
|
||||||
|
|
||||||
|
The Noise IK session is still the transport: handshake, **one** application
|
||||||
|
frame, close, one circuit per message. Chat stacks a Double Ratchet *inside*
|
||||||
|
that frame (`rat `, [PROTOCOL.md](PROTOCOL.md)), with per-friend state persisted
|
||||||
|
in the encrypted store (`ratchet_sessions`). The ratchet changes what a stolen
|
||||||
|
chat line is worth; it does not re-open any lock: no relay, no server-side
|
||||||
|
queue, one frame per Noise session, and the ratchet state never leaves the
|
||||||
|
device.
|
||||||
|
|
||||||
|
**Gains.**
|
||||||
|
|
||||||
|
- *Per-chain forward secrecy.* Every message key is `HMAC-SHA256(chain_key,
|
||||||
|
0x01)` over a chain key that is replaced by `HMAC-SHA256(chain_key, 0x02)`
|
||||||
|
after each message, so state recovered after a chain has moved on does not
|
||||||
|
decrypt the messages already sent on it — outside the skipped-key window
|
||||||
|
below.
|
||||||
|
- *Post-compromise security after a DH ratchet step.* An attacker holding a
|
||||||
|
snapshot of one side's state cannot read the conversation past the next DH
|
||||||
|
ratchet step: that step feeds a fresh X25519 output into the root, and the
|
||||||
|
snapshot stops producing chain keys. The window is not zero — it lasts until
|
||||||
|
the next step — but no attacker can prevent it closing.
|
||||||
|
- *The ratchet header is not on the wire.* `dh_pub`, `N` and `PN` ride inside
|
||||||
|
the Noise ciphertext (authenticated as AEAD associated data), so message
|
||||||
|
counts and ratchet-key changes are not observable, and a tampered header fails
|
||||||
|
closed.
|
||||||
|
|
||||||
|
**Honest limits.**
|
||||||
|
|
||||||
|
- *Skipped-key window.* Up to `MAX_SKIP` (2000) message keys of one chain, or up
|
||||||
|
to `MAX_SKIPPED_KEYS` (2000) entries across a friend, stay decryptable to
|
||||||
|
whoever holds the state until they are used (deleted on use) or evicted
|
||||||
|
oldest-first. A snapshot also carries the current sending and receiving chain
|
||||||
|
keys, which read the current chain until it advances. This is the price of
|
||||||
|
out-of-order delivery, and it is per friend.
|
||||||
|
- *The bootstrap epoch is prekey-bound.* The initial root and both initial
|
||||||
|
ratchet secrets are HKDF outputs of the X25519 DH between the two long-lived
|
||||||
|
signed prekeys, and the identity pubkeys that separate them are public. An
|
||||||
|
attacker who has both peers' prekey statics can therefore reconstruct the
|
||||||
|
**first** epoch. What that does not buy is a recorded message: every `rat `
|
||||||
|
frame travels inside a one-shot Noise session whose ephemerals are not derived
|
||||||
|
from the prekeys, so the prekeys alone do not open stored traffic. From the
|
||||||
|
first DH ratchet step on, fresh X25519 secrets enter and the prekeys derive
|
||||||
|
nothing — the bootstrap epoch is the exception, not the rule, and it is the
|
||||||
|
reason the state is dropped when a peer's prekey changes.
|
||||||
|
- *No deniability and no non-repudiation claim.* Chat frames are not signed and
|
||||||
|
both parties derive the same chain keys, so nothing here would let a third
|
||||||
|
party decide which of the two authored a chat line. Identity is proven per
|
||||||
|
Noise session (the 96-byte proof), not per message.
|
||||||
|
- *No one-time prekeys.* The bootstrap epoch uses the long-lived signed prekey
|
||||||
|
only, so there is no per-session prekey consumption. A peer prekey change
|
||||||
|
drops the state locally and the next chat frame re-bootstraps; there is no
|
||||||
|
in-band reset and no key confirmation.
|
||||||
|
- *A compromised endpoint is out of scope.* The ratchet state lives in the same
|
||||||
|
SQLCipher file as the chat log, under the same passphrase. Anyone who opens
|
||||||
|
the store holds the roots, both chain keys, the skipped keys and the plaintext
|
||||||
|
history. `/wipe` clears chat, payments and outbox rows but **keeps** the
|
||||||
|
ratchet state (roster and identity stay), so chat resumes on the same epoch;
|
||||||
|
`/wipe-all` removes the data dir with it.
|
||||||
|
- *No metadata protection beyond Noise.* One Noise session per message, no
|
||||||
|
padding: sizes and timing are what they were before the ratchet.
|
||||||
|
- *The ratchet does not re-open the "no server-side outbox" lock.* The state is
|
||||||
|
device-local, one row per friend in the encrypted store, and nothing about it
|
||||||
|
is transmitted. The local retry queue's two accepted consequences (device
|
||||||
|
seizure, retry cadence) are unchanged.
|
||||||
|
|
||||||
## Profile is friend-visible, not a directory
|
## Profile is friend-visible, not a directory
|
||||||
|
|
||||||
A signed `prf` frame is shown to people who already have a session with you. Apply only for existing friends. There is still no name lookup, DHT, or public profile server. Anyone who already has a Noise session can see the profile you send them; that is not confidentiality against that friend.
|
A signed `prf` frame is shown to people who already have a session with you. Apply only for existing friends. There is still no name lookup, DHT, or public profile server. Anyone who already has a Noise session can see the profile you send them; that is not confidentiality against that friend.
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ document explains why, and what breaks when you do.
|
||||||
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. |
|
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. |
|
||||||
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. |
|
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. |
|
||||||
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. |
|
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. |
|
||||||
|
| `ONIONWIRE_MONEROD` | `1` / `true` / `yes` / `on` → OnionWire spawns a pruned local `monerod` as the chain source (option 1 below). Unset → no local chain; the wallet child uses whatever daemon you gave it. |
|
||||||
|
|
||||||
`README.md` carries the operator summary; this file is the long form.
|
`README.md` carries the operator summary; this file is the long form.
|
||||||
|
|
||||||
|
|
@ -78,6 +79,31 @@ does not pick a public remote node for you.
|
||||||
Remote daemons are untrusted (`--trusted-daemon` off). Unsynced or unreachable
|
Remote daemons are untrusted (`--trusted-daemon` off). Unsynced or unreachable
|
||||||
→ receipts stay unverified and spend is refused. That is the honest state.
|
→ receipts stay unverified and spend is refused. That is the honest state.
|
||||||
|
|
||||||
|
### Option 1 in practice: the in-app spawn
|
||||||
|
|
||||||
|
Set `ONIONWIRE_MONEROD=1` and the app starts the daemon itself — you do not run
|
||||||
|
`monerod` by hand. It looks for `monerod` on `PATH`, keeps its chain data in
|
||||||
|
`$ONIONWIRE_HOME/monero/` (mode 0700, never `/tmp` and never a shared location),
|
||||||
|
and starts it with `--prune-blockchain --non-interactive`, its RPC bound to
|
||||||
|
loopback only (`--rpc-bind-ip 127.0.0.1 --rpc-bind-port 18089`), logging to
|
||||||
|
`$ONIONWIRE_HOME/monero/monerod.log`. The wallet child is pointed at that RPC
|
||||||
|
with `--daemon-address 127.0.0.1:18089`; which process runs the wallet RPC (and
|
||||||
|
how it is started) is separate from this and unchanged.
|
||||||
|
|
||||||
|
Zero trust is not optional here either: the spawn never passes
|
||||||
|
`--trusted-daemon`, and the daemon's RPC is loopback so only this machine can
|
||||||
|
talk to it. p2p is untouched (`monerod`'s own defaults, port 18081): a pruned
|
||||||
|
node still dials peers on the Monero network to sync, so "local daemon" means
|
||||||
|
you are not handing your addresses to someone else's node — it does not mean the
|
||||||
|
sync is offline.
|
||||||
|
|
||||||
|
On start the app waits up to 5s for the RPC port to answer. A missing binary or
|
||||||
|
a port that never comes up is **not** fatal: it is logged, no local chain is
|
||||||
|
assumed, and the wallet reports the unsynced state above. On shutdown the daemon
|
||||||
|
is SIGTERMed (SIGKILL after 10s). If you stop the app with SIGKILL, `monerod`
|
||||||
|
keeps running and keeps syncing; kill it yourself or leave it — the next start
|
||||||
|
reuses the same data dir.
|
||||||
|
|
||||||
## Create a view-only wallet
|
## Create a view-only wallet
|
||||||
|
|
||||||
Either path produces a wallet file with the view key only. Keep the seed /
|
Either path produces a wallet file with the view key only. Keep the seed /
|
||||||
|
|
|
||||||
|
|
@ -10,10 +10,17 @@ pub enum Kind {
|
||||||
Tip,
|
Tip,
|
||||||
Ping,
|
Ping,
|
||||||
File,
|
File,
|
||||||
|
/// Double Ratchet frame (`rat `, `src/ratchet.rs`). Chat travels as a
|
||||||
|
/// ratchet frame; the plaintext only exists after decryption.
|
||||||
|
Ratchet,
|
||||||
Drop,
|
Drop,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn classify(pt: &[u8]) -> Kind {
|
pub fn classify(pt: &[u8]) -> Kind {
|
||||||
|
// Before the `[a-z]{3} ` catch-all below, which would drop it as unknown.
|
||||||
|
if pt.starts_with(crate::ratchet::FRAME_PREFIX) {
|
||||||
|
return Kind::Ratchet;
|
||||||
|
}
|
||||||
if pt.starts_with(b"loc ") {
|
if pt.starts_with(b"loc ") {
|
||||||
return Kind::Loc;
|
return Kind::Loc;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ pub mod file;
|
||||||
pub mod frame;
|
pub mod frame;
|
||||||
pub mod hs;
|
pub mod hs;
|
||||||
pub mod loc;
|
pub mod loc;
|
||||||
|
pub mod monerod;
|
||||||
pub mod node;
|
pub mod node;
|
||||||
pub mod outbox;
|
pub mod outbox;
|
||||||
pub mod pay;
|
pub mod pay;
|
||||||
|
|
|
||||||
416
src/monerod.rs
Normal file
416
src/monerod.rs
Normal file
|
|
@ -0,0 +1,416 @@
|
||||||
|
//! Optional local `monerod` as the chain source (spawn + lifecycle).
|
||||||
|
//!
|
||||||
|
//! OnionWire never picks a public remote daemon: the chain source is either a
|
||||||
|
//! daemon the operator already runs, or this module's pruned `monerod` child on
|
||||||
|
//! loopback. The wallet child (`monero-wallet-rpc`) is a *separate* process —
|
||||||
|
//! this module only manages the daemon it is told to point `--daemon-address`
|
||||||
|
//! at (`Monerod::rpc_addr`).
|
||||||
|
//!
|
||||||
|
//! Locks, all pinned by tests:
|
||||||
|
//! - RPC binds `127.0.0.1:18089` only. No `--trusted-daemon`, no SOCKS, no
|
||||||
|
//! clearnet default, no UDP.
|
||||||
|
//! - `--prune-blockchain`: the on-device target is a pruned node, never an
|
||||||
|
//! archive. The operator accepts disk and first-sync time.
|
||||||
|
//! - `--data-dir` is `$ONIONWIRE_HOME/monero/`, created 0700 — never `/tmp`.
|
||||||
|
//! - A missing binary is an `Err`, and the caller is expected to fall back to
|
||||||
|
//! "no local chain" (the wallet then reports an honest unsynced state)
|
||||||
|
//! rather than aborting the app.
|
||||||
|
|
||||||
|
use std::ffi::OsStr;
|
||||||
|
use std::fs;
|
||||||
|
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Child, Command, Stdio};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
/// `monerod`'s default RPC port. We bind it, loopback-only.
|
||||||
|
pub const RPC_PORT: u16 = 18089;
|
||||||
|
/// `monerod`'s default p2p port, for the operator's reference. Peer dials keep
|
||||||
|
/// monerod's own defaults; this module does not touch p2p.
|
||||||
|
pub const P2P_PORT: u16 = 18081;
|
||||||
|
const BINARY: &str = "monerod";
|
||||||
|
/// Numeric loopback literal — never `localhost`, which would `getaddrinfo`.
|
||||||
|
const RPC_BIND_IP: &str = "127.0.0.1";
|
||||||
|
/// How long [`Monerod::spawn`] waits for the RPC port before giving up.
|
||||||
|
pub const READY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
const READY_POLL: Duration = Duration::from_millis(200);
|
||||||
|
const CONNECT_TIMEOUT: Duration = Duration::from_millis(250);
|
||||||
|
/// SIGTERM gets this long before SIGKILL.
|
||||||
|
const TERM_GRACE: Duration = Duration::from_secs(10);
|
||||||
|
const STOP_POLL: Duration = Duration::from_millis(100);
|
||||||
|
|
||||||
|
/// A local, pruned `monerod` child. Dropping it does not kill the process —
|
||||||
|
/// call [`Monerod::stop`] (the node does this on shutdown).
|
||||||
|
pub struct Monerod {
|
||||||
|
child: Child,
|
||||||
|
data_dir: PathBuf,
|
||||||
|
rpc_addr: SocketAddr,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loopback RPC address for a port. The wallet child is pointed here with
|
||||||
|
/// `--daemon-address`.
|
||||||
|
pub fn rpc_addr(port: u16) -> SocketAddr {
|
||||||
|
SocketAddr::from((Ipv4Addr::LOCALHOST, port))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll `addr` until something listens, or `timeout` elapses.
|
||||||
|
///
|
||||||
|
/// A listening port is "ready enough": `monerod` binds RPC before it serves
|
||||||
|
/// blocks, and the wallet child reports its own sync progress from there. We do
|
||||||
|
/// not speak HTTP ourselves.
|
||||||
|
pub fn wait_for_ready(addr: SocketAddr, timeout: Duration) -> Result<(), String> {
|
||||||
|
let started = Instant::now();
|
||||||
|
loop {
|
||||||
|
if TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).is_ok() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if started.elapsed() >= timeout {
|
||||||
|
return Err(format!("no listener on {addr} after {timeout:?}"));
|
||||||
|
}
|
||||||
|
std::thread::sleep(READY_POLL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `path` is a file we could exec.
|
||||||
|
fn is_executable(path: &Path) -> bool {
|
||||||
|
fs::metadata(path)
|
||||||
|
.map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve `name` in a `PATH`-style search path. `None` as the path, or no
|
||||||
|
/// executable match, is `None` — a directory entry that is not executable
|
||||||
|
/// (e.g. a `monerod` data dir) is not a binary.
|
||||||
|
fn find_in(name: &str, path: Option<&OsStr>) -> Option<PathBuf> {
|
||||||
|
let path = path?;
|
||||||
|
std::env::split_paths(path)
|
||||||
|
.map(|dir| dir.join(name))
|
||||||
|
.find(|candidate| is_executable(candidate))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find `monerod` on `PATH`.
|
||||||
|
pub fn find_binary() -> Result<PathBuf, String> {
|
||||||
|
find_in(BINARY, std::env::var_os("PATH").as_deref()).ok_or_else(not_on_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn not_on_path() -> String {
|
||||||
|
"monerod not found on PATH — install monero, or point the wallet child at a \
|
||||||
|
daemon address you supply"
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The argv for the daemon. Pure, so the locks are testable.
|
||||||
|
fn args(data_dir: &Path) -> Vec<String> {
|
||||||
|
let data_dir = data_dir.display().to_string();
|
||||||
|
vec![
|
||||||
|
"--data-dir".into(),
|
||||||
|
data_dir.clone(),
|
||||||
|
"--non-interactive".into(),
|
||||||
|
"--prune-blockchain".into(),
|
||||||
|
"--rpc-bind-ip".into(),
|
||||||
|
RPC_BIND_IP.into(),
|
||||||
|
"--rpc-bind-port".into(),
|
||||||
|
RPC_PORT.to_string(),
|
||||||
|
"--log-file".into(),
|
||||||
|
Path::new(&data_dir)
|
||||||
|
.join("monerod.log")
|
||||||
|
.display()
|
||||||
|
.to_string(),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `mkdir -p` + `chmod 0700`, the `store::mkdir_700` idiom.
|
||||||
|
fn mkdir_700(path: &Path) -> Result<(), String> {
|
||||||
|
fs::create_dir_all(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||||
|
let mut perms = fs::metadata(path)
|
||||||
|
.map_err(|e| format!("{}: {e}", path.display()))?
|
||||||
|
.permissions();
|
||||||
|
perms.set_mode(0o700);
|
||||||
|
fs::set_permissions(path, perms).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Monerod {
|
||||||
|
/// Spawn a pruned local `monerod` under `home` and wait for its RPC port.
|
||||||
|
///
|
||||||
|
/// `Err` means "no local chain": a missing binary, a data dir we cannot
|
||||||
|
/// create, or an RPC port that never came up (the child is stopped before
|
||||||
|
/// returning). The caller falls back; the wallet then reports unsynced.
|
||||||
|
pub fn spawn(home: &Path) -> Result<Self, String> {
|
||||||
|
Self::spawn_with_path(home, std::env::var_os("PATH").as_deref())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_with_path(home: &Path, path: Option<&OsStr>) -> Result<Self, String> {
|
||||||
|
let binary = find_in(BINARY, path).ok_or_else(not_on_path)?;
|
||||||
|
Self::spawn_binary(&binary, home)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_binary(binary: &Path, home: &Path) -> Result<Self, String> {
|
||||||
|
let me = Self::spawn_process(binary, home)?;
|
||||||
|
let addr = me.rpc_addr();
|
||||||
|
if let Err(e) = wait_for_ready(addr, READY_TIMEOUT) {
|
||||||
|
let _ = me.stop();
|
||||||
|
return Err(format!("monerod never answered on {addr}: {e}"));
|
||||||
|
}
|
||||||
|
Ok(me)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create the chain data dir (0700) and start the child, without waiting.
|
||||||
|
fn spawn_process(binary: &Path, home: &Path) -> Result<Self, String> {
|
||||||
|
let data_dir = home.join("monero");
|
||||||
|
mkdir_700(&data_dir)?;
|
||||||
|
let child = Command::new(binary)
|
||||||
|
.args(args(&data_dir))
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| format!("spawn {}: {e}", binary.display()))?;
|
||||||
|
Ok(Self {
|
||||||
|
child,
|
||||||
|
data_dir,
|
||||||
|
rpc_addr: rpc_addr(RPC_PORT),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the wallet child should be pointed (`--daemon-address`).
|
||||||
|
pub fn rpc_addr(&self) -> SocketAddr {
|
||||||
|
self.rpc_addr
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `$ONIONWIRE_HOME/monero/` — the chain data this process owns.
|
||||||
|
pub fn data_dir(&self) -> &Path {
|
||||||
|
&self.data_dir
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SIGTERM, then SIGKILL after [`TERM_GRACE`]; reap the child.
|
||||||
|
///
|
||||||
|
/// `Err` means we could not signal or reap it — the chain is then in an
|
||||||
|
/// unknown state and must not be reported as cleanly stopped.
|
||||||
|
pub fn stop(mut self) -> Result<(), String> {
|
||||||
|
if matches!(self.child.try_wait(), Ok(Some(_))) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// std has no signal API and this crate takes no libc dependency, so
|
||||||
|
// SIGTERM goes through `kill(1)`. If that is unavailable, SIGKILL.
|
||||||
|
if !sigterm(self.child.id()) {
|
||||||
|
self.child
|
||||||
|
.kill()
|
||||||
|
.map_err(|e| format!("kill monerod: {e}"))?;
|
||||||
|
}
|
||||||
|
let started = Instant::now();
|
||||||
|
loop {
|
||||||
|
match self.child.try_wait() {
|
||||||
|
Ok(Some(_)) => return Ok(()),
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(e) => return Err(format!("wait monerod: {e}")),
|
||||||
|
}
|
||||||
|
if started.elapsed() >= TERM_GRACE {
|
||||||
|
self.child
|
||||||
|
.kill()
|
||||||
|
.map_err(|e| format!("kill monerod: {e}"))?;
|
||||||
|
self.child
|
||||||
|
.wait()
|
||||||
|
.map_err(|e| format!("wait monerod: {e}"))?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
std::thread::sleep(STOP_POLL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sigterm(pid: u32) -> bool {
|
||||||
|
Command::new("kill")
|
||||||
|
.arg("-TERM")
|
||||||
|
.arg(pid.to_string())
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(Stdio::null())
|
||||||
|
.status()
|
||||||
|
.map(|s| s.success())
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::ffi::OsStr;
|
||||||
|
use std::net::TcpListener;
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn write_script(dir: &Path, name: &str, body: &str) -> PathBuf {
|
||||||
|
let path = dir.join(name);
|
||||||
|
std::fs::write(&path, body).expect("write script");
|
||||||
|
let mut perms = std::fs::metadata(&path).expect("metadata").permissions();
|
||||||
|
perms.set_mode(0o700);
|
||||||
|
std::fs::set_permissions(&path, perms).expect("chmod 0700");
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
fn alive(pid: u32) -> bool {
|
||||||
|
Command::new("kill")
|
||||||
|
.arg("-0")
|
||||||
|
.arg(pid.to_string())
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(Stdio::null())
|
||||||
|
.status()
|
||||||
|
.map(|s| s.success())
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn args_are_pruned_loopback_rpc() {
|
||||||
|
let dir = Path::new("/home/op/.onionwire/monero");
|
||||||
|
let args = args(dir);
|
||||||
|
let joined = args.join(" ");
|
||||||
|
assert!(
|
||||||
|
joined.contains("--prune-blockchain"),
|
||||||
|
"pruned is the on-device target: {joined}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
joined.contains("--rpc-bind-ip 127.0.0.1") && joined.contains("--rpc-bind-port 18089"),
|
||||||
|
"daemon RPC is loopback 18089 only: {joined}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
joined.contains(&format!("--data-dir {}", dir.display())),
|
||||||
|
"data dir comes from the home we were handed: {joined}"
|
||||||
|
);
|
||||||
|
// Zero trust, and no transport the threat model forbids.
|
||||||
|
for forbidden in [
|
||||||
|
"trusted-daemon",
|
||||||
|
"socks",
|
||||||
|
"proxy",
|
||||||
|
"udp",
|
||||||
|
"--bind-ip 0.0.0.0",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
!joined.contains(forbidden),
|
||||||
|
"{forbidden} must never be a monerod arg: {joined}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn find_in_requires_an_executable() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
write_script(dir.path(), "monerod-not-exec", "#!/bin/sh\nexit 0\n");
|
||||||
|
let mut perms = std::fs::metadata(dir.path().join("monerod-not-exec"))
|
||||||
|
.expect("metadata")
|
||||||
|
.permissions();
|
||||||
|
perms.set_mode(0o600);
|
||||||
|
std::fs::set_permissions(dir.path().join("monerod-not-exec"), perms).expect("chmod");
|
||||||
|
|
||||||
|
let path = dir.path().as_os_str();
|
||||||
|
assert!(
|
||||||
|
find_in("monerod-not-exec", Some(path)).is_none(),
|
||||||
|
"a non-executable name match is not a binary"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
find_in("monerod-absent", Some(path)).is_none(),
|
||||||
|
"no file, no binary"
|
||||||
|
);
|
||||||
|
|
||||||
|
write_script(dir.path(), "monerod-exec", "#!/bin/sh\nexit 0\n");
|
||||||
|
assert_eq!(
|
||||||
|
find_in("monerod-exec", Some(path)),
|
||||||
|
Some(dir.path().join("monerod-exec")),
|
||||||
|
"an executable on PATH resolves"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn spawn_without_monerod_on_path_is_a_clear_error() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let empty = OsStr::new("");
|
||||||
|
let err = match Monerod::spawn_with_path(dir.path(), Some(empty)) {
|
||||||
|
Ok(_) => panic!("no monerod on PATH"),
|
||||||
|
Err(e) => e,
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
err.contains("monerod") && err.contains("PATH"),
|
||||||
|
"the error names the missing binary and where we looked: {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn spawn_process_missing_binary_errors_and_leaves_a_0700_data_dir() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let err = match Monerod::spawn_process(Path::new("/nonexistent/ow/monerod"), dir.path()) {
|
||||||
|
Ok(_) => panic!("no such binary"),
|
||||||
|
Err(e) => e,
|
||||||
|
};
|
||||||
|
assert!(err.contains("monerod"), "the error names the binary: {err}");
|
||||||
|
let data_dir = dir.path().join("monero");
|
||||||
|
let mode = std::fs::metadata(&data_dir)
|
||||||
|
.expect("data dir is created before the spawn is attempted")
|
||||||
|
.permissions()
|
||||||
|
.mode()
|
||||||
|
& 0o777;
|
||||||
|
assert_eq!(mode, 0o700, "chain data dir is private");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_rpc_addr_is_loopback_18089() {
|
||||||
|
assert_eq!(RPC_PORT, 18089);
|
||||||
|
assert_eq!(P2P_PORT, 18081);
|
||||||
|
assert_eq!(READY_TIMEOUT, Duration::from_secs(5));
|
||||||
|
assert_eq!(
|
||||||
|
rpc_addr(RPC_PORT),
|
||||||
|
"127.0.0.1:18089".parse().expect("literal addr")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wait_for_ready_times_out_without_a_listener() {
|
||||||
|
// A bound-then-dropped port: no listener, no risk of racing a real
|
||||||
|
// monerod on the default port.
|
||||||
|
let addr = {
|
||||||
|
let l = TcpListener::bind(("127.0.0.1", 0)).expect("bind");
|
||||||
|
let addr = l.local_addr().expect("local_addr");
|
||||||
|
drop(l);
|
||||||
|
addr
|
||||||
|
};
|
||||||
|
let start = Instant::now();
|
||||||
|
let err = wait_for_ready(addr, Duration::from_secs(1)).expect_err("nothing is listening");
|
||||||
|
let elapsed = start.elapsed();
|
||||||
|
assert!(err.contains("no listener"), "honest error: {err}");
|
||||||
|
assert!(
|
||||||
|
elapsed >= Duration::from_secs(1) && elapsed < Duration::from_secs(5),
|
||||||
|
"polls until its budget, then gives up: {elapsed:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_spawned_daemon_reports_its_addr_and_stops() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let pidfile = dir.path().join("pid");
|
||||||
|
let script = write_script(
|
||||||
|
dir.path(),
|
||||||
|
"monerod",
|
||||||
|
&format!(
|
||||||
|
"#!/bin/sh\necho $$ > {}\nexec sleep 60\n",
|
||||||
|
pidfile.display()
|
||||||
|
),
|
||||||
|
);
|
||||||
|
let daemon = Monerod::spawn_process(&script, dir.path()).expect("spawn fake daemon");
|
||||||
|
assert_eq!(daemon.rpc_addr(), "127.0.0.1:18089".parse().expect("addr"));
|
||||||
|
assert_eq!(daemon.data_dir(), dir.path().join("monero"));
|
||||||
|
|
||||||
|
let pid = loop {
|
||||||
|
match std::fs::read_to_string(&pidfile) {
|
||||||
|
Ok(s) => break s.trim().parse::<u32>().expect("pid"),
|
||||||
|
Err(_) => {
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
assert!(alive(pid), "fake daemon is running");
|
||||||
|
daemon.stop().expect("stop");
|
||||||
|
assert!(!alive(pid), "SIGTERM took the child down (pid {pid})");
|
||||||
|
}
|
||||||
|
}
|
||||||
525
src/node.rs
525
src/node.rs
|
|
@ -1,5 +1,6 @@
|
||||||
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
|
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
@ -7,8 +8,11 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use futures::io::{AsyncRead, AsyncWrite};
|
use futures::io::{AsyncRead, AsyncWrite};
|
||||||
|
use hkdf::Hkdf;
|
||||||
|
use sha2::Sha256;
|
||||||
use tor_cell::relaycell::msg::Connected;
|
use tor_cell::relaycell::msg::Connected;
|
||||||
use tor_hsservice::{RunningOnionService, handle_rend_requests};
|
use tor_hsservice::{RunningOnionService, handle_rend_requests};
|
||||||
|
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
|
||||||
use zeroize::Zeroizing;
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
use crate::dispatch::{self, Kind};
|
use crate::dispatch::{self, Kind};
|
||||||
|
|
@ -16,10 +20,12 @@ use crate::file;
|
||||||
use crate::frame;
|
use crate::frame;
|
||||||
use crate::hs::{self, Client, HS_PORT, TorState};
|
use crate::hs::{self, Client, HS_PORT, TorState};
|
||||||
use crate::loc;
|
use crate::loc;
|
||||||
|
use crate::monerod::Monerod;
|
||||||
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
|
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
|
||||||
use crate::pay;
|
use crate::pay;
|
||||||
use crate::profile;
|
use crate::profile;
|
||||||
use crate::qr;
|
use crate::qr;
|
||||||
|
use crate::ratchet::{RatchetKeyPair, RatchetState};
|
||||||
use crate::ratelimit::TokenBucket;
|
use crate::ratelimit::TokenBucket;
|
||||||
use crate::sanitize;
|
use crate::sanitize;
|
||||||
use crate::session::{self, Keys};
|
use crate::session::{self, Keys};
|
||||||
|
|
@ -78,6 +84,10 @@ pub struct Node {
|
||||||
onion: Mutex<String>,
|
onion: Mutex<String>,
|
||||||
keys: Mutex<Keys>,
|
keys: Mutex<Keys>,
|
||||||
wallet: Wallet,
|
wallet: Wallet,
|
||||||
|
/// Opt-in local chain source (`ONIONWIRE_MONEROD=1`). `None` is the honest
|
||||||
|
/// "no local chain": the wallet child then has whatever `--daemon-address`
|
||||||
|
/// the operator gave it, or none, and reports unsynced.
|
||||||
|
monerod: Mutex<Option<Monerod>>,
|
||||||
incoming_limit: Mutex<TokenBucket>,
|
incoming_limit: Mutex<TokenBucket>,
|
||||||
inbox: Mutex<file::Inbox>,
|
inbox: Mutex<file::Inbox>,
|
||||||
outbox: Arc<Outbox>,
|
outbox: Arc<Outbox>,
|
||||||
|
|
@ -124,6 +134,7 @@ impl Node {
|
||||||
let (svc, rend) = launched;
|
let (svc, rend) = launched;
|
||||||
let onion = hs::onion_string(&svc)?;
|
let onion = hs::onion_string(&svc)?;
|
||||||
let inbox = file::Inbox::new(home.join("inbox"));
|
let inbox = file::Inbox::new(home.join("inbox"));
|
||||||
|
let monerod = start_monerod(&home).await;
|
||||||
let store = Arc::new(Mutex::new(store));
|
let store = Arc::new(Mutex::new(store));
|
||||||
let outbox = Arc::new(Outbox::new(
|
let outbox = Arc::new(Outbox::new(
|
||||||
Arc::clone(&store),
|
Arc::clone(&store),
|
||||||
|
|
@ -140,6 +151,7 @@ impl Node {
|
||||||
onion: Mutex::new(onion.clone()),
|
onion: Mutex::new(onion.clone()),
|
||||||
keys: Mutex::new(keys),
|
keys: Mutex::new(keys),
|
||||||
wallet: Wallet::from_env(),
|
wallet: Wallet::from_env(),
|
||||||
|
monerod: Mutex::new(monerod),
|
||||||
incoming_limit: Mutex::new(TokenBucket::default()),
|
incoming_limit: Mutex::new(TokenBucket::default()),
|
||||||
inbox: Mutex::new(inbox),
|
inbox: Mutex::new(inbox),
|
||||||
outbox: Arc::clone(&outbox),
|
outbox: Arc::clone(&outbox),
|
||||||
|
|
@ -213,7 +225,7 @@ impl Node {
|
||||||
/// Order matters: drain the outbox while the Tor client is still alive,
|
/// Order matters: drain the outbox while the Tor client is still alive,
|
||||||
/// then drop the onion service (its rendezvous task is aborted and the v3
|
/// then drop the onion service (its rendezvous task is aborted and the v3
|
||||||
/// service goes down), then abort the retry worker so nothing dials after
|
/// service goes down), then abort the retry worker so nothing dials after
|
||||||
/// this, then checkpoint the WAL.
|
/// this, then stop a spawned local chain source, then checkpoint the WAL.
|
||||||
///
|
///
|
||||||
/// Idempotent: the flag is swapped first, so a second call — or a call
|
/// Idempotent: the flag is swapped first, so a second call — or a call
|
||||||
/// racing another teardown — returns `Ok(())` without touching anything
|
/// racing another teardown — returns `Ok(())` without touching anything
|
||||||
|
|
@ -241,10 +253,40 @@ impl Node {
|
||||||
Ok(mut g) => drop(g.take()),
|
Ok(mut g) => drop(g.take()),
|
||||||
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
|
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
|
||||||
}
|
}
|
||||||
|
// Take the daemon out of the lock before awaiting: the guard must not
|
||||||
|
// live across `spawn_blocking`.
|
||||||
|
let daemon = match self.monerod.lock() {
|
||||||
|
Ok(mut g) => g.take(),
|
||||||
|
Err(_) => {
|
||||||
|
eprintln!("shutdown: monerod lock poisoned");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(daemon) = daemon {
|
||||||
|
let addr = daemon.rpc_addr();
|
||||||
|
// `stop` SIGTERMs and waits up to 10s for it: keep that off the
|
||||||
|
// reactor. A daemon we cannot stop is reported, not silently
|
||||||
|
// reported as clean.
|
||||||
|
match tokio::task::spawn_blocking(move || daemon.stop()).await {
|
||||||
|
Ok(Ok(())) => eprintln!("monerod: stopped {addr}"),
|
||||||
|
Ok(Err(e)) => eprintln!("monerod: {e}"),
|
||||||
|
Err(e) => eprintln!("monerod: stop task failed: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
self.checkpoint();
|
self.checkpoint();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where the spawned local chain source listens, if this node started one
|
||||||
|
/// (`ONIONWIRE_MONEROD=1`). This is what the wallet child is pointed at
|
||||||
|
/// with `--daemon-address`; `None` means no local chain.
|
||||||
|
pub fn monerod_rpc_addr(&self) -> Option<SocketAddr> {
|
||||||
|
self.monerod
|
||||||
|
.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|g| g.as_ref().map(Monerod::rpc_addr))
|
||||||
|
}
|
||||||
|
|
||||||
/// One bounded pass over every outstanding outbox row.
|
/// One bounded pass over every outstanding outbox row.
|
||||||
///
|
///
|
||||||
/// A timeout cancels the pass mid-flight, which can leave a row in
|
/// A timeout cancels the pass mid-flight, which can leave a row in
|
||||||
|
|
@ -387,12 +429,23 @@ impl Node {
|
||||||
|
|
||||||
pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> {
|
pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> {
|
||||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||||
|
let prekey_changed = store
|
||||||
|
.get_friend(&p.pubkey)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.map(|f| f.prekey != p.signed_prekey)
|
||||||
|
.unwrap_or(false);
|
||||||
store
|
store
|
||||||
.upsert_friend(&p.pubkey, &p.onion, None)
|
.upsert_friend(&p.pubkey, &p.onion, None)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
store
|
store
|
||||||
.set_friend_prekey(&p.pubkey, &p.signed_prekey)
|
.set_friend_prekey(&p.pubkey, &p.signed_prekey)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
if prekey_changed {
|
||||||
|
// The bootstrap epoch is derived from the peers' static prekey DH,
|
||||||
|
// so a refreshed invite makes the stored ratchet state unusable on
|
||||||
|
// both sides. Drop it: the next frame rebuilds a fresh state.
|
||||||
|
store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -876,9 +929,18 @@ impl Node {
|
||||||
/// when the peer's onion is unreachable — the outbox worker then retries with
|
/// when the peer's onion is unreachable — the outbox worker then retries with
|
||||||
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
|
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
|
||||||
/// frame) still fails immediately and is never retried.
|
/// frame) still fails immediately and is never retried.
|
||||||
|
///
|
||||||
|
/// Chat travels as a `rat ` frame: the plaintext is ratchet-encrypted once,
|
||||||
|
/// here, before the first attempt, and the frame is what the outbox retries.
|
||||||
|
/// Local history keeps the plaintext (the store is encrypted at rest).
|
||||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||||||
self.ensure_running()?;
|
self.ensure_running()?;
|
||||||
self.outbox.send(friend_pk, plaintext).await
|
let keys = self.keys()?;
|
||||||
|
let frame = {
|
||||||
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||||
|
encode_chat_frame(&store, &keys, friend_pk, plaintext)?
|
||||||
|
};
|
||||||
|
self.outbox.send_payload(friend_pk, plaintext, &frame).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pending and failed outbox rows for a friend, for UI surfacing.
|
/// Pending and failed outbox rows for a friend, for UI surfacing.
|
||||||
|
|
@ -1001,6 +1063,17 @@ impl Node {
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Kind::Ratchet => {
|
||||||
|
// Chat arrives as a ratchet frame: decrypt, log the plaintext,
|
||||||
|
// drop the frame. A bad frame is logged and dropped — the
|
||||||
|
// ciphertext is never stored and there is no plaintext fallback.
|
||||||
|
let keys = self.keys()?;
|
||||||
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||||
|
if let Err(e) = ingest_chat_frame(&store, &keys, &sess.peer_identity, &pt) {
|
||||||
|
eprintln!("rat dropped ({e})");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Kind::Invoice => self.ingest_invoice(&sess.peer_identity, &pt).await,
|
Kind::Invoice => self.ingest_invoice(&sess.peer_identity, &pt).await,
|
||||||
Kind::Receipt => self.ingest_receipt(&sess.peer_identity, &pt).await,
|
Kind::Receipt => self.ingest_receipt(&sess.peer_identity, &pt).await,
|
||||||
Kind::Tip => self.ingest_tip(&sess.peer_identity, &pt).await,
|
Kind::Tip => self.ingest_tip(&sess.peer_identity, &pt).await,
|
||||||
|
|
@ -1175,6 +1248,173 @@ impl Node {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// HKDF info strings for the bootstrap derivation (see [`bootstrap_ratchet`]).
|
||||||
|
const RATCHET_BOOTSTRAP_SALT: &[u8] = b"onionwire-ratchet-v1-bootstrap";
|
||||||
|
const RATCHET_BOOTSTRAP_ROOT_INFO: &[u8] = b"root";
|
||||||
|
const RATCHET_BOOTSTRAP_KEY_INFO: &[u8] = b"ratchet-key";
|
||||||
|
|
||||||
|
/// Bootstrap a peer's ratchet state from key material both sides already have.
|
||||||
|
///
|
||||||
|
/// The Noise handshake is frozen and carries no payload, so no wire field can
|
||||||
|
/// hand over an initial ratchet public key. Both peers instead derive the
|
||||||
|
/// bootstrap epoch from the X25519 DH of the two signed prekeys — each side
|
||||||
|
/// computes the same secret — and seed each side's initial ratchet keypair with
|
||||||
|
/// that DH plus *its own* identity pubkey. Each peer therefore derives its own
|
||||||
|
/// keypair and the peer's, and the two agree on the epoch without a new wire
|
||||||
|
/// field; fresh entropy enters at the first DH ratchet step. Because the
|
||||||
|
/// derivation is prekey-bound, a peer whose prekey changed gets its stored state
|
||||||
|
/// dropped (`Node::add_friend_payload`).
|
||||||
|
fn bootstrap_ratchet(
|
||||||
|
keys: &Keys,
|
||||||
|
peer_pk: &[u8],
|
||||||
|
peer_prekey: &[u8],
|
||||||
|
) -> Result<RatchetState, String> {
|
||||||
|
let peer_pk: [u8; 32] = peer_pk
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| "peer pubkey is not 32 bytes".to_string())?;
|
||||||
|
let peer_prekey: [u8; 32] = peer_prekey
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| "peer prekey is not 32 bytes".to_string())?;
|
||||||
|
let shared =
|
||||||
|
StaticSecret::from(keys.prekey_sk).diffie_hellman(&X25519Public::from(peer_prekey));
|
||||||
|
let hk = Hkdf::<Sha256>::new(Some(RATCHET_BOOTSTRAP_SALT), shared.as_bytes());
|
||||||
|
|
||||||
|
let mut root_key = [0u8; 32];
|
||||||
|
hk.expand(RATCHET_BOOTSTRAP_ROOT_INFO, &mut root_key)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let local = RatchetKeyPair::from_secret(ratchet_seed(&hk, &keys.identity_pk)?);
|
||||||
|
let remote = ratchet_seed(&hk, &peer_pk)?;
|
||||||
|
let remote_pub = X25519Public::from(&StaticSecret::from(remote)).to_bytes();
|
||||||
|
Ok(RatchetState::bootstrap(root_key, local, remote_pub))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `HKDF(info = "ratchet-key" || pubkey)` — the initial ratchet secret both
|
||||||
|
/// peers compute for the peer with that identity pubkey.
|
||||||
|
fn ratchet_seed(hk: &Hkdf<Sha256>, pubkey: &[u8; 32]) -> Result<[u8; 32], String> {
|
||||||
|
let mut info = Vec::with_capacity(RATCHET_BOOTSTRAP_KEY_INFO.len() + 32);
|
||||||
|
info.extend_from_slice(RATCHET_BOOTSTRAP_KEY_INFO);
|
||||||
|
info.extend_from_slice(pubkey);
|
||||||
|
let mut seed = Zeroizing::new([0u8; 32]);
|
||||||
|
hk.expand(&info, &mut seed[..]).map_err(|e| e.to_string())?;
|
||||||
|
Ok(*seed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The peer's ratchet state: the persisted blob when there is one, a freshly
|
||||||
|
/// bootstrapped state otherwise.
|
||||||
|
///
|
||||||
|
/// The blob is opaque to the store; `RatchetState::to_bytes`/`from_bytes` own
|
||||||
|
/// the format. Nothing is written here — the caller persists once, after a
|
||||||
|
/// successful encrypt/decrypt, so a rejected frame cannot leave a half-created
|
||||||
|
/// session behind.
|
||||||
|
fn ratchet_for(store: &Store, keys: &Keys, friend_pk: &[u8]) -> Result<RatchetState, String> {
|
||||||
|
if let Some(blob) = store.load_ratchet(friend_pk).map_err(|e| e.to_string())? {
|
||||||
|
return RatchetState::from_bytes(&blob).map_err(|e| format!("ratchet state: {e}"));
|
||||||
|
}
|
||||||
|
let f = store
|
||||||
|
.get_friend(friend_pk)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.ok_or_else(|| "unknown friend".to_string())?;
|
||||||
|
if f.prekey.len() != 32 {
|
||||||
|
return Err("friend missing prekey".into());
|
||||||
|
}
|
||||||
|
bootstrap_ratchet(keys, friend_pk, &f.prekey)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode one chat send as a `rat ` frame, then persist the advanced state.
|
||||||
|
///
|
||||||
|
/// Exactly one frame per call, and the caller passes those bytes to
|
||||||
|
/// `Outbox::send_payload`, so a retry re-sends them verbatim instead of
|
||||||
|
/// advancing the sending chain a second time.
|
||||||
|
///
|
||||||
|
/// Public because it is the wire half of `Node::send`: `tests/ratchet_wire.rs`
|
||||||
|
/// drives the real path without Tor. Callers hold the store lock across
|
||||||
|
/// load → encrypt → save.
|
||||||
|
pub fn encode_chat_frame(
|
||||||
|
store: &Store,
|
||||||
|
keys: &Keys,
|
||||||
|
friend_pk: &[u8],
|
||||||
|
plaintext: &[u8],
|
||||||
|
) -> Result<Vec<u8>, String> {
|
||||||
|
let mut state = ratchet_for(store, keys, friend_pk)?;
|
||||||
|
let frame = state.encrypt(plaintext).map_err(|e| e.to_string())?;
|
||||||
|
let blob = Zeroizing::new(state.to_bytes());
|
||||||
|
store
|
||||||
|
.save_ratchet(friend_pk, &blob)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decrypt one inbound `rat ` frame and append it to the chat log as an
|
||||||
|
/// incoming line, then persist the advanced state.
|
||||||
|
///
|
||||||
|
/// Returns the logged plaintext, or `Err` for anything that did not
|
||||||
|
/// authenticate — a bad frame writes no chat row and leaves the stored state
|
||||||
|
/// untouched, because `RatchetState` validates fully before it mutates. The
|
||||||
|
/// ciphertext is never stored and there is no plaintext fallback.
|
||||||
|
///
|
||||||
|
/// Public for the same reason as [`encode_chat_frame`]. Callers hold the store
|
||||||
|
/// lock across load → decrypt → append → save, which is what makes the
|
||||||
|
/// read-modify-write atomic against a second inbound session on the same peer.
|
||||||
|
pub fn ingest_chat_frame(
|
||||||
|
store: &Store,
|
||||||
|
keys: &Keys,
|
||||||
|
peer_pk: &[u8],
|
||||||
|
frame: &[u8],
|
||||||
|
) -> Result<Vec<u8>, String> {
|
||||||
|
let mut state = ratchet_for(store, keys, peer_pk)?;
|
||||||
|
let plaintext = state.decrypt(frame).map_err(|e| e.to_string())?;
|
||||||
|
let line = Zeroizing::new(sanitize::display_text(&plaintext).as_bytes().to_vec());
|
||||||
|
store
|
||||||
|
.append_message(peer_pk, "in", &line[..])
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let blob = Zeroizing::new(state.to_bytes());
|
||||||
|
store
|
||||||
|
.save_ratchet(peer_pk, &blob)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(line.to_vec())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ONIONWIRE_MONEROD=1` opts into a spawned, pruned local `monerod` as the
|
||||||
|
/// chain source. Failure is never fatal: the node starts, and the wallet child
|
||||||
|
/// reports the honest unsynced state.
|
||||||
|
async fn start_monerod(home: &Path) -> Option<Monerod> {
|
||||||
|
if !env_flag("ONIONWIRE_MONEROD") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let home = home.to_path_buf();
|
||||||
|
// Spawning waits up to `monerod::READY_TIMEOUT` for the RPC port: not on
|
||||||
|
// the reactor.
|
||||||
|
match tokio::task::spawn_blocking(move || Monerod::spawn(&home)).await {
|
||||||
|
Ok(Ok(daemon)) => {
|
||||||
|
eprintln!(
|
||||||
|
"monerod: pruned chain source, rpc {} (data {})",
|
||||||
|
daemon.rpc_addr(),
|
||||||
|
daemon.data_dir().display()
|
||||||
|
);
|
||||||
|
Some(daemon)
|
||||||
|
}
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
eprintln!("monerod: no local chain: {e}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("monerod: spawn task failed: {e}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_flag(name: &str) -> bool {
|
||||||
|
std::env::var(name)
|
||||||
|
.map(|v| {
|
||||||
|
matches!(
|
||||||
|
v.trim().to_ascii_lowercase().as_str(),
|
||||||
|
"1" | "true" | "yes" | "on"
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
fn spawn_rend(
|
fn spawn_rend(
|
||||||
node: Arc<Node>,
|
node: Arc<Node>,
|
||||||
rend: impl futures::Stream<Item = tor_hsservice::RendRequest> + Send + 'static,
|
rend: impl futures::Stream<Item = tor_hsservice::RendRequest> + Send + 'static,
|
||||||
|
|
@ -1266,3 +1506,284 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
|
use futures::io::{AsyncRead, AsyncWrite};
|
||||||
|
use tokio::io::AsyncRead as TokioRead;
|
||||||
|
use tokio::io::AsyncWrite as TokioWrite;
|
||||||
|
|
||||||
|
const PASS: &str = "node-ratchet-test-pass";
|
||||||
|
|
||||||
|
/// Never dials: every send queues, which is what leaves the encoded frame
|
||||||
|
/// visible on the outbox row.
|
||||||
|
struct NoDial;
|
||||||
|
|
||||||
|
impl crate::outbox::Deliverer for NoDial {
|
||||||
|
fn deliver<'a>(
|
||||||
|
&'a self,
|
||||||
|
_onion: &'a str,
|
||||||
|
_pinned_id: &'a [u8],
|
||||||
|
_prekey: &'a [u8],
|
||||||
|
_payload: &'a [u8],
|
||||||
|
) -> crate::outbox::BoxFut<'a, Result<(), String>> {
|
||||||
|
Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `handle_incoming` is generic over `futures::io` streams while
|
||||||
|
/// `tokio::io::duplex` hands out `tokio::io` ones; one line per method
|
||||||
|
/// beats a new dev-dependency.
|
||||||
|
struct Duplex(tokio::io::DuplexStream);
|
||||||
|
|
||||||
|
impl AsyncRead for Duplex {
|
||||||
|
fn poll_read(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &mut [u8],
|
||||||
|
) -> Poll<std::io::Result<usize>> {
|
||||||
|
let mut read_buf = tokio::io::ReadBuf::new(buf);
|
||||||
|
match Pin::new(&mut self.get_mut().0).poll_read(cx, &mut read_buf) {
|
||||||
|
Poll::Ready(Ok(())) => Poll::Ready(Ok(read_buf.filled().len())),
|
||||||
|
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
|
||||||
|
Poll::Pending => Poll::Pending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncWrite for Duplex {
|
||||||
|
fn poll_write(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &[u8],
|
||||||
|
) -> Poll<std::io::Result<usize>> {
|
||||||
|
Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
Pin::new(&mut self.get_mut().0).poll_flush(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||||
|
Pin::new(&mut self.get_mut().0).poll_shutdown(cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A real `Node` with no Tor: an unbootstrapped client, no onion service,
|
||||||
|
/// and a deliverer that never dials. `Node::start` / `start_with_passphrase`
|
||||||
|
/// are the only public constructors and both bootstrap Tor and publish an
|
||||||
|
/// onion service, so this is the only way to drive the shipped send and
|
||||||
|
/// receive path offline.
|
||||||
|
fn offline_node(home: &Path, deliverer: Arc<dyn crate::outbox::Deliverer>) -> Node {
|
||||||
|
std::fs::create_dir_all(home).expect("create home");
|
||||||
|
let store = Store::open_at_with_passphrase(home, PASS).expect("open store");
|
||||||
|
let keys = Keys::from_self(&store.self_identity().expect("self identity")).expect("keys");
|
||||||
|
let client = arti_client::TorClient::builder()
|
||||||
|
.config(hs::client_config(&home.join("arti"), &home.join("cache")))
|
||||||
|
.create_unbootstrapped()
|
||||||
|
.expect("unbootstrapped Tor client");
|
||||||
|
let store = Arc::new(Mutex::new(store));
|
||||||
|
let outbox = Arc::new(Outbox::new(Arc::clone(&store), deliverer));
|
||||||
|
Node {
|
||||||
|
home: home.to_path_buf(),
|
||||||
|
store,
|
||||||
|
client,
|
||||||
|
hs: Mutex::new(None),
|
||||||
|
onion: Mutex::new("test.onion".to_string()),
|
||||||
|
keys: Mutex::new(keys),
|
||||||
|
wallet: Wallet::disabled(),
|
||||||
|
// No local chain in tests: `Monerod::spawn` is never called here.
|
||||||
|
monerod: Mutex::new(None),
|
||||||
|
incoming_limit: Mutex::new(TokenBucket::default()),
|
||||||
|
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
|
||||||
|
outbox,
|
||||||
|
worker: Mutex::new(None),
|
||||||
|
stopped: AtomicBool::new(false),
|
||||||
|
onion_reachable: AtomicBool::new(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The friend row a scanned invite leaves behind.
|
||||||
|
fn befriend(store: &Store, other_pk: &[u8], other_prekey: &[u8], onion: &str) {
|
||||||
|
store
|
||||||
|
.upsert_friend(other_pk, onion, None)
|
||||||
|
.expect("upsert friend");
|
||||||
|
store
|
||||||
|
.set_friend_prekey(other_pk, other_prekey)
|
||||||
|
.expect("set friend prekey");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn node_prekey(node: &Node) -> [u8; 32] {
|
||||||
|
node.keys.lock().unwrap().prekey_pk
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One peer→node dial, end to end: a real Noise IK handshake and one
|
||||||
|
/// already-encoded frame over an in-memory stream, into `handle_incoming`.
|
||||||
|
async fn deliver_frame(node: &Node, peer: &Keys, frame: &[u8]) -> Result<(), String> {
|
||||||
|
let node_pk = node.identity_pk();
|
||||||
|
let node_prekey = node_prekey(node);
|
||||||
|
let (client_side, server_side) = tokio::io::duplex(64 * 1024);
|
||||||
|
|
||||||
|
let send = async {
|
||||||
|
let mut stream = Duplex(client_side);
|
||||||
|
let mut sess = session::handshake_initiator(&mut stream, peer, &node_pk, &node_prekey)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.into_message())?;
|
||||||
|
let ct = sess.encrypt(frame).map_err(|e| e.into_message())?;
|
||||||
|
frame::write_frame(&mut stream, &ct)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
};
|
||||||
|
let receive = async {
|
||||||
|
let mut stream = Duplex(server_side);
|
||||||
|
node.handle_incoming(&mut stream).await
|
||||||
|
};
|
||||||
|
let (sent, received) = futures::join!(send, receive);
|
||||||
|
sent?;
|
||||||
|
received
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chat_lines(node: &Node, peer: &Keys) -> Vec<(String, String)> {
|
||||||
|
node.list_messages(&peer.identity_pk)
|
||||||
|
.expect("list messages")
|
||||||
|
.into_iter()
|
||||||
|
.map(|m| {
|
||||||
|
(
|
||||||
|
m.dir,
|
||||||
|
String::from_utf8(m.plaintext).expect("utf8 chat line"),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn send_queues_one_ratchet_frame_and_keeps_the_plaintext_local() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||||||
|
let peer = Keys::generate();
|
||||||
|
befriend(
|
||||||
|
&node.store.lock().unwrap(),
|
||||||
|
&peer.identity_pk,
|
||||||
|
&peer.prekey_pk,
|
||||||
|
"peer.onion",
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
node.send(&peer.identity_pk, b"hello bob").await.unwrap(),
|
||||||
|
OutboxStatus::Queued,
|
||||||
|
"with nothing to dial, the send queues for the retry worker"
|
||||||
|
);
|
||||||
|
|
||||||
|
let rows = node.outbox_pending(&peer.identity_pk).unwrap();
|
||||||
|
assert_eq!(rows.len(), 1);
|
||||||
|
let payload = rows[0]
|
||||||
|
.payload
|
||||||
|
.clone()
|
||||||
|
.expect("the encoded frame rides on the outbox row");
|
||||||
|
assert!(
|
||||||
|
payload.starts_with(b"rat "),
|
||||||
|
"chat goes out as a ratchet frame"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!payload.windows(9).any(|w| w == b"hello bob"),
|
||||||
|
"the plaintext is not on the wire"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
rows[0].body, b"hello bob",
|
||||||
|
"local history keeps the plaintext"
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
chat_lines(&node, &peer),
|
||||||
|
vec![("out".to_string(), "hello bob".to_string())]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_inbound_frame_is_dispatched_to_the_ratchet_and_logged() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||||||
|
let peer = Keys::generate();
|
||||||
|
befriend(
|
||||||
|
&node.store.lock().unwrap(),
|
||||||
|
&peer.identity_pk,
|
||||||
|
&peer.prekey_pk,
|
||||||
|
"peer.onion",
|
||||||
|
);
|
||||||
|
// The peer's own store holds its ratchet state, as a second Node does.
|
||||||
|
let peer_store =
|
||||||
|
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
|
||||||
|
befriend(
|
||||||
|
&peer_store,
|
||||||
|
&node.identity_pk(),
|
||||||
|
&node_prekey(&node),
|
||||||
|
"node.onion",
|
||||||
|
);
|
||||||
|
|
||||||
|
let frame =
|
||||||
|
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"hi bob").expect("encode");
|
||||||
|
deliver_frame(&node, &peer, &frame).await.expect("receive");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
chat_lines(&node, &peer),
|
||||||
|
vec![("in".to_string(), "hi bob".to_string())],
|
||||||
|
"`rat ` is dispatched to the ratchet, not logged as ciphertext chat"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial));
|
||||||
|
let peer = Keys::generate();
|
||||||
|
befriend(
|
||||||
|
&node.store.lock().unwrap(),
|
||||||
|
&peer.identity_pk,
|
||||||
|
&peer.prekey_pk,
|
||||||
|
"peer.onion",
|
||||||
|
);
|
||||||
|
let peer_store =
|
||||||
|
Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store");
|
||||||
|
befriend(
|
||||||
|
&peer_store,
|
||||||
|
&node.identity_pk(),
|
||||||
|
&node_prekey(&node),
|
||||||
|
"node.onion",
|
||||||
|
);
|
||||||
|
|
||||||
|
let frames: Vec<Vec<u8>> = ["m0", "m1", "m2"]
|
||||||
|
.iter()
|
||||||
|
.map(|t| {
|
||||||
|
encode_chat_frame(&peer_store, &peer, &node.identity_pk(), t.as_bytes())
|
||||||
|
.expect("encode")
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Arrival order 2, 0, 1 — the ratchet holds the two it has not seen.
|
||||||
|
deliver_frame(&node, &peer, &frames[2]).await.unwrap();
|
||||||
|
deliver_frame(&node, &peer, &frames[0]).await.unwrap();
|
||||||
|
deliver_frame(&node, &peer, &frames[1]).await.unwrap();
|
||||||
|
// A replay of an already-consumed frame, and a corrupted one: both are
|
||||||
|
// dropped inside `handle_incoming` without a chat row and without
|
||||||
|
// wedging the session.
|
||||||
|
deliver_frame(&node, &peer, &frames[0]).await.unwrap();
|
||||||
|
let mut corrupt = frames[1].clone();
|
||||||
|
let last = corrupt.len() - 1;
|
||||||
|
corrupt[last] ^= 0x01;
|
||||||
|
deliver_frame(&node, &peer, &corrupt).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
chat_lines(&node, &peer),
|
||||||
|
vec![
|
||||||
|
("in".to_string(), "m2".to_string()),
|
||||||
|
("in".to_string(), "m0".to_string()),
|
||||||
|
("in".to_string(), "m1".to_string())
|
||||||
|
],
|
||||||
|
"three lines, arrival order, no duplicates"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -143,9 +143,38 @@ impl Outbox {
|
||||||
/// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is
|
/// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is
|
||||||
/// unreachable, the message is persisted and will be retried. `Err` — a
|
/// unreachable, the message is persisted and will be retried. `Err` — a
|
||||||
/// protocol error or a bad local state, never retried.
|
/// protocol error or a bad local state, never retried.
|
||||||
|
///
|
||||||
|
/// The bytes on the wire are `plaintext`; the *retry* path is where chat
|
||||||
|
/// differs, so chat uses [`Self::send_payload`].
|
||||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||||||
|
self.send_inner(friend_pk, plaintext, None).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Same as [`Self::send`], but the wire bytes are an opaque `payload` that
|
||||||
|
/// a retry re-sends verbatim while the chat history keeps `plaintext`.
|
||||||
|
///
|
||||||
|
/// Chat calls this with its ratchet frame: encoding the frame inside the
|
||||||
|
/// retry loop would advance the sending chain a second time and the peer
|
||||||
|
/// would see a second chat line under a new key. The frame is encoded once
|
||||||
|
/// by the caller, stored on the row, and replayed byte-for-byte.
|
||||||
|
pub async fn send_payload(
|
||||||
|
&self,
|
||||||
|
friend_pk: &[u8],
|
||||||
|
plaintext: &[u8],
|
||||||
|
payload: &[u8],
|
||||||
|
) -> Result<OutboxStatus, String> {
|
||||||
|
self.send_inner(friend_pk, plaintext, Some(payload)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_inner(
|
||||||
|
&self,
|
||||||
|
friend_pk: &[u8],
|
||||||
|
plaintext: &[u8],
|
||||||
|
payload: Option<&[u8]>,
|
||||||
|
) -> Result<OutboxStatus, String> {
|
||||||
let (onion, prekey) = self.target(friend_pk)?;
|
let (onion, prekey) = self.target(friend_pk)?;
|
||||||
match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await {
|
let wire = payload.unwrap_or(plaintext);
|
||||||
|
match self.deliverer.deliver(&onion, friend_pk, &prekey, wire).await {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
self.store()?.append_message(friend_pk, "out", plaintext)?;
|
self.store()?.append_message(friend_pk, "out", plaintext)?;
|
||||||
Ok(OutboxStatus::Sent)
|
Ok(OutboxStatus::Sent)
|
||||||
|
|
@ -155,14 +184,13 @@ impl Outbox {
|
||||||
let now = unix_now();
|
let now = unix_now();
|
||||||
let store = self.store()?;
|
let store = self.store()?;
|
||||||
let message_id = store.append_message_id(friend_pk, "out", plaintext)?;
|
let message_id = store.append_message_id(friend_pk, "out", plaintext)?;
|
||||||
store.enqueue_outbox(
|
let next = now + backoff_secs(0);
|
||||||
friend_pk,
|
match payload {
|
||||||
message_id,
|
Some(payload) => store.enqueue_outbox_payload(
|
||||||
1,
|
friend_pk, message_id, payload, next, &e, now,
|
||||||
now + backoff_secs(0),
|
)?,
|
||||||
&e,
|
None => store.enqueue_outbox(friend_pk, message_id, 1, next, &e, now)?,
|
||||||
now,
|
};
|
||||||
)?;
|
|
||||||
Ok(OutboxStatus::Queued)
|
Ok(OutboxStatus::Queued)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -248,7 +276,13 @@ impl Outbox {
|
||||||
};
|
};
|
||||||
let result = self
|
let result = self
|
||||||
.deliverer
|
.deliverer
|
||||||
.deliver(&onion, &entry.friend_pk, &prekey, &entry.body)
|
.deliver(
|
||||||
|
&onion,
|
||||||
|
&entry.friend_pk,
|
||||||
|
&prekey,
|
||||||
|
// Chat stores its frame here; everything else sends its body.
|
||||||
|
entry.payload.as_deref().unwrap_or(&entry.body),
|
||||||
|
)
|
||||||
.await;
|
.await;
|
||||||
let status = match result {
|
let status = match result {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
|
|
|
||||||
217
src/store.rs
217
src/store.rs
|
|
@ -154,6 +154,12 @@ pub struct OutboxEntry {
|
||||||
pub friend_pk: Vec<u8>,
|
pub friend_pk: Vec<u8>,
|
||||||
pub message_id: i64,
|
pub message_id: i64,
|
||||||
pub body: Vec<u8>,
|
pub body: Vec<u8>,
|
||||||
|
/// What to put on the wire when it is set, instead of `body`. A chat send
|
||||||
|
/// stores its already-encoded ratchet frame here so a retry re-sends the
|
||||||
|
/// identical bytes instead of re-encrypting (which would burn a second
|
||||||
|
/// chain key and land as a second chat line at the peer). `None` means the
|
||||||
|
/// row predates payloads or is a locator/profile/payment row: send `body`.
|
||||||
|
pub payload: Option<Vec<u8>>,
|
||||||
pub attempts: u32,
|
pub attempts: u32,
|
||||||
pub next_attempt_at: i64,
|
pub next_attempt_at: i64,
|
||||||
pub created_at: i64,
|
pub created_at: i64,
|
||||||
|
|
@ -272,9 +278,15 @@ impl Store {
|
||||||
status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')),
|
status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')),
|
||||||
last_error TEXT,
|
last_error TEXT,
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
updated_at INTEGER NOT NULL
|
updated_at INTEGER NOT NULL,
|
||||||
|
payload BLOB
|
||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at);
|
CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at);
|
||||||
|
CREATE TABLE IF NOT EXISTS ratchet_sessions (
|
||||||
|
friend_id INTEGER PRIMARY KEY REFERENCES friends(id) ON DELETE CASCADE,
|
||||||
|
state BLOB NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
|
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
|
||||||
",
|
",
|
||||||
)?;
|
)?;
|
||||||
|
|
@ -345,6 +357,14 @@ impl Store {
|
||||||
"hs_nickname",
|
"hs_nickname",
|
||||||
"ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'",
|
"ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'",
|
||||||
)?;
|
)?;
|
||||||
|
// Opaque send payload for rows that cannot re-derive their bytes (a
|
||||||
|
// chat send's ratchet frame). NULL means "send the message body", the
|
||||||
|
// pre-payload behaviour, so locator/profile/payment rows are unchanged.
|
||||||
|
self.add_column_if_missing(
|
||||||
|
"outbox",
|
||||||
|
"payload",
|
||||||
|
"ALTER TABLE outbox ADD COLUMN payload BLOB",
|
||||||
|
)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -898,6 +918,39 @@ impl Store {
|
||||||
Ok(self.conn.last_insert_rowid())
|
Ok(self.conn.last_insert_rowid())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Queue one already-stored chat message for retry, with the exact bytes to
|
||||||
|
/// put on the wire. Chat uses this: the frame is encoded once, before the
|
||||||
|
/// first attempt, and every retry re-sends these bytes, so a retried
|
||||||
|
/// message cannot arrive as a second chat line under a new key.
|
||||||
|
///
|
||||||
|
/// Narrower than [`Self::enqueue_outbox`] on purpose: a payload row is only
|
||||||
|
/// ever queued by the first attempt failing, so it is created at
|
||||||
|
/// `attempts = 1` and takes no attempt count.
|
||||||
|
pub fn enqueue_outbox_payload(
|
||||||
|
&self,
|
||||||
|
friend_pk: &[u8],
|
||||||
|
message_id: i64,
|
||||||
|
payload: &[u8],
|
||||||
|
next_attempt_at: i64,
|
||||||
|
last_error: &str,
|
||||||
|
now: i64,
|
||||||
|
) -> Result<i64> {
|
||||||
|
let friend_id: i64 = self
|
||||||
|
.conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT id FROM friends WHERE pubkey = ?1",
|
||||||
|
params![friend_pk],
|
||||||
|
|row| row.get(0),
|
||||||
|
)
|
||||||
|
.map_err(|_| Error("friend not found".into()))?;
|
||||||
|
self.conn.execute(
|
||||||
|
"INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at, payload)
|
||||||
|
VALUES (?1, ?2, 1, ?3, 'queued', ?4, ?5, ?5, ?6)",
|
||||||
|
params![friend_id, message_id, next_attempt_at, last_error, now, payload],
|
||||||
|
)?;
|
||||||
|
Ok(self.conn.last_insert_rowid())
|
||||||
|
}
|
||||||
|
|
||||||
/// Rows whose backoff has elapsed: the timer trigger for the worker.
|
/// Rows whose backoff has elapsed: the timer trigger for the worker.
|
||||||
pub fn due_outbox(&self, now: i64, limit: i64) -> Result<Vec<OutboxEntry>> {
|
pub fn due_outbox(&self, now: i64, limit: i64) -> Result<Vec<OutboxEntry>> {
|
||||||
self.outbox_query(
|
self.outbox_query(
|
||||||
|
|
@ -1004,6 +1057,54 @@ impl Store {
|
||||||
Ok(n)
|
Ok(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The persisted Double Ratchet state for one peer, exactly as
|
||||||
|
/// `RatchetState::to_bytes` wrote it. Opaque here: the store never parses or
|
||||||
|
/// re-serializes it, so a state-format change stays a `src/ratchet.rs`
|
||||||
|
/// concern. `Ok(None)` means no session yet, not a failure.
|
||||||
|
pub fn load_ratchet(&self, friend_pk: &[u8]) -> Result<Option<Vec<u8>>> {
|
||||||
|
let state = self
|
||||||
|
.conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT r.state FROM ratchet_sessions r
|
||||||
|
JOIN friends f ON f.id = r.friend_id
|
||||||
|
WHERE f.pubkey = ?1",
|
||||||
|
params![friend_pk],
|
||||||
|
|row| row.get::<_, Vec<u8>>(0),
|
||||||
|
)
|
||||||
|
.optional()?;
|
||||||
|
Ok(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upsert the session blob for one peer, stamping `updated_at`.
|
||||||
|
pub fn save_ratchet(&self, friend_pk: &[u8], state: &[u8]) -> Result<()> {
|
||||||
|
let friend_id: i64 = self
|
||||||
|
.conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT id FROM friends WHERE pubkey = ?1",
|
||||||
|
params![friend_pk],
|
||||||
|
|row| row.get(0),
|
||||||
|
)
|
||||||
|
.map_err(|_| Error("friend not found".into()))?;
|
||||||
|
self.conn.execute(
|
||||||
|
"INSERT INTO ratchet_sessions (friend_id, state, updated_at) VALUES (?1, ?2, ?3)
|
||||||
|
ON CONFLICT(friend_id) DO UPDATE SET
|
||||||
|
state = excluded.state, updated_at = excluded.updated_at",
|
||||||
|
params![friend_id, state, unix_now()],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forget the session: a peer prekey change or an explicit reset. A missing
|
||||||
|
/// row is a no-op.
|
||||||
|
pub fn clear_ratchet(&self, friend_pk: &[u8]) -> Result<()> {
|
||||||
|
self.conn.execute(
|
||||||
|
"DELETE FROM ratchet_sessions WHERE friend_id IN
|
||||||
|
(SELECT id FROM friends WHERE pubkey = ?1)",
|
||||||
|
params![friend_pk],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<OutboxEntry>> {
|
fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<OutboxEntry>> {
|
||||||
let mut stmt = self.conn.prepare(sql)?;
|
let mut stmt = self.conn.prepare(sql)?;
|
||||||
let rows = stmt.query_map(args, |row| {
|
let rows = stmt.query_map(args, |row| {
|
||||||
|
|
@ -1019,6 +1120,7 @@ impl Store {
|
||||||
row.get::<_, i64>(8)?,
|
row.get::<_, i64>(8)?,
|
||||||
row.get::<_, String>(9)?,
|
row.get::<_, String>(9)?,
|
||||||
row.get::<_, Vec<u8>>(10)?,
|
row.get::<_, Vec<u8>>(10)?,
|
||||||
|
row.get::<_, Option<Vec<u8>>>(11)?,
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
|
|
@ -1035,6 +1137,7 @@ impl Store {
|
||||||
m_friend_id,
|
m_friend_id,
|
||||||
dir,
|
dir,
|
||||||
blob,
|
blob,
|
||||||
|
payload,
|
||||||
) = row?;
|
) = row?;
|
||||||
let aad = message_aad(m_friend_id, &dir, message_id);
|
let aad = message_aad(m_friend_id, &dir, message_id);
|
||||||
let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
|
let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
|
||||||
|
|
@ -1044,6 +1147,7 @@ impl Store {
|
||||||
friend_pk,
|
friend_pk,
|
||||||
message_id,
|
message_id,
|
||||||
body,
|
body,
|
||||||
|
payload,
|
||||||
attempts: attempts as u32,
|
attempts: attempts as u32,
|
||||||
next_attempt_at,
|
next_attempt_at,
|
||||||
created_at,
|
created_at,
|
||||||
|
|
@ -1080,6 +1184,10 @@ impl Store {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drop chat + payments history. Identity + friends stay.
|
/// Drop chat + payments history. Identity + friends stay.
|
||||||
|
///
|
||||||
|
/// Ratchet sessions are deliberately left alone: wiping chat history is not
|
||||||
|
/// a session reset, and silently resetting would break decryption against a
|
||||||
|
/// peer that still holds the old state.
|
||||||
/// Not a forensic erase: SSD wear-leveling can keep copies.
|
/// Not a forensic erase: SSD wear-leveling can keep copies.
|
||||||
pub fn wipe_messages(&self) -> Result<()> {
|
pub fn wipe_messages(&self) -> Result<()> {
|
||||||
self.conn.execute("DELETE FROM outbox", [])?;
|
self.conn.execute("DELETE FROM outbox", [])?;
|
||||||
|
|
@ -1374,7 +1482,7 @@ fn mkdir_700(path: &Path) -> Result<()> {
|
||||||
/// Base projection for outbox rows: the body comes from the `messages` row the
|
/// Base projection for outbox rows: the body comes from the `messages` row the
|
||||||
/// outbox row points at, so it stays under that row's AEAD + AAD.
|
/// outbox row points at, so it stays under that row's AEAD + AAD.
|
||||||
const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \
|
const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \
|
||||||
o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \
|
o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext, o.payload \
|
||||||
FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id";
|
FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id";
|
||||||
|
|
||||||
/// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64
|
/// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64
|
||||||
|
|
@ -1831,4 +1939,109 @@ mod at_rest {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `ratchet_sessions` keys on `friend_id`, and nothing in the crate deletes
|
||||||
|
/// friends yet, so the cascade is exercised with the raw statement a future
|
||||||
|
/// friend-removal path would run.
|
||||||
|
#[test]
|
||||||
|
fn removing_a_friend_cascades_to_its_ratchet_row_and_wipe_messages_keeps_it() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "cascade-pass").unwrap();
|
||||||
|
let foreign_keys: i64 = store
|
||||||
|
.conn
|
||||||
|
.query_row("PRAGMA foreign_keys", [], |row| row.get(0))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(foreign_keys, 1, "ON DELETE CASCADE needs foreign_keys ON");
|
||||||
|
|
||||||
|
let pk = [0x21u8; 32];
|
||||||
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
||||||
|
store.save_ratchet(&pk, b"ratchet-state-blob").unwrap();
|
||||||
|
store.append_message(&pk, "out", b"hi").unwrap();
|
||||||
|
|
||||||
|
// Wiping chat history is not a session reset: the peer still holds the
|
||||||
|
// old ratchet state, so dropping ours would break its next frame.
|
||||||
|
store.wipe_messages().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
store.load_ratchet(&pk).unwrap().as_deref(),
|
||||||
|
Some(&b"ratchet-state-blob"[..]),
|
||||||
|
"wipe_messages must not clear ratchet state"
|
||||||
|
);
|
||||||
|
|
||||||
|
store
|
||||||
|
.conn
|
||||||
|
.execute(
|
||||||
|
"DELETE FROM friends WHERE pubkey = ?1",
|
||||||
|
params![pk.as_slice()],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
store.load_ratchet(&pk).unwrap(),
|
||||||
|
None,
|
||||||
|
"deleting the friend must take its ratchet row with it"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ratchet_save_overwrites_the_row_and_bumps_updated_at() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "upsert-pass").unwrap();
|
||||||
|
let pk = [0x22u8; 32];
|
||||||
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
||||||
|
store.save_ratchet(&pk, b"first-state").unwrap();
|
||||||
|
// Park the clock so the assertion cannot pass on an untouched row.
|
||||||
|
store
|
||||||
|
.conn
|
||||||
|
.execute("UPDATE ratchet_sessions SET updated_at = 0", [])
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
store.save_ratchet(&pk, b"second-state-longer").unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
store.load_ratchet(&pk).unwrap().as_deref(),
|
||||||
|
Some(&b"second-state-longer"[..])
|
||||||
|
);
|
||||||
|
let rows: i64 = store
|
||||||
|
.conn
|
||||||
|
.query_row("SELECT count(*) FROM ratchet_sessions", [], |row| {
|
||||||
|
row.get(0)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(rows, 1, "save_ratchet upserts, it does not insert twice");
|
||||||
|
let updated_at: i64 = store
|
||||||
|
.conn
|
||||||
|
.query_row("SELECT updated_at FROM ratchet_sessions", [], |row| {
|
||||||
|
row.get(0)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert!(updated_at > 0, "save_ratchet must set updated_at");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The table is additive: a store written before this card existed gains it
|
||||||
|
/// from `CREATE TABLE IF NOT EXISTS` on the next open, with no data loss.
|
||||||
|
#[test]
|
||||||
|
fn store_predating_the_ratchet_table_gains_it_on_reopen() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let pk = [0x23u8; 32];
|
||||||
|
{
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "old-pass").unwrap();
|
||||||
|
store.upsert_friend(&pk, "peer.onion", None).unwrap();
|
||||||
|
store.append_message(&pk, "in", b"written-before").unwrap();
|
||||||
|
store
|
||||||
|
.conn
|
||||||
|
.execute_batch("DROP TABLE ratchet_sessions")
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "old-pass").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
store.list_messages(&pk).unwrap()[0].plaintext,
|
||||||
|
b"written-before"
|
||||||
|
);
|
||||||
|
assert_eq!(store.load_ratchet(&pk).unwrap(), None);
|
||||||
|
store.save_ratchet(&pk, b"fresh-state").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
store.load_ratchet(&pk).unwrap().as_deref(),
|
||||||
|
Some(&b"fresh-state"[..])
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -32,6 +32,20 @@ fn known_prefixes_are_typed() {
|
||||||
assert_eq!(classify(b"png 1"), Kind::Ping);
|
assert_eq!(classify(b"png 1"), Kind::Ping);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ratchet_frame_is_ratchet() {
|
||||||
|
// `rat ` is a typed prefix, not chat: the plaintext is a ratchet frame.
|
||||||
|
assert_eq!(classify(b"rat \x01rest-of-frame"), Kind::Ratchet);
|
||||||
|
// Matched before the unknown-lowercase-prefix rule, which would Drop it.
|
||||||
|
assert_eq!(classify(b"rat x"), Kind::Ratchet);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_lowercase_prefix_still_drops() {
|
||||||
|
assert_eq!(classify(b"rax not a real type"), Kind::Drop);
|
||||||
|
assert_eq!(classify(b"rat"), Kind::Chat, "3 letters is not a prefix");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn uppercase_or_digit_prefix_is_chat() {
|
fn uppercase_or_digit_prefix_is_chat() {
|
||||||
assert_eq!(classify(b"ZZZ not typed"), Kind::Chat);
|
assert_eq!(classify(b"ZZZ not typed"), Kind::Chat);
|
||||||
|
|
|
||||||
|
|
@ -275,6 +275,62 @@ async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() {
|
||||||
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn payload_row_sends_the_payload_and_keeps_the_body_as_history() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = store_and_friend(dir.path(), "flaky.onion");
|
||||||
|
// First dial fails, the retry succeeds: the payload must survive that.
|
||||||
|
let flaky = Flaky::new(1, "connect flaky.onion:80: timed out");
|
||||||
|
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
||||||
|
let frame = b"rat \x01opaque-frame";
|
||||||
|
|
||||||
|
let status = ob.send_payload(&pk(1), b"chat text", frame).await.unwrap();
|
||||||
|
assert_eq!(status, OutboxStatus::Queued);
|
||||||
|
|
||||||
|
let pending = ob.pending(&pk(1)).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
pending[0].payload.as_deref(),
|
||||||
|
Some(&frame[..]),
|
||||||
|
"the queued row carries the frame, not the plaintext"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
pending[0].body, b"chat text",
|
||||||
|
"the chat row still holds the plaintext"
|
||||||
|
);
|
||||||
|
|
||||||
|
let now = pending[0].next_attempt_at;
|
||||||
|
let fired = ob.flush_friend(&pk(1), now).await.unwrap();
|
||||||
|
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||||
|
assert_eq!(
|
||||||
|
flaky.delivered(),
|
||||||
|
vec![frame.to_vec()],
|
||||||
|
"the retry put the frame on the wire, not the body"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn null_payload_rows_still_send_their_body() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = store_and_friend(dir.path(), "flaky.onion");
|
||||||
|
let flaky = Flaky::new(1, "connect flaky.onion:80: timed out");
|
||||||
|
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
||||||
|
|
||||||
|
// A locator/profile/payment-style row: no payload, so the body is the wire
|
||||||
|
// form. This is the pre-payload behaviour, row for row.
|
||||||
|
assert_eq!(
|
||||||
|
ob.send(&pk(1), b"loc abc.onion\n1").await.unwrap(),
|
||||||
|
OutboxStatus::Queued
|
||||||
|
);
|
||||||
|
assert_eq!(ob.pending(&pk(1)).unwrap()[0].payload, None);
|
||||||
|
|
||||||
|
let now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
|
||||||
|
assert_eq!(
|
||||||
|
ob.flush_friend(&pk(1), now).await.unwrap()[0].1,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
assert_eq!(flaky.delivered(), vec![b"loc abc.onion\n1".to_vec()]);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn wipe_clears_outbox_rows() {
|
async fn wipe_clears_outbox_rows() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|
|
||||||
477
tests/ratchet_adversarial.rs
Normal file
477
tests/ratchet_adversarial.rs
Normal file
|
|
@ -0,0 +1,477 @@
|
||||||
|
//! What the chat ratchet refuses: attacks, bounds, desync, corruption.
|
||||||
|
//!
|
||||||
|
//! Same offline harness as `tests/ratchet_e2e.rs` — real encrypted stores, real
|
||||||
|
//! identity keys, the real `encode_chat_frame` / `ingest_chat_frame` pair that
|
||||||
|
//! `Node::send` and `Node::handle_incoming` call, and a capture-and-release
|
||||||
|
//! `Deliverer` so the test decides what arrives, when, and how often.
|
||||||
|
//!
|
||||||
|
//! The load-bearing assertions are that a rejected frame is *dropped* (no chat
|
||||||
|
//! line) and that it leaves the persisted `ratchet_sessions` blob byte-identical
|
||||||
|
//! — not merely that a message did not appear.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use onionwire::Store;
|
||||||
|
use onionwire::node::{encode_chat_frame, ingest_chat_frame};
|
||||||
|
use onionwire::outbox::{BoxFut, Deliverer, Outbox, OutboxStatus};
|
||||||
|
use onionwire::ratchet::{HEADER_OFFSET, MAX_SKIP, RatchetState};
|
||||||
|
use onionwire::session::Keys;
|
||||||
|
|
||||||
|
const PASS: &str = "ratchet-adv-pass";
|
||||||
|
const ONION: &str = "peer.onion";
|
||||||
|
|
||||||
|
/// Capture-and-release transport: a delivery is recorded for its recipient and
|
||||||
|
/// reported successful, so the test controls arrival order and drops.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Wire {
|
||||||
|
queues: Mutex<HashMap<Vec<u8>, VecDeque<Vec<u8>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Wire {
|
||||||
|
fn new() -> Arc<Self> {
|
||||||
|
Arc::new(Self::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take(&self, to: &[u8]) -> Vec<Vec<u8>> {
|
||||||
|
self.queues
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.remove(to)
|
||||||
|
.map(|q| q.into_iter().collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deliverer for Wire {
|
||||||
|
fn deliver<'a>(
|
||||||
|
&'a self,
|
||||||
|
_onion: &'a str,
|
||||||
|
pinned_id: &'a [u8],
|
||||||
|
_prekey: &'a [u8],
|
||||||
|
payload: &'a [u8],
|
||||||
|
) -> BoxFut<'a, Result<(), String>> {
|
||||||
|
self.queues
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.entry(pinned_id.to_vec())
|
||||||
|
.or_default()
|
||||||
|
.push_back(payload.to_vec());
|
||||||
|
Box::pin(async { Ok(()) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Peer {
|
||||||
|
store: Arc<Mutex<Store>>,
|
||||||
|
keys: Keys,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Peer {
|
||||||
|
fn open_at(home: &Path) -> Self {
|
||||||
|
let store = Store::open_at_with_passphrase(home, PASS).expect("open store");
|
||||||
|
let me = store.self_identity().expect("self identity");
|
||||||
|
let keys = Keys::from_self(&me).expect("keys from store identity");
|
||||||
|
Self {
|
||||||
|
store: Arc::new(Mutex::new(store)),
|
||||||
|
keys,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pk(&self) -> Vec<u8> {
|
||||||
|
self.keys.identity_pk.to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_friend(&self, other: &Peer) {
|
||||||
|
let s = self.store.lock().unwrap();
|
||||||
|
s.upsert_friend(&other.pk(), ONION, None)
|
||||||
|
.expect("upsert friend");
|
||||||
|
s.set_friend_prekey(&other.pk(), &other.keys.prekey_pk)
|
||||||
|
.expect("set friend prekey");
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send(&self, outbox: &Outbox, to: &Peer, text: &[u8]) -> OutboxStatus {
|
||||||
|
let frame = {
|
||||||
|
let s = self.store.lock().unwrap();
|
||||||
|
encode_chat_frame(&s, &self.keys, &to.pk(), text).expect("encode chat frame")
|
||||||
|
};
|
||||||
|
outbox
|
||||||
|
.send_payload(&to.pk(), text, &frame)
|
||||||
|
.await
|
||||||
|
.expect("send payload")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ingest(&self, from: &Peer, frame: &[u8]) -> Result<Vec<u8>, String> {
|
||||||
|
let s = self.store.lock().unwrap();
|
||||||
|
ingest_chat_frame(&s, &self.keys, &from.pk(), frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lines(&self, other: &Peer) -> Vec<(String, String)> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.list_messages(&other.pk())
|
||||||
|
.expect("list messages")
|
||||||
|
.into_iter()
|
||||||
|
.map(|m| {
|
||||||
|
(
|
||||||
|
m.dir,
|
||||||
|
String::from_utf8(m.plaintext).expect("utf8 chat line"),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ratchet_blob(&self, other: &Peer) -> Option<Vec<u8>> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.load_ratchet(&other.pk())
|
||||||
|
.expect("load ratchet")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_ratchet(&self, other: &Peer) {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.clear_ratchet(&other.pk())
|
||||||
|
.expect("clear ratchet");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send `count` chat lines from `from` and hand back the captured frames.
|
||||||
|
async fn send_n(from: &Peer, to: &Peer, wire: &Arc<Wire>, count: usize) -> Vec<Vec<u8>> {
|
||||||
|
let outbox = Outbox::new(Arc::clone(&from.store), wire.clone());
|
||||||
|
for i in 0..count {
|
||||||
|
let text = format!("m{i}");
|
||||||
|
assert_eq!(
|
||||||
|
from.send(&outbox, to, text.as_bytes()).await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let frames = wire.take(&to.pk());
|
||||||
|
assert_eq!(frames.len(), count, "one captured frame per send");
|
||||||
|
frames
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `N` (sender's index in its sending chain) carried by a frame header.
|
||||||
|
fn frame_n(frame: &[u8]) -> u32 {
|
||||||
|
let at = HEADER_OFFSET + 32;
|
||||||
|
u32::from_be_bytes(frame[at..at + 4].try_into().expect("4 bytes"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A frame with a rewritten `N`, still well-formed: whatever rejects it in
|
||||||
|
/// `decrypt` is the bound, not the parser.
|
||||||
|
fn with_n(frame: &[u8], n: u32) -> Vec<u8> {
|
||||||
|
let mut out = frame.to_vec();
|
||||||
|
let at = HEADER_OFFSET + 32;
|
||||||
|
out[at..at + 4].copy_from_slice(&n.to_be_bytes());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn two_peers(dir: &Path) -> (Peer, Peer, Arc<Wire>) {
|
||||||
|
let wire = Wire::new();
|
||||||
|
let alice = Peer::open_at(&dir.join("alice"));
|
||||||
|
let bob = Peer::open_at(&dir.join("bob"));
|
||||||
|
alice.add_friend(&bob);
|
||||||
|
bob.add_friend(&alice);
|
||||||
|
(alice, bob, wire)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_frame_claiming_a_skip_past_max_skip_is_dropped_with_the_state_untouched() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob, wire) = two_peers(dir.path());
|
||||||
|
|
||||||
|
let frames = send_n(&alice, &bob, &wire, 2).await;
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0");
|
||||||
|
|
||||||
|
// The next frame Alice would send claims index 1 on the chain Bob is on.
|
||||||
|
let fresh = frames[1].clone();
|
||||||
|
assert_eq!(frame_n(&fresh), 1, "the sender's chain index");
|
||||||
|
let before = bob.ratchet_blob(&alice).expect("bob has a session");
|
||||||
|
let lines_before = bob.lines(&alice);
|
||||||
|
|
||||||
|
// A well-formed frame claiming 2001 messages further along the chain.
|
||||||
|
let crafted = with_n(&fresh, 1 + MAX_SKIP + 1);
|
||||||
|
let err = bob
|
||||||
|
.ingest(&alice, &crafted)
|
||||||
|
.expect_err("a jump past MAX_SKIP must be dropped");
|
||||||
|
assert!(
|
||||||
|
err.contains("MAX_SKIP"),
|
||||||
|
"the bound must reject it, not the AEAD: {err}"
|
||||||
|
);
|
||||||
|
assert_eq!(bob.lines(&alice), lines_before, "no chat line");
|
||||||
|
assert_eq!(
|
||||||
|
bob.ratchet_blob(&alice).expect("session still there"),
|
||||||
|
before,
|
||||||
|
"the persisted ratchet state is byte-identical"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The bound is exclusive of the limit: a jump of exactly MAX_SKIP is inside
|
||||||
|
// it, so that frame is rejected for its tag, not for its length. This pins
|
||||||
|
// the off-by-one in the other direction.
|
||||||
|
let at_limit = with_n(&fresh, 1 + MAX_SKIP);
|
||||||
|
let err = bob
|
||||||
|
.ingest(&alice, &at_limit)
|
||||||
|
.expect_err("a tampered header still fails to authenticate");
|
||||||
|
assert!(
|
||||||
|
!err.contains("MAX_SKIP"),
|
||||||
|
"MAX_SKIP itself is allowed through the bound: {err}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bob.ratchet_blob(&alice).expect("session still there"),
|
||||||
|
before,
|
||||||
|
"and it too left the state byte-identical"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Nothing is wedged: the real frame still lands.
|
||||||
|
assert_eq!(bob.ingest(&alice, &fresh).unwrap(), b"m1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_snapshot_heals_only_once_the_ratchet_key_it_held_has_been_replaced() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob, wire) = two_peers(dir.path());
|
||||||
|
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
|
||||||
|
let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone());
|
||||||
|
|
||||||
|
// Three frames on one chain; Bob takes the last two, so his state also
|
||||||
|
// legitimately holds the skipped key for the first.
|
||||||
|
let frames = send_n(&alice, &bob, &wire, 3).await;
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[1]).unwrap(), b"m1");
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[2]).unwrap(), b"m2");
|
||||||
|
|
||||||
|
// The compromise: everything Bob's session was at this point.
|
||||||
|
let snapshot_blob = bob.ratchet_blob(&alice).expect("bob has a session");
|
||||||
|
let mut snapshot = RatchetState::from_bytes(&snapshot_blob).expect("snapshot parses");
|
||||||
|
|
||||||
|
// What the snapshot can still read: exactly the skipped key it was holding,
|
||||||
|
// once. Everything it already consumed is gone.
|
||||||
|
assert_eq!(
|
||||||
|
snapshot.decrypt(&frames[0]).unwrap(),
|
||||||
|
b"m0",
|
||||||
|
"a skipped key it legitimately holds"
|
||||||
|
);
|
||||||
|
let again = snapshot
|
||||||
|
.decrypt(&frames[0])
|
||||||
|
.expect_err("the skipped key is used up")
|
||||||
|
.to_string();
|
||||||
|
assert!(again.contains("already used"), "{again}");
|
||||||
|
let used = snapshot
|
||||||
|
.decrypt(&frames[1])
|
||||||
|
.expect_err("a consumed message key is gone")
|
||||||
|
.to_string();
|
||||||
|
assert!(used.contains("already used"), "{used}");
|
||||||
|
|
||||||
|
// Round one: Bob speaks, Alice adopts his key and answers. That epoch is
|
||||||
|
// built on Bob's ratchet key, which the snapshot still holds — a Double
|
||||||
|
// Ratchet heals on the *next* step, not this one.
|
||||||
|
assert_eq!(bob.send(&to_alice, &alice, b"r0").await, OutboxStatus::Sent);
|
||||||
|
let r0 = wire.take(&alice.pk()).remove(0);
|
||||||
|
assert_eq!(alice.ingest(&bob, &r0).unwrap(), b"r0");
|
||||||
|
assert_eq!(alice.send(&to_bob, &bob, b"a3").await, OutboxStatus::Sent);
|
||||||
|
let a3 = wire.take(&bob.pk()).remove(0);
|
||||||
|
assert_eq!(bob.ingest(&alice, &a3).unwrap(), b"a3");
|
||||||
|
|
||||||
|
// Round two: Bob answers on the key he minted when he adopted `a3`, and
|
||||||
|
// Alice adopts that. This epoch needs a ratchet secret the snapshot never
|
||||||
|
// had — Bob generated it after the compromise.
|
||||||
|
assert_eq!(bob.send(&to_alice, &alice, b"r1").await, OutboxStatus::Sent);
|
||||||
|
let r1 = wire.take(&alice.pk()).remove(0);
|
||||||
|
assert_eq!(alice.ingest(&bob, &r1).unwrap(), b"r1");
|
||||||
|
assert_eq!(alice.send(&to_bob, &bob, b"a4").await, OutboxStatus::Sent);
|
||||||
|
let a4 = wire.take(&bob.pk()).remove(0);
|
||||||
|
assert_eq!(
|
||||||
|
bob.ingest(&alice, &a4).unwrap(),
|
||||||
|
b"a4",
|
||||||
|
"the live session, which minted a new ratchet key, keeps working"
|
||||||
|
);
|
||||||
|
|
||||||
|
let live = RatchetState::from_bytes(&bob.ratchet_blob(&alice).expect("live session"))
|
||||||
|
.expect("live state parses");
|
||||||
|
assert!(
|
||||||
|
live.public() != snapshot.public() && live.remote_pub() != snapshot.remote_pub(),
|
||||||
|
"at least one DH ratchet step happened after the snapshot"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The epoch built on the snapshot's own key is still readable: that is the
|
||||||
|
// documented Double Ratchet hop, and it is why the claim below is worded
|
||||||
|
// about the epoch that requires a secret minted after the compromise.
|
||||||
|
assert_eq!(
|
||||||
|
snapshot.decrypt(&a3).unwrap(),
|
||||||
|
b"a3",
|
||||||
|
"the epoch built on the key the snapshot already held"
|
||||||
|
);
|
||||||
|
|
||||||
|
let after = snapshot
|
||||||
|
.decrypt(&a4)
|
||||||
|
.expect_err("the compromised snapshot must not read the healed epoch")
|
||||||
|
.to_string();
|
||||||
|
assert!(
|
||||||
|
!after.contains("MAX_SKIP") && !after.contains("bad frame"),
|
||||||
|
"it fails on the keys, not the framing: {after}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The live session's history is the whole conversation and nothing extra.
|
||||||
|
assert_eq!(
|
||||||
|
bob.lines(&alice)
|
||||||
|
.iter()
|
||||||
|
.map(|(_, t)| t.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
["m1", "m2", "r0", "a3", "r1", "a4"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_ratchet_frame_for_an_unknown_friend_is_dropped_without_a_session() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob, wire) = two_peers(dir.path());
|
||||||
|
// A third identity Bob has never scanned an invite from.
|
||||||
|
let stranger = Peer::open_at(&dir.path().join("stranger"));
|
||||||
|
stranger.add_friend(&bob);
|
||||||
|
|
||||||
|
let outbox = Outbox::new(Arc::clone(&stranger.store), wire.clone());
|
||||||
|
assert_eq!(
|
||||||
|
stranger.send(&outbox, &bob, b"who am i").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let frames = wire.take(&bob.pk());
|
||||||
|
assert_eq!(frames.len(), 1);
|
||||||
|
|
||||||
|
let err = bob
|
||||||
|
.ingest(&stranger, &frames[0])
|
||||||
|
.expect_err("no friend row");
|
||||||
|
assert!(err.contains("unknown friend"), "{err}");
|
||||||
|
assert!(bob.lines(&stranger).is_empty(), "no chat line");
|
||||||
|
assert!(
|
||||||
|
bob.ratchet_blob(&stranger).is_none(),
|
||||||
|
"a dropped frame writes no session row"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Bob's real conversation is unaffected.
|
||||||
|
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
|
||||||
|
assert_eq!(alice.send(&to_bob, &bob, b"m0").await, OutboxStatus::Sent);
|
||||||
|
let frames = wire.take(&bob.pk());
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_frame_from_a_retired_epoch_is_dropped_and_the_resynced_epoch_works() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob, wire) = two_peers(dir.path());
|
||||||
|
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
|
||||||
|
let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone());
|
||||||
|
|
||||||
|
// Get both sides off the bootstrap epoch.
|
||||||
|
assert_eq!(alice.send(&to_bob, &bob, b"m0").await, OutboxStatus::Sent);
|
||||||
|
let m0 = wire.take(&bob.pk()).remove(0);
|
||||||
|
assert_eq!(bob.ingest(&alice, &m0).unwrap(), b"m0");
|
||||||
|
assert_eq!(bob.send(&to_alice, &alice, b"r0").await, OutboxStatus::Sent);
|
||||||
|
let r0 = wire.take(&alice.pk()).remove(0);
|
||||||
|
assert_eq!(alice.ingest(&bob, &r0).unwrap(), b"r0");
|
||||||
|
|
||||||
|
// A refreshed invite: Bob's friend row now carries Alice's *new* signed
|
||||||
|
// prekey, and the bootstrap epoch is derived from exactly that prekey — so
|
||||||
|
// `Node::add_friend_payload` drops the stored session on this change. Bob's
|
||||||
|
// side of the old epoch is gone, and the epoch he would now derive is a
|
||||||
|
// different one.
|
||||||
|
let refreshed = Keys::generate();
|
||||||
|
bob.clear_ratchet(&alice);
|
||||||
|
bob.store
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.set_friend_prekey(&alice.pk(), &refreshed.prekey_pk)
|
||||||
|
.expect("refresh the prekey");
|
||||||
|
let lines_before = bob.lines(&alice);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
alice.send(&to_bob, &bob, b"stale").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let stale = wire.take(&bob.pk()).remove(0);
|
||||||
|
let err = bob
|
||||||
|
.ingest(&alice, &stale)
|
||||||
|
.expect_err("an epoch derived from a prekey Bob no longer holds");
|
||||||
|
assert!(
|
||||||
|
err.contains("authentication"),
|
||||||
|
"well-formed, but its keys come from an epoch Bob cannot derive: {err}"
|
||||||
|
);
|
||||||
|
assert_eq!(bob.lines(&alice), lines_before, "no chat line");
|
||||||
|
assert!(
|
||||||
|
bob.ratchet_blob(&alice).is_none(),
|
||||||
|
"the rejected frame must not leave a half-built session behind"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Recovery is the documented one: the invite is scanned again with the right
|
||||||
|
// prekey and both sides re-derive from it, then keep talking both ways.
|
||||||
|
bob.store
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.set_friend_prekey(&alice.pk(), &alice.keys.prekey_pk)
|
||||||
|
.expect("re-scan the invite");
|
||||||
|
alice.clear_ratchet(&bob);
|
||||||
|
assert_eq!(
|
||||||
|
alice.send(&to_bob, &bob, b"fresh").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let fresh = wire.take(&bob.pk()).remove(0);
|
||||||
|
assert_eq!(bob.ingest(&alice, &fresh).unwrap(), b"fresh");
|
||||||
|
assert_eq!(
|
||||||
|
bob.send(&to_alice, &alice, b"fresh-reply").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let reply = wire.take(&alice.pk()).remove(0);
|
||||||
|
assert_eq!(alice.ingest(&bob, &reply).unwrap(), b"fresh-reply");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn corrupted_frames_are_dropped_without_touching_the_state() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob, wire) = two_peers(dir.path());
|
||||||
|
|
||||||
|
let frames = send_n(&alice, &bob, &wire, 2).await;
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0");
|
||||||
|
|
||||||
|
let before = bob.ratchet_blob(&alice).expect("bob has a session");
|
||||||
|
let lines_before = bob.lines(&alice);
|
||||||
|
let good = frames[1].clone();
|
||||||
|
|
||||||
|
let mut bad_version = good.clone();
|
||||||
|
bad_version[4] ^= 0xff;
|
||||||
|
let mut flipped_key = good.clone();
|
||||||
|
flipped_key[HEADER_OFFSET] ^= 0x01;
|
||||||
|
let mut flipped_n = good.clone();
|
||||||
|
flipped_n[HEADER_OFFSET + 32 + 3] ^= 0x01;
|
||||||
|
let mut flipped_ct = good.clone();
|
||||||
|
let last = flipped_ct.len() - 1;
|
||||||
|
flipped_ct[last] ^= 0x01;
|
||||||
|
|
||||||
|
let cases: [(&str, Vec<u8>); 6] = [
|
||||||
|
("truncated", good[..good.len() - 1].to_vec()),
|
||||||
|
("header only", b"rat \x01".to_vec()),
|
||||||
|
("bad version", bad_version),
|
||||||
|
("flipped dh_pub", flipped_key),
|
||||||
|
("flipped N", flipped_n),
|
||||||
|
("flipped ciphertext", flipped_ct),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (label, frame) in cases {
|
||||||
|
assert!(
|
||||||
|
bob.ingest(&alice, &frame).is_err(),
|
||||||
|
"{label}: must be dropped"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bob.lines(&alice),
|
||||||
|
lines_before,
|
||||||
|
"{label}: must log no chat line"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bob.ratchet_blob(&alice).expect("session still there"),
|
||||||
|
before,
|
||||||
|
"{label}: must leave the persisted state byte-identical"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_eq!(bob.ingest(&alice, &good).unwrap(), b"m1");
|
||||||
|
}
|
||||||
406
tests/ratchet_e2e.rs
Normal file
406
tests/ratchet_e2e.rs
Normal file
|
|
@ -0,0 +1,406 @@
|
||||||
|
//! The chat ratchet on the wired path: the lifecycle, offline.
|
||||||
|
//!
|
||||||
|
//! `Node::send` is three lines — encode exactly one `rat ` frame with
|
||||||
|
//! [`encode_chat_frame`], then hand *the frame* (not the plaintext) to
|
||||||
|
//! `Outbox::send_payload` so a retry re-sends identical bytes. The receive half,
|
||||||
|
//! `Node::handle_incoming`'s `Kind::Ratchet` arm, is [`ingest_chat_frame`]:
|
||||||
|
//! load the session under the store lock, decrypt, log the plaintext, drop
|
||||||
|
//! anything that does not authenticate.
|
||||||
|
//!
|
||||||
|
//! `Node::start` is the only public constructor and it bootstraps Tor and
|
||||||
|
//! publishes an onion service, so a test outside the crate cannot build one.
|
||||||
|
//! These tests therefore drive that exact pair of functions against real
|
||||||
|
//! encrypted stores with a capture-and-release `Deliverer`, which is what makes
|
||||||
|
//! delivery order and drops controllable; the `Node` struct itself (its send
|
||||||
|
//! body and its dispatch arm, over a real Noise session on an in-memory stream)
|
||||||
|
//! is driven in `src/node.rs`'s test module, and the live Tor path stays
|
||||||
|
//! `#[ignore]`d in `tests/two_node.rs`.
|
||||||
|
//!
|
||||||
|
//! Every store here is a real SQLCipher file in a temp dir, and every identity
|
||||||
|
//! is loaded back out of it, so "restart" means reopening the same home
|
||||||
|
//! directory exactly as `Node::start_with_passphrase` does.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use onionwire::Store;
|
||||||
|
use onionwire::node::{encode_chat_frame, ingest_chat_frame};
|
||||||
|
use onionwire::outbox::{BoxFut, Deliverer, Outbox, OutboxStatus};
|
||||||
|
use onionwire::session::Keys;
|
||||||
|
|
||||||
|
const PASS: &str = "ratchet-e2e-pass";
|
||||||
|
const ONION: &str = "peer.onion";
|
||||||
|
|
||||||
|
/// Capture-and-release transport.
|
||||||
|
///
|
||||||
|
/// A delivery is recorded for its recipient and reported successful, so the
|
||||||
|
/// sending side believes it went out; the test then decides when each captured
|
||||||
|
/// frame reaches the recipient and in what order. `fail_next` makes the next
|
||||||
|
/// `n` dials fail, which is how a queued row — and therefore a byte-identical
|
||||||
|
/// retry — is produced.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Wire {
|
||||||
|
queues: Mutex<HashMap<Vec<u8>, VecDeque<Vec<u8>>>>,
|
||||||
|
fail_next: AtomicUsize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Wire {
|
||||||
|
fn new() -> Arc<Self> {
|
||||||
|
Arc::new(Self::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next `n` dials fail and are not captured.
|
||||||
|
fn fail_next(&self, n: usize) {
|
||||||
|
self.fail_next.store(n, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frames captured for `to`, in send order, drained.
|
||||||
|
fn take(&self, to: &[u8]) -> Vec<Vec<u8>> {
|
||||||
|
self.queues
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.remove(to)
|
||||||
|
.map(|q| q.into_iter().collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deliverer for Wire {
|
||||||
|
fn deliver<'a>(
|
||||||
|
&'a self,
|
||||||
|
_onion: &'a str,
|
||||||
|
pinned_id: &'a [u8],
|
||||||
|
_prekey: &'a [u8],
|
||||||
|
payload: &'a [u8],
|
||||||
|
) -> BoxFut<'a, Result<(), String>> {
|
||||||
|
if self.fail_next.load(Ordering::SeqCst) > 0 {
|
||||||
|
self.fail_next.fetch_sub(1, Ordering::SeqCst);
|
||||||
|
return Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) });
|
||||||
|
}
|
||||||
|
self.queues
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.entry(pinned_id.to_vec())
|
||||||
|
.or_default()
|
||||||
|
.push_back(payload.to_vec());
|
||||||
|
Box::pin(async { Ok(()) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One peer: a real encrypted store on disk plus the identity and prekey loaded
|
||||||
|
/// back out of it, which is what `Node::start_with_passphrase` builds.
|
||||||
|
struct Peer {
|
||||||
|
store: Arc<Mutex<Store>>,
|
||||||
|
keys: Keys,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Peer {
|
||||||
|
fn open_at(home: &Path) -> Self {
|
||||||
|
let store = Store::open_at_with_passphrase(home, PASS).expect("open store");
|
||||||
|
let me = store.self_identity().expect("self identity");
|
||||||
|
let keys = Keys::from_self(&me).expect("keys from store identity");
|
||||||
|
Self {
|
||||||
|
store: Arc::new(Mutex::new(store)),
|
||||||
|
keys,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pk(&self) -> Vec<u8> {
|
||||||
|
self.keys.identity_pk.to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The friend row a scanned invite leaves behind.
|
||||||
|
fn add_friend(&self, other: &Peer) {
|
||||||
|
let s = self.store.lock().unwrap();
|
||||||
|
s.upsert_friend(&other.pk(), ONION, None)
|
||||||
|
.expect("upsert friend");
|
||||||
|
s.set_friend_prekey(&other.pk(), &other.keys.prekey_pk)
|
||||||
|
.expect("set friend prekey");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Node::send`: encode the frame once, hand the frame to the outbox.
|
||||||
|
async fn send(&self, outbox: &Outbox, to: &Peer, text: &[u8]) -> OutboxStatus {
|
||||||
|
let frame = {
|
||||||
|
let s = self.store.lock().unwrap();
|
||||||
|
encode_chat_frame(&s, &self.keys, &to.pk(), text).expect("encode chat frame")
|
||||||
|
};
|
||||||
|
outbox
|
||||||
|
.send_payload(&to.pk(), text, &frame)
|
||||||
|
.await
|
||||||
|
.expect("send payload")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Node::handle_incoming`'s `Kind::Ratchet` arm.
|
||||||
|
fn ingest(&self, from: &Peer, frame: &[u8]) -> Result<Vec<u8>, String> {
|
||||||
|
let s = self.store.lock().unwrap();
|
||||||
|
ingest_chat_frame(&s, &self.keys, &from.pk(), frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Chat lines with one peer as `(dir, plaintext)`, in row order.
|
||||||
|
fn lines(&self, other: &Peer) -> Vec<(String, String)> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.list_messages(&other.pk())
|
||||||
|
.expect("list messages")
|
||||||
|
.into_iter()
|
||||||
|
.map(|m| {
|
||||||
|
(
|
||||||
|
m.dir,
|
||||||
|
String::from_utf8(m.plaintext).expect("utf8 chat line"),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The persisted `ratchet_sessions` blob for one peer.
|
||||||
|
fn ratchet_blob(&self, other: &Peer) -> Option<Vec<u8>> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.load_ratchet(&other.pk())
|
||||||
|
.expect("load ratchet")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Just the plaintexts of a peer's chat lines, for a readable assertion.
|
||||||
|
fn texts(lines: &[(String, String)]) -> Vec<&str> {
|
||||||
|
lines.iter().map(|(_, t)| t.as_str()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chat(dir: &str, text: &str) -> (String, String) {
|
||||||
|
(dir.to_string(), text.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn two_peers(dir: &Path) -> (Peer, Peer, Arc<Wire>) {
|
||||||
|
let wire = Wire::new();
|
||||||
|
let alice = Peer::open_at(&dir.join("alice"));
|
||||||
|
let bob = Peer::open_at(&dir.join("bob"));
|
||||||
|
alice.add_friend(&bob);
|
||||||
|
bob.add_friend(&alice);
|
||||||
|
(alice, bob, wire)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_full_exchange_in_both_directions_logs_each_frame_once() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob, wire) = two_peers(dir.path());
|
||||||
|
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
|
||||||
|
let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone());
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
alice.send(&to_bob, &bob, b"hi bob").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let frames = wire.take(&bob.pk());
|
||||||
|
assert_eq!(frames.len(), 1, "one frame per send");
|
||||||
|
assert!(
|
||||||
|
frames[0].starts_with(b"rat "),
|
||||||
|
"chat goes out as a ratchet frame"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!frames[0].windows(6).any(|w| w == b"hi bob"),
|
||||||
|
"the plaintext is not on the wire"
|
||||||
|
);
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"hi bob");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
bob.send(&to_alice, &alice, b"hi alice").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let frames = wire.take(&alice.pk());
|
||||||
|
assert_eq!(frames.len(), 1);
|
||||||
|
assert_eq!(alice.ingest(&bob, &frames[0]).unwrap(), b"hi alice");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
alice.lines(&bob),
|
||||||
|
vec![chat("out", "hi bob"), chat("in", "hi alice")]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bob.lines(&alice),
|
||||||
|
vec![chat("in", "hi bob"), chat("out", "hi alice")]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn out_of_order_delivery_keeps_every_message_once_in_arrival_order() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob, wire) = two_peers(dir.path());
|
||||||
|
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
|
||||||
|
|
||||||
|
for text in [b"m0".as_slice(), b"m1", b"m2"] {
|
||||||
|
assert_eq!(alice.send(&to_bob, &bob, text).await, OutboxStatus::Sent);
|
||||||
|
}
|
||||||
|
let mut frames = wire.take(&bob.pk());
|
||||||
|
assert_eq!(frames.len(), 3, "one captured frame per send");
|
||||||
|
|
||||||
|
// Arrival order 2, 0, 1: the ratchet must hold message keys for the two it
|
||||||
|
// has not seen yet and never log a frame twice.
|
||||||
|
let last = frames.remove(2);
|
||||||
|
let first = frames.remove(0);
|
||||||
|
let second = frames.remove(0);
|
||||||
|
assert_eq!(bob.ingest(&alice, &last).unwrap(), b"m2");
|
||||||
|
assert_eq!(bob.ingest(&alice, &first).unwrap(), b"m0");
|
||||||
|
assert_eq!(bob.ingest(&alice, &second).unwrap(), b"m1");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
bob.lines(&alice),
|
||||||
|
vec![chat("in", "m2"), chat("in", "m0"), chat("in", "m1")],
|
||||||
|
"three lines, arrival order, no duplicates"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_frame_that_never_arrives_does_not_stall_the_conversation() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob, wire) = two_peers(dir.path());
|
||||||
|
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
|
||||||
|
|
||||||
|
for text in [b"m0".as_slice(), b"m1", b"m2", b"m3"] {
|
||||||
|
assert_eq!(alice.send(&to_bob, &bob, text).await, OutboxStatus::Sent);
|
||||||
|
}
|
||||||
|
let frames = wire.take(&bob.pk());
|
||||||
|
assert_eq!(frames.len(), 4);
|
||||||
|
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0");
|
||||||
|
// frames[1] is lost: nothing is delivered for it at all.
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[2]).unwrap(), b"m2");
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[3]).unwrap(), b"m3");
|
||||||
|
assert_eq!(
|
||||||
|
texts(&bob.lines(&alice)),
|
||||||
|
["m0", "m2", "m3"],
|
||||||
|
"the messages after the gap still decrypt"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The gap was held as a skipped key, not a stall: the lost frame is still
|
||||||
|
// readable inside the skip window when it finally turns up.
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[1]).unwrap(), b"m1");
|
||||||
|
assert_eq!(texts(&bob.lines(&alice)), ["m0", "m2", "m3", "m1"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_retry_that_re_sends_the_same_bytes_is_not_logged_twice() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob, wire) = two_peers(dir.path());
|
||||||
|
wire.fail_next(1);
|
||||||
|
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
|
||||||
|
|
||||||
|
// The dial fails, so the frame is persisted on the outbox row.
|
||||||
|
assert_eq!(alice.send(&to_bob, &bob, b"m0").await, OutboxStatus::Queued);
|
||||||
|
let rows = to_bob.pending(&bob.pk()).unwrap();
|
||||||
|
assert_eq!(rows.len(), 1);
|
||||||
|
assert!(
|
||||||
|
rows[0]
|
||||||
|
.payload
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|p| p.starts_with(b"rat ")),
|
||||||
|
"the row carries the encoded frame, not the body"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The worker retries: the very same bytes go out.
|
||||||
|
let fired = to_bob
|
||||||
|
.flush_friend(&bob.pk(), rows[0].next_attempt_at)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||||
|
let frames = wire.take(&bob.pk());
|
||||||
|
assert_eq!(frames.len(), 1);
|
||||||
|
|
||||||
|
assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0");
|
||||||
|
let replay = bob
|
||||||
|
.ingest(&alice, &frames[0])
|
||||||
|
.expect_err("a replay must not authenticate");
|
||||||
|
assert!(
|
||||||
|
replay.contains("already used"),
|
||||||
|
"the message key is gone, not a decryption failure: {replay}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
texts(&bob.lines(&alice)),
|
||||||
|
["m0"],
|
||||||
|
"exactly one chat line after the retry"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_conversation_continues_after_both_peers_restart() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let wire = Wire::new();
|
||||||
|
let alice_home = dir.path().join("alice");
|
||||||
|
let bob_home = dir.path().join("bob");
|
||||||
|
|
||||||
|
let alice_pk;
|
||||||
|
let bob_pk;
|
||||||
|
{
|
||||||
|
let alice = Peer::open_at(&alice_home);
|
||||||
|
let bob = Peer::open_at(&bob_home);
|
||||||
|
alice.add_friend(&bob);
|
||||||
|
bob.add_friend(&alice);
|
||||||
|
alice_pk = alice.pk();
|
||||||
|
bob_pk = bob.pk();
|
||||||
|
|
||||||
|
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
|
||||||
|
assert_eq!(
|
||||||
|
alice.send(&to_bob, &bob, b"before").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let frame = wire.take(&bob_pk).remove(0);
|
||||||
|
assert_eq!(bob.ingest(&alice, &frame).unwrap(), b"before");
|
||||||
|
|
||||||
|
let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone());
|
||||||
|
assert_eq!(
|
||||||
|
bob.send(&to_alice, &alice, b"before-reply").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let frame = wire.take(&alice_pk).remove(0);
|
||||||
|
assert_eq!(alice.ingest(&bob, &frame).unwrap(), b"before-reply");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
alice.ratchet_blob(&bob).is_some() && bob.ratchet_blob(&alice).is_some(),
|
||||||
|
"both sides persisted the session they just used"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Both processes are gone: reopen the same home directories, which is the
|
||||||
|
// only way the state can come back.
|
||||||
|
let alice = Peer::open_at(&alice_home);
|
||||||
|
let bob = Peer::open_at(&bob_home);
|
||||||
|
assert_eq!(alice.pk(), alice_pk, "identity survives the restart");
|
||||||
|
assert_eq!(bob.pk(), bob_pk);
|
||||||
|
|
||||||
|
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
|
||||||
|
assert_eq!(
|
||||||
|
alice.send(&to_bob, &bob, b"after").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let frame = wire.take(&bob_pk).remove(0);
|
||||||
|
assert_eq!(bob.ingest(&alice, &frame).unwrap(), b"after");
|
||||||
|
|
||||||
|
let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone());
|
||||||
|
assert_eq!(
|
||||||
|
bob.send(&to_alice, &alice, b"after-reply").await,
|
||||||
|
OutboxStatus::Sent
|
||||||
|
);
|
||||||
|
let frame = wire.take(&alice_pk).remove(0);
|
||||||
|
assert_eq!(alice.ingest(&bob, &frame).unwrap(), b"after-reply");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
bob.lines(&alice),
|
||||||
|
vec![
|
||||||
|
chat("in", "before"),
|
||||||
|
chat("out", "before-reply"),
|
||||||
|
chat("in", "after"),
|
||||||
|
chat("out", "after-reply")
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
alice.lines(&bob),
|
||||||
|
vec![
|
||||||
|
chat("out", "before"),
|
||||||
|
chat("in", "before-reply"),
|
||||||
|
chat("out", "after"),
|
||||||
|
chat("in", "after-reply")
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
281
tests/ratchet_wire.rs
Normal file
281
tests/ratchet_wire.rs
Normal file
|
|
@ -0,0 +1,281 @@
|
||||||
|
//! Chat travels as a `rat ` frame end to end: exactly one frame per send,
|
||||||
|
//! byte-identical retries, and a decrypt that appends the plaintext once.
|
||||||
|
//!
|
||||||
|
//! All offline. The peers are two stores holding each other's friend row, the
|
||||||
|
//! transport is a fake `Deliverer`, and `onionwire::node::{encode_chat_frame,
|
||||||
|
//! ingest_chat_frame}` are the same functions `Node::send` / `handle_incoming`
|
||||||
|
//! call, so this exercises the shipped wire path without Tor.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use onionwire::Store;
|
||||||
|
use onionwire::node::{encode_chat_frame, ingest_chat_frame};
|
||||||
|
use onionwire::outbox::{BoxFut, Deliverer, Outbox, OutboxStatus};
|
||||||
|
use onionwire::session::Keys;
|
||||||
|
|
||||||
|
const PASS: &str = "ratchet-wire-pass";
|
||||||
|
const ONION: &str = "peer.onion";
|
||||||
|
|
||||||
|
/// Records every payload it is handed — including the ones it rejects — so a
|
||||||
|
/// retry can be compared byte-for-byte with the attempt before it. Fails the
|
||||||
|
/// first `fail_times` dials.
|
||||||
|
struct Recorder {
|
||||||
|
fail_times: AtomicUsize,
|
||||||
|
sent: Mutex<Vec<Vec<u8>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Recorder {
|
||||||
|
fn new(fail_times: usize) -> Arc<Self> {
|
||||||
|
Arc::new(Self {
|
||||||
|
fail_times: AtomicUsize::new(fail_times),
|
||||||
|
sent: Mutex::new(Vec::new()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sent(&self) -> Vec<Vec<u8>> {
|
||||||
|
self.sent.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deliverer for Recorder {
|
||||||
|
fn deliver<'a>(
|
||||||
|
&'a self,
|
||||||
|
_onion: &'a str,
|
||||||
|
_pinned_id: &'a [u8],
|
||||||
|
_prekey: &'a [u8],
|
||||||
|
payload: &'a [u8],
|
||||||
|
) -> BoxFut<'a, Result<(), String>> {
|
||||||
|
self.sent.lock().unwrap().push(payload.to_vec());
|
||||||
|
if self.fail_times.load(Ordering::SeqCst) > 0 {
|
||||||
|
self.fail_times.fetch_sub(1, Ordering::SeqCst);
|
||||||
|
return Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) });
|
||||||
|
}
|
||||||
|
Box::pin(async { Ok(()) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One node's local state: an encrypted store plus its identity/prekey keypair.
|
||||||
|
struct Peer {
|
||||||
|
store: Arc<Mutex<Store>>,
|
||||||
|
keys: Keys,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Peer {
|
||||||
|
fn new(dir: &Path) -> Self {
|
||||||
|
let store = Store::open_at_with_passphrase(dir, PASS).expect("open store");
|
||||||
|
Self {
|
||||||
|
store: Arc::new(Mutex::new(store)),
|
||||||
|
keys: Keys::generate(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pk(&self) -> Vec<u8> {
|
||||||
|
self.keys.identity_pk.to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The friend row this peer would have after scanning the other's invite.
|
||||||
|
fn add_friend(&self, other: &Peer) {
|
||||||
|
let s = self.store.lock().unwrap();
|
||||||
|
s.upsert_friend(&other.pk(), ONION, None).unwrap();
|
||||||
|
s.set_friend_prekey(&other.pk(), &other.keys.prekey_pk)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode(&self, to: &Peer, text: &[u8]) -> Vec<u8> {
|
||||||
|
let s = self.store.lock().unwrap();
|
||||||
|
encode_chat_frame(&s, &self.keys, &to.pk(), text).expect("encode chat frame")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ingest(&self, from: &Peer, frame: &[u8]) -> Result<Vec<u8>, String> {
|
||||||
|
let s = self.store.lock().unwrap();
|
||||||
|
ingest_chat_frame(&s, &self.keys, &from.pk(), frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Chat lines with one peer: `(dir, plaintext)`, in row order.
|
||||||
|
fn lines(&self, other: &Peer) -> Vec<(String, String)> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.list_messages(&other.pk())
|
||||||
|
.unwrap()
|
||||||
|
.into_iter()
|
||||||
|
.map(|m| {
|
||||||
|
(
|
||||||
|
m.dir,
|
||||||
|
String::from_utf8(m.plaintext).expect("utf8 chat line"),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_ratchet_row(&self, other: &Peer) -> bool {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.load_ratchet(&other.pk())
|
||||||
|
.unwrap()
|
||||||
|
.is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Alice and Bob with mutual friend rows.
|
||||||
|
fn two_peers(dir: &Path) -> (Peer, Peer) {
|
||||||
|
let alice = Peer::new(&dir.join("alice"));
|
||||||
|
let bob = Peer::new(&dir.join("bob"));
|
||||||
|
alice.add_friend(&bob);
|
||||||
|
bob.add_friend(&alice);
|
||||||
|
(alice, bob)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn send_encodes_one_frame_and_a_retry_resends_the_same_bytes() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob) = two_peers(dir.path());
|
||||||
|
|
||||||
|
let frame = alice.encode(&bob, b"hello bob");
|
||||||
|
assert!(
|
||||||
|
frame.starts_with(b"rat "),
|
||||||
|
"chat must go out as a ratchet frame"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!frame.windows(9).any(|w| w == b"hello bob"),
|
||||||
|
"the plaintext must not appear in the frame"
|
||||||
|
);
|
||||||
|
|
||||||
|
// First dial fails, so the send queues; the worker then delivers.
|
||||||
|
let recorder = Recorder::new(1);
|
||||||
|
let ob = Outbox::new(Arc::clone(&alice.store), recorder.clone());
|
||||||
|
let status = ob
|
||||||
|
.send_payload(&bob.pk(), b"hello bob", &frame)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(status, OutboxStatus::Queued);
|
||||||
|
|
||||||
|
let rows = ob.pending(&bob.pk()).unwrap();
|
||||||
|
assert_eq!(rows.len(), 1, "one outbox row");
|
||||||
|
assert_eq!(
|
||||||
|
rows[0].payload.as_deref(),
|
||||||
|
Some(frame.as_slice()),
|
||||||
|
"the row carries the frame, not the plaintext"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
rows[0].body, b"hello bob",
|
||||||
|
"local history keeps the plaintext"
|
||||||
|
);
|
||||||
|
|
||||||
|
let fired = ob
|
||||||
|
.flush_friend(&bob.pk(), rows[0].next_attempt_at)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||||
|
|
||||||
|
let sent = recorder.sent();
|
||||||
|
assert_eq!(sent.len(), 2, "one immediate attempt plus one retry");
|
||||||
|
assert_eq!(
|
||||||
|
sent[0], sent[1],
|
||||||
|
"a retry re-sends the identical frame bytes"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
sent[1], frame,
|
||||||
|
"and those bytes are the frame that was encoded"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The receiver logs the plaintext exactly once, from that one frame.
|
||||||
|
assert_eq!(bob.ingest(&alice, &frame).unwrap(), b"hello bob");
|
||||||
|
assert_eq!(bob.lines(&alice), vec![("in".into(), "hello bob".into())]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn out_of_order_frames_both_land_in_arrival_order() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob) = two_peers(dir.path());
|
||||||
|
|
||||||
|
let first = alice.encode(&bob, b"first");
|
||||||
|
let second = alice.encode(&bob, b"second");
|
||||||
|
|
||||||
|
// Delivered the wrong way round: the ratchet must hold a skipped key.
|
||||||
|
assert_eq!(bob.ingest(&alice, &second).unwrap(), b"second");
|
||||||
|
assert_eq!(bob.ingest(&alice, &first).unwrap(), b"first");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
bob.lines(&alice),
|
||||||
|
vec![
|
||||||
|
("in".into(), "second".into()),
|
||||||
|
("in".into(), "first".into())
|
||||||
|
],
|
||||||
|
"chat lines follow arrival order, each with its own plaintext"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replayed_frame_produces_no_second_chat_line() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob) = two_peers(dir.path());
|
||||||
|
|
||||||
|
let frame = alice.encode(&bob, b"only once");
|
||||||
|
assert_eq!(bob.ingest(&alice, &frame).unwrap(), b"only once");
|
||||||
|
assert!(
|
||||||
|
bob.ingest(&alice, &frame).is_err(),
|
||||||
|
"a replay must not authenticate a second time"
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(bob.lines(&alice), vec![("in".into(), "only once".into())]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn garbage_rat_frames_are_dropped_and_the_next_good_one_still_lands() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob) = two_peers(dir.path());
|
||||||
|
|
||||||
|
let good = alice.encode(&bob, b"first");
|
||||||
|
|
||||||
|
// Truncated header, and a flipped ciphertext byte: both must be dropped
|
||||||
|
// without a chat row and without panicking.
|
||||||
|
assert!(bob.ingest(&alice, b"rat \x01").is_err());
|
||||||
|
let mut tampered = good.clone();
|
||||||
|
*tampered.last_mut().unwrap() ^= 0x01;
|
||||||
|
assert!(bob.ingest(&alice, &tampered).is_err());
|
||||||
|
assert!(
|
||||||
|
bob.lines(&alice).is_empty(),
|
||||||
|
"a rejected frame is never stored, as ciphertext or plaintext"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The same state still handles the good frame, then the next one.
|
||||||
|
assert_eq!(bob.ingest(&alice, &good).unwrap(), b"first");
|
||||||
|
let next = alice.encode(&bob, b"second");
|
||||||
|
assert_eq!(bob.ingest(&alice, &next).unwrap(), b"second");
|
||||||
|
assert_eq!(
|
||||||
|
bob.lines(&alice),
|
||||||
|
vec![
|
||||||
|
("in".into(), "first".into()),
|
||||||
|
("in".into(), "second".into())
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_fresh_friend_creates_state_on_demand_in_both_directions() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (alice, bob) = two_peers(dir.path());
|
||||||
|
assert!(
|
||||||
|
!alice.has_ratchet_row(&bob) && !bob.has_ratchet_row(&alice),
|
||||||
|
"a fresh friend starts with no ratchet row"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Bob speaks first: no state existed for him to send on either.
|
||||||
|
let from_bob = bob.encode(&alice, b"hi alice");
|
||||||
|
assert_eq!(alice.ingest(&bob, &from_bob).unwrap(), b"hi alice");
|
||||||
|
assert_eq!(alice.lines(&bob), vec![("in".into(), "hi alice".into())]);
|
||||||
|
|
||||||
|
// Alice replies on the same session, and Bob reads it.
|
||||||
|
let from_alice = alice.encode(&bob, b"hi bob");
|
||||||
|
assert_eq!(bob.ingest(&alice, &from_alice).unwrap(), b"hi bob");
|
||||||
|
assert_eq!(bob.lines(&alice), vec![("in".into(), "hi bob".into())]);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
alice.has_ratchet_row(&bob) && bob.has_ratchet_row(&alice),
|
||||||
|
"both sides persisted the state they created on demand"
|
||||||
|
);
|
||||||
|
}
|
||||||
100
tests/store.rs
100
tests/store.rs
|
|
@ -440,3 +440,103 @@ fn missing_env_empty_secret_is_rejected() {
|
||||||
let err = onionwire::resolve_store_passphrase(|_| Ok(String::new())).unwrap_err();
|
let err = onionwire::resolve_store_passphrase(|_| Ok(String::new())).unwrap_err();
|
||||||
assert!(err.to_string().contains("empty"), "got {err}");
|
assert!(err.to_string().contains("empty"), "got {err}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A stand-in for `RatchetState::to_bytes()`: version byte then secrets. The
|
||||||
|
/// store must treat it as opaque, so the exact bytes are the contract.
|
||||||
|
fn ratchet_blob(tag: u8) -> Vec<u8> {
|
||||||
|
let mut blob = Vec::with_capacity(64);
|
||||||
|
blob.push(1);
|
||||||
|
blob.extend_from_slice(&[tag; 63]);
|
||||||
|
blob
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ratchet_save_load_round_trips_exact_bytes() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "ratchet-pass").expect("open");
|
||||||
|
store
|
||||||
|
.upsert_friend(&pk(1), "a.onion", None)
|
||||||
|
.expect("friend");
|
||||||
|
let blob = ratchet_blob(0x11);
|
||||||
|
store.save_ratchet(&pk(1), &blob).expect("save");
|
||||||
|
assert_eq!(
|
||||||
|
store.load_ratchet(&pk(1)).expect("load"),
|
||||||
|
Some(blob.clone())
|
||||||
|
);
|
||||||
|
drop(store);
|
||||||
|
assert!(
|
||||||
|
!store_contains(dir.path(), &blob),
|
||||||
|
"ratchet secrets must not sit in the db file in the clear"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ratchet_load_for_friend_without_a_row_is_none() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "ratchet-pass").expect("open");
|
||||||
|
store
|
||||||
|
.upsert_friend(&pk(1), "a.onion", None)
|
||||||
|
.expect("friend");
|
||||||
|
assert_eq!(store.load_ratchet(&pk(1)).expect("known friend"), None);
|
||||||
|
assert_eq!(
|
||||||
|
store.load_ratchet(&pk(2)).expect("unknown friend"),
|
||||||
|
None,
|
||||||
|
"an unknown peer is not an error, just no session"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ratchet_sessions_are_per_friend() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "ratchet-pass").expect("open");
|
||||||
|
store
|
||||||
|
.upsert_friend(&pk(1), "a.onion", None)
|
||||||
|
.expect("friend a");
|
||||||
|
store
|
||||||
|
.upsert_friend(&pk(2), "b.onion", None)
|
||||||
|
.expect("friend b");
|
||||||
|
let a = ratchet_blob(0xaa);
|
||||||
|
let b = ratchet_blob(0xbb);
|
||||||
|
store.save_ratchet(&pk(1), &a).expect("save a");
|
||||||
|
store.save_ratchet(&pk(2), &b).expect("save b");
|
||||||
|
assert_eq!(store.load_ratchet(&pk(1)).unwrap(), Some(a.clone()));
|
||||||
|
assert_eq!(store.load_ratchet(&pk(2)).unwrap(), Some(b.clone()));
|
||||||
|
|
||||||
|
store.clear_ratchet(&pk(1)).expect("clear a");
|
||||||
|
assert_eq!(store.load_ratchet(&pk(1)).unwrap(), None);
|
||||||
|
assert_eq!(store.load_ratchet(&pk(2)).unwrap(), Some(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ratchet_clear_on_missing_row_is_a_no_op() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "ratchet-pass").expect("open");
|
||||||
|
store
|
||||||
|
.upsert_friend(&pk(1), "a.onion", None)
|
||||||
|
.expect("friend");
|
||||||
|
store.clear_ratchet(&pk(1)).expect("no row to clear");
|
||||||
|
store
|
||||||
|
.clear_ratchet(&pk(9))
|
||||||
|
.expect("unknown friend is not an error");
|
||||||
|
let blob = ratchet_blob(0x22);
|
||||||
|
store.save_ratchet(&pk(1), &blob).expect("save");
|
||||||
|
store.clear_ratchet(&pk(1)).expect("clear");
|
||||||
|
assert_eq!(store.load_ratchet(&pk(1)).unwrap(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ratchet_state_survives_reopening_the_store() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let blob = ratchet_blob(0x33);
|
||||||
|
{
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "same-pass").expect("open");
|
||||||
|
store
|
||||||
|
.upsert_friend(&pk(1), "a.onion", None)
|
||||||
|
.expect("friend");
|
||||||
|
store.append_message(&pk(1), "in", b"hello").expect("msg");
|
||||||
|
store.save_ratchet(&pk(1), &blob).expect("save");
|
||||||
|
}
|
||||||
|
let store = Store::open_at_with_passphrase(dir.path(), "same-pass").expect("reopen");
|
||||||
|
assert_eq!(store.load_ratchet(&pk(1)).expect("load"), Some(blob));
|
||||||
|
assert_eq!(store.list_messages(&pk(1)).unwrap()[0].plaintext, b"hello");
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -417,6 +417,7 @@ fn pending_row(
|
||||||
friend_pk: vec![9u8; 32],
|
friend_pk: vec![9u8; 32],
|
||||||
message_id,
|
message_id,
|
||||||
body: body.as_bytes().to_vec(),
|
body: body.as_bytes().to_vec(),
|
||||||
|
payload: None,
|
||||||
attempts,
|
attempts,
|
||||||
next_attempt_at: now + next_in,
|
next_attempt_at: now + next_in,
|
||||||
created_at: now,
|
created_at: now,
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue