Compare commits

...

5 commits

Author SHA1 Message Date
8f69182cf8
fix(hub): use a transparent logo and formal address in code emails
Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
2026-10-24 22:33:51 +02:00
f43a69a26f
docs: TLS 1.3 trust model, LNEx v3 and operator guide
Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
2026-10-24 22:05:30 +02:00
0d2af0ddd6
feat(gateway): TLS 1.3 only control plane and LNEx v3 channel-bound handshake
Replace the X25519/HKDF/ChaCha20 TCP layer with rustls TLS 1.3 (ALPN
vnox-lnex/3). Auto-generate a self-signed certificate keyed by the server
identity or load an operator certificate, publish the SPKI fingerprint,
bind HELLO and AUTH signatures to the TLS exporter, reject plaintext, TLS 1.2
and LNEx v2 peers with an explicit error. BREAKING: protocol v3.

Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
2026-10-24 22:05:30 +02:00
a5b9c324f7
fix(hub): repair Cargo.lock so the hub builds with --locked
Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
2026-10-24 21:51:44 +02:00
a2b0f26645
feat(hub): let users upload their own avatar
POST/DELETE /v1/account/avatar (session, exact Origin, CSRF) and public
GET /v1/avatars/<id>. Uploads are sniffed, size and dimension limited,
fully decoded, re-encoded to a 256x256 PNG without metadata and stored in
SQLite, one per account. avatar_url in the session points to it, with the
provider avatar as fallback.

Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
2026-10-24 21:48:05 +02:00
74 changed files with 3012 additions and 965 deletions

View file

@ -5,6 +5,14 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]
### Changed (breaking): LNEx v3, TLS 1.3 on the TCP control plane
- The custom X25519 + HKDF + ChaCha20-Poly1305 layer on TCP is removed. The gateway listens with TLS 1.3 only (rustls, ALPN `vnox-lnex/3`); there is no plaintext, TLS 1.2 or LNEx v2 mode.
- Protocol version bumped `v2` to `v3`. `Hello.server_eph_pubkey` and `Auth.client_eph_pubkey` are reserved. Old clients cannot connect and old gateways are refused by new clients with an explicit error.
- Ed25519 server HELLO and client AUTH signatures now cover a TLS exporter value (channel binding) and cannot be replayed on another connection.
- Certificate: auto generated on first start in `data_dir/tls/self-signed.pem` using the server identity key (fingerprint stable, no extra secret), or `tls_cert_path` / `tls_key_path` for a CA certificate. The SPKI SHA-256 fingerprint is logged and written to `data_dir/tls/fingerprint.txt`.
- `gateway.tls_enabled = false` is now a startup error. UDP voice is unchanged.
- Design: `docs/02-protocol/tls.md`.
### Added — Phase 2 guild member list + identity export/import + channel rate limit (fourth batch)
#### Phase 2 guild member list with kick / role-assign UI (Phase E4)

169
Cargo.lock generated
View file

@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aead"
version = "0.6.1"
@ -242,12 +248,24 @@ version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.12.1"
@ -417,6 +435,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
[[package]]
name = "crc32fast"
version = "1.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-queue"
version = "0.3.14"
@ -652,6 +679,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "fiat-crypto"
version = "0.3.0"
@ -670,6 +706,17 @@ version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
[[package]]
name = "flate2"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]]
name = "flume"
version = "0.12.0"
@ -1134,6 +1181,32 @@ dependencies = [
"icu_properties",
]
[[package]]
name = "image"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"image-webp",
"moxcms",
"num-traits",
"png",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "image-webp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]]
name = "indexmap"
version = "2.14.2"
@ -1370,6 +1443,26 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "mio"
version = "1.2.4"
@ -1381,6 +1474,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "moxcms"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "multimap"
version = "0.10.1"
@ -1557,6 +1660,19 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "poly1305"
version = "0.9.1"
@ -1661,6 +1777,18 @@ dependencies = [
"prost",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quinn"
version = "0.11.12"
@ -2223,6 +2351,12 @@ dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "simd_cesu8"
version = "1.2.0"
@ -2952,7 +3086,6 @@ dependencies = [
"chacha20poly1305",
"ed25519-dalek",
"hex",
"hkdf",
"hmac",
"prost",
"prost-build",
@ -2972,7 +3105,6 @@ dependencies = [
"tracing-subscriber",
"url",
"uuid",
"x25519-dalek",
]
[[package]]
@ -2985,6 +3117,7 @@ dependencies = [
"ed25519-dalek",
"hex",
"hmac",
"image",
"lettre",
"oauth2",
"rand 0.10.3",
@ -3333,17 +3466,6 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
"curve25519-dalek",
"rand_core 0.10.1",
"zeroize",
]
[[package]]
name = "x509-parser"
version = "0.18.1"
@ -3475,8 +3597,29 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zune-core"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core",
]

View file

@ -20,12 +20,10 @@ tokio = { version = "1.54", features = ["fs", "io-util", "macros", "net", "rt-mu
serde = { version = "1", features = ["derive"] }
serde_json = "1"
ed25519-dalek = { version = "3", features = ["rand_core"] }
x25519-dalek = "3"
chacha20poly1305 = "0.11"
rand = "0.10"
uuid = { version = "1", features = ["v4"] }
hex = "0.4"
hkdf = "0.13"
sha2 = "0.11"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

View file

@ -72,7 +72,7 @@ Full architecture details: [docs/01-architecture.md](docs/01-architecture.md)
### Implemented
- **Auth:** Ed25519 challenge-response, session tokens, reconnect with backoff
- **Encryption:** ChaCha20-Poly1305 AEAD + X25519 ECDH key exchange + HKDF key derivation
- **Encryption:** TLS 1.3 (rustls) on TCP with SPKI pinning, ChaCha20-Poly1305 on UDP voice
- **Channels:** Create, delete, list; text and voice channel types
- **Text chat:** Persistent history via SQLite, reactions, replies, edit, delete, typing indicators, read receipts
- **Direct Messages:** 1:1 DMs with persistent history, unread badges, search
@ -89,7 +89,6 @@ Full architecture details: [docs/01-architecture.md](docs/01-architecture.md)
- **Keyfile export/import:** Encrypted or plain JSON keyfile with passphrase
### Planned
- TLS 1.3 on TCP (Phase 2)
- Protobuf wire format (Phase 2)
- PostgreSQL backend (Phase 2)
- Federation protocol (Phase 3)
@ -107,7 +106,7 @@ Phase 1 is implemented. Not production ready.
| Voice node | UDP relay, voice packet routing, jitter buffer |
| Desktop client | Slint UI, net layer, audio pipeline (partial) |
| LNEx protocol | Specified and implemented (JSON in Phase 1) |
| Encryption | ChaCha20-Poly1305 AEAD + X25519 ECDH — DONE |
| Encryption | TLS 1.3 (TCP) + ChaCha20-Poly1305 (UDP voice) - DONE |
| Federation | Planned (Phase 3) |
| Mobile client | Planned (Phase 3) |

View file

@ -12,6 +12,12 @@ admin_bind = "127.0.0.1:7601"
message_rate_per_sec = 5
# Burst size for the token bucket.
message_rate_burst = 10
# TLS 1.3 is always on (LNEx v3). With neither option below the gateway generates
# a self-signed certificate in <data_dir>/tls/ (key = server identity) and prints its
# SPKI SHA-256 fingerprint at startup. Clients pin it on first use.
# For a public CA certificate (for example Let's Encrypt) set both paths and restart on renewal:
# tls_cert_path = "/etc/letsencrypt/live/chat.example.org/fullchain.pem"
# tls_key_path = "/etc/letsencrypt/live/chat.example.org/privkey.pem"
[voice]
bind = "127.0.0.1:7700"

View file

@ -43,7 +43,7 @@ You run it, you own it.
**Federated** — nodes can talk to each other. Your community isn't an island (Phase 3).
**Encrypted** — all traffic is encrypted with ChaCha20-Poly1305 AEAD + X25519 ECDH key exchange. Forward secrecy by default.
**Encrypted** - the control plane runs over TLS 1.3, voice over per-route ChaCha20-Poly1305 keys. Forward secrecy by default.
**Plugin-first** — extend the platform with plugins via WebSocket RPC. Bots, moderation, automations. Sandboxed by design.

View file

@ -7,13 +7,20 @@ Last updated: 2026-10-24.
---
## Update 2026-10 (LNEx v3, TLS 1.3)
- TCP control plane is TLS 1.3 only (rustls); the custom X25519/HKDF/ChaCha20 TCP layer was removed (**breaking**, protocol `v3`). See [02-protocol/tls.md](02-protocol/tls.md).
- Self-hosted trust model: certificate pinned by SPKI SHA-256 with trust on first use in the client, changed fingerprint is blocked; public CA certificates work without a prompt.
- Ed25519 auth is bound to the TLS session (exporter), UDP voice unchanged.
## Update 2026-10 (protocol v2)
- Signed v2 handshake and protobuf payloads between client and gateway (verified by `VNOX-Client/tests/gateway_interop.rs`).
- Authenticated, encrypted UDP voice relay in voice-node.
- Voice access is revoked when a channel is deleted, a member is kicked or permissions change.
- Senders get acknowledgements for their own chat messages.
- Hub email sign-in by one-time code (HMAC-protected, rate-limited; enabled only when SMTP is configured; code-ready, not yet enabled in production). Handle/avatar selection after first sign-in is not implemented.
- Hub email sign-in by one-time code (HMAC-protected, rate-limited; enabled only when SMTP is configured; code-ready, not yet enabled in production). Handle selection after first sign-in is not implemented.
- Hub own avatar (web): upload, remove and public serving of a re-encoded 256x256 PNG; code-ready, not deployed. Backup rotation to 30 days for deleted data is decided but not implemented.
- Channel webhooks, GitHub sign-in, hub service, screen sharing and media broadcast.
- `cargo audit`: no known vulnerabilities in both workspaces (2026-10-24).
@ -73,7 +80,6 @@ Last updated: 2026-10-24.
| Feature | Target phase |
|---------|--------------|
| TLS 1.3 on TCP | Phase 2 |
| Seed phrase / encrypted keyfile export UI | Phase 2 |
| Gateway to voice-node membership signaling | Phase 2 |
| Protobuf payloads (replacing JSON) | Phase 2 |
@ -89,11 +95,11 @@ Last updated: 2026-10-24.
## Security notes
- **TCP control plane:** Encrypted with ChaCha20-Poly1305 (✅ Phase 1.1)
- **TCP control plane:** TLS 1.3 only, channel-bound Ed25519 auth (LNEx v3)
- **UDP voice data:** Encrypted with ChaCha20-Poly1305 (✅ Phase 1.1)
- **Client auth:** Ed25519 challenge-response; identity proven, transport encrypted.
- **Server pubkey:** Real (Ed25519), verified during handshake.
- **Ephemeral keys:** X25519 ECDH with HKDF-SHA256 key derivation for forward secrecy.
- **Forward secrecy on TCP:** provided by TLS 1.3. UDP voice keys are random per route and delivered over TLS.
- **Voice node:** Transparent relay (does not decrypt voice — encrypted end-to-end between clients).
- **Identity at rest:** Optional Argon2id passphrase + ChaCha20-Poly1305 AEAD vault (✅ Phase 2).
- **Rate limiting:** Per-session token bucket on chat + DM (✅ Phase 2).

View file

@ -29,7 +29,7 @@ encryption, routing, identity, and federation.
## Version
Current version: `LNEx v1`
Current version: `LNEx v3` (TCP runs inside TLS 1.3, see [tls.md](tls.md)). There is no negotiation with older versions.
Version is negotiated during handshake. Clients and servers advertise
their supported versions. If no common version exists, the connection
@ -83,3 +83,4 @@ Full state machine: see individual spec files.
- [federation/README.md](federation/README.md) — node discovery, cross-node routing
- [identity.md](identity.md) — keypair model, auth flow, permissions
- [security.md](security.md) — encryption, threat model
- [tls.md](tls.md) — TLS 1.3 control plane, trust model, LNEx v3 handshake

View file

@ -22,7 +22,7 @@ All LNEx packets share a common header, regardless of transport.
```
bit 0 — COMPRESSED payload is zstd compressed
bit 1 — ENCRYPTED payload is encrypted (ChaCha20-Poly1305)
bit 1 — ENCRYPTED reserved; must be 0 on TCP since LNEx v3 (TLS protects the stream)
bit 2 — FRAGMENTED this is a fragment of a larger payload
bit 3 — LAST_FRAG this is the last fragment
bit 4 — ACK_REQ sender requests acknowledgement (TCP path only)

View file

@ -1,6 +1,6 @@
# Security
> **Phase 1.1 status.** TCP traffic is encrypted with ChaCha20-Poly1305 AEAD.
> **LNEx v3 status.** TCP traffic runs over TLS 1.3.
> UDP voice path is still plaintext (Phase 2). See
> [features/encryption.md](../05-features/encryption.md) for details.
@ -11,7 +11,7 @@ The threat model covers:
| Threat | Mitigated by |
|--------|--------------|
| MITM on client-server connection | LNEx packet encryption (ChaCha20-Poly1305) active on TCP |
| MITM on client-server connection | TLS 1.3 with SPKI pinning / public CA, channel-bound Ed25519 auth |
| MITM on UDP voice path | LNEx packet encryption (Phase 2; not active in v0.1.x) |
| Rogue node in federation | Mutual keypair authentication on federation handshake (Phase 3) |
| Identity spoofing | Ed25519 signature on every auth (challenge-response) |
@ -31,47 +31,15 @@ The threat model covers:
## Encryption
> **Phase 1.1 target.** See [features/encryption.md](../05-features/encryption.md) for the implementation plan.
> Phase 1 uses JSON over plain TCP and raw Opus over UDP.
TCP control traffic is protected by **TLS 1.3** (rustls, ALPN `vnox-lnex/3`). The earlier
LNEx v2 per-frame ChaCha20-Poly1305 layer is removed. Trust model, certificate handling,
channel binding and version bump: see [tls.md](tls.md).
### LNEx packet encryption
All LNEx packets (both TCP and UDP paths) are encrypted at the LNEx layer.
Algorithm: **ChaCha20-Poly1305** (AEAD)
- ChaCha20 for stream cipher
- Poly1305 for authentication tag (16 bytes)
- 96-bit nonce, derived from: `session_id || sequence`
- Key derived from ECDH exchange during handshake (X25519)
ChaCha20-Poly1305 is chosen over AES-GCM because:
- constant-time on all platforms (no hardware AES requirement)
- faster in software on hardware without AES-NI (common on ARM)
- simpler nonce management
### Key exchange
During the LNEx handshake:
1. Server sends its ephemeral X25519 public key in HELLO
2. Client generates its own ephemeral X25519 keypair
3. Both compute the shared secret via X25519 ECDH
4. Shared secret is passed through HKDF-SHA256 to derive:
- client → server encryption key
- server → client encryption key
Ephemeral keys are discarded after the session. This provides
**forward secrecy** — compromising the long-term identity keypair
does not expose past sessions.
### TCP transport
TCP connections additionally use TLS 1.3.
LNEx packet encryption runs inside TLS — defense in depth.
TLS certificate: self-signed by default, pinned on first connect (TOFU).
Node operators may configure a proper CA-signed certificate.
- Self-hosted servers: self-signed certificate (key = server identity), client pins the SPKI
SHA-256 fingerprint on first use and blocks any change.
- Public CA certificates are accepted without a prompt.
- Ed25519 client authentication is signed over a TLS exporter value so it cannot be relayed.
- A TLS-terminating reverse proxy is not supported (it breaks the channel binding); use TCP passthrough.
### UDP transport
@ -141,7 +109,7 @@ temporary ban depending on node configuration.
### Recommended hardening
- run gateway behind a reverse proxy (nginx / caddy) for TLS termination
- if a proxy is used, pass TCP through (no TLS termination)
- restrict UDP port to known IP ranges if possible
- enable fail2ban or equivalent on auth failure logs
- back up the node keypair (used for federation identity)

275
docs/02-protocol/tls.md Normal file
View file

@ -0,0 +1,275 @@
# TLS 1.3 for the TCP control plane (LNEx v3)
> Status: design accepted and implemented together with this document.
> This is a **breaking change**: LNEx v2 (custom X25519 + HKDF + ChaCha20-Poly1305
> layer on TCP) is removed. The protocol version is bumped to `v3`.
> UDP voice is **not** affected (see [Voice](#voice-udp-is-unchanged)).
## Goals
1. Replace the home-grown encrypted framing on the TCP control plane with standard
TLS 1.3 ([RFC 8446](https://www.rfc-editor.org/rfc/rfc8446)) implemented by `rustls`
(no OpenSSL).
2. Work for self-hosted servers that have no public CA certificate, without asking
users to click through "accept anything" warnings.
3. Keep the existing Ed25519 identity model: the server identity (`server_identity.json`)
and the client identity keep their meaning.
4. No silent fallback: no plaintext mode, no TLS 1.2, no LNEx v2 handshake.
## Non-goals
- Changing the UDP voice relay or its keys.
- Federation (node to node) TLS. This document covers client to gateway only.
- Mutual TLS with client certificates. The client is authenticated at the LNEx layer
with its Ed25519 key (see [Client authentication](#client-authentication-over-tls)).
## Summary of decisions
| # | Decision |
|---|----------|
| D1 | `rustls` 0.23 with the `aws_lc_rs` provider, **TLS 1.3 only** on both sides. ALPN `vnox-lnex/3` is required. |
| D2 | The server certificate is either user supplied (`tls_cert_path` / `tls_key_path`, for example Let's Encrypt) or **auto generated** on first start and stored in `data_dir/tls/self-signed.pem`. |
| D3 | The auto generated certificate uses the **server identity Ed25519 key as its TLS key**. Therefore the certificate fingerprint is a pure function of the identity key, survives certificate regeneration, and no second private key is stored. |
| D4 | The **pin** is `SHA-256(SubjectPublicKeyInfo DER)` of the leaf certificate (the "SPKI fingerprint"). It is the trust anchor for self-signed servers. |
| D5 | Client trust is **pin first**: stored pin wins over everything. No pin: try normal WebPKI validation (bundled Mozilla roots, hostname must match). If that fails, **TOFU**: the user sees the fingerprint and must confirm before anything is sent. |
| D6 | A changed fingerprint is a **hard block** with a warning. There is no "connect anyway". The only way forward is an explicit "forget this server" followed by a new trust decision. |
| D7 | The Ed25519 client authentication stays, but its signature covers a **TLS exporter value (channel binding)**, so it cannot be relayed over another TLS connection. The server HELLO is signed with its identity key over the same binding. |
| D8 | The X25519 + HKDF + ChaCha20-Poly1305 layer on TCP, the `ENCRYPTED` packet flag on TCP and the ephemeral key fields in `Hello` and `Auth` are removed. |
| D9 | LNEx version is bumped from `v2` to `v3`. Old clients and old servers fail with an explicit error. Downgrade is impossible by construction. |
## Threat model
| Threat | Mitigation |
|--------|-----------|
| Passive network observer | TLS 1.3 (AEAD, forward secrecy). |
| Active MITM terminating TLS with its own certificate | Pin mismatch (known server) or TOFU prompt showing a different fingerprint (new server). Even if the user accepted a wrong fingerprint, the MITM cannot produce the server's Ed25519 signature over this connection's exporter, and the client rejects a server identity that differs from the stored one. |
| MITM relaying the server's HELLO to the client | HELLO signature covers the exporter of the TLS session between the client and the relay, which differs from the relay to server session. Verification fails. |
| Malicious server relaying a client's AUTH to another server | AUTH signature covers the exporter of the connection to the malicious server. Another server computes a different value and rejects it. |
| Downgrade to plaintext, TLS 1.2 or LNEx v2 | The client never opens a plaintext socket, the rustls configs list only TLS 1.3, the server requires ALPN `vnox-lnex/3`, and the version string `v3` is inside the signed transcripts. |
| First connection MITM (TOFU weakness) | Unavoidable without a CA or out of band data. Mitigation: the server prints its fingerprint at startup and writes it to `data_dir/tls/fingerprint.txt`; owners should publish it with the invitation, users compare before confirming. Public CA certificates skip TOFU. |
| Compromised or replaced server key | Fingerprint changes, clients block (D6). |
Out of scope: a compromised server host, a user who ignores a fingerprint mismatch and
explicitly forgets the server.
## Server
### Certificate sources
```toml
[gateway]
bind = "0.0.0.0:7600"
# Optional. Both or none. PEM certificate chain (leaf first) and PKCS#8/SEC1/PKCS#1 key.
# tls_cert_path = "/etc/letsencrypt/live/chat.example.org/fullchain.pem"
# tls_key_path = "/etc/letsencrypt/live/chat.example.org/privkey.pem"
```
- Neither set: the gateway loads `data_dir/tls/self-signed.pem`. If the file is missing,
unreadable or its public key does not match the server identity, it is regenerated
(it contains no secret, the key is the identity key). SAN entries: `node.address`,
`localhost`, `127.0.0.1`, `::1`. Validity is long (the client does not use expiry for
pinned servers).
- Both set: the chain and key are loaded at start, validated to match, and used as is.
Renewal requires a gateway restart (hot reload is a possible follow-up).
- Only one set: startup error.
- `tls_enabled` is deprecated. `true` is accepted with a warning, `false` is a startup
error: **plaintext is no longer supported**.
At startup the gateway logs `TLS SPKI SHA-256 fingerprint: <hex>` and writes it to
`data_dir/tls/fingerprint.txt` (public information).
### TLS parameters
- Protocol versions: TLS 1.3 only (`rustls::version::TLS13`).
- Cipher suites: the rustls defaults for TLS 1.3 (AES-GCM, ChaCha20-Poly1305).
- ALPN: `vnox-lnex/3`. A connection without the negotiated ALPN is dropped before any
LNEx byte is read.
- No client certificates.
- Handshake timeouts: 15 seconds for the TLS handshake and 15 seconds for the LNEx HELLO/AUTH/SESSION exchange.
### Reverse proxies
The exporter binding (below) is computed per TLS session. A proxy that **terminates**
TLS breaks authentication by design. If a proxy is used it must forward the TCP stream
(`stream`/SNI passthrough, HAProxy `mode tcp`) and must not terminate TLS.
### Legacy and plaintext clients
The server peeks at the first byte of a new connection (up to 2 seconds).
A TLS client sends a handshake record (`0x16`) immediately. Anything else (a v2 client
waits for the server HELLO and sends nothing, a plaintext client sends LNEx bytes)
receives one plaintext LNEx `Error` frame, `ErrorCode::VersionMismatch`, with the message
`TLS 1.3 required (LNEx v3): update your client`, and the connection is closed. This
frame is the only plaintext the gateway ever writes and it contains no secrets.
## Client
### Trust store
File: `<config dir>/vnox/known_servers.json` (Linux: `~/.config/vnox/`), written atomically
with mode `0600` on Unix.
```json
{
"version": 1,
"servers": {
"chat.example.org:7600": {
"trust": "pin",
"spki_sha256": "9f...64 hex chars...",
"identity": "ab...64 hex chars (Ed25519 server key)...",
"first_seen": 1790000000
}
}
}
```
The key is the lower-cased `host:port` (default port 7600). `trust` is `pin` or `ca`.
`spki_sha256` exists only for `pin`. `identity` is stored after the first successful
authenticated handshake.
Bookmarks (the "saved servers" list) are only address labels; trust decisions are
independent of them and keyed by `host:port`, so removing a bookmark does not revoke trust.
### Connection algorithm
```
parse address (scheme lnexs:// or lnex:// is cosmetic, both mean TLS 1.3)
rec = trust_store[host:port]
TLS 1.3 handshake with a custom ServerCertVerifier:
rec.trust == pin : cert SPKI sha256 must equal rec.spki_sha256
else ERROR FingerprintChanged (hard block, D6)
rec.trust == ca : WebPKI chain + hostname validation must succeed
else ERROR CertificateInvalid (hard block, no TOFU downgrade)
no record : WebPKI validation succeeds -> trust = ca
otherwise -> probe: finish the TLS
handshake, send NOTHING, close, and report
UntrustedServer { fingerprint } to the UI
(in every case the TLS 1.3 CertificateVerify signature is verified by rustls)
UI on UntrustedServer: show host, fingerprint (grouped hex), "Trust" / "Cancel".
Trust -> trust_store[host:port] = { pin, fingerprint }, reconnect.
LNEx v3 handshake inside the tunnel (see below)
after a valid server HELLO:
rec.identity set and != server_pubkey -> ERROR IdentityChanged (hard block)
otherwise store identity (TOFU of the identity inside an already trusted channel)
```
Because the probe finishes the TLS handshake without sending application data, the
client's Ed25519 signature and nickname are never sent to an unverified endpoint.
The client uses the bundled Mozilla root set (`webpki-roots`), not the operating system
store, so behaviour is identical on all platforms. Servers with a private CA use the
pin path.
### Fingerprint changes
When a pinned server presents another SPKI the client:
1. aborts the connection before sending any LNEx data,
2. does **not** retry automatically (auto reconnect is suspended for this error),
3. shows a warning with the expected and the received fingerprint,
4. offers "Forget this server". After forgetting, the next connect starts a fresh
TOFU decision. This is deliberate friction: it is the only path for a legitimate
server migration (for example moving from a self-signed certificate to Let's Encrypt
or restoring a server without its `server_identity.json`).
## LNEx v3 handshake inside TLS
The 12 byte packet header and protobuf payloads are unchanged. Frames are written
directly into the TLS stream. The `flags` field must be `0` on the TCP control plane
(the `ENCRYPTED` flag is rejected).
```
Client Gateway
| -- TCP + TLS 1.3 handshake (ALPN) ---> |
| both sides: binding = Export("EXPORTER-VNOX-LNEx-v3-channel-binding", no context, 32)
| <------ HELLO (seq 0) ---------------- | lnex_version="v3", server_pubkey, challenge_nonce,
| | node_name, private_mode, server_signature
| ------- AUTH (seq 0) ----------------> | client_pubkey, nickname, lnex_version="v3", signature
| <------ SESSION (seq 1) -------------- | session_id, token, expires_at
```
Signatures (Ed25519, strict verification):
```
server_signature = Sign(server_key,
"VNOX-LNEx-v3-server-hello\0" || binding || protobuf(Hello with server_signature empty))
client signature = Sign(client_key,
"VNOX-LNEx-v3-client-auth\0" || binding
|| u32be(len(signed_hello)) || signed_hello
|| protobuf(Auth with signature empty))
```
`binding` is unique per TLS session (RFC 8446 section 7.5, RFC 5705), so a signature made on
one connection fails on every other connection. The client signature also covers the
signed HELLO, which carries the server challenge and server key, so the client proves
"I am talking to this server key on this channel".
### What stays from v2
- Ed25519 client identity and challenge-response authentication (now channel bound).
- Server Ed25519 identity and signed HELLO (now channel bound, identity is the stable
anchor that survives certificate changes).
- `Session` packet with `session_id` and `token`.
- Ban check, rate limiting, protobuf payloads, packet ids, packet header, sequence
numbers (kept as a cheap ordering sanity check, no longer part of a nonce).
### What is removed
- `Hello.server_eph_pubkey` (field 5) and `Auth.client_eph_pubkey` (field 5) are reserved
in `lnex.proto`.
- `SessionCrypto` (X25519 ECDH, HKDF-SHA256, ChaCha20-Poly1305 per frame) on the gateway and
the client, and the `ENCRYPTED` flag on TCP frames.
- The optional, off by default `tls_enabled` listener that wrapped the old protocol.
- The client's plaintext loopback shortcut and the `lnex://` plaintext scheme.
### Voice (UDP) is unchanged
Voice keys are not derived from the TCP handshake. The gateway creates per route random
`c2s_key` and `s2c_key` and delivers them in the `VoiceSession` packet over the control
connection. Previously they were protected by the LNEx layer, now by TLS 1.3. The UDP
format, nonces and the voice node are untouched. `vnox-e2e-voice` keeps working and only
needs the client to trust the gateway certificate (`--trust-first-use` or `--fingerprint`).
## Version bump and incompatibility behaviour
| Client | Server | Result |
|--------|--------|--------|
| v3 | v3 | works |
| v2 (old) | v3 | server sends a plaintext `Error(VersionMismatch)` "TLS 1.3 required (LNEx v3): update your client"; an old client shows a handshake error or times out. Nothing is negotiated. |
| v3 | v2 (old) | the server answers the TLS ClientHello with LNEx bytes. The client maps the rustls decode failure to "The server does not speak TLS 1.3 (LNEx v3). It is probably an outdated server, ask the owner to update." No retry in plaintext. |
| v3, TLS 1.2 only peer | v3 | handshake failure, protocol version alert, same explicit message. |
| v3 | v3 with `lnex_version` other than `v3` in HELLO/AUTH | `VersionMismatch`, connection closed. |
There is no version negotiation and no compatibility window: the old handshake is not
implemented in the new binaries.
## Operations: enabling it on a server
1. Update the gateway (and `serverd`) to the LNEx v3 build. Remove `tls_enabled = false`
if present.
2. Self-signed: nothing to configure. Start the gateway, read the fingerprint from the
log or `data_dir/tls/fingerprint.txt`, publish it to your users.
CA certificate: set `tls_cert_path` and `tls_key_path`, restart after renewals.
3. Make sure the firewall allows TCP 7600 as before and that no TLS terminating proxy is
in front of it.
4. Update all clients. Old clients cannot connect.
5. Users: on the first connection compare the shown fingerprint with the published one
and press "Trust".
## Test plan
- Fingerprint extraction from a certificate (DER SPKI) and formatting.
- Pin accepted, changed pin rejected, unknown server reported with its fingerprint,
CA-mode failure not downgraded to TOFU.
- A TLS 1.2 only client is rejected by the gateway listener.
- A client without ALPN is rejected.
- A plaintext or v2 client receives the explicit version error.
- A client signature made for connection A is rejected on connection B.
- A server HELLO signature made for connection A is rejected by a client on connection B.
- Full interoperability test `tests/gateway_interop.rs` against the real gateway binary,
including the TOFU prompt flow.
- `vnox-e2e-voice` against `vnox-serverd` still relays voice.

View file

@ -76,10 +76,11 @@ max_pps_per_user = 60
# Generated automatically on first start if not present.
keypair_path = "/var/lib/vnox/node.key"
# TLS certificate for the TCP gateway.
# If not set, a self-signed certificate is generated.
# tls_cert = "/etc/vnox/tls/cert.pem"
# tls_key = "/etc/vnox/tls/key.pem"
# TLS 1.3 is always on (LNEx v3). TLS keys live in the [gateway] section:
# tls_cert_path = "/etc/letsencrypt/live/chat.example.org/fullchain.pem"
# tls_key_path = "/etc/letsencrypt/live/chat.example.org/privkey.pem"
# Both unset: a self-signed certificate is generated in <data_dir>/tls/ and its
# fingerprint is logged. See docs/02-protocol/tls.md.
# ─── CHANNELS ──────────────────────────────────────────────────────────────

View file

@ -214,5 +214,5 @@ with a migration guide.
- [ ] `node.key` backup exists and is stored securely
- [ ] `VNOX_LOGGING_LEVEL` is `info` or `warn` in production (not `trace`)
- [ ] `[gateway.rate_limits]` are configured appropriately for your user base
- [ ] TLS certificate is valid (or TOFU is acceptable for your use case)
- [ ] TLS: either a CA certificate (`tls_cert_path`/`tls_key_path`) or the self-signed fingerprint (`data_dir/tls/fingerprint.txt`) is published to users; no TLS-terminating proxy in front of TCP 7600
- [ ] Federation disabled if not needed (`[federation] enabled = false`)

View file

@ -1,78 +1,44 @@
# Encryption — Phase 1.1
# Encryption
> **Phase 1.1 status:** Fully implemented. ChaCha20-Poly1305 AEAD with X25519 ECDH + HKDF-SHA256 key exchange. Both TCP (control) and UDP (voice) paths are now encrypted. Forward secrecy via ephemeral session keys.
> **Status (LNEx v3):** the TCP control plane is protected by **TLS 1.3** (rustls).
> The UDP voice path is protected by per route ChaCha20-Poly1305 keys delivered over the
> TLS control connection. The earlier custom X25519 + HKDF + ChaCha20-Poly1305 layer on
> TCP (LNEx v2) was removed. Design and trust model: [02-protocol/tls.md](../02-protocol/tls.md).
## Goal
## Layers
Replace all plaintext traffic (TCP + UDP) with ChaCha20-Poly1305 AEAD encryption.
X25519 ECDH ephemeral key exchange during handshake for forward secrecy.
| Path | Protection | Keys |
|------|------------|------|
| TCP control (chat, channels, auth) | TLS 1.3, ALPN `vnox-lnex/3`, no fallback | TLS handshake, server cert pinned by SPKI SHA-256 (TOFU) or a public CA |
| Server authenticity | Ed25519 server identity signs HELLO over the TLS exporter (channel binding) | `server_identity.json` |
| Client authenticity | Ed25519 client key signs AUTH over the same exporter | client identity |
| UDP voice | ChaCha20-Poly1305 AEAD per route | random `c2s_key` / `s2c_key` sent in `VoiceSession` over TLS |
| Direct messages E2EE (optional) | X25519 + HKDF + ChaCha20-Poly1305 between clients | per conversation keys, unchanged |
✅ **COMPLETED in Phase 1.1**
## What changed from v2
## Key exchange (during HELLO handshake)
- Removed: ephemeral X25519 exchange in HELLO/AUTH, HKDF session key derivation for TCP,
per frame ChaCha20-Poly1305 with the `ENCRYPTED` flag, `SessionCrypto` in gateway and client.
- Added: mandatory TLS 1.3 listener and connector, certificate management, client trust store,
channel bound Ed25519 signatures.
- Unchanged: UDP voice packet format, voice node, E2EE for direct messages, Ed25519 identities.
1. Server generates ephemeral X25519 keypair per session
2. Server sends public key in `HELLO` packet
3. Client generates own ephemeral X25519 keypair
4. Both compute shared secret via X25519 ECDH
5. Shared secret → HKDF-SHA256 → two keys:
- `client→server` encryption key
- `server→client` encryption key
6. Ephemeral keys discarded after session (forward secrecy)
## Why TLS instead of a custom layer
## Packet encryption
- Reviewed, widely deployed handshake and record layer instead of a protocol we maintain.
- Standard tooling and key lifecycle (Let's Encrypt works out of the box).
- Forward secrecy, key updates and replay protection are provided by TLS 1.3.
- Algorithm: **ChaCha20-Poly1305** (AEAD)
- 96-bit nonce: `session_id || packet_sequence`
- 16-byte Poly1305 authentication tag per packet
- Applied to ALL packets on both TCP and UDP
## Voice keys
## Why ChaCha20-Poly1305 over AES-GCM
- Constant-time on all platforms (no hardware AES requirement)
- Faster in software on ARM (common for mobile — Phase 3)
- Simpler nonce management (no IV collision risk)
## Implementation plan
### ✅ Client (DONE)
- `client/src/net/crypto.rs` — SessionCrypto with ChaCha20-Poly1305
- `client/src/net/voice.rs` — `build_packet()` encrypts voice payloads with c2s_key
- `client/src/net/voice.rs` — `spawn_recv()` decrypts incoming voice with s2c_key
- `client/src/net/session/session_loop.rs` — voice_seq counter for encryption nonces
### ✅ Gateway (DONE)
- `gateway/src/proto/crypto.rs` — X25519 ECDH, HKDF-SHA256, ChaCha20-Poly1305
- `gateway/src/net/handshake.rs` — ephemeral key exchange in HELLO/AUTH
- `gateway/src/net/io.rs` — TCP framing with encryption
### ✅ Voice
- `client/src/net/voice.rs` — encrypted voice packets on UDP (plaintext at rest in voice-node, encrypted on wire)
- Voice-node treats packets as opaque bytes (transparent relay)
- End-to-end encryption: client A → encrypted → voice-node → encrypted → client B
## Nonce management
Each session has a monotonic sequence counter:
- Start at 0 on session establishment
- Increment per packet (both directions independently)
- Nonce = `session_id (8 bytes) || sequence (4 bytes)`
- 12-byte nonce fits ChaCha20-Poly1305 standard
## Key dependencies
Already in `Cargo.toml` (workspace):
- `chacha20poly1305 = "0.10"`
- `x25519-dalek = { version = "2", features = ["static_secrets"] }`
Need to add:
- `hkdf = "0.12"` for key derivation
- `sha2 = "0.10"` (HKDF dependency, likely already transitive)
`VoiceSession` is delivered after the channel authorization check. Keys are random per
route and never derived from the TCP session, so the UDP implementation did not need to
change when the TCP layer was replaced.
## Testing
- ✅ Unit test: encrypt → decrypt round-trip with known keys (`client/src/net/crypto.rs`)
- ✅ Unit test: tampered ciphertext fails authentication
- ✅ Unit test: build_packet creates valid encrypted packets
- Manual test: Run client + gateway + voice-node, join voice channel, verify packets encrypted
- Wireshark: Capture UDP traffic, confirm it's not readable plaintext
- Unit: SPKI fingerprint extraction, pin match and mismatch, unknown server, TLS 1.2 client
rejected, plaintext/v2 client gets an explicit error, channel binding signature replay rejected.
- Integration: `VNOX_GATEWAY_BIN=... cargo test --test gateway_interop -- --ignored`
in `VNOX-Client`, including the first trust flow.
- Voice: `cargo run --bin vnox-e2e-voice -- 127.0.0.1:7600 --trust-first-use` against `vnox-serverd`.

View file

@ -36,7 +36,7 @@ Goal: production-safe for small private communities.
### Encryption (Priority 1) ✅ DONE
- [x] Replace plaintext with ChaCha20-Poly1305 on all packets
- [x] X25519 ECDH key exchange during HELLO handshake
- [x] X25519 ECDH key exchange during HELLO handshake (UDP/E2EE only; TCP moved to TLS 1.3 in LNEx v3)
- [x] HKDF-SHA256 key derivation (client→server / server→client keys)
- [x] Encrypted TCP (control) + UDP (voice) paths
- [x] Forward secrecy via ephemeral session keys
@ -152,7 +152,7 @@ Goal: typing indicators, read receipts, typing states.
Goal: scalability, federation preparation, advanced security.
### Server
- [ ] TLS 1.3 on TCP control plane
- [x] TLS 1.3 on TCP control plane (LNEx v3, see 02-protocol/tls.md)
- [ ] Permission system enforcement in gateway
- [ ] Rate limiting refinement
- [ ] PostgreSQL backend (sqlx support ready, config not exposed yet)

View file

@ -10,7 +10,7 @@
Связать второй способ входа можно из аутентифицированного аккаунта после повторного подтверждения; требуется доказать владение добавляемым способом. Отвязка последнего способа входа запрещена без настроенного восстановления. Добавление/отзыв устройств, email и способов входа сопровождаются уведомлениями.
**Статус реализации (Hub, этап 1):** вход по почте с одноразовым кодом работает (`hub/AUTH.md`). Новый аккаунт получает сгенерированный handle `u_...` и нейтральное имя; выбор handle, отображаемого имени и аватара после первого подтверждения ещё не реализован. Связывание второго способа входа, passkey/MFA и уведомления о новых способах входа тоже впереди.
**Статус реализации (Hub, этап 1):** вход по почте с одноразовым кодом работает (`hub/AUTH.md`). Новый аккаунт получает сгенерированный handle `u_...` и нейтральное имя; выбор handle и отображаемого имени после первого подтверждения ещё не реализован. Собственный аватар можно загрузить и убрать на странице аккаунта сайта (реализовано в Hub, см. ниже). Связывание второго способа входа, passkey/MFA и уведомления о новых способах входа тоже впереди.
## GitHub OAuth
@ -42,6 +42,8 @@ Email подтверждает контроль почтового ящика,
Первоначальные ограничения клиента: исходный файл до10MiB, сторона до4096px, лимит памяти декодера64MiB. Ограничения проверяются при чтении/декодировании, ошибки показываются в диалоге. SVG, внешние URL и анимации не поддерживаются в первой версии. Оригинал не сохраняется после нормализации; выходной PNG не переносит исходные EXIF/геометки. Отмена и ошибка не заменяют прежний аватар; запись атомарная.
**Реализация в Hub (веб):** `POST/DELETE /v1/account/avatar`, `GET /v1/avatars/<id>` (`hub/AUTH.md`). Hub принимает PNG/JPEG/WebP до 2 МиБ и 4096 px, проверяет тип по сигнатуре, полностью декодирует и заново кодирует в PNG 256×256 без метаданных, хранит один аватар на аккаунт в SQLite BLOB; адрес содержит хеш содержимого и кэшируется как immutable. Для сайта кадрирование делается на canvas до отправки, Hub дополнительно обрезает по центру. Для аккаунта GitHub «Убрать фото» возвращает аватар GitHub. Клиент Vnox пока не использует этот API. Резервные копии базы могут хранить удалённые данные до 30 дней (решение владельца; ротацию копий ещё нужно реализовать).
До Hub API аватар собственный/локальный и не выдаётся за синхронизированный с друзьями. Впоследствии Hub принимает нормализованное изображение, повторно проверяет/перекодирует его, обновляет avatar_id/revision и доступ по политике профиля. Изображение хранится до замены/удаления профиля; правило DM-вложения «4 дня» не применяется. Старые версии и кэши очищаются по отдельной политике.
## Ещё решения до публичного запуска

View file

@ -21,9 +21,7 @@ tokio.workspace = true
serde.workspace = true
serde_json.workspace = true
ed25519-dalek.workspace = true
x25519-dalek.workspace = true
chacha20poly1305.workspace = true
hkdf.workspace = true
sha2.workspace = true
rand.workspace = true
tracing.workspace = true
@ -50,3 +48,7 @@ url = "2"
[build-dependencies]
prost-build = "0.14"
[dev-dependencies]
# Test clients: a TLS 1.2 only client needs the `tls12` feature of rustls.
rustls = { version = "0.23", features = ["tls12"] }

View file

@ -19,6 +19,11 @@ impl ServerIdentity {
use ed25519_dalek::Signer;
self.signing_key.sign(message).to_bytes().to_vec()
}
/// Ed25519 seed. Only used to derive the TLS key of the auto generated certificate
/// (see `crate::tls`), so the certificate fingerprint is a function of the identity.
pub(crate) fn signing_seed(&self) -> [u8; 32] {
self.signing_key.to_bytes()
}
pub fn pubkey_hex(&self) -> String {
hex::encode(self.signing_key.verifying_key().to_bytes())
}

View file

@ -90,17 +90,34 @@ pub struct GatewayConfig {
/// Defaults to 10.
#[serde(default)]
pub message_rate_burst: Option<u32>,
/// Enable TLS 1.3 on the TCP listener.
/// Deprecated. TLS 1.3 is always on since LNEx v3. `true` is accepted with a warning,
/// `false` is a startup error because plaintext is no longer supported.
#[serde(default)]
pub tls_enabled: bool,
/// Path to TLS certificate file (PEM).
pub tls_enabled: Option<bool>,
/// Path to the TLS certificate chain (PEM, leaf first). Set together with `tls_key_path`.
/// When both are unset a self-signed certificate is generated in `data_dir/tls/`.
#[serde(default)]
pub tls_cert_path: Option<String>,
/// Path to TLS private key file (PEM).
/// Path to the TLS private key (PEM).
#[serde(default)]
pub tls_key_path: Option<String>,
}
impl GatewayConfig {
/// Reject configurations that would weaken or break the mandatory TLS 1.3 listener.
pub fn validate_tls(&self) -> Result<()> {
if self.tls_enabled == Some(false) {
anyhow::bail!(
"gateway.tls_enabled = false is no longer supported: LNEx v3 requires TLS 1.3; remove the option"
);
}
if self.tls_cert_path.is_some() != self.tls_key_path.is_some() {
anyhow::bail!("gateway.tls_cert_path and gateway.tls_key_path must be set together");
}
Ok(())
}
}
#[derive(Debug, Deserialize)]
pub struct VoiceConfig {
pub bind: String,
@ -125,3 +142,33 @@ pub fn load() -> Result<Config> {
toml::from_str(&text).map_err(|e| anyhow::anyhow!("invalid config: {e}"))
}
#[cfg(test)]
mod tests {
use super::*;
fn gateway(extra: &str) -> GatewayConfig {
toml::from_str(&format!("bind = \"127.0.0.1:0\"\n{extra}")).unwrap()
}
#[test]
fn tls_defaults_to_generated_certificate() {
gateway("").validate_tls().unwrap();
}
#[test]
fn plaintext_opt_out_is_a_startup_error() {
let error = gateway("tls_enabled = false").validate_tls().unwrap_err();
assert!(error.to_string().contains("TLS 1.3"));
gateway("tls_enabled = true").validate_tls().unwrap();
}
#[test]
fn certificate_and_key_must_be_configured_together() {
assert!(gateway("tls_cert_path = \"c.pem\"").validate_tls().is_err());
assert!(gateway("tls_key_path = \"k.pem\"").validate_tls().is_err());
gateway("tls_cert_path = \"c.pem\"\ntls_key_path = \"k.pem\"")
.validate_tls()
.unwrap();
}
}

View file

@ -8,7 +8,7 @@ use crate::{
net::{io, state::State},
proto::{
ChannelCreatePayload, ChannelDeletePayload, ChannelListItem, ChannelListPayload,
ChannelStatePayload, PacketId, SessionCrypto, encode_packet, to_payload,
ChannelStatePayload, PacketId, encode_packet, to_payload,
},
};
@ -19,7 +19,6 @@ pub async fn handle_channel_create(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = ChannelCreatePayload::decode(payload)?;
@ -37,7 +36,7 @@ pub async fn handle_channel_create(
"channel_create from {}: invalid kind '{other}'",
sess.nickname
);
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -45,7 +44,6 @@ pub async fn handle_channel_create(
code: crate::proto::ErrorCode::InvalidPacket as u32,
message: format!("invalid channel kind: {other}"),
}),
crypto,
)
.await?;
return Ok(());
@ -65,7 +63,7 @@ pub async fn handle_channel_create(
|| channel_id.chars().any(char::is_control)
|| channel_name.chars().any(char::is_control)
{
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -73,7 +71,6 @@ pub async fn handle_channel_create(
code: crate::proto::ErrorCode::InvalidPacket as u32,
message: "channel_id is required".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -84,7 +81,7 @@ pub async fn handle_channel_create(
if !state.rate_limiter.try_consume(session_id) {
state.metrics.inc(&state.metrics.rate_limited_events);
warn!("rate-limited channel_create from {}", sess.nickname);
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -92,7 +89,6 @@ pub async fn handle_channel_create(
code: crate::proto::ErrorCode::RateLimited as u32,
message: "slow down — too many channel operations".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -101,7 +97,7 @@ pub async fn handle_channel_create(
let access = state.access.write().await;
if !super::may_manage(state, &sess.user_id, req.guild_id.as_deref()).await? {
drop(access);
super::denied(stream, seq, crypto).await?;
super::denied(stream, seq).await?;
return Ok(());
}
@ -133,7 +129,7 @@ pub async fn handle_channel_create(
drop(access);
if !created {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -141,7 +137,6 @@ pub async fn handle_channel_create(
code: crate::proto::ErrorCode::ChannelNotFound as u32,
message: "channel already exists".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -164,14 +159,7 @@ pub async fn handle_channel_create(
voice_endpoint: state.config.voice.bind.clone(),
guild_id: req.guild_id.clone(),
};
io::send_encrypted(
stream,
PacketId::ChannelState,
seq,
&to_payload(&sp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::ChannelState, seq, &to_payload(&sp)).await?;
super::notify_guild(
state,
@ -200,7 +188,6 @@ pub async fn handle_channel_delete(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = ChannelDeletePayload::decode(payload)?;
@ -211,7 +198,7 @@ pub async fn handle_channel_delete(
// Protect default channels from deletion.
if req.channel_id == "general" || req.channel_id == "voice" {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -219,7 +206,6 @@ pub async fn handle_channel_delete(
code: crate::proto::ErrorCode::PermissionDenied as u32,
message: "cannot delete default channels".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -235,7 +221,7 @@ pub async fn handle_channel_delete(
.await?
{
drop(access);
super::denied(stream, seq, crypto).await?;
super::denied(stream, seq).await?;
return Ok(());
}
state.storage.delete_channel(&req.channel_id).await?;
@ -244,7 +230,7 @@ pub async fn handle_channel_delete(
drop(access);
if !existed {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -252,7 +238,6 @@ pub async fn handle_channel_delete(
code: crate::proto::ErrorCode::ChannelNotFound as u32,
message: "channel not found".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -288,7 +273,6 @@ pub async fn handle_channel_list(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let Some(sess) = session::get(&state.sessions, session_id).await else {
@ -329,6 +313,6 @@ pub async fn handle_channel_list(
channels: items,
guild_id: None,
};
io::send_encrypted(stream, PacketId::ChannelList, seq, &to_payload(&p), crypto).await?;
io::send_frame(stream, PacketId::ChannelList, seq, &to_payload(&p)).await?;
Ok(())
}

View file

@ -6,7 +6,7 @@ use tracing::info;
use crate::{
domain::{channels, session},
net::{io, state::State},
proto::{ChannelEditPayload, PacketId, SessionCrypto, encode_packet, to_payload},
proto::{ChannelEditPayload, PacketId, encode_packet, to_payload},
};
pub async fn handle_channel_edit(
@ -14,7 +14,6 @@ pub async fn handle_channel_edit(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = ChannelEditPayload::decode(payload)?;
@ -32,7 +31,7 @@ pub async fn handle_channel_edit(
|| channel_name.chars().count() > 100
|| channel_name.chars().any(char::is_control)
{
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -40,7 +39,6 @@ pub async fn handle_channel_edit(
code: crate::proto::ErrorCode::InvalidPacket as u32,
message: "channel_id and channel_name are required".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -56,7 +54,7 @@ pub async fn handle_channel_edit(
.await?
{
drop(access);
super::denied(stream, seq, crypto).await?;
super::denied(stream, seq).await?;
return Ok(());
}
state
@ -67,7 +65,7 @@ pub async fn handle_channel_edit(
drop(access);
if !renamed {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -75,7 +73,6 @@ pub async fn handle_channel_edit(
code: crate::proto::ErrorCode::ChannelNotFound as u32,
message: "channel not found".into(),
}),
crypto,
)
.await?;
return Ok(());

View file

@ -6,8 +6,8 @@ use crate::{
state::{BroadcastMsg, State},
},
proto::{
self, ChannelStatePayload, ChatHistoryPayload, MemberInfo, PacketId, SessionCrypto,
UserJoinPayload, encode_packet, to_payload,
self, ChannelStatePayload, ChatHistoryPayload, MemberInfo, PacketId, UserJoinPayload,
encode_packet, to_payload,
},
};
use anyhow::Result;
@ -20,7 +20,6 @@ pub async fn join(
seq: &mut u32,
session_id: &str,
channel_id: &str,
crypto: &SessionCrypto,
state: &State,
_addr: SocketAddr,
) -> Result<()> {
@ -30,7 +29,7 @@ pub async fn join(
};
let Some(ch) = channels::get_channel(&state.channels, channel_id).await else {
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -38,7 +37,6 @@ pub async fn join(
code: proto::ErrorCode::ChannelNotFound as u32,
message: "not found".into(),
}),
crypto,
)
.await;
};
@ -51,7 +49,7 @@ pub async fn join(
.any(|g| g.id == *guild)
{
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -59,14 +57,13 @@ pub async fn join(
code: proto::ErrorCode::PermissionDenied as u32,
message: "guild membership required".into(),
}),
crypto,
)
.await;
}
let is_voice = ch.kind == channels::ChannelKind::Voice;
if is_voice && state.voice_member_tx.is_none() {
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -74,7 +71,6 @@ pub async fn join(
code: proto::ErrorCode::NodeUnavailable as u32,
message: "voice requires the combined server process".into(),
}),
crypto,
)
.await;
}
@ -93,7 +89,7 @@ pub async fn join(
.has(crate::domain::permissions::Permissions::VOICE_SPEAK)
{
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -101,7 +97,6 @@ pub async fn join(
code: proto::ErrorCode::PermissionDenied as u32,
message: "VOICE_SPEAK permission required".into(),
}),
crypto,
)
.await;
}
@ -149,7 +144,7 @@ pub async fn join(
channels::leave(&state.channels, channel_id, session_id).await;
set_voice_channel(state, session_id, None).await;
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -157,7 +152,6 @@ pub async fn join(
code: proto::ErrorCode::NodeUnavailable as u32,
message: "voice service unavailable".into(),
}),
crypto,
)
.await;
}
@ -203,21 +197,13 @@ pub async fn join(
voice_endpoint: state.config.voice.bind.clone(),
guild_id: ch.guild_id,
};
io::send_encrypted(
stream,
PacketId::ChannelState,
seq,
&to_payload(&payload),
crypto,
)
.await?;
io::send_frame(stream, PacketId::ChannelState, seq, &to_payload(&payload)).await?;
if let Some(credentials) = credentials {
io::send_encrypted(
io::send_frame(
stream,
PacketId::VoiceSession,
seq,
&to_payload(&credentials),
crypto,
)
.await?;
}

View file

@ -38,7 +38,6 @@ async fn attempt_join(state: &State, session_id: &str, channel_id: &str) {
&mut 0,
session_id,
channel_id,
&SessionCrypto::derive(&[7; 32], session_id),
state,
"127.0.0.1:12345".parse().unwrap(),
)
@ -169,29 +168,15 @@ async fn text_navigation_preserves_voice_and_leaving_unrelated_channel_is_noop()
.contains(&sid)
);
let (mut stream, _) = tokio::io::duplex(65536);
super::super::leave(
&mut stream,
&mut 0,
&sid,
"general",
&SessionCrypto::derive(&[7; 32], &sid),
&state,
)
.await
.unwrap();
super::super::leave(&mut stream, &mut 0, &sid, "general", &state)
.await
.unwrap();
let sess = session::get(&state.sessions, &sid).await.unwrap();
assert_eq!(sess.channel_id.as_deref(), Some("other-text"));
assert_eq!(sess.voice_channel_id.as_deref(), Some("voice"));
super::super::leave(
&mut stream,
&mut 0,
&sid,
"voice",
&SessionCrypto::derive(&[7; 32], &sid),
&state,
)
.await
.unwrap();
super::super::leave(&mut stream, &mut 0, &sid, "voice", &state)
.await
.unwrap();
let sess = session::get(&state.sessions, &sid).await.unwrap();
assert_eq!(sess.channel_id.as_deref(), Some("other-text"));
assert_eq!(sess.voice_channel_id, None);
@ -220,7 +205,6 @@ async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_cr
.await
.unwrap();
let (mut stream, _peer) = tokio::io::duplex(65536);
let crypto = SessionCrypto::derive(&[7; 32], &sid);
crate::handler::channel::handle_channel_edit(
&mut stream,
&mut 0,
@ -229,7 +213,6 @@ async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_cr
channel_id: "managed".into(),
channel_name: "stolen".into(),
}),
&crypto,
&state,
)
.await
@ -248,7 +231,6 @@ async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_cr
&to_payload(&ChannelDeletePayload {
channel_id: "managed".into(),
}),
&crypto,
&state,
)
.await
@ -275,7 +257,6 @@ async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_cr
&to_payload(&ChannelDeletePayload {
channel_id: "managed".into(),
}),
&crypto,
&state,
)
.await
@ -324,7 +305,6 @@ async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation
.await
.unwrap();
let (mut stream, _peer) = tokio::io::duplex(65536);
let crypto = SessionCrypto::derive(&[7; 32], &sid);
crate::handler::guild::handle_role_assign(
&mut stream,
&mut 0,
@ -334,7 +314,6 @@ async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation
user_id: "visitor".into(),
role_id: foreign.clone(),
}),
&crypto,
&state,
)
.await
@ -347,7 +326,6 @@ async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation
guild_id: guild.clone(),
role_id: foreign.clone(),
}),
&crypto,
&state,
)
.await
@ -407,7 +385,6 @@ async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation
user_id: "visitor".into(),
role_id: powerful,
}),
&crypto,
&state,
)
.await
@ -476,7 +453,6 @@ async fn removing_voice_role_revokes_existing_udp_membership() {
user_id: "visitor".into(),
role_id: role,
}),
&SessionCrypto::derive(&[7; 32], &owner.session_id),
&state,
)
.await
@ -515,7 +491,6 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
let member = session::create(&state.sessions, "member".into(), "Member".into()).await;
let outsider = session::create(&state.sessions, "outsider".into(), "Outsider".into()).await;
let mut events = state.broadcast.subscribe();
let crypto = SessionCrypto::derive(&[7; 32], &owner_sid);
let (mut stream, _peer) = tokio::io::duplex(65536);
let creation = ChannelCreatePayload {
channel_id: "private-notification".into(),
@ -528,7 +503,6 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
&mut 0,
&owner_sid,
&to_payload(&creation),
&crypto,
&state,
)
.await
@ -541,7 +515,6 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
channel_id: creation.channel_id.clone(),
channel_name: "Renamed privately".into(),
}),
&crypto,
&state,
)
.await
@ -553,7 +526,6 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
&to_payload(&ChannelDeletePayload {
channel_id: creation.channel_id.clone(),
}),
&crypto,
&state,
)
.await
@ -607,7 +579,6 @@ async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
use std::time::Duration;
use tokio::io::AsyncReadExt;
let (state, sid) = fixture().await;
let crypto = SessionCrypto::derive(&[7; 32], &sid);
let history = |channel: &str| BroadcastMsg {
channel_id: Some(channel.into()),
exclude_session: None,
@ -624,12 +595,11 @@ async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
// The same queued target/channel envelope is deliverable while subscribed.
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut seq = 2;
crate::handler::deliver::deliver_encrypted(
crate::handler::deliver::deliver_frame(
&mut stream,
&mut seq,
&sid,
&history("general"),
&crypto,
&state,
)
.await
@ -642,16 +612,15 @@ async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
);
assert_eq!(seq, 3);
super::super::leave(&mut stream, &mut seq, &sid, "general", &crypto, &state)
super::super::leave(&mut stream, &mut seq, &sid, "general", &state)
.await
.unwrap();
let (mut stream, mut peer) = tokio::io::duplex(65536);
crate::handler::deliver::deliver_encrypted(
crate::handler::deliver::deliver_frame(
&mut stream,
&mut seq,
&sid,
&history("general"),
&crypto,
&state,
)
.await
@ -696,16 +665,9 @@ async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
super::super::revoke_guild_access(&state, &guild, Some("visitor")).await;
}
let (mut stream, mut peer) = tokio::io::duplex(65536);
crate::handler::deliver::deliver_encrypted(
&mut stream,
&mut seq,
&sid,
&queued,
&crypto,
&state,
)
.await
.unwrap();
crate::handler::deliver::deliver_frame(&mut stream, &mut seq, &sid, &queued, &state)
.await
.unwrap();
assert_eq!(seq, 3);
assert!(
tokio::time::timeout(Duration::from_millis(15), peer.read_u8())

View file

@ -5,7 +5,6 @@ use tracing::info;
use crate::{
domain::{channels, session},
net::state::State,
proto::SessionCrypto,
};
use super::{broadcast_leave, set_channel, set_voice_channel};
@ -15,7 +14,6 @@ pub async fn leave(
_seq: &mut u32,
session_id: &str,
channel_id: &str,
_crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let Some(sess) = session::get(&state.sessions, session_id).await else {

View file

@ -117,9 +117,8 @@ pub(super) async fn may_manage(
pub(super) async fn denied(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
seq: &mut u32,
crypto: &crate::proto::SessionCrypto,
) -> anyhow::Result<()> {
crate::net::io::send_encrypted(
crate::net::io::send_frame(
stream,
PacketId::Error,
seq,
@ -127,7 +126,6 @@ pub(super) async fn denied(
code: crate::proto::ErrorCode::PermissionDenied as u32,
message: "guild MANAGE_CHANNELS permission required".into(),
}),
crypto,
)
.await
}

View file

@ -10,7 +10,7 @@ use crate::{
},
proto::{
PacketId, PresenceEventPayload, PresenceInfo, PresenceSyncPayload, PresenceUpdatePayload,
SessionCrypto, encode_packet, to_payload,
encode_packet, to_payload,
},
};
@ -33,7 +33,6 @@ pub async fn handle_presence_update(
seq: &mut u32,
session_id: &str,
payload: &[u8],
_crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = PresenceUpdatePayload::decode(payload)?;
@ -99,7 +98,6 @@ pub async fn handle_presence_sync(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let _sess = session::get(&state.sessions, session_id)
@ -108,12 +106,11 @@ pub async fn handle_presence_sync(
let presences: Vec<PresenceInfo> = state.presences.read().await.values().cloned().collect();
io::send_encrypted(
io::send_frame(
stream,
PacketId::PresenceSync,
seq,
&to_payload(&PresenceSyncPayload { presences }),
crypto,
)
.await?;
Ok(())

View file

@ -12,7 +12,6 @@ pub async fn handle_read_receipt(
seq: &mut u32,
session_id: &str,
payload: &[u8],
_crypto: &crate::proto::SessionCrypto,
state: &State,
) -> Result<()> {
let req = ReadReceiptPayload::decode(payload)?;

View file

@ -4,15 +4,13 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::BroadcastMsg, state::State},
proto::SessionCrypto,
};
pub async fn deliver_encrypted(
pub async fn deliver_frame(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
msg: &BroadcastMsg,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
if msg.exclude_session.as_deref() == Some(session_id)
@ -69,5 +67,5 @@ pub async fn deliver_encrypted(
}
drop(access);
}
io::deliver_encrypted(stream, crypto, seq, &msg.data).await
io::deliver_frame(stream, seq, &msg.data).await
}

View file

@ -5,7 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{DmHistoryPayload, PacketId, SessionCrypto, to_payload},
proto::{DmHistoryPayload, PacketId, to_payload},
};
pub async fn handle_dm_history(
@ -13,7 +13,6 @@ pub async fn handle_dm_history(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = DmHistoryPayload::decode(payload)?;
@ -42,6 +41,6 @@ pub async fn handle_dm_history(
search_query: None,
limit: None,
};
io::send_encrypted(stream, PacketId::DmHistory, seq, &to_payload(&resp), crypto).await?;
io::send_frame(stream, PacketId::DmHistory, seq, &to_payload(&resp)).await?;
Ok(())
}

View file

@ -9,9 +9,7 @@ use crate::{
io,
state::{BroadcastMsg, State},
},
proto::{
self, DmMessagePayload, ErrorCode, PacketId, SessionCrypto, encode_packet, to_payload,
},
proto::{self, DmMessagePayload, ErrorCode, PacketId, encode_packet, to_payload},
};
pub async fn handle_dm_message(
@ -19,7 +17,6 @@ pub async fn handle_dm_message(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let msg = DmMessagePayload::decode(payload)?;
@ -34,7 +31,7 @@ pub async fn handle_dm_message(
if !state.rate_limiter.try_consume(session_id) {
state.metrics.inc(&state.metrics.rate_limited_events);
warn!("rate-limited DM session {session_id}");
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -42,7 +39,6 @@ pub async fn handle_dm_message(
code: ErrorCode::RateLimited as u32,
message: "you are sending messages too quickly".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -54,7 +50,7 @@ pub async fn handle_dm_message(
.await?
.ok_or_else(|| anyhow::anyhow!("user not in DM"))?;
if state.storage.is_blocked(&other_id, &my_id).await? {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -62,7 +58,6 @@ pub async fn handle_dm_message(
code: proto::ErrorCode::Blocked as u32,
message: "blocked".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -102,13 +97,6 @@ pub async fn handle_dm_message(
warn!("dm recipient offline: {}", &other_id[..8]);
}
io::send_encrypted(
stream,
PacketId::DmMessage,
seq,
&to_payload(&saved),
crypto,
)
.await?;
io::send_frame(stream, PacketId::DmMessage, seq, &to_payload(&saved)).await?;
Ok(())
}

View file

@ -5,7 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{self, DmStartPayload, DmStartResponsePayload, PacketId, SessionCrypto, to_payload},
proto::{self, DmStartPayload, DmStartResponsePayload, PacketId, to_payload},
};
pub async fn handle_dm_start(
@ -13,7 +13,6 @@ pub async fn handle_dm_start(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = DmStartPayload::decode(payload)?;
@ -29,7 +28,7 @@ pub async fn handle_dm_start(
.is_blocked(&req.target_user_id, &my_id)
.await?
{
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -37,14 +36,13 @@ pub async fn handle_dm_start(
code: proto::ErrorCode::Blocked as u32,
message: "blocked".into(),
}),
crypto,
)
.await?;
return Ok(());
}
if req.target_user_id == my_id {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -52,7 +50,6 @@ pub async fn handle_dm_start(
code: proto::ErrorCode::InvalidPacket as u32,
message: "cannot DM yourself".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -84,7 +81,7 @@ pub async fn handle_dm_start(
messages,
unread_count: unread_count as u32,
};
io::send_encrypted(stream, PacketId::DmStart, seq, &to_payload(&resp), crypto).await?;
io::send_frame(stream, PacketId::DmStart, seq, &to_payload(&resp)).await?;
Ok(())
}
@ -93,7 +90,6 @@ pub async fn handle_dm_read_ack(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = crate::proto::DmReadAckPayload::decode(payload)?;
@ -106,6 +102,6 @@ pub async fn handle_dm_read_ack(
state.storage.reset_dm_unread(&req.dm_id, &my_id).await?;
io::send_encrypted(stream, PacketId::DmReadAck, seq, b"{}", crypto).await?;
io::send_frame(stream, PacketId::DmReadAck, seq, b"{}").await?;
Ok(())
}

View file

@ -30,14 +30,13 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
}
PacketId::Ping => {
let ping = PingPayload::decode(payload)?;
io::send_encrypted(
io::send_frame(
ctx.stream,
PacketId::Pong,
ctx.seq,
&to_payload(&PongPayload {
timestamp: ping.timestamp,
}),
ctx.crypto,
)
.await?;
}
@ -48,7 +47,6 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
ctx.seq,
session_id,
&m.channel_id,
ctx.crypto,
ctx.state,
addr,
)
@ -56,217 +54,140 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
}
PacketId::LeaveChannel => {
let m = LeaveChannelPayload::decode(payload)?;
channel::leave(
ctx.stream,
ctx.seq,
session_id,
&m.channel_id,
ctx.crypto,
ctx.state,
)
.await?;
channel::leave(ctx.stream, ctx.seq, session_id, &m.channel_id, ctx.state).await?;
}
PacketId::ChannelCreate => {
channel::handle_channel_create(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
channel::handle_channel_create(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::ChannelDelete => {
channel::handle_channel_delete(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
channel::handle_channel_delete(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::ChannelEdit => {
channel::handle_channel_edit(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
channel::handle_channel_edit(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::ChannelList => {
channel::handle_channel_list(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
channel::handle_channel_list(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::ChatMessage => {
let m = ChatMessagePayload::decode(payload)?;
content::chat::handle(session_id, m, ctx.state).await?;
}
PacketId::DmStart => {
direct_message::handle_dm_start(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::DmMessage => {
direct_message::handle_dm_message(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::DmHistory => {
direct_message::handle_dm_history(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::DmReadAck => {
direct_message::handle_dm_read_ack(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::GuildCreate => {
guild::handle_guild_create(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::GuildDelete => {
guild::handle_guild_delete(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::GuildList => {
guild::handle_guild_list(ctx.stream, ctx.seq, session_id, ctx.crypto, ctx.state)
direct_message::handle_dm_start(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::DmMessage => {
direct_message::handle_dm_message(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::DmHistory => {
direct_message::handle_dm_history(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::DmReadAck => {
direct_message::handle_dm_read_ack(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildCreate => {
guild::handle_guild_create(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::GuildDelete => {
guild::handle_guild_delete(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::GuildList => {
guild::handle_guild_list(ctx.stream, ctx.seq, session_id, ctx.state).await?;
}
PacketId::GuildMemberJoin => {
guild::handle_guild_member_join(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_guild_member_join(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildMemberLeave => {
guild::handle_guild_member_leave(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_guild_member_leave(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildMemberKick => {
guild::handle_guild_member_kick(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_guild_member_kick(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::RoleCreate => {
guild::handle_role_create(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_create(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::RoleDelete => {
guild::handle_role_delete(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_delete(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::InviteCreate => {
guild::handle_invite_create(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_invite_create(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::InviteAccept => {
guild::handle_invite_accept(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_invite_accept(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::InviteDelete => {
guild::handle_invite_delete(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_invite_delete(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildAuditLogFetch => {
guild::handle_audit_log_fetch(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_audit_log_fetch(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildMemberListFetch => {
guild::handle_member_list_fetch(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_member_list_fetch(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildRoleAssign => {
guild::handle_role_assign(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_assign(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::GuildRoleUnassign => {
guild::handle_role_unassign(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_unassign(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildRoleListFetch => {
guild::handle_role_list_fetch(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_list_fetch(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::PresenceUpdate => {
content::presence::handle_presence_update(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
ctx.stream, ctx.seq, session_id, payload, ctx.state,
)
.await?;
}
PacketId::PresenceSync => {
content::presence::handle_presence_sync(
ctx.stream, ctx.seq, session_id, ctx.crypto, ctx.state,
)
.await?;
content::presence::handle_presence_sync(ctx.stream, ctx.seq, session_id, ctx.state)
.await?;
}
PacketId::FriendRequest => {
friends::handle_friend_request(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_friend_request(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::FriendAccept => {
friends::handle_friend_accept(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_friend_accept(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::FriendDecline => {
friends::handle_friend_decline(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_friend_decline(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::FriendRemove => {
friends::handle_friend_remove(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_friend_remove(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::FriendList => {
friends::handle_friend_list(ctx.stream, ctx.seq, session_id, ctx.crypto, ctx.state)
.await?;
friends::handle_friend_list(ctx.stream, ctx.seq, session_id, ctx.state).await?;
}
PacketId::BlockUser => {
friends::handle_block_user(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_block_user(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::UnblockUser => {
friends::handle_unblock_user(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_unblock_user(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::BlockList => {
friends::handle_block_list(ctx.stream, ctx.seq, session_id, ctx.crypto, ctx.state)
.await?;
friends::handle_block_list(ctx.stream, ctx.seq, session_id, ctx.state).await?;
}
PacketId::MessageReactionAdd => {
let m = ReactionPayload::decode(payload)?;
@ -286,34 +207,24 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
content::handle_typing_start(session_id, payload, ctx.state).await?;
}
PacketId::ReadReceipt => {
content::handle_read_receipt(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
content::handle_read_receipt(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::E2eeDmKeyExchange => {
e2ee::handle_e2ee_key_exchange(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
e2ee::handle_e2ee_key_exchange(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::E2eeDmKeyExchangeAck => {
e2ee::handle_e2ee_key_exchange_ack(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
e2ee::handle_e2ee_key_exchange_ack(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::E2eeDmMessage => {
e2ee::handle_e2ee_dm_message(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
e2ee::handle_e2ee_dm_message(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::E2eeDmHistory => {
e2ee::handle_e2ee_dm_history(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
e2ee::handle_e2ee_dm_history(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::Disconnect => debug!("{addr} DISCONNECT"),
other => debug!("{addr} unhandled {:?}", other),

View file

@ -11,7 +11,7 @@ use crate::{
},
proto::{
self, E2eeDmKeyExchangeAckPayload, E2eeDmKeyExchangePayload, ErrorCode, PacketId,
SessionCrypto, encode_packet, to_payload,
encode_packet, to_payload,
},
};
@ -20,7 +20,6 @@ pub async fn handle_e2ee_key_exchange(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let msg = E2eeDmKeyExchangePayload::decode(payload)?;
@ -38,7 +37,7 @@ pub async fn handle_e2ee_key_exchange(
.ok_or_else(|| anyhow::anyhow!("user not in DM"))?;
if state.storage.is_blocked(&other_id, &my_id).await? {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -46,7 +45,6 @@ pub async fn handle_e2ee_key_exchange(
code: ErrorCode::Blocked as u32,
message: "blocked".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -78,12 +76,11 @@ pub async fn handle_e2ee_key_exchange(
warn!("e2ee key exchange recipient offline: {}", &other_id[..8]);
}
io::send_encrypted(
io::send_frame(
stream,
PacketId::E2eeDmKeyExchange,
seq,
&to_payload(&E2eeDmKeyExchangeAckPayload { dm_id: msg.dm_id }),
crypto,
)
.await?;
Ok(())
@ -94,7 +91,6 @@ pub async fn handle_e2ee_key_exchange_ack(
_seq: &mut u32,
session_id: &str,
payload: &[u8],
_crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let msg = E2eeDmKeyExchangeAckPayload::decode(payload)?;

View file

@ -10,8 +10,8 @@ use crate::{
state::{BroadcastMsg, State},
},
proto::{
self, E2eeDmHistoryPayload, E2eeDmMessagePayload, ErrorCode, PacketId, SessionCrypto,
encode_packet, to_payload,
self, E2eeDmHistoryPayload, E2eeDmMessagePayload, ErrorCode, PacketId, encode_packet,
to_payload,
},
};
@ -20,7 +20,6 @@ pub async fn handle_e2ee_dm_message(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let msg = E2eeDmMessagePayload::decode(payload)?;
@ -34,7 +33,7 @@ pub async fn handle_e2ee_dm_message(
if !state.rate_limiter.try_consume(session_id) {
state.metrics.inc(&state.metrics.rate_limited_events);
warn!("rate-limited e2ee dm session {session_id}");
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -42,7 +41,6 @@ pub async fn handle_e2ee_dm_message(
code: ErrorCode::RateLimited as u32,
message: "you are sending messages too quickly".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -55,7 +53,7 @@ pub async fn handle_e2ee_dm_message(
.ok_or_else(|| anyhow::anyhow!("user not in DM"))?;
if state.storage.is_blocked(&other_id, &my_id).await? {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -63,7 +61,6 @@ pub async fn handle_e2ee_dm_message(
code: proto::ErrorCode::Blocked as u32,
message: "blocked".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -103,14 +100,7 @@ pub async fn handle_e2ee_dm_message(
warn!("e2ee dm recipient offline: {}", &other_id[..8]);
}
io::send_encrypted(
stream,
PacketId::E2eeDmMessage,
seq,
&to_payload(&saved),
crypto,
)
.await?;
io::send_frame(stream, PacketId::E2eeDmMessage, seq, &to_payload(&saved)).await?;
Ok(())
}
@ -119,7 +109,6 @@ pub async fn handle_e2ee_dm_history(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = E2eeDmHistoryPayload::decode(payload)?;
@ -147,13 +136,6 @@ pub async fn handle_e2ee_dm_history(
messages,
limit: None,
};
io::send_encrypted(
stream,
PacketId::E2eeDmHistory,
seq,
&to_payload(&resp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::E2eeDmHistory, seq, &to_payload(&resp)).await?;
Ok(())
}

View file

@ -5,7 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::io,
proto::{FriendDeclinePayload, PacketId, SessionCrypto, SimpleResponsePayload, to_payload},
proto::{FriendDeclinePayload, PacketId, SimpleResponsePayload, to_payload},
};
pub async fn handle_friend_decline(
@ -13,7 +13,6 @@ pub async fn handle_friend_decline(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &crate::net::state::State,
) -> Result<()> {
let req = FriendDeclinePayload::decode(payload)?;
@ -26,7 +25,7 @@ pub async fn handle_friend_decline(
.decline_friend_request(&req.from_user_id, &sess.user_id)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendDecline,
seq,
@ -35,7 +34,6 @@ pub async fn handle_friend_decline(
user_id: None,
role_id: None,
}),
crypto,
)
.await?;
Ok(())

View file

@ -4,14 +4,13 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{FriendInfo, FriendListPayload, PacketId, SessionCrypto, to_payload},
proto::{FriendInfo, FriendListPayload, PacketId, to_payload},
};
pub async fn handle_friend_list(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let sess = session::get(&state.sessions, session_id)
@ -35,12 +34,11 @@ pub async fn handle_friend_list(
});
}
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendList,
seq,
&to_payload(&FriendListPayload { friends }),
crypto,
)
.await?;
Ok(())

View file

@ -6,8 +6,8 @@ use crate::{
domain::session,
net::{io, state::State},
proto::{
BlockListPayload, BlockUserPayload, FriendRemovePayload, PacketId, SessionCrypto,
SimpleResponsePayload, UnblockUserPayload, to_payload,
BlockListPayload, BlockUserPayload, FriendRemovePayload, PacketId, SimpleResponsePayload,
UnblockUserPayload, to_payload,
},
};
@ -16,7 +16,6 @@ pub async fn handle_friend_remove(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = FriendRemovePayload::decode(payload)?;
@ -29,7 +28,7 @@ pub async fn handle_friend_remove(
.remove_friend(&sess.user_id, &req.user_id)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendRemove,
seq,
@ -38,7 +37,6 @@ pub async fn handle_friend_remove(
user_id: None,
role_id: None,
}),
crypto,
)
.await?;
Ok(())
@ -49,7 +47,6 @@ pub async fn handle_block_user(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = BlockUserPayload::decode(payload)?;
@ -62,7 +59,7 @@ pub async fn handle_block_user(
.block_user(&sess.user_id, &req.user_id)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::BlockUser,
seq,
@ -71,7 +68,6 @@ pub async fn handle_block_user(
user_id: None,
role_id: None,
}),
crypto,
)
.await?;
Ok(())
@ -82,7 +78,6 @@ pub async fn handle_unblock_user(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = UnblockUserPayload::decode(payload)?;
@ -95,7 +90,7 @@ pub async fn handle_unblock_user(
.unblock_user(&sess.user_id, &req.user_id)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::UnblockUser,
seq,
@ -104,7 +99,6 @@ pub async fn handle_unblock_user(
user_id: None,
role_id: None,
}),
crypto,
)
.await?;
Ok(())
@ -114,7 +108,6 @@ pub async fn handle_block_list(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let sess = session::get(&state.sessions, session_id)
@ -123,12 +116,11 @@ pub async fn handle_block_list(
let blocked = state.storage.list_blocks(&sess.user_id).await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::BlockList,
seq,
&to_payload(&BlockListPayload { blocked }),
crypto,
)
.await?;
Ok(())

View file

@ -8,7 +8,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
net::io,
proto::{ErrorPayload, PacketId, SessionCrypto, to_payload},
proto::{ErrorPayload, PacketId, to_payload},
};
async fn send_err(
@ -16,9 +16,8 @@ async fn send_err(
seq: &mut u32,
code: crate::proto::ErrorCode,
msg: &str,
crypto: &SessionCrypto,
) -> Result<()> {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -26,7 +25,6 @@ async fn send_err(
code: code as u32,
message: msg.into(),
}),
crypto,
)
.await
}

View file

@ -5,10 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{
FriendAcceptPayload, FriendEventPayload, FriendRequestPayload, PacketId, SessionCrypto,
to_payload,
},
proto::{FriendAcceptPayload, FriendEventPayload, FriendRequestPayload, PacketId, to_payload},
};
use super::send_err;
@ -18,7 +15,6 @@ pub async fn handle_friend_request(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = FriendRequestPayload::decode(payload)?;
@ -36,7 +32,6 @@ pub async fn handle_friend_request(
seq,
crate::proto::ErrorCode::Blocked,
"you are blocked by this user",
crypto,
)
.await?;
return Ok(());
@ -52,7 +47,6 @@ pub async fn handle_friend_request(
seq,
crate::proto::ErrorCode::InvalidPacket,
"already friends",
crypto,
)
.await?;
return Ok(());
@ -68,7 +62,6 @@ pub async fn handle_friend_request(
seq,
crate::proto::ErrorCode::InvalidPacket,
"already friends or request pending",
crypto,
)
.await?;
return Ok(());
@ -81,14 +74,13 @@ pub async fn handle_friend_request(
};
super::notify_user(state, &req.to_user_id, &ev).await;
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendRequest,
seq,
&to_payload(&FriendRequestPayload {
to_user_id: req.to_user_id.clone(),
}),
crypto,
)
.await?;
Ok(())
@ -99,7 +91,6 @@ pub async fn handle_friend_accept(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = FriendAcceptPayload::decode(payload)?;
@ -117,7 +108,6 @@ pub async fn handle_friend_accept(
seq,
crate::proto::ErrorCode::InvalidPacket,
"no pending request",
crypto,
)
.await?;
return Ok(());
@ -130,14 +120,13 @@ pub async fn handle_friend_accept(
};
super::notify_user(state, &req.from_user_id, &ev).await;
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendAccept,
seq,
&to_payload(&FriendAcceptPayload {
from_user_id: req.from_user_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -6,8 +6,7 @@ use crate::{
domain::permissions::Permissions,
net::{io, state::State},
proto::{
AuditLogEntryPayload, GuildAuditLogFetchPayload, GuildAuditLogPayload, PacketId,
SessionCrypto, to_payload,
AuditLogEntryPayload, GuildAuditLogFetchPayload, GuildAuditLogPayload, PacketId, to_payload,
},
};
@ -17,7 +16,6 @@ pub async fn handle_audit_log_fetch(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = GuildAuditLogFetchPayload::decode(payload)?;
@ -42,7 +40,7 @@ pub async fn handle_audit_log_fetch(
};
if !allowed {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -50,7 +48,6 @@ pub async fn handle_audit_log_fetch(
code: crate::proto::ErrorCode::PermissionDenied as u32,
message: "audit log access requires MANAGE_GUILD".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -75,13 +72,6 @@ pub async fn handle_audit_log_fetch(
guild_id: req.guild_id,
entries,
};
io::send_encrypted(
stream,
PacketId::GuildAuditLog,
seq,
&to_payload(&resp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::GuildAuditLog, seq, &to_payload(&resp)).await?;
Ok(())
}

View file

@ -6,7 +6,7 @@ use tracing::debug;
use crate::{
domain::session,
net::{io, state::State},
proto::{GuildCreatePayload, GuildInfo, PacketId, SessionCrypto, to_payload},
proto::{GuildCreatePayload, GuildInfo, PacketId, to_payload},
};
use super::send_err;
@ -16,7 +16,6 @@ pub async fn handle_guild_create(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = GuildCreatePayload::decode(payload)?;
@ -30,7 +29,6 @@ pub async fn handle_guild_create(
seq,
crate::proto::ErrorCode::InvalidPacket,
"guild name must be 2-100 chars",
crypto,
)
.await?;
return Ok(());
@ -51,14 +49,7 @@ pub async fn handle_guild_create(
created_at: guild.created_at,
};
io::send_encrypted(
stream,
PacketId::GuildCreate,
seq,
&to_payload(&info),
crypto,
)
.await?;
io::send_frame(stream, PacketId::GuildCreate, seq, &to_payload(&info)).await?;
debug!(
"guild: {} created {} (owner={})",
@ -72,7 +63,6 @@ pub async fn handle_guild_delete(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let guard = state.access.write().await;
@ -93,7 +83,6 @@ pub async fn handle_guild_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"only owner can delete guild",
crypto,
)
.await?;
return Ok(());
@ -114,14 +103,13 @@ pub async fn handle_guild_delete(
.await?;
drop(guard);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildDelete,
seq,
&to_payload(&crate::proto::GuildDeletePayload {
guild_id: req.guild_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -7,7 +7,7 @@ use crate::{
net::{io, state::State},
proto::{
InviteAcceptPayload, InviteCreatePayload, InviteDeletePayload, InviteInfo, PacketId,
SessionCrypto, to_payload,
to_payload,
},
};
@ -18,7 +18,6 @@ pub async fn handle_invite_create(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = InviteCreatePayload::decode(payload)?;
@ -39,7 +38,6 @@ pub async fn handle_invite_create(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing CREATE_INVITE permission",
crypto,
)
.await?;
return Ok(());
@ -78,14 +76,7 @@ pub async fn handle_invite_create(
expires_at: inv.expires_at,
created_at: inv.created_at,
};
io::send_encrypted(
stream,
PacketId::InviteCreate,
seq,
&to_payload(&info),
crypto,
)
.await?;
io::send_frame(stream, PacketId::InviteCreate, seq, &to_payload(&info)).await?;
Ok(())
}
@ -94,7 +85,6 @@ pub async fn handle_invite_accept(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = InviteAcceptPayload::decode(payload)?;
@ -116,7 +106,6 @@ pub async fn handle_invite_accept(
seq,
crate::proto::ErrorCode::InvalidPacket,
"invite expired",
crypto,
)
.await?;
return Ok(());
@ -130,7 +119,6 @@ pub async fn handle_invite_accept(
seq,
crate::proto::ErrorCode::InvalidPacket,
"invite max uses reached",
crypto,
)
.await?;
return Ok(());
@ -153,7 +141,7 @@ pub async fn handle_invite_accept(
)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::InviteAccept,
seq,
@ -162,7 +150,6 @@ pub async fn handle_invite_accept(
guild_id: inv.guild_id.clone(),
guild_name: inv.guild_name.clone(),
}),
crypto,
)
.await?;
Ok(())
@ -173,7 +160,6 @@ pub async fn handle_invite_delete(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = InviteDeletePayload::decode(payload)?;
@ -194,7 +180,6 @@ pub async fn handle_invite_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_GUILD permission",
crypto,
)
.await?;
return Ok(());
@ -212,7 +197,7 @@ pub async fn handle_invite_delete(
None,
)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::InviteDelete,
seq,
@ -220,7 +205,6 @@ pub async fn handle_invite_delete(
guild_id: req.guild_id.clone(),
invite_id: req.invite_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -4,16 +4,13 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{
GuildInfo, GuildListPayload, PacketId, SessionCrypto, UserRoleUpdatePayload, to_payload,
},
proto::{GuildInfo, GuildListPayload, PacketId, UserRoleUpdatePayload, to_payload},
};
pub async fn handle_guild_list(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let sess = session::get(&state.sessions, session_id)
@ -39,7 +36,7 @@ pub async fn handle_guild_list(
.max_by_key(|r| r.position)
.map(|r| r.color.clone())
.unwrap_or_else(|| "#ffffff".into());
io::send_encrypted(
io::send_frame(
stream,
PacketId::UserRoleUpdate,
seq,
@ -48,17 +45,15 @@ pub async fn handle_guild_list(
guild_id: g.id.clone(),
color,
}),
crypto,
)
.await?;
}
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildList,
seq,
&to_payload(&GuildListPayload { guilds }),
crypto,
)
.await?;
Ok(())

View file

@ -7,7 +7,7 @@ use crate::{
net::{io, state::State},
proto::{
GuildMemberJoinPayload, GuildMemberKickPayload, GuildMemberLeavePayload, PacketId,
SessionCrypto, to_payload,
to_payload,
},
};
@ -18,7 +18,6 @@ pub async fn handle_guild_member_join(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let guard = state.access.write().await;
@ -40,7 +39,6 @@ pub async fn handle_guild_member_join(
seq,
crate::proto::ErrorCode::PermissionDenied,
"a valid invitation is required",
crypto,
)
.await?;
return Ok(());
@ -61,18 +59,17 @@ pub async fn handle_guild_member_join(
.unwrap_or_else(|| "#ffffff".into());
drop(guard);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildMemberJoin,
seq,
&to_payload(&crate::proto::GuildMemberJoinPayload {
guild_id: req.guild_id.clone(),
}),
crypto,
)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::UserRoleUpdate,
seq,
@ -81,7 +78,6 @@ pub async fn handle_guild_member_join(
guild_id: req.guild_id.clone(),
color,
}),
crypto,
)
.await?;
Ok(())
@ -92,7 +88,6 @@ pub async fn handle_guild_member_leave(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let guard = state.access.write().await;
@ -118,7 +113,6 @@ pub async fn handle_guild_member_leave(
seq,
crate::proto::ErrorCode::PermissionDenied,
"only a non-owner may leave their own membership",
crypto,
)
.await?;
return Ok(());
@ -129,7 +123,7 @@ pub async fn handle_guild_member_leave(
.await?;
crate::handler::channel::revoke_guild_access(state, &req.guild_id, Some(&target)).await;
drop(guard);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildMemberLeave,
seq,
@ -137,7 +131,6 @@ pub async fn handle_guild_member_leave(
guild_id: req.guild_id.clone(),
user_id: target,
}),
crypto,
)
.await?;
Ok(())
@ -148,7 +141,6 @@ pub async fn handle_guild_member_kick(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let guard = state.access.write().await;
@ -171,7 +163,6 @@ pub async fn handle_guild_member_kick(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing KICK_MEMBERS permission",
crypto,
)
.await?;
return Ok(());
@ -189,7 +180,6 @@ pub async fn handle_guild_member_kick(
seq,
crate::proto::ErrorCode::PermissionDenied,
"guild owner cannot be kicked",
crypto,
)
.await?;
return Ok(());
@ -211,7 +201,7 @@ pub async fn handle_guild_member_kick(
)
.await?;
drop(guard);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildMemberKick,
seq,
@ -219,7 +209,6 @@ pub async fn handle_guild_member_kick(
guild_id: req.guild_id.clone(),
user_id: req.user_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -8,7 +8,7 @@ use crate::{
proto::{
GuildMemberInfoPayload, GuildMemberListFetchPayload, GuildMemberListPayload,
GuildRoleInfoPayload, GuildRoleListFetchPayload, GuildRoleListPayload, PacketId,
RoleAssignPayload, SessionCrypto, to_payload,
RoleAssignPayload, to_payload,
},
};
@ -20,7 +20,6 @@ pub async fn handle_member_list_fetch(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = GuildMemberListFetchPayload::decode(payload)?;
@ -41,7 +40,6 @@ pub async fn handle_member_list_fetch(
seq,
crate::proto::ErrorCode::PermissionDenied,
"guild membership required",
crypto,
)
.await?;
return Ok(());
@ -70,14 +68,7 @@ pub async fn handle_member_list_fetch(
guild_id: req.guild_id,
members,
};
io::send_encrypted(
stream,
PacketId::GuildMemberList,
seq,
&to_payload(&resp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::GuildMemberList, seq, &to_payload(&resp)).await?;
Ok(())
}
@ -87,7 +78,6 @@ pub async fn handle_role_assign(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = RoleAssignPayload::decode(payload)?;
@ -111,7 +101,6 @@ pub async fn handle_role_assign(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_ROLES permission",
crypto,
)
.await?;
return Ok(());
@ -137,7 +126,6 @@ pub async fn handle_role_assign(
seq,
crate::proto::ErrorCode::PermissionDenied,
"role or target not permitted in this guild",
crypto,
)
.await?;
return Ok(());
@ -160,7 +148,7 @@ pub async fn handle_role_assign(
drop(access);
// Confirm to caller.
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildRoleAssign,
seq,
@ -169,7 +157,6 @@ pub async fn handle_role_assign(
user_id: req.user_id.clone(),
role_id: req.role_id.clone(),
}),
crypto,
)
.await?;
Ok(())
@ -181,7 +168,6 @@ pub async fn handle_role_unassign(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = RoleAssignPayload::decode(payload)?;
@ -205,7 +191,6 @@ pub async fn handle_role_unassign(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_ROLES permission",
crypto,
)
.await?;
return Ok(());
@ -231,7 +216,6 @@ pub async fn handle_role_unassign(
seq,
crate::proto::ErrorCode::PermissionDenied,
"role or target not permitted in this guild",
crypto,
)
.await?;
return Ok(());
@ -255,7 +239,7 @@ pub async fn handle_role_unassign(
.await?;
drop(access);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildRoleUnassign,
seq,
@ -264,7 +248,6 @@ pub async fn handle_role_unassign(
user_id: req.user_id.clone(),
role_id: req.role_id.clone(),
}),
crypto,
)
.await?;
Ok(())
@ -276,7 +259,6 @@ pub async fn handle_role_list_fetch(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = GuildRoleListFetchPayload::decode(payload)?;
@ -295,7 +277,6 @@ pub async fn handle_role_list_fetch(
seq,
crate::proto::ErrorCode::PermissionDenied,
"guild membership required",
crypto,
)
.await?;
return Ok(());
@ -317,13 +298,6 @@ pub async fn handle_role_list_fetch(
guild_id: req.guild_id,
roles,
};
io::send_encrypted(
stream,
PacketId::GuildRoleList,
seq,
&to_payload(&resp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::GuildRoleList, seq, &to_payload(&resp)).await?;
Ok(())
}

View file

@ -12,7 +12,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::permissions::Permissions,
net::{io, state::State},
proto::{ErrorPayload, PacketId, SessionCrypto, to_payload},
proto::{ErrorPayload, PacketId, to_payload},
};
async fn send_err(
@ -20,9 +20,8 @@ async fn send_err(
seq: &mut u32,
code: crate::proto::ErrorCode,
msg: &str,
crypto: &SessionCrypto,
) -> Result<()> {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -30,7 +29,6 @@ async fn send_err(
code: code as u32,
message: msg.into(),
}),
crypto,
)
.await
}

View file

@ -5,7 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::{permissions::Permissions, session},
net::{io, state::State},
proto::{PacketId, RoleCreatePayload, RoleDeletePayload, SessionCrypto, to_payload},
proto::{PacketId, RoleCreatePayload, RoleDeletePayload, to_payload},
};
use super::send_err;
@ -15,7 +15,6 @@ pub async fn handle_role_create(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = RoleCreatePayload::decode(payload)?;
@ -38,7 +37,6 @@ pub async fn handle_role_create(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_ROLES permission",
crypto,
)
.await?;
return Ok(());
@ -57,7 +55,6 @@ pub async fn handle_role_create(
seq,
crate::proto::ErrorCode::PermissionDenied,
"cannot grant requested role",
crypto,
)
.await?;
return Ok(());
@ -79,7 +76,7 @@ pub async fn handle_role_create(
)
.await?;
drop(access);
io::send_encrypted(
io::send_frame(
stream,
PacketId::RoleCreate,
seq,
@ -90,7 +87,6 @@ pub async fn handle_role_create(
permissions: req.permissions,
id: role_id,
}),
crypto,
)
.await?;
Ok(())
@ -101,7 +97,6 @@ pub async fn handle_role_delete(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = RoleDeletePayload::decode(payload)?;
@ -124,7 +119,6 @@ pub async fn handle_role_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_ROLES permission",
crypto,
)
.await?;
return Ok(());
@ -137,7 +131,6 @@ pub async fn handle_role_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"role is outside this guild",
crypto,
)
.await?;
return Ok(());
@ -149,7 +142,6 @@ pub async fn handle_role_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"cannot manage requested role",
crypto,
)
.await?;
return Ok(());
@ -168,7 +160,7 @@ pub async fn handle_role_delete(
)
.await?;
drop(access);
io::send_encrypted(
io::send_frame(
stream,
PacketId::RoleDelete,
seq,
@ -176,7 +168,6 @@ pub async fn handle_role_delete(
guild_id: req.guild_id.clone(),
role_id: req.role_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -13,11 +13,10 @@ pub use run::run_session;
use tokio::io::{AsyncRead, AsyncWrite};
use crate::{net::state::State, proto::SessionCrypto};
use crate::net::state::State;
pub struct Ctx<'a, S: AsyncRead + AsyncWrite + Unpin> {
pub stream: &'a mut S,
pub seq: &'a mut u32,
pub crypto: &'a SessionCrypto,
pub state: &'a State,
}

View file

@ -5,39 +5,33 @@ use tracing::warn;
use crate::{
net::{io, state::BroadcastMsg, state::State},
proto::{self, PacketId, SessionCrypto, to_payload},
proto::{self, PacketId, to_payload},
};
use super::{Ctx, deliver::deliver_encrypted, dispatch};
use super::{Ctx, deliver::deliver_frame, dispatch};
pub async fn run_session<S: AsyncRead + AsyncWrite + Unpin>(
stream: &mut S,
addr: std::net::SocketAddr,
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
bcast_rx: &mut broadcast::Receiver<BroadcastMsg>,
) -> Result<()> {
let mut ctx = Ctx {
stream,
seq,
crypto,
state,
};
let mut reader = io::EncryptedReader::default();
let mut ctx = Ctx { stream, seq, state };
let mut reader = io::FrameReader::default();
loop {
tokio::select! {
result = reader.read(ctx.stream, ctx.crypto) => {
result = reader.read(ctx.stream) => {
let (hdr, payload) = result?;
let pid = match PacketId::from_u16(hdr.packet_id) {
Some(p) => p,
None => {
warn!("{addr} unknown 0x{:04X}", hdr.packet_id);
io::send_encrypted(ctx.stream, PacketId::Error, ctx.seq, &to_payload(&proto::ErrorPayload {
io::send_frame(ctx.stream, PacketId::Error, ctx.seq, &to_payload(&proto::ErrorPayload {
code: proto::ErrorCode::InvalidPacket as u32,
message: "unknown packet".into(),
}), ctx.crypto).await?;
})).await?;
continue;
}
};
@ -46,7 +40,7 @@ pub async fn run_session<S: AsyncRead + AsyncWrite + Unpin>(
}
bcast = bcast_rx.recv() => {
match bcast {
Ok(msg) => deliver_encrypted(ctx.stream, ctx.seq, session_id, &msg, ctx.crypto, ctx.state).await?,
Ok(msg) => deliver_frame(ctx.stream, ctx.seq, session_id, &msg, ctx.state).await?,
Err(broadcast::error::RecvError::Lagged(n)) => warn!("{addr} lagged {n}"),
Err(broadcast::error::RecvError::Closed) => return Ok(()),
}

View file

@ -5,6 +5,7 @@ pub mod handler;
pub mod media;
pub mod net;
pub mod proto;
pub mod tls;
pub mod webhooks;
use anyhow::Result;
@ -28,6 +29,10 @@ impl Drop for ConnGuard {
}
pub async fn run(cfg: Arc<config::Config>, voice_member_tx: Option<VoiceMemberTx>) -> Result<()> {
cfg.gateway.validate_tls()?;
if cfg.gateway.tls_enabled == Some(true) {
warn!("gateway.tls_enabled is deprecated: TLS 1.3 is always on, remove the option");
}
let private_mode = cfg.is_private();
if private_mode {
info!("private mode enabled, federation disabled");
@ -72,6 +77,26 @@ pub async fn run(cfg: Arc<config::Config>, voice_member_tx: Option<VoiceMemberTx
&server_pubkey[..8.min(server_pubkey.len())]
);
let material = tls::load_material(
&cfg.gateway,
&cfg.storage.data_dir,
&server_identity,
&cfg.node.address,
)?;
info!(
"TLS 1.3 certificate: {} (SPKI SHA-256 fingerprint {})",
if material.self_signed {
"self-signed, key = server identity"
} else {
"operator supplied"
},
tls::fingerprint_hex(&material.fingerprint)
);
if let Err(e) = tls::publish_fingerprint(&cfg.storage.data_dir, &material.fingerprint) {
warn!("could not write tls/fingerprint.txt: {e}");
}
let tls_config = tls::server_config(material)?;
let (tx, _) = broadcast::channel(256);
let metrics = admin::metrics::Metrics::new();
let sessions_count = Arc::new(AtomicUsize::new(0));
@ -130,71 +155,24 @@ pub async fn run(cfg: Arc<config::Config>, voice_member_tx: Option<VoiceMemberTx
tokio::spawn(admin::run(admin_bind, admin_state, state.clone()));
let listener = TcpListener::bind(&cfg.gateway.bind).await?;
info!("listening on {}", cfg.gateway.bind);
if cfg.gateway.tls_enabled {
run_tls(listener, cfg, state, max_connections, conn_count).await
} else {
run_plain(listener, state, max_connections, conn_count).await
}
info!("listening on {} (TLS 1.3)", cfg.gateway.bind);
run_tls(listener, tls_config, state, max_connections, conn_count).await
}
/// Grace period for the first byte of a connection. A TLS client speaks immediately;
/// an LNEx v2 client waits for the server HELLO and gets the explicit upgrade error.
const FIRST_BYTE_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
const TLS_HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
async fn run_tls(
listener: TcpListener,
cfg: Arc<config::Config>,
tls_config: Arc<rustls::ServerConfig>,
state: State,
max_connections: Option<usize>,
conn_count: Arc<AtomicUsize>,
) -> Result<()> {
let (certs, key) = load_or_generate_tls_certs(&cfg.gateway)?;
if cfg.gateway.tls_cert_path.is_none() {
warn!("using self-signed TLS certificate — clients must accept it manually");
}
let server_config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(certs, key)?;
let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config));
let acceptor = tokio_rustls::TlsAcceptor::from(tls_config);
loop {
match listener.accept().await {
Ok((stream, addr)) => {
let current = conn_count.load(std::sync::atomic::Ordering::Relaxed);
if let Some(limit) = max_connections
&& current >= limit
{
warn!("connection rejected from {addr}: at max_connections ({limit})");
drop(stream);
continue;
}
conn_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
info!("connection from {addr} (TLS)");
state.metrics.inc(&state.metrics.connections_total);
let s = state.clone();
let acceptor = acceptor.clone();
let conn_count_clone = conn_count.clone();
tokio::spawn(async move {
let _guard = ConnGuard(conn_count_clone);
match acceptor.accept(stream).await {
Ok(tls_stream) => {
if let Err(e) = handle(tls_stream, addr, s).await {
debug!("{addr} closed: {e}");
}
}
Err(e) => error!("TLS accept error from {addr}: {e}"),
}
});
}
Err(e) => error!("accept: {e}"),
}
}
}
async fn run_plain(
listener: TcpListener,
state: State,
max_connections: Option<usize>,
conn_count: Arc<AtomicUsize>,
) -> Result<()> {
loop {
match listener.accept().await {
Ok((stream, addr)) => {
@ -210,11 +188,33 @@ async fn run_plain(
info!("connection from {addr}");
state.metrics.inc(&state.metrics.connections_total);
let s = state.clone();
let acceptor = acceptor.clone();
let conn_count_clone = conn_count.clone();
tokio::spawn(async move {
let _guard = ConnGuard(conn_count_clone);
if let Err(e) = handle(stream, addr, s).await {
debug!("{addr} closed: {e}");
let mut stream = stream;
if !tls::looks_like_tls(&mut stream, FIRST_BYTE_GRACE).await {
s.metrics.inc(&s.metrics.auth_failures);
debug!("{addr} rejected: not a TLS 1.3 client");
return;
}
let accepted = tokio::time::timeout(TLS_HANDSHAKE_TIMEOUT, async {
let tls_stream = acceptor.accept(stream).await?;
let binding = tls::channel_binding(tls_stream.get_ref().1)?;
anyhow::Ok((tls_stream, binding))
})
.await;
match accepted {
Ok(Ok((tls_stream, binding))) => {
if let Err(e) = handle(tls_stream, addr, s, binding).await {
debug!("{addr} closed: {e}");
}
}
Ok(Err(e)) => {
s.metrics.inc(&s.metrics.auth_failures);
warn!("TLS handshake from {addr} failed: {e}");
}
Err(_) => warn!("TLS handshake from {addr} timed out"),
}
});
}
@ -227,11 +227,12 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
mut stream: S,
addr: std::net::SocketAddr,
state: State,
binding: [u8; tls::BINDING_LEN],
) -> Result<()> {
let mut seq = 0u32;
let (sess, crypto) = tokio::time::timeout(
let sess = tokio::time::timeout(
std::time::Duration::from_secs(15),
net::handshake::run(&mut stream, addr, &state, &mut seq),
net::handshake::run(&mut stream, addr, &state, &mut seq, &binding),
)
.await??;
let sid = sess.session_id.clone();
@ -240,26 +241,17 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut bcast_rx = state.broadcast.subscribe();
let result = handler::run_session(
&mut stream,
addr,
&mut seq,
&sid,
&crypto,
&state,
&mut bcast_rx,
)
.await;
let result =
handler::run_session(&mut stream, addr, &mut seq, &sid, &state, &mut bcast_rx).await;
if result.is_err() {
let p = proto::DisconnectPayload {
reason: "session closed".into(),
};
let _ = net::io::send_encrypted(
let _ = net::io::send_frame(
&mut stream,
proto::PacketId::Disconnect,
&mut seq,
&proto::to_payload(&p),
&crypto,
)
.await;
}
@ -327,32 +319,3 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
debug!("{addr} cleaned up");
result
}
fn load_or_generate_tls_certs(
cfg: &config::GatewayConfig,
) -> Result<(
Vec<rustls::pki_types::CertificateDer<'static>>,
rustls::pki_types::PrivateKeyDer<'static>,
)> {
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
match (&cfg.tls_cert_path, &cfg.tls_key_path) {
(Some(cert_path), Some(key_path)) => {
let cert_pem = std::fs::read_to_string(cert_path)?;
let key_pem = std::fs::read_to_string(key_path)?;
let cert = CertificateDer::from_pem_reader(&mut cert_pem.as_bytes())?;
let key = PrivateKeyDer::from_pem_reader(&mut key_pem.as_bytes())?;
Ok((vec![cert], key))
}
_ => {
info!("No TLS cert/key configured, generating self-signed certificate");
let certified_key = rcgen::generate_simple_self_signed(vec!["VNOX Server".into()])?;
let cert_der = certified_key.cert.der().clone();
let key_der = PrivateKeyDer::from(PrivatePkcs8KeyDer::from(
certified_key.signing_key.serialize_der(),
));
Ok((vec![cert_der], key_der))
}
}
}

View file

@ -294,7 +294,7 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
Ok(())
}
Err(error) => {
io::send_encrypted(
io::send_frame(
ctx.stream,
PacketId::Error,
ctx.seq,
@ -302,7 +302,6 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
code: proto::ErrorCode::PermissionDenied as u32,
message: format!("media: {error}"),
}),
ctx.crypto,
)
.await
}

View file

@ -7,26 +7,49 @@ use crate::{
domain::{auth, session},
net::io,
net::state::State,
proto::{self, AuthPayload, HelloPayload, PacketId, SessionCrypto, SessionPayload, to_payload},
proto::{self, AuthPayload, HelloPayload, PacketId, SessionPayload, to_payload},
};
const LNEX_VERSION: &str = "v2";
/// LNEx protocol version. v3 runs inside TLS 1.3 (see `docs/02-protocol/tls.md`).
pub const LNEX_VERSION: &str = "v3";
/// Run HELLO → AUTH → SESSION with X25519 ECDH key exchange.
const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v3-server-hello\0";
const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v3-client-auth\0";
/// Bytes the server identity signs: context, TLS exporter, HELLO without its signature.
pub fn server_hello_transcript(binding: &[u8], unsigned_hello: &[u8]) -> Vec<u8> {
let mut out = SERVER_HELLO_CONTEXT.to_vec();
out.extend_from_slice(binding);
out.extend_from_slice(unsigned_hello);
out
}
/// Bytes the client identity signs: context, TLS exporter, the signed HELLO, AUTH without
/// its signature. The exporter makes the signature valid for this TLS connection only.
pub fn client_auth_transcript(
binding: &[u8],
signed_hello: &[u8],
unsigned_auth: &[u8],
) -> Vec<u8> {
let mut out = CLIENT_AUTH_CONTEXT.to_vec();
out.extend_from_slice(binding);
out.extend_from_slice(&(signed_hello.len() as u32).to_be_bytes());
out.extend_from_slice(signed_hello);
out.extend_from_slice(unsigned_auth);
out
}
/// Run HELLO, AUTH, SESSION inside an established TLS 1.3 connection.
///
/// Returns the session and the derived crypto context (encryption keys).
/// All subsequent packets must be encrypted with `crypto`.
/// `binding` is the TLS exporter value of this connection; both signatures cover it.
pub async fn run(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
addr: std::net::SocketAddr,
state: &State,
seq: &mut u32,
) -> Result<(session::Session, SessionCrypto)> {
// Generate ephemeral X25519 keypair for forward secrecy
let (eph_sk, eph_pk) = SessionCrypto::new_ephemeral();
let eph_pk_raw = eph_pk.as_bytes();
// HELLO — include server's ephemeral public key + privacy mode
binding: &[u8],
) -> Result<session::Session> {
// HELLO: server key, challenge, privacy mode, signature bound to this TLS connection.
let challenge = auth::new_challenge();
let private_mode = state.config.is_private();
let mut hello = HelloPayload {
@ -34,22 +57,17 @@ pub async fn run(
server_pubkey: hex::decode(state.server_identity.pubkey_hex())?,
challenge_nonce: challenge.to_vec(),
node_name: state.config.node.name.clone(),
server_eph_pubkey: eph_pk_raw.to_vec(),
private_mode,
server_signature: Vec::new(),
};
let mut hello_transcript = b"VNOX-LNEx-v2-server-hello\0".to_vec();
hello_transcript.extend_from_slice(&hello.encode_to_vec());
let hello_transcript = server_hello_transcript(binding, &hello.encode_to_vec());
hello.server_signature = state.server_identity.sign(&hello_transcript);
io::send_packet(stream, PacketId::Hello, seq, &to_payload(&hello)).await?;
debug!("{addr} ← HELLO (eph key included)");
debug!("{addr} HELLO sent");
// AUTH — receive client's ephemeral public key
// AUTH
let (hdr, payload) = io::read_packet(stream).await?;
if PacketId::from_u16(hdr.packet_id) != Some(PacketId::Auth)
|| hdr.flags != 0
|| hdr.sequence != 0
{
if PacketId::from_u16(hdr.packet_id) != Some(PacketId::Auth) || hdr.sequence != 0 {
io::send_error(
stream,
seq,
@ -61,33 +79,32 @@ pub async fn run(
}
let msg = AuthPayload::decode(payload.as_slice())?;
anyhow::ensure!(
!msg.nickname.trim().is_empty() && msg.nickname.chars().count() <= 64,
"invalid nickname"
);
debug!("{addr} → AUTH");
if msg.lnex_version != LNEX_VERSION {
io::send_error(
stream,
seq,
proto::ErrorCode::VersionMismatch,
"unsupported version",
"unsupported version: LNEx v3 required",
)
.await?;
return Err(anyhow::anyhow!("version mismatch"));
}
anyhow::ensure!(
!msg.nickname.trim().is_empty() && msg.nickname.chars().count() <= 64,
"invalid nickname"
);
debug!("{addr} AUTH received");
let pubkey: [u8; 32] = msg.client_pubkey.as_slice().try_into()?;
let sig: [u8; 64] = msg.signature.as_slice().try_into()?;
let mut auth_without_signature = msg.clone();
auth_without_signature.signature.clear();
let hello_bytes = hello.encode_to_vec();
let mut auth_transcript = b"VNOX-LNEx-v2-client-auth\0".to_vec();
auth_transcript.extend_from_slice(&(hello_bytes.len() as u32).to_be_bytes());
auth_transcript.extend_from_slice(&hello_bytes);
auth_transcript.extend_from_slice(&auth_without_signature.encode_to_vec());
let auth_transcript = client_auth_transcript(
binding,
&hello.encode_to_vec(),
&auth_without_signature.encode_to_vec(),
);
if let Err(e) = auth::verify_auth(&auth_transcript, &pubkey, &sig) {
warn!("{addr} auth failed: {e}");
state.metrics.inc(&state.metrics.auth_failures);
@ -116,12 +133,6 @@ pub async fn run(
.upsert_user(&hex::encode(&msg.client_pubkey), &msg.nickname)
.await?;
// ECDH: compute shared secret from server's ephemeral sk + client's ephemeral pk
let client_eph_raw: [u8; 32] = msg.client_eph_pubkey.as_slice().try_into()?;
let client_eph_pk = x25519_dalek::PublicKey::from(client_eph_raw);
let shared_secret = SessionCrypto::ecdh(eph_sk, &client_eph_pk);
anyhow::ensure!(shared_secret.was_contributory(), "invalid ephemeral key");
// SESSION
let sess = session::create(
&state.sessions,
@ -130,9 +141,6 @@ pub async fn run(
)
.await;
// Derive encryption keys from shared secret + session_id
let crypto = SessionCrypto::derive(shared_secret.as_bytes(), &sess.session_id);
let timeout_secs = state.config.gateway.session_timeout.unwrap_or(600);
let expires_at = std::time::SystemTime::now()
.checked_add(std::time::Duration::from_secs(timeout_secs))
@ -146,10 +154,159 @@ pub async fn run(
};
io::send_packet(stream, PacketId::Session, seq, &to_payload(&sp)).await?;
info!(
"{addr} auth ok — nick={} sid={} encrypted",
"{addr} auth ok, nick={} sid={}",
sess.nickname,
&sess.session_id[..8]
);
Ok((sess, crypto))
Ok(sess)
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::{Signer, SigningKey};
use std::sync::{Arc, atomic::AtomicUsize};
use tokio::io::{AsyncWriteExt, DuplexStream};
async fn state() -> State {
let storage = crate::domain::storage::Storage::connect_sqlite(":memory:")
.await
.unwrap();
let config = toml::from_str(include_str!("../../../dev/config.toml")).unwrap();
let dir = std::env::temp_dir().join(format!("vnox-hs-test-{}", uuid::Uuid::new_v4()));
let identity =
crate::bootstrap::server_identity::ServerIdentity::load_or_generate(&dir).unwrap();
let _ = std::fs::remove_dir_all(dir);
let (broadcast, _) = tokio::sync::broadcast::channel(16);
State::new(
session::new_store(),
crate::domain::channels::new_store(),
Arc::new(storage),
Arc::new(config),
Arc::new(identity),
broadcast,
crate::admin::metrics::Metrics::new(),
Arc::new(AtomicUsize::new(0)),
Arc::new(AtomicUsize::new(0)),
None,
)
}
/// Minimal client: reads HELLO, signs AUTH over `client_binding`, sends it.
async fn client_auth(
peer: &mut DuplexStream,
client_binding: &[u8],
version: &str,
) -> HelloPayload {
let (hdr, payload) = io::read_packet(peer).await.unwrap();
assert_eq!(hdr.packet_id, PacketId::Hello as u16);
let hello = HelloPayload::decode(payload.as_slice()).unwrap();
let key = SigningKey::generate(&mut rand::rng());
let mut auth = AuthPayload {
client_pubkey: key.verifying_key().to_bytes().to_vec(),
nickname: "tester".into(),
lnex_version: version.into(),
signature: Vec::new(),
};
let transcript = client_auth_transcript(client_binding, &payload, &auth.encode_to_vec());
auth.signature = key.sign(&transcript).to_bytes().to_vec();
let mut seq = 0;
io::send_packet(peer, PacketId::Auth, &mut seq, &to_payload(&auth))
.await
.unwrap();
hello
}
async fn handshake(
server_binding: &[u8],
client_binding: &[u8],
version: &str,
) -> (Result<session::Session>, proto::ErrorPayload) {
let state = state().await;
let (mut server, mut peer) = tokio::io::duplex(65536);
let server_binding = server_binding.to_vec();
let task = tokio::spawn(async move {
let mut seq = 0;
let result = run(
&mut server,
"127.0.0.1:1".parse().unwrap(),
&state,
&mut seq,
&server_binding,
)
.await;
let _ = server.shutdown().await;
result
});
client_auth(&mut peer, client_binding, version).await;
let (hdr, payload) = io::read_packet(&mut peer).await.unwrap();
let error = if hdr.packet_id == PacketId::Error as u16 {
proto::ErrorPayload::decode(payload.as_slice()).unwrap()
} else {
assert_eq!(hdr.packet_id, PacketId::Session as u16);
proto::ErrorPayload::default()
};
(task.await.unwrap(), error)
}
#[tokio::test]
async fn signature_for_the_same_channel_binding_is_accepted() {
let (result, _) = handshake(&[9; 32], &[9; 32], LNEX_VERSION).await;
result.unwrap();
}
#[tokio::test]
async fn client_signature_cannot_be_replayed_on_another_connection() {
// The AUTH was signed for TLS connection A (binding [1;32]) but arrives on B ([2;32]).
let (result, error) = handshake(&[2; 32], &[1; 32], LNEX_VERSION).await;
assert!(result.is_err());
assert_eq!(error.code, proto::ErrorCode::AuthFailed as u32);
}
#[tokio::test]
async fn old_protocol_version_is_rejected_with_explicit_error() {
let (result, error) = handshake(&[3; 32], &[3; 32], "v2").await;
assert!(result.is_err());
assert_eq!(error.code, proto::ErrorCode::VersionMismatch as u32);
assert!(error.message.contains("v3"));
}
#[tokio::test]
async fn server_hello_signature_is_bound_to_the_connection() {
let state = state().await;
let verifying = ed25519_dalek::VerifyingKey::from_bytes(
&hex::decode(state.server_identity.pubkey_hex())
.unwrap()
.try_into()
.unwrap(),
)
.unwrap();
let (mut server, mut peer) = tokio::io::duplex(65536);
tokio::spawn(async move {
let mut seq = 0;
let _ = run(
&mut server,
"127.0.0.1:1".parse().unwrap(),
&state,
&mut seq,
&[5; 32],
)
.await;
});
let (_, payload) = io::read_packet(&mut peer).await.unwrap();
let mut hello = HelloPayload::decode(payload.as_slice()).unwrap();
let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature).unwrap();
hello.server_signature.clear();
let unsigned = hello.encode_to_vec();
verifying
.verify_strict(&server_hello_transcript(&[5; 32], &unsigned), &signature)
.unwrap();
assert!(
verifying
.verify_strict(&server_hello_transcript(&[6; 32], &unsigned), &signature)
.is_err(),
"a relay with a different TLS session cannot reuse the server HELLO"
);
}
}

View file

@ -1,10 +1,10 @@
//! LNEx v3 TCP framing. Frames are written directly into the TLS 1.3 stream, so there is
//! no per frame encryption: the 12 byte header is followed by the protobuf payload and
//! `flags` must be zero on the control plane.
use anyhow::Result;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use crate::proto::{
ErrorCode, ErrorPayload, PacketHeader, PacketId, SessionCrypto, encode_packet, flags,
to_payload,
};
use crate::proto::{ErrorCode, ErrorPayload, PacketHeader, PacketId, encode_packet, to_payload};
const MAX_PAYLOAD: u32 = 4 * 1024 * 1024;
@ -14,6 +14,11 @@ pub async fn send_packet(
seq: &mut u32,
payload: &[u8],
) -> Result<()> {
anyhow::ensure!(
payload.len() <= MAX_PAYLOAD as usize,
"payload too large: {}",
payload.len()
);
let data = encode_packet(id, *seq, payload);
*seq = seq.wrapping_add(1);
stream.write_all(&data).await?;
@ -34,15 +39,18 @@ pub async fn send_error(
send_packet(stream, PacketId::Error, seq, &to_payload(&p)).await
}
/// Read one frame during the handshake (strictly `flags == 0`).
pub async fn read_packet(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
) -> Result<(PacketHeader, Vec<u8>)> {
let mut buf = [0u8; PacketHeader::SIZE];
stream.read_exact(&mut buf).await?;
let hdr = PacketHeader::from_bytes(&buf);
if hdr.flags & !flags::KNOWN_MASK != 0 {
return Err(anyhow::anyhow!("unknown packet flags: 0x{:04X}", hdr.flags));
}
anyhow::ensure!(
hdr.flags == 0,
"unsupported packet flags: 0x{:04X}",
hdr.flags
);
if hdr.payload_length > MAX_PAYLOAD {
return Err(anyhow::anyhow!("payload too large: {}", hdr.payload_length));
}
@ -53,114 +61,68 @@ pub async fn read_packet(
Ok((hdr, payload))
}
pub async fn send_encrypted(
/// Send one session frame. The sequence number never wraps inside a connection.
pub async fn send_frame(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
id: PacketId,
seq: &mut u32,
payload: &[u8],
crypto: &SessionCrypto,
) -> Result<()> {
anyhow::ensure!(*seq < u32::MAX, "session sequence exhausted");
anyhow::ensure!(
payload.len() <= MAX_PAYLOAD as usize - 16,
"payload too large"
);
let flags_val = flags::ENCRYPTED;
let mut hdr_buf = [0u8; PacketHeader::SIZE];
hdr_buf[0..2].copy_from_slice(&(id as u16).to_be_bytes());
hdr_buf[2..4].copy_from_slice(&flags_val.to_be_bytes());
hdr_buf[4..8].copy_from_slice(&seq.to_be_bytes());
hdr_buf[8..12].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes());
let encrypted = crypto.encrypt_s2c_frame(*seq as u64, payload, &hdr_buf);
*seq += 1;
let mut out = Vec::with_capacity(PacketHeader::SIZE + encrypted.len());
out.extend_from_slice(&hdr_buf);
out.extend_from_slice(&encrypted);
stream.write_all(&out).await?;
Ok(())
send_packet(stream, id, seq, payload).await
}
pub async fn read_encrypted(
/// Forward a pre-encoded broadcast packet (`header || payload`) re-sequenced for this session.
pub async fn deliver_frame(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
crypto: &SessionCrypto,
) -> Result<(PacketHeader, Vec<u8>)> {
let mut buf = [0u8; PacketHeader::SIZE];
stream.read_exact(&mut buf).await?;
let hdr = PacketHeader::from_bytes(&buf);
if hdr.flags & !flags::KNOWN_MASK != 0 {
return Err(anyhow::anyhow!("unknown packet flags: 0x{:04X}", hdr.flags));
}
if hdr.flags & flags::ENCRYPTED == 0 {
return Err(anyhow::anyhow!("packet not encrypted"));
}
if hdr.payload_length > MAX_PAYLOAD {
return Err(anyhow::anyhow!("payload too large: {}", hdr.payload_length));
}
let mut encrypted = vec![0u8; hdr.payload_length as usize];
if !encrypted.is_empty() {
stream.read_exact(&mut encrypted).await?;
}
let payload = crypto.decrypt_c2s_frame(hdr.sequence as u64, &encrypted, &buf)?;
Ok((hdr, payload))
}
pub async fn deliver_encrypted(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
crypto: &SessionCrypto,
seq: &mut u32,
raw_data: &[u8],
) -> Result<()> {
if raw_data.len() < PacketHeader::SIZE {
return Err(anyhow::anyhow!("deliver: packet too short"));
}
let raw_hdr = PacketHeader::from_bytes(raw_data[..PacketHeader::SIZE].try_into().unwrap());
let pid = match PacketId::from_u16(raw_hdr.packet_id) {
Some(p) => p,
None => {
return Err(anyhow::anyhow!(
"deliver: unknown packet id 0x{:04X}",
raw_hdr.packet_id
));
}
};
let payload = &raw_data[PacketHeader::SIZE..];
send_encrypted(stream, pid, seq, payload, crypto).await
let raw_hdr = PacketHeader::from_bytes(
raw_data[..PacketHeader::SIZE]
.try_into()
.map_err(|_| anyhow::anyhow!("deliver: bad header"))?,
);
let pid = PacketId::from_u16(raw_hdr.packet_id)
.ok_or_else(|| anyhow::anyhow!("deliver: unknown packet id 0x{:04X}", raw_hdr.packet_id))?;
send_frame(stream, pid, seq, &raw_data[PacketHeader::SIZE..]).await
}
/// Incremental framing state survives cancellation by broadcast delivery.
pub struct EncryptedReader {
pub struct FrameReader {
bytes: Vec<u8>,
expected_sequence: u32,
}
impl Default for EncryptedReader {
impl Default for FrameReader {
fn default() -> Self {
Self {
bytes: Vec::new(),
// The client AUTH used sequence 0, the first session frame is 1.
expected_sequence: 1,
}
}
}
impl EncryptedReader {
impl FrameReader {
pub async fn read(
&mut self,
stream: &mut (impl AsyncRead + Unpin),
crypto: &SessionCrypto,
) -> Result<(PacketHeader, Vec<u8>)> {
loop {
let needed = if self.bytes.len() < PacketHeader::SIZE {
PacketHeader::SIZE
} else {
let header: &[u8; PacketHeader::SIZE] =
self.bytes[..PacketHeader::SIZE].try_into().unwrap();
let hdr = PacketHeader::from_bytes(header);
let header: [u8; PacketHeader::SIZE] = self.bytes[..PacketHeader::SIZE]
.try_into()
.map_err(|_| anyhow::anyhow!("short header"))?;
let hdr = PacketHeader::from_bytes(&header);
anyhow::ensure!(hdr.flags == 0, "unsupported frame flags");
anyhow::ensure!(
hdr.flags == flags::ENCRYPTED,
"unsupported encrypted frame flags"
);
anyhow::ensure!(
hdr.payload_length >= 16 && hdr.payload_length <= MAX_PAYLOAD,
"invalid encrypted payload size"
hdr.payload_length <= MAX_PAYLOAD,
"payload too large: {}",
hdr.payload_length
);
anyhow::ensure!(
hdr.sequence == self.expected_sequence && hdr.sequence < u32::MAX,
@ -168,15 +130,12 @@ impl EncryptedReader {
);
PacketHeader::SIZE + hdr.payload_length as usize
};
if self.bytes.len() == needed && needed > PacketHeader::SIZE {
let header: &[u8; PacketHeader::SIZE] =
self.bytes[..PacketHeader::SIZE].try_into().unwrap();
let hdr = PacketHeader::from_bytes(header);
let payload = crypto.decrypt_c2s_frame(
hdr.sequence as u64,
&self.bytes[PacketHeader::SIZE..],
header,
)?;
if self.bytes.len() == needed && self.bytes.len() >= PacketHeader::SIZE {
let header: [u8; PacketHeader::SIZE] = self.bytes[..PacketHeader::SIZE]
.try_into()
.map_err(|_| anyhow::anyhow!("short header"))?;
let hdr = PacketHeader::from_bytes(&header);
let payload = self.bytes[PacketHeader::SIZE..].to_vec();
self.bytes.clear();
self.expected_sequence += 1;
return Ok((hdr, payload));
@ -193,49 +152,52 @@ impl EncryptedReader {
#[cfg(test)]
mod reader_tests {
use super::*;
fn frame(crypto: &SessionCrypto, seq: u32) -> Vec<u8> {
let mut header = [0u8; 12];
header[..2].copy_from_slice(&(PacketId::Ping as u16).to_be_bytes());
header[2..4].copy_from_slice(&flags::ENCRYPTED.to_be_bytes());
header[4..8].copy_from_slice(&seq.to_be_bytes());
header[8..].copy_from_slice(&20u32.to_be_bytes());
let mut bytes = header.to_vec();
bytes.extend_from_slice(&crypto.encrypt_c2s_frame(seq as u64, b"ping", &header));
fn frame(seq: u32, flags: u16, body: &[u8]) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.extend_from_slice(&(PacketId::Ping as u16).to_be_bytes());
bytes.extend_from_slice(&flags.to_be_bytes());
bytes.extend_from_slice(&seq.to_be_bytes());
bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
bytes.extend_from_slice(body);
bytes
}
#[tokio::test]
async fn cancelled_partial_read_preserves_framing_and_rejects_replay() {
let crypto = SessionCrypto::derive(&[7; 32], "fixture");
let bytes = frame(&crypto, 1);
let bytes = frame(1, 0, b"ping");
let (mut server, mut peer) = tokio::io::duplex(128);
let mut reader = EncryptedReader::default();
let mut reader = FrameReader::default();
peer.write_all(&bytes[..5]).await.unwrap();
assert!(
tokio::time::timeout(
std::time::Duration::from_millis(2),
reader.read(&mut server, &crypto)
reader.read(&mut server)
)
.await
.is_err()
);
peer.write_all(&bytes[5..]).await.unwrap();
let (_, body) = reader.read(&mut server, &crypto).await.unwrap();
let (_, body) = reader.read(&mut server).await.unwrap();
assert_eq!(body, b"ping");
peer.write_all(&bytes).await.unwrap();
assert!(reader.read(&mut server, &crypto).await.is_err());
assert!(reader.read(&mut server).await.is_err());
}
#[tokio::test]
async fn modifying_authenticated_packet_type_is_rejected() {
let crypto = SessionCrypto::derive(&[7; 32], "fixture");
let mut bytes = frame(&crypto, 1);
bytes[1] ^= 1;
async fn legacy_encrypted_flag_is_rejected() {
let bytes = frame(1, crate::proto::flags::ENCRYPTED, b"0123456789abcdef");
let (mut server, mut peer) = tokio::io::duplex(128);
peer.write_all(&bytes).await.unwrap();
assert!(
EncryptedReader::default()
.read(&mut server, &crypto)
.await
.is_err()
);
let error = FrameReader::default().read(&mut server).await.unwrap_err();
assert!(error.to_string().contains("flags"));
}
#[tokio::test]
async fn out_of_order_sequence_is_rejected() {
let bytes = frame(2, 0, b"");
let (mut server, mut peer) = tokio::io::duplex(128);
peer.write_all(&bytes).await.unwrap();
assert!(FrameReader::default().read(&mut server).await.is_err());
}
}

View file

@ -1,4 +1,3 @@
mod crypto;
mod framing;
mod packet;
@ -8,8 +7,6 @@ pub mod lnex {
pub use lnex::*;
pub use crypto::SessionCrypto;
// Re-export everything so `crate::proto::X` works as before
pub use framing::{encode_packet, to_payload};
pub use packet::{ErrorCode, PacketHeader, PacketId, flags};

388
gateway/src/tls.rs Normal file
View file

@ -0,0 +1,388 @@
//! TLS 1.3 for the TCP control plane (LNEx v3). See `docs/02-protocol/tls.md`.
//!
//! * TLS 1.3 only, ALPN `vnox-lnex/3`, no client certificates, no plaintext fallback.
//! * Certificate: user supplied (PEM chain + key) or auto generated and stored in the data
//! directory. The auto generated certificate is signed with the server identity Ed25519
//! key, so its SPKI fingerprint is a pure function of the identity.
//! * Channel binding: both sides derive a 32 byte TLS exporter value that is signed by the
//! LNEx handshake, so signatures cannot be replayed on another connection.
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
use sha2::{Digest, Sha256};
use crate::bootstrap::server_identity::ServerIdentity;
use crate::domain::config::GatewayConfig;
/// Application protocol negotiated through ALPN. A connection without it is dropped.
pub const ALPN: &[u8] = b"vnox-lnex/3";
/// TLS exporter label (RFC 5705 / RFC 8446 section 7.5) used for the channel binding.
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding";
/// Size of the exported channel binding value.
pub const BINDING_LEN: usize = 32;
/// Message shown to peers that do not speak TLS 1.3 (old LNEx v2 clients, plaintext probes).
pub const LEGACY_MESSAGE: &str = "TLS 1.3 required (LNEx v3): update your client";
/// Certificate chain, private key and the fingerprint of the leaf public key.
pub struct TlsMaterial {
pub chain: Vec<CertificateDer<'static>>,
pub key: PrivateKeyDer<'static>,
/// SHA-256 of the leaf SubjectPublicKeyInfo DER.
pub fingerprint: [u8; 32],
/// `true` when the certificate was generated by the gateway (not supplied by the operator).
pub self_signed: bool,
}
/// Lower-case hex of a fingerprint.
pub fn fingerprint_hex(fingerprint: &[u8; 32]) -> String {
hex::encode(fingerprint)
}
/// Read one DER TLV at the start of `data`: `(tag, header_len, content_len)`.
fn read_tlv(data: &[u8]) -> Result<(u8, usize, usize)> {
let tag = *data.first().context("truncated DER")?;
let first = *data.get(1).context("truncated DER")?;
let (header, length) = if first & 0x80 == 0 {
(2usize, first as usize)
} else {
let count = (first & 0x7F) as usize;
if count == 0 || count > 4 {
bail!("unsupported DER length");
}
let bytes = data.get(2..2 + count).context("truncated DER")?;
(
2 + count,
bytes.iter().fold(0usize, |acc, b| (acc << 8) | *b as usize),
)
};
if data.len() < header + length {
bail!("truncated DER");
}
Ok((tag, header, length))
}
/// Extract the complete SubjectPublicKeyInfo SEQUENCE (header included) from a certificate.
pub fn spki_der(cert_der: &[u8]) -> Result<&[u8]> {
let (tag, header, length) = read_tlv(cert_der)?;
anyhow::ensure!(tag == 0x30, "certificate is not a SEQUENCE");
let tbs_all = &cert_der[header..header + length];
let (tag, header, length) = read_tlv(tbs_all)?;
anyhow::ensure!(tag == 0x30, "tbsCertificate is not a SEQUENCE");
let mut rest = &tbs_all[header..header + length];
// Optional [0] version, then serial, signature, issuer, validity, subject.
let mut skip = if rest.first() == Some(&0xA0) { 6 } else { 5 };
// `skip` counts fields before SubjectPublicKeyInfo: [version], serial, sigalg, issuer, validity, subject.
while skip > 0 {
let (_, header, length) = read_tlv(rest)?;
rest = &rest[header + length..];
skip -= 1;
}
let (tag, header, length) = read_tlv(rest)?;
anyhow::ensure!(tag == 0x30, "SubjectPublicKeyInfo is not a SEQUENCE");
Ok(&rest[..header + length])
}
/// SHA-256 over the SubjectPublicKeyInfo DER of a certificate.
pub fn spki_fingerprint(cert_der: &[u8]) -> Result<[u8; 32]> {
Ok(Sha256::digest(spki_der(cert_der)?).into())
}
/// PKCS#8 v1 wrapper for a raw Ed25519 seed (RFC 8410).
pub fn ed25519_pkcs8(seed: &[u8; 32]) -> Vec<u8> {
let mut der = vec![
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04,
0x20,
];
der.extend_from_slice(seed);
der
}
fn self_signed_pem_path(data_dir: &Path) -> std::path::PathBuf {
data_dir.join("tls").join("self-signed.pem")
}
fn parse_chain(pem: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
CertificateDer::pem_slice_iter(pem)
.collect::<std::result::Result<Vec<_>, _>>()
.context("invalid certificate PEM")
}
/// Generate a self-signed certificate whose key is the server identity key.
fn generate_self_signed(
seed: &[u8; 32],
node_address: &str,
) -> Result<(CertificateDer<'static>, String)> {
use rcgen::{CertificateParams, DnType, KeyPair, PKCS_ED25519, SanType, date_time_ymd};
let pkcs8 = PrivatePkcs8KeyDer::from(ed25519_pkcs8(seed));
let key_pair = KeyPair::from_pkcs8_der_and_sign_algo(&pkcs8, &PKCS_ED25519)
.context("server identity key rejected by rcgen")?;
let mut names = vec!["localhost".to_string()];
let host = node_address.trim();
if !host.is_empty() && host != "localhost" && host.parse::<std::net::IpAddr>().is_err() {
names.push(host.to_string());
}
let mut params = CertificateParams::new(names).context("invalid certificate names")?;
for ip in [
std::net::IpAddr::from([127, 0, 0, 1]),
std::net::IpAddr::from(std::net::Ipv6Addr::LOCALHOST),
] {
params.subject_alt_names.push(SanType::IpAddress(ip));
}
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
params.subject_alt_names.push(SanType::IpAddress(ip));
}
params
.distinguished_name
.push(DnType::CommonName, "VNOX gateway");
// Pinned clients ignore validity; keep it long so tools that check it do not complain.
params.not_before = date_time_ymd(2024, 1, 1);
params.not_after = date_time_ymd(2124, 1, 1);
let cert = params.self_signed(&key_pair)?;
Ok((cert.der().clone(), cert.pem()))
}
fn write_atomically(path: &Path, contents: &str) -> Result<()> {
let parent = path.parent().context("path has no parent")?;
std::fs::create_dir_all(parent)?;
let temporary = parent.join(format!(".tls-{}.tmp", uuid::Uuid::new_v4()));
std::fs::write(&temporary, contents)?;
std::fs::rename(&temporary, path).inspect_err(|_| {
let _ = std::fs::remove_file(&temporary);
})?;
Ok(())
}
/// Load the operator certificate or the stored self-signed certificate (generating it
/// when missing, unreadable or not matching the server identity).
pub fn load_material(
cfg: &GatewayConfig,
data_dir: &Path,
identity: &ServerIdentity,
node_address: &str,
) -> Result<TlsMaterial> {
match (&cfg.tls_cert_path, &cfg.tls_key_path) {
(Some(cert_path), Some(key_path)) => {
let chain = parse_chain(
&std::fs::read(cert_path).with_context(|| format!("read {cert_path}"))?,
)?;
anyhow::ensure!(!chain.is_empty(), "no certificate found in {cert_path}");
let key = PrivateKeyDer::from_pem_slice(
&std::fs::read(key_path).with_context(|| format!("read {key_path}"))?,
)
.context("invalid private key PEM")?;
let fingerprint = spki_fingerprint(chain[0].as_ref())?;
Ok(TlsMaterial {
chain,
key,
fingerprint,
self_signed: false,
})
}
(None, None) => {
let seed = identity.signing_seed();
let expected = {
let (der, _) = generate_self_signed(&seed, node_address)?;
spki_fingerprint(der.as_ref())?
};
let path = self_signed_pem_path(data_dir);
let stored = std::fs::read(&path)
.ok()
.and_then(|pem| parse_chain(&pem).ok())
.filter(|chain| {
chain
.first()
.and_then(|c| spki_fingerprint(c.as_ref()).ok())
.is_some_and(|f| f == expected)
});
let chain = match stored {
Some(chain) => chain,
None => {
let (der, pem) = generate_self_signed(&seed, node_address)?;
write_atomically(&path, &pem)?;
vec![der]
}
};
let key = PrivateKeyDer::from(PrivatePkcs8KeyDer::from(ed25519_pkcs8(&seed)));
Ok(TlsMaterial {
chain,
key,
fingerprint: expected,
self_signed: true,
})
}
_ => bail!("tls_cert_path and tls_key_path must be set together"),
}
}
/// Write the public fingerprint next to the certificate for operators.
pub fn publish_fingerprint(data_dir: &Path, fingerprint: &[u8; 32]) -> Result<()> {
write_atomically(
&data_dir.join("tls").join("fingerprint.txt"),
&format!("{}\n", fingerprint_hex(fingerprint)),
)
}
/// Server config: TLS 1.3 only with the required ALPN.
pub fn server_config(material: TlsMaterial) -> Result<Arc<rustls::ServerConfig>> {
let mut config = rustls::ServerConfig::builder_with_provider(Arc::new(
rustls::crypto::aws_lc_rs::default_provider(),
))
.with_protocol_versions(&[&rustls::version::TLS13])?
.with_no_client_auth()
.with_single_cert(material.chain, material.key)
.context("certificate and private key do not match")?;
config.alpn_protocols = vec![ALPN.to_vec()];
Ok(Arc::new(config))
}
/// Channel binding of an established server side session.
pub fn channel_binding(connection: &rustls::ServerConnection) -> Result<[u8; BINDING_LEN]> {
anyhow::ensure!(
connection.protocol_version() == Some(rustls::ProtocolVersion::TLSv1_3),
"TLS 1.3 required"
);
anyhow::ensure!(
connection.alpn_protocol() == Some(ALPN),
"ALPN vnox-lnex/3 required"
);
connection
.export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None)
.context("TLS exporter unavailable")
}
/// Reply to a peer that did not start a TLS handshake. This is the only plaintext the
/// gateway writes and it carries no secret.
pub async fn reject_legacy(stream: &mut tokio::net::TcpStream) {
use tokio::io::AsyncWriteExt;
let payload = crate::proto::to_payload(&crate::proto::ErrorPayload {
code: crate::proto::ErrorCode::VersionMismatch as u32,
message: LEGACY_MESSAGE.into(),
});
let frame = crate::proto::encode_packet(crate::proto::PacketId::Error, 0, &payload);
let _ = stream.write_all(&frame).await;
let _ = stream.shutdown().await;
}
/// First byte of a TLS handshake record.
const TLS_HANDSHAKE_RECORD: u8 = 0x16;
/// Wait briefly for the first byte. `true` means "looks like TLS, continue".
/// Anything else (no bytes within the grace period, other first byte) is answered with
/// the legacy error and `false`.
pub async fn looks_like_tls(
stream: &mut tokio::net::TcpStream,
grace: std::time::Duration,
) -> bool {
let mut first = [0u8; 1];
match tokio::time::timeout(grace, stream.peek(&mut first)).await {
Ok(Ok(1)) if first[0] == TLS_HANDSHAKE_RECORD => true,
Ok(Ok(0)) | Ok(Err(_)) => false,
_ => {
reject_legacy(stream).await;
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn identity(dir: &Path) -> ServerIdentity {
ServerIdentity::load_or_generate(dir).unwrap()
}
fn temp_dir() -> std::path::PathBuf {
std::env::temp_dir().join(format!("vnox-tls-{}", uuid::Uuid::new_v4()))
}
fn cfg() -> GatewayConfig {
toml::from_str("bind = \"127.0.0.1:0\"").unwrap()
}
#[test]
fn self_signed_fingerprint_is_sha256_of_identity_spki() {
let dir = temp_dir();
let id = identity(&dir);
let material = load_material(&cfg(), &dir, &id, "chat.example.org").unwrap();
// SPKI of an Ed25519 key is a fixed 12 byte prefix followed by the 32 byte key.
let mut spki = vec![
0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
];
spki.extend_from_slice(&hex::decode(id.pubkey_hex()).unwrap());
let expected: [u8; 32] = Sha256::digest(&spki).into();
assert_eq!(material.fingerprint, expected);
assert_eq!(
spki_der(material.chain[0].as_ref()).unwrap(),
spki.as_slice()
);
assert!(material.self_signed);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn self_signed_certificate_is_stored_and_reused() {
let dir = temp_dir();
let id = identity(&dir);
let first = load_material(&cfg(), &dir, &id, "127.0.0.1").unwrap();
let path = dir.join("tls").join("self-signed.pem");
let stored = std::fs::read(&path).unwrap();
let second = load_material(&cfg(), &dir, &id, "127.0.0.1").unwrap();
assert_eq!(first.chain[0], second.chain[0]);
assert_eq!(std::fs::read(&path).unwrap(), stored);
// A certificate for a different key is replaced.
let other = temp_dir();
let other_id = identity(&other);
let swapped = load_material(&cfg(), &dir, &other_id, "127.0.0.1").unwrap();
assert_ne!(swapped.fingerprint, first.fingerprint);
std::fs::remove_dir_all(dir).unwrap();
std::fs::remove_dir_all(other).unwrap();
}
#[test]
fn operator_certificate_requires_both_paths() {
let dir = temp_dir();
let id = identity(&dir);
let mut partial = cfg();
partial.tls_cert_path = Some("/nonexistent/cert.pem".into());
assert!(load_material(&partial, &dir, &id, "x").is_err());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn operator_certificate_is_loaded_and_fingerprinted() {
let dir = temp_dir();
let id = identity(&dir);
std::fs::create_dir_all(&dir).unwrap();
let key = rcgen::KeyPair::generate().unwrap();
let cert = rcgen::CertificateParams::new(vec!["chat.example.org".into()])
.unwrap()
.self_signed(&key)
.unwrap();
let cert_path = dir.join("cert.pem");
let key_path = dir.join("key.pem");
std::fs::write(&cert_path, cert.pem()).unwrap();
std::fs::write(&key_path, key.serialize_pem()).unwrap();
let mut config = cfg();
config.tls_cert_path = Some(cert_path.to_string_lossy().into());
config.tls_key_path = Some(key_path.to_string_lossy().into());
let material = load_material(&config, &dir, &id, "x").unwrap();
assert!(!material.self_signed);
assert_eq!(
material.fingerprint,
spki_fingerprint(cert.der().as_ref()).unwrap()
);
server_config(material).unwrap();
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn spki_parser_rejects_garbage() {
assert!(spki_der(&[]).is_err());
assert!(spki_der(&[0x30, 0x03, 0x01, 0x02]).is_err());
assert!(spki_der(b"not a certificate").is_err());
}
}

View file

@ -102,12 +102,11 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
.iter()
.map(info)
.collect();
return io::send_encrypted(
return io::send_frame(
ctx.stream,
PacketId::WebhookListResult,
ctx.seq,
&to_payload(&WebhookListResult { hooks, request_id }),
ctx.crypto,
)
.await;
}
@ -221,7 +220,7 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
}
h
};
io::send_encrypted(
io::send_frame(
ctx.stream,
PacketId::WebhookResult,
ctx.seq,
@ -230,7 +229,6 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
secret,
request_id,
}),
ctx.crypto,
)
.await
}
@ -240,7 +238,7 @@ async fn error<S: AsyncRead + AsyncWrite + Unpin>(
code: ErrorCode,
msg: &str,
) -> Result<()> {
io::send_encrypted(
io::send_frame(
ctx.stream,
PacketId::WebhookErrorResult,
ctx.seq,
@ -249,7 +247,6 @@ async fn error<S: AsyncRead + AsyncWrite + Unpin>(
code: code as u32,
message: msg.into(),
}),
ctx.crypto,
)
.await
}

View file

@ -327,7 +327,7 @@ fn rate_limit_and_content_boundaries() {
#[tokio::test]
async fn lnex_management_rejects_stranger_and_creates_only_for_owner() {
use crate::proto::{PacketId, SessionCrypto, WebhookRequest, flags, to_payload};
use crate::proto::{PacketId, WebhookRequest, to_payload};
let (s, _, _) = fixture().await;
let req = WebhookRequest {
id: String::new(),
@ -343,13 +343,11 @@ async fn lnex_management_rejects_stranger_and_creates_only_for_owner() {
("owner", PacketId::WebhookResult),
] {
let session = session::create(&s.sessions, user.into(), user.into()).await;
let crypto = SessionCrypto::derive(&[3; 32], &session.session_id);
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut seq = 0;
let mut ctx = crate::handler::Ctx {
stream: &mut stream,
seq: &mut seq,
crypto: &crypto,
state: &s,
};
management::handle(
@ -362,7 +360,10 @@ async fn lnex_management_rejects_stranger_and_creates_only_for_owner() {
.unwrap();
let (header, _) = crate::net::io::read_packet(&mut peer).await.unwrap();
assert_eq!(header.packet_id, expected as u16);
assert_ne!(header.flags & flags::ENCRYPTED, 0);
assert_eq!(
header.flags, 0,
"TLS protects the stream; frames carry no flags"
);
}
let hooks = s.storage.hooks("target").await.unwrap();
assert_eq!(hooks.len(), 2);

View file

@ -0,0 +1,321 @@
//! Black box tests of the gateway TCP listener: TLS 1.3 only, ALPN, legacy rejection,
//! certificate fingerprint and the channel bound LNEx v3 handshake.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use ed25519_dalek::{Signer, SigningKey};
use prost::Message;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{DigitallySignedStruct, SignatureScheme};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use vnox_gateway::net::handshake::{LNEX_VERSION, client_auth_transcript, server_hello_transcript};
use vnox_gateway::proto::{AuthPayload, ErrorCode, ErrorPayload, HelloPayload, PacketId};
use vnox_gateway::tls::{ALPN, EXPORTER_LABEL, spki_fingerprint};
struct Server {
task: tokio::task::JoinHandle<()>,
port: u16,
directory: std::path::PathBuf,
}
impl Drop for Server {
fn drop(&mut self) {
self.task.abort();
let _ = std::fs::remove_dir_all(&self.directory);
}
}
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port()
}
async fn start() -> Server {
let directory = std::env::temp_dir().join(format!("vnox-tls-it-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&directory).unwrap();
let port = free_port();
let config = format!(
r#"
[node]
name = "tls-test"
address = "127.0.0.1"
[gateway]
bind = "127.0.0.1:{port}"
admin_bind = "127.0.0.1:0"
[voice]
bind = "127.0.0.1:0"
[storage]
data_dir = "{dir}"
backend = "sqlite"
sqlite_path = "{dir}/t.db"
[server]
mode = "private"
"#,
dir = directory.display()
);
let cfg: vnox_gateway::domain::config::Config = toml::from_str(&config).unwrap();
let task = tokio::spawn(async move {
let _ = vnox_gateway::run(Arc::new(cfg), None).await;
});
for _ in 0..200 {
if TcpStream::connect(("127.0.0.1", port)).await.is_ok() {
return Server {
task,
port,
directory,
};
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!("gateway did not start");
}
/// Accepts every certificate (the tests pin the fingerprint themselves) but still checks
/// the TLS 1.3 handshake signature.
#[derive(Debug)]
struct AcceptAll {
leaf: Mutex<Option<Vec<u8>>>,
}
impl ServerCertVerifier for AcceptAll {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
_: &[CertificateDer<'_>],
_: &ServerName<'_>,
_: &[u8],
_: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
*self.leaf.lock().unwrap() = Some(end_entity.to_vec());
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(
message,
cert,
dss,
&rustls::crypto::aws_lc_rs::default_provider().signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(
message,
cert,
dss,
&rustls::crypto::aws_lc_rs::default_provider().signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
rustls::crypto::aws_lc_rs::default_provider()
.signature_verification_algorithms
.supported_schemes()
}
}
fn client_config(
versions: &[&'static rustls::SupportedProtocolVersion],
alpn: bool,
) -> (rustls::ClientConfig, Arc<AcceptAll>) {
let verifier = Arc::new(AcceptAll {
leaf: Mutex::new(None),
});
let mut config = rustls::ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::aws_lc_rs::default_provider(),
))
.with_protocol_versions(versions)
.unwrap()
.dangerous()
.with_custom_certificate_verifier(verifier.clone())
.with_no_client_auth();
if alpn {
config.alpn_protocols = vec![ALPN.to_vec()];
}
(config, verifier)
}
async fn connect_tls(
server: &Server,
config: rustls::ClientConfig,
) -> std::io::Result<tokio_rustls::client::TlsStream<TcpStream>> {
let tcp = TcpStream::connect(("127.0.0.1", server.port)).await?;
tokio_rustls::TlsConnector::from(Arc::new(config))
.connect(ServerName::try_from("127.0.0.1").unwrap(), tcp)
.await
}
async fn read_frame<S: tokio::io::AsyncRead + Unpin>(stream: &mut S) -> (u16, u32, Vec<u8>) {
let mut header = [0u8; 12];
stream.read_exact(&mut header).await.unwrap();
let id = u16::from_be_bytes([header[0], header[1]]);
let flags = u16::from_be_bytes([header[2], header[3]]);
assert_eq!(flags, 0);
let sequence = u32::from_be_bytes(header[4..8].try_into().unwrap());
let length = u32::from_be_bytes(header[8..12].try_into().unwrap()) as usize;
let mut payload = vec![0u8; length];
stream.read_exact(&mut payload).await.unwrap();
(id, sequence, payload)
}
fn frame(id: PacketId, sequence: u32, payload: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&(id as u16).to_be_bytes());
out.extend_from_slice(&0u16.to_be_bytes());
out.extend_from_slice(&sequence.to_be_bytes());
out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
out.extend_from_slice(payload);
out
}
#[tokio::test]
async fn tls13_with_alpn_works_and_certificate_fingerprint_matches_the_published_one() {
let server = start().await;
let (config, verifier) = client_config(&[&rustls::version::TLS13], true);
let tls = connect_tls(&server, config).await.unwrap();
assert_eq!(
tls.get_ref().1.protocol_version(),
Some(rustls::ProtocolVersion::TLSv1_3)
);
assert_eq!(tls.get_ref().1.alpn_protocol(), Some(ALPN));
let leaf = verifier.leaf.lock().unwrap().clone().unwrap();
let seen = hex::encode(spki_fingerprint(&leaf).unwrap());
let published =
std::fs::read_to_string(server.directory.join("tls").join("fingerprint.txt")).unwrap();
assert_eq!(seen, published.trim());
}
#[tokio::test]
async fn tls12_only_client_is_rejected() {
let server = start().await;
let (config, _) = client_config(&[&rustls::version::TLS12], true);
let result = connect_tls(&server, config).await;
assert!(result.is_err(), "the listener must not negotiate TLS 1.2");
}
#[tokio::test]
async fn client_without_alpn_is_rejected_before_any_lnex_byte() {
let server = start().await;
let (config, _) = client_config(&[&rustls::version::TLS13], false);
match connect_tls(&server, config).await {
Err(_) => {}
Ok(mut tls) => {
let mut byte = [0u8; 1];
let read = tokio::time::timeout(Duration::from_secs(3), tls.read(&mut byte)).await;
assert!(
!matches!(read, Ok(Ok(n)) if n > 0),
"no LNEx data may be sent without ALPN vnox-lnex/3"
);
}
}
}
#[tokio::test]
async fn plaintext_garbage_gets_explicit_version_error() {
let server = start().await;
let mut tcp = TcpStream::connect(("127.0.0.1", server.port))
.await
.unwrap();
tcp.write_all(&frame(PacketId::Auth, 0, b"old client"))
.await
.unwrap();
let (id, _, payload) = tokio::time::timeout(Duration::from_secs(5), read_frame(&mut tcp))
.await
.unwrap();
assert_eq!(id, PacketId::Error as u16);
let error = ErrorPayload::decode(payload.as_slice()).unwrap();
assert_eq!(error.code, ErrorCode::VersionMismatch as u32);
assert!(error.message.contains("TLS 1.3"));
let mut rest = Vec::new();
tcp.read_to_end(&mut rest).await.unwrap();
assert!(rest.is_empty(), "connection is closed after the error");
}
#[tokio::test]
async fn silent_v2_style_client_gets_explicit_version_error() {
// An LNEx v2 client waits for the server HELLO and sends nothing.
let server = start().await;
let mut tcp = TcpStream::connect(("127.0.0.1", server.port))
.await
.unwrap();
let (id, _, payload) = tokio::time::timeout(Duration::from_secs(8), read_frame(&mut tcp))
.await
.unwrap();
assert_eq!(id, PacketId::Error as u16);
let error = ErrorPayload::decode(payload.as_slice()).unwrap();
assert_eq!(error.code, ErrorCode::VersionMismatch as u32);
assert!(error.message.contains("LNEx v3"));
}
async fn authenticate(
tls: &mut tokio_rustls::client::TlsStream<TcpStream>,
signing_binding: Option<[u8; 32]>,
) -> (u16, Vec<u8>) {
let binding = tls
.get_ref()
.1
.export_keying_material([0u8; 32], EXPORTER_LABEL, None)
.unwrap();
let (id, sequence, payload) = read_frame(tls).await;
assert_eq!((id, sequence), (PacketId::Hello as u16, 0));
let mut hello = HelloPayload::decode(payload.as_slice()).unwrap();
assert_eq!(hello.lnex_version, LNEX_VERSION);
// The server HELLO is signed over this connection's exporter.
let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature).unwrap();
let verifying =
ed25519_dalek::VerifyingKey::from_bytes(&hello.server_pubkey.clone().try_into().unwrap())
.unwrap();
hello.server_signature.clear();
verifying
.verify_strict(
&server_hello_transcript(&binding, &hello.encode_to_vec()),
&signature,
)
.unwrap();
let key = SigningKey::generate(&mut rand::rng());
let mut auth = AuthPayload {
client_pubkey: key.verifying_key().to_bytes().to_vec(),
nickname: "tls-test".into(),
lnex_version: LNEX_VERSION.into(),
signature: Vec::new(),
};
let signed_with = signing_binding.unwrap_or(binding);
let transcript = client_auth_transcript(&signed_with, &payload, &auth.encode_to_vec());
auth.signature = key.sign(&transcript).to_bytes().to_vec();
tls.write_all(&frame(PacketId::Auth, 0, &auth.encode_to_vec()))
.await
.unwrap();
let (id, _, payload) = read_frame(tls).await;
(id, payload)
}
#[tokio::test]
async fn full_handshake_over_tls_creates_a_session() {
let server = start().await;
let (config, _) = client_config(&[&rustls::version::TLS13], true);
let mut tls = connect_tls(&server, config).await.unwrap();
let (id, _) = authenticate(&mut tls, None).await;
assert_eq!(id, PacketId::Session as u16);
}
#[tokio::test]
async fn auth_signed_for_another_tls_connection_is_rejected() {
let server = start().await;
let (config, _) = client_config(&[&rustls::version::TLS13], true);
let mut tls = connect_tls(&server, config).await.unwrap();
let (id, payload) = authenticate(&mut tls, Some([0x42; 32])).await;
assert_eq!(id, PacketId::Error as u16);
let error = ErrorPayload::decode(payload.as_slice()).unwrap();
assert_eq!(error.code, ErrorCode::AuthFailed as u32);
}

View file

@ -55,7 +55,7 @@ Per address 1 per 60 s and 5 per hour; per source (`X-Forwarded-For`, as GitHub
Addresses are trimmed and lowercased; only ASCII, a local part of `[a-z0-9._%+-]` without leading/trailing/double dots, at most 64 characters, a multi-label hostname whose last label is alphabetic, at most 254 characters in total. `+tag` is not stripped and Gmail dots are not folded. Unusual legal addresses are rejected on purpose.
The identity is `external_identities(provider='email', subject=<normalized address>)`, reusing the existing table so one address maps to one account, and it can never collide with `github.com` subjects. A matching GitHub account or email is never merged automatically. A first successful verification creates an account with a generated `u_<uuid>` handle and the neutral display name `Vnox user`; the local part of the address is never used. Choosing a handle, display name and avatar after registration is not implemented yet (see `design/accounts-and-avatars.md`). The address is kept in plain normalized form in `external_identities` because later features (security notices, adding a second sign-in method) need it; it is used for nothing except sending codes today.
The identity is `external_identities(provider='email', subject=<normalized address>)`, reusing the existing table so one address maps to one account, and it can never collide with `github.com` subjects. A matching GitHub account or email is never merged automatically. A first successful verification creates an account with a generated `u_<uuid>` handle and the neutral display name `Vnox user`; the local part of the address is never used. Choosing a handle and display name after registration is not implemented yet (an own avatar can be uploaded, see below) (see `design/accounts-and-avatars.md`). The address is kept in plain normalized form in `external_identities` because later features (security notices, adding a second sign-in method) need it; it is used for nothing except sending codes today.
### Mail and logging
@ -68,3 +68,39 @@ The message is rendered by `mail::templates::render_email_code` (Russian or Engl
- Rate-limit counters for the in-memory limiter reset on restart; the email ledger persists.
- Access to the mailbox, or to the SQLite file together with `email-auth.key` during the ten-minute window, defeats the code.
- Tests use an injected sender; real SMTP delivery has not been exercised from tests.
## Own avatar
A signed-in web session can set its own photo. Without one, `avatar_url` in `GET /v1/auth/session` (and in the email verify answer) is the provider's avatar (GitHub) or `null`; with one it is the same-origin path `/v1/avatars/<id>`.
### Contract
- `POST /v1/account/avatar`: the body is the raw image, `Content-Type` is `image/png`, `image/jpeg` or `image/webp`. Answers `200 {"avatar_url":"/v1/avatars/<id>"}`.
- `DELETE /v1/account/avatar`: removes the own photo. Answers `200 {"avatar_url": <provider URL or null>}`; repeating it is harmless.
- `GET /v1/avatars/<id>`: public. `<id>` is 64 lowercase hex characters, the SHA-256 of the stored bytes. `Cache-Control: public, max-age=31536000, immutable`, `Content-Type: image/png`, `X-Content-Type-Options: nosniff`, `Content-Security-Policy: default-src 'none'; sandbox; frame-ancestors 'none'`, `ETag`. Unknown or malformed ids give a `404` JSON error. After a replacement or removal the old URL gives `404` (browser caches may still hold it until they evict it).
- The two changing endpoints require the exact `Origin`, the session cookie and `X-CSRF-Token`, checked in that order, exactly as logout (shared `authorized` gate). All their responses, errors included, are `no-store`.
- Errors: `401 not_authenticated`, `403 invalid_origin` / `invalid_csrf`, `413 too_large`, `415 unsupported_type` / `type_mismatch`, `422 bad_dimensions` / `invalid_image`, `429 try_later`, `503 try_later`.
### Upload pipeline
1. Authentication, Origin and CSRF are checked before the body is read.
2. The declared `Content-Type` must be one of the three types. A cheap refusal here does not spend rate-limit budget.
3. Rate limit, in memory: 10 changes per hour per account and 30 per hour per source (`X-Forwarded-For`, /64 grouping for IPv6, as above). Uploads and removals both count; a refused request is not recorded. At most two decodes run at the same time, the rest get `429`.
4. Body limit 2 MiB: refused from `Content-Length` when announced, and the read itself stops at the limit for chunked bodies.
5. Magic bytes decide the real format (PNG, JPEG, WebP; SVG, GIF and everything else are `unsupported_type`). A different declared type is `type_mismatch`, so a renamed file does not pass.
6. The header is read first: more than 4096 or fewer than 32 pixels on a side is `bad_dimensions` before any pixel buffer exists (decoder limits: 4096 per side, 128 MiB allocation). A small file that claims 60000x60000 never allocates.
7. The image is fully decoded (corrupt or truncated data is `invalid_image`), rotated by its EXIF orientation, center-cropped to a square, resized to 256x256 (Lanczos3) and written as a new PNG (RGB, or RGBA when the source has transparency). Nothing from the source file is copied, so EXIF, GPS, ICC profiles, text chunks and trailing data are gone. The decode runs on a blocking thread. Animated sources yield a single still frame or are refused.
8. The row is written with `INSERT ... ON CONFLICT(user_id) DO UPDATE`, so there is one avatar per account and the old bytes are overwritten in the same statement. The original upload is never stored.
### Storage
SQLite BLOB in table `avatars` (migration `0005_avatars.sql`), keyed by `user_id` with `ON DELETE CASCADE`. Reasons: a normalized avatar is small (typically 20 to 150 KB), so the database stays small; replacement and account deletion are transactional with the account row; there is no second directory whose permissions, orphan files or backup consistency need care; the existing data-directory rules and the existing backup (database plus issuer together) cover it with no new moving parts. Files stay `0600` because they are inside the private data directory like the database itself. If avatars ever grow in number or size, serving can move to files or object storage behind the same URLs.
The provider avatar URL stays on `accounts.avatar_url` and is the fallback after removal.
### Known limits
- Rate-limit counters are in memory and reset on restart.
- Avatars are public to anyone who knows the id; ids are not secret but are not listed anywhere. Identical images from two accounts share an id.
- Deleted photos can remain in database backups. The project owner decided that backups keep deleted data for up to 30 days; this needs backup rotation to be implemented and is not enforced by the Hub.
- Decoding uses the `image` crate with only the `png`, `jpeg` and `webp` features. `cargo audit` reported no advisories when this was added. Decoder bugs in these crates are the main residual risk; decoding is bounded in size, memory and concurrency.

View file

@ -23,6 +23,8 @@ uuid = { workspace = true, features = ["serde"] }
sqlx = { version = "0.9", default-features = false, features = ["sqlite", "runtime-tokio", "migrate", "macros"] }
lettre = { version = "0.11.23", default-features = false, features = ["builder", "smtp-transport", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] }
url = "2"
# Avatar re-encoding: only PNG, JPEG and WebP decoders and the PNG encoder; no GIF, SVG or other formats.
image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp"] }
reqwest.workspace = true
sha2.workspace = true

View file

@ -12,6 +12,7 @@ Community messages and voice never pass through this process.
- `/v1/info`: public issuer ID/key and honest feature availability.
- `/`: deployment status page; `/assets/vnox-mark.svg`: approved V connection mark.
- Durable SQLite schema and issuer identity with a private `0600` key file.
- Own avatar for signed-in web sessions: `POST`/`DELETE /v1/account/avatar`, public `GET /v1/avatars/<id>` (re-encoded 256x256 PNG in SQLite, see `AUTH.md`).
- TLS-only SMTP transport and HTML/plain-text transactional email templates.
GitHub OAuth and email one-time-code sign-in are implemented (`AUTH.md`); email sign-in

View file

@ -0,0 +1,12 @@
-- One own avatar per account, stored as a re-encoded PNG (no source metadata). The row is
-- replaced on upload and removed on "remove photo" or when the account is deleted. `id` is the
-- hex SHA-256 of the stored bytes; it names the immutable public URL /v1/avatars/<id>.
-- accounts.avatar_url keeps the provider (GitHub) avatar as the fallback.
CREATE TABLE avatars (
user_id TEXT PRIMARY KEY REFERENCES accounts(user_id) ON DELETE CASCADE,
id TEXT NOT NULL,
content_type TEXT NOT NULL,
bytes BLOB NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX avatars_by_id ON avatars(id);

View file

@ -26,8 +26,17 @@ pub struct AuthService {
/// Present only when a mail transport is configured.
pub email: Option<email::EmailAuth>,
limits: Mutex<HashMap<String, (i64, u32)>>,
avatar_events: Mutex<HashMap<String, Vec<i64>>>,
/// Bounds concurrent image decodes, which are the most expensive thing a session can ask for.
pub avatar_decoding: tokio::sync::Semaphore,
}
/// Avatar changes (upload or removal) per account and per source within one hour.
const AVATAR_PER_USER_HOUR: usize = 10;
const AVATAR_PER_SOURCE_HOUR: usize = 30;
const AVATAR_WINDOW: i64 = 3600;
const AVATAR_TRACKED_KEYS: usize = 8192;
impl AuthService {
pub fn new(
pool: SqlitePool,
@ -53,6 +62,8 @@ impl AuthService {
provider,
email: None,
limits: Mutex::new(HashMap::new()),
avatar_events: Mutex::new(HashMap::new()),
avatar_decoding: tokio::sync::Semaphore::new(2),
}
}
/// Enables email sign-in. Callers do this only when SMTP is configured (or a test sender).
@ -86,4 +97,29 @@ impl AuthService {
limits.entry(ip.to_owned()).or_insert((now, 0)).1 += 1;
true
}
/// Records one avatar change attempt for `user` and `source` and reports whether both
/// budgets still had room. A refused attempt is not recorded, so a blocked client does
/// not extend its own block.
pub fn allow_avatar(&self, user: &str, source: &str) -> bool {
let Ok(mut events) = self.avatar_events.lock() else {
return false;
};
let now = store::now();
events.retain(|_, times| {
times.retain(|at| now - *at < AVATAR_WINDOW);
!times.is_empty()
});
let user_key = format!("u:{user}");
let source_key = format!("s:{source}");
let count = |key: &str| events.get(key).map_or(0, Vec::len);
if count(&user_key) >= AVATAR_PER_USER_HOUR
|| count(&source_key) >= AVATAR_PER_SOURCE_HOUR
|| events.len() + 2 > AVATAR_TRACKED_KEYS
{
return false;
}
events.entry(user_key).or_default().push(now);
events.entry(source_key).or_default().push(now);
true
}
}

View file

@ -14,6 +14,7 @@ use cookie::{Cookie, SameSite};
use oauth2::{CsrfToken, PkceCodeChallenge};
use serde::Deserialize;
use serde_json::json;
mod avatar;
use std::sync::Arc;
use subtle::ConstantTimeEq;
const BROWSER: &str = "__Host-vnox_oauth";
@ -33,6 +34,11 @@ pub fn router() -> Router<Arc<HubState>> {
)
.route("/v1/auth/session", get(session))
.route("/v1/auth/logout", post(logout))
.route(
"/v1/account/avatar",
post(avatar::upload).delete(avatar::remove),
)
.route("/v1/avatars/{id}", get(avatar::serve))
}
fn failure(status: StatusCode, code: &'static str) -> Response {
(status, Json(json!({"error":code}))).into_response()
@ -336,23 +342,44 @@ async fn session(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Resp
}
Json(json!({"authenticated":false})).into_response()
}
async fn logout(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
if !same_origin(&state.auth, &headers) {
return failure(StatusCode::FORBIDDEN, "invalid_origin");
/// Session gate for state-changing requests by a signed-in user: exact `Origin`, a live
/// session, and the session's CSRF token in `X-CSRF-Token`. Returns the user and session token.
async fn authorized(
state: &HubState,
headers: &HeaderMap,
) -> Result<(store::User, String), Box<Response>> {
if !same_origin(&state.auth, headers) {
return Err(Box::new(failure(StatusCode::FORBIDDEN, "invalid_origin")));
}
let Some(token) = cookie(&headers, SESSION) else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
let Some(token) = cookie(headers, SESSION) else {
return Err(Box::new(failure(
StatusCode::UNAUTHORIZED,
"not_authenticated",
)));
};
let Ok(Some((_, csrf))) = store::get_session(&state.auth.pool, &token).await else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
let Ok(Some((user, csrf))) = store::get_session(&state.auth.pool, &token).await else {
return Err(Box::new(failure(
StatusCode::UNAUTHORIZED,
"not_authenticated",
)));
};
let supplied = headers
.get("x-csrf-token")
.map(|v| v.as_bytes())
.unwrap_or_default();
if !bool::from(csrf.as_bytes().ct_eq(supplied)) {
return failure(StatusCode::FORBIDDEN, "invalid_csrf");
return Err(Box::new(failure(StatusCode::FORBIDDEN, "invalid_csrf")));
}
Ok((user, token))
}
fn allowed_avatar(auth: &AuthService, user_id: &str, headers: &HeaderMap) -> bool {
auth.allow_avatar(user_id, &client_ip(headers))
}
async fn logout(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
let token = match authorized(&state, &headers).await {
Ok((_, token)) => token,
Err(response) => return *response,
};
if sqlx::query("DELETE FROM web_sessions WHERE token_hash=?")
.bind(store::hash(&token))
.execute(&state.auth.pool)

View file

@ -0,0 +1,132 @@
//! Own-avatar endpoints. Changing requires an authenticated web session, the exact `Origin`
//! and the session's `X-CSRF-Token` (the same gate as logout). Serving is public.
use super::{HeaderMap, StatusCode, allowed_avatar, authorized, failure};
use crate::{avatar, web::HubState};
use axum::{
Json,
body::{Body, to_bytes},
extract::{Path, State},
http::{HeaderValue, header},
response::{IntoResponse, Response},
};
use serde_json::json;
use std::sync::Arc;
/// `POST /v1/account/avatar`: body is the raw image, `Content-Type` its type.
pub(super) async fn upload(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
body: Body,
) -> Response {
let user = match authorized(&state, &headers).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
let declared = headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|v| {
v.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase()
})
.unwrap_or_default();
if !matches!(declared.as_str(), "image/png" | "image/jpeg" | "image/webp") {
return failure(StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported_type");
}
if !allowed_avatar(&state.auth, &user.user_id, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
// Reject by announced size first; the read below enforces the limit for chunked bodies.
let announced = headers
.get(header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<usize>().ok());
if announced.is_some_and(|n| n > avatar::MAX_UPLOAD_BYTES) {
return failure(StatusCode::PAYLOAD_TOO_LARGE, "too_large");
}
let Ok(data) = to_bytes(body, avatar::MAX_UPLOAD_BYTES).await else {
return failure(StatusCode::PAYLOAD_TOO_LARGE, "too_large");
};
let Ok(permit) = state.auth.avatar_decoding.try_acquire() else {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
};
let processed = tokio::task::spawn_blocking(move || avatar::normalize(&declared, &data)).await;
drop(permit);
let png = match processed {
Ok(Ok(png)) => png,
Ok(Err(avatar::AvatarError::UnsupportedType)) => {
return failure(StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported_type");
}
Ok(Err(avatar::AvatarError::TypeMismatch)) => {
return failure(StatusCode::UNSUPPORTED_MEDIA_TYPE, "type_mismatch");
}
Ok(Err(avatar::AvatarError::BadDimensions)) => {
return failure(StatusCode::UNPROCESSABLE_ENTITY, "bad_dimensions");
}
Ok(Err(avatar::AvatarError::Invalid)) => {
return failure(StatusCode::UNPROCESSABLE_ENTITY, "invalid_image");
}
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
};
match avatar::replace(&state.auth.pool, &user.user_id, &png).await {
Ok(url) => Json(json!({"avatar_url": url})).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
/// `DELETE /v1/account/avatar`: drops the own photo; the answer carries the avatar now in
/// effect (the provider's, or null for the default).
pub(super) async fn remove(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
let user = match authorized(&state, &headers).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
if !allowed_avatar(&state.auth, &user.user_id, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let pool = &state.auth.pool;
if avatar::remove(pool, &user.user_id).await.is_err() {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
}
match avatar::provider_url(pool, &user.user_id).await {
Ok(url) => Json(json!({"avatar_url": url})).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
/// `GET /v1/avatars/<id>`: public and immutable, because the id is the content hash.
pub(super) async fn serve(State(state): State<Arc<HubState>>, Path(id): Path<String>) -> Response {
if !avatar::valid_id(&id) {
return failure(StatusCode::NOT_FOUND, "not_found");
}
let (content_type, bytes) = match avatar::fetch(&state.auth.pool, &id).await {
Ok(Some(found)) => found,
Ok(None) => return failure(StatusCode::NOT_FOUND, "not_found"),
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
};
let mut response = bytes.into_response();
let headers = response.headers_mut();
if let Ok(value) = HeaderValue::from_str(&content_type) {
headers.insert(header::CONTENT_TYPE, value);
}
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000, immutable"),
);
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static("default-src 'none'; sandbox; frame-ancestors 'none'"),
);
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_static("inline; filename=\"avatar.png\""),
);
if let Ok(value) = HeaderValue::from_str(&format!("\"{id}\"")) {
headers.insert(header::ETAG, value);
}
response
}

View file

@ -144,7 +144,8 @@ async fn lookup_identity(
provider: &str,
subject: &str,
) -> anyhow::Result<Option<User>> {
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url FROM accounts a JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider=? AND e.subject=?")
// The own avatar (same-origin path) wins over the provider URL kept on the account.
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,a.avatar_url) AS avatar_url FROM accounts a LEFT JOIN avatars v ON v.user_id=a.user_id JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider=? AND e.subject=?")
.bind(provider).bind(subject).fetch_optional(pool).await?)
}
@ -168,7 +169,7 @@ pub async fn get_session(
avatar_url: Option<String>,
csrf_token: String,
}
let row: Option<Row> = sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url,s.csrf_token FROM web_sessions s JOIN accounts a ON a.user_id=s.user_id WHERE s.token_hash=? AND s.expires_at>?")
let row: Option<Row> = sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,a.avatar_url) AS avatar_url,s.csrf_token FROM web_sessions s JOIN accounts a ON a.user_id=s.user_id LEFT JOIN avatars v ON v.user_id=a.user_id WHERE s.token_hash=? AND s.expires_at>?")
.bind(hash(session)).bind(now()).fetch_optional(pool).await?;
Ok(row.map(|r| {
(

165
hub/src/avatar.rs Normal file
View file

@ -0,0 +1,165 @@
//! Own-avatar processing and storage.
//!
//! Uploads are never stored as received. The bytes are sniffed (PNG, JPEG or WebP only),
//! the header dimensions are checked before any pixel buffer exists, the image is fully
//! decoded under a memory limit, rotated by its EXIF orientation, cropped to a square,
//! resized and written again as a fresh PNG. A fresh PNG carries no EXIF, GPS, ICC, text or
//! other ancillary chunks from the source, so metadata cannot survive.
use std::io::Cursor;
use image::{
DynamicImage, ImageDecoder, ImageEncoder, ImageFormat, Limits, codecs::png::PngEncoder,
imageops::FilterType,
};
use sha2::{Digest, Sha256};
use sqlx::SqlitePool;
/// Request body limit (2 MiB).
pub const MAX_UPLOAD_BYTES: usize = 2 * 1024 * 1024;
/// Largest accepted source side, checked from the header before decoding.
pub const MAX_SOURCE_SIDE: u32 = 4096;
/// Smallest accepted source side.
pub const MIN_SOURCE_SIDE: u32 = 32;
/// Side of the stored square.
pub const OUTPUT_SIDE: u32 = 256;
/// Decoder allocation budget; a 4096x4096 RGBA frame is 64 MiB.
const MAX_DECODE_ALLOC: u64 = 128 * 1024 * 1024;
#[derive(Debug, PartialEq, Eq)]
pub enum AvatarError {
/// Not PNG, JPEG or WebP (SVG, GIF and everything else included).
UnsupportedType,
/// Declared and detected types differ.
TypeMismatch,
/// Larger than 4096 on a side, or smaller than 32.
BadDimensions,
/// Looks like a supported image but does not decode.
Invalid,
}
/// The MIME type of a supported format.
pub fn mime_for(format: ImageFormat) -> Option<&'static str> {
match format {
ImageFormat::Png => Some("image/png"),
ImageFormat::Jpeg => Some("image/jpeg"),
ImageFormat::WebP => Some("image/webp"),
_ => None,
}
}
/// Validates and re-encodes an upload. `declared` is the request `Content-Type` without
/// parameters. CPU and memory heavy: call from a blocking thread.
pub fn normalize(declared: &str, data: &[u8]) -> Result<Vec<u8>, AvatarError> {
let format = image::guess_format(data).map_err(|_| AvatarError::UnsupportedType)?;
let detected = mime_for(format).ok_or(AvatarError::UnsupportedType)?;
if detected != declared {
return Err(AvatarError::TypeMismatch);
}
let mut limits = Limits::default();
limits.max_image_width = Some(MAX_SOURCE_SIDE);
limits.max_image_height = Some(MAX_SOURCE_SIDE);
limits.max_alloc = Some(MAX_DECODE_ALLOC);
let mut reader = image::ImageReader::with_format(Cursor::new(data), format);
reader.limits(limits);
let mut decoder = reader.into_decoder().map_err(|error| match error {
image::ImageError::Limits(_) => AvatarError::BadDimensions,
_ => AvatarError::Invalid,
})?;
// Header-only: nothing has been allocated for pixels yet.
let (width, height) = decoder.dimensions();
if width > MAX_SOURCE_SIDE
|| height > MAX_SOURCE_SIDE
|| width < MIN_SOURCE_SIDE
|| height < MIN_SOURCE_SIDE
{
return Err(AvatarError::BadDimensions);
}
let orientation = decoder.orientation().map_err(|_| AvatarError::Invalid)?;
let mut picture = DynamicImage::from_decoder(decoder).map_err(|_| AvatarError::Invalid)?;
picture.apply_orientation(orientation);
let square = picture.resize_to_fill(OUTPUT_SIDE, OUTPUT_SIDE, FilterType::Lanczos3);
let mut out = Vec::new();
let encoder = PngEncoder::new(&mut out);
let written = if square.color().has_alpha() {
let pixels = square.to_rgba8();
encoder.write_image(
pixels.as_raw(),
OUTPUT_SIDE,
OUTPUT_SIDE,
image::ExtendedColorType::Rgba8,
)
} else {
let pixels = square.to_rgb8();
encoder.write_image(
pixels.as_raw(),
OUTPUT_SIDE,
OUTPUT_SIDE,
image::ExtendedColorType::Rgb8,
)
};
written.map_err(|_| AvatarError::Invalid)?;
Ok(out)
}
/// Public identifier: hex SHA-256 of the stored bytes.
pub fn content_id(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
/// True for a 64 character lowercase hex identifier.
pub fn valid_id(id: &str) -> bool {
id.len() == 64 && id.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))
}
/// Replaces the account's avatar atomically and returns its URL path.
pub async fn replace(pool: &SqlitePool, user_id: &str, png: &[u8]) -> anyhow::Result<String> {
let id = content_id(png);
sqlx::query(
"INSERT INTO avatars(user_id,id,content_type,bytes,created_at) VALUES(?,?,?,?,?) \
ON CONFLICT(user_id) DO UPDATE SET id=excluded.id,content_type=excluded.content_type,\
bytes=excluded.bytes,created_at=excluded.created_at",
)
.bind(user_id)
.bind(&id)
.bind("image/png")
.bind(png)
.bind(crate::auth::store::now())
.execute(pool)
.await?;
Ok(url_path(&id))
}
/// Deletes the account's own avatar; true if one existed.
pub async fn remove(pool: &SqlitePool, user_id: &str) -> anyhow::Result<bool> {
let done = sqlx::query("DELETE FROM avatars WHERE user_id=?")
.bind(user_id)
.execute(pool)
.await?;
Ok(done.rows_affected() > 0)
}
/// Content type and bytes for a public avatar id.
pub async fn fetch(pool: &SqlitePool, id: &str) -> anyhow::Result<Option<(String, Vec<u8>)>> {
Ok(
sqlx::query_as("SELECT content_type,bytes FROM avatars WHERE id=? LIMIT 1")
.bind(id)
.fetch_optional(pool)
.await?,
)
}
/// The provider avatar kept on the account, if any.
pub async fn provider_url(pool: &SqlitePool, user_id: &str) -> anyhow::Result<Option<String>> {
Ok(
sqlx::query_scalar("SELECT avatar_url FROM accounts WHERE user_id=?")
.bind(user_id)
.fetch_optional(pool)
.await?
.flatten(),
)
}
pub fn url_path(id: &str) -> String {
format!("/v1/avatars/{id}")
}

View file

@ -1,4 +1,5 @@
pub mod auth;
pub mod avatar;
pub mod config;
pub mod database;
pub mod identity;

View file

@ -98,7 +98,7 @@ pub fn render(content: &Content<'_>) -> String {
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#101011"><tr><td align="center" style="padding:32px 12px">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" bgcolor="#1c1c1e" style="width:100%;max-width:600px;border:1px solid #383634;border-radius:18px;overflow:hidden;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif">
<tr><td bgcolor="#38312a" style="background:#38312a;background-image:linear-gradient(125deg,#514033 0%,#39312c 55%,#242426 100%);padding:30px 32px 32px">
<table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td width="42" height="42" align="center" bgcolor="#151516" style="border-radius:11px;color:#e8d5b8;font-size:19px;font-weight:800"><img src="{origin}/assets/vnox-mark.png" width="42" height="42" alt="V" style="display:block;border:0;border-radius:11px"></td><td style="padding-left:12px;color:#f6f0e7;font-size:23px;font-weight:700">Vnox</td></tr></table>
<table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td width="42" height="42" align="center" bgcolor="#151516" style="border-radius:11px;color:#e8d5b8;font-size:19px;font-weight:800"><img src="{origin}/assets/vnox-mark-email.png" width="42" height="42" alt="V" style="display:block;border:0;border-radius:11px"></td><td style="padding-left:12px;color:#f6f0e7;font-size:23px;font-weight:700">Vnox</td></tr></table>
<p style="margin:25px 0 10px;color:#d1b998;font-size:12px">{tagline}</p>
<h1 style="margin:0;color:#fff9ef;font-size:28px;line-height:35px;font-weight:700">{title}</h1>
</td></tr><tr><td style="padding:32px 32px 12px">{paragraphs}{code}{link}

View file

@ -38,9 +38,9 @@ pub fn render(origin: &Url, kind: Kind<'_>) -> Result<Email> {
bail!("login code must contain exactly eight ASCII digits");
}
(
"Твой код входа",
"Ваш код входа",
vec![
"Используй этот одноразовый код, чтобы войти в Vnox. Никому его не сообщай."
"Используйте этот одноразовый код, чтобы войти в Vnox. Никому его не сообщайте."
.to_owned(),
],
Some(code),
@ -55,7 +55,7 @@ pub fn render(origin: &Url, kind: Kind<'_>) -> Result<Email> {
}
(
"Новое устройство в аккаунте",
vec![format!("К твоему аккаунту подключено устройство: {device}."), "Если это был не ты, проверь список устройств и отзови доступ незнакомого сеанса.".to_owned()],
vec![format!("К вашему аккаунту подключено устройство: {device}."), "Если это были не вы, проверьте список устройств и отзовите доступ незнакомого сеанса.".to_owned()],
None,
"Проверить устройства",
("account/devices", None),
@ -80,7 +80,7 @@ pub fn render(origin: &Url, kind: Kind<'_>) -> Result<Email> {
url: url.as_str(),
}),
expiry,
warning: "Не запрашивал это действие? Не передавай код или ссылку другим людям. Если это письмо о новом устройстве, проверь активные сеансы.",
warning: "Не запрашивали это действие? Не передавайте код или ссылку другим людям. Если это письмо о новом устройстве, проверьте активные сеансы.",
origin: origin_text,
};
let text = format!(
@ -107,9 +107,9 @@ pub fn render_email_code(origin: &Url, code: &str, lang: Lang) -> Result<Email>
let (title, paragraph, expiry, warning, subject, label) = match lang {
Lang::Ru => (
"Код для входа в Vnox",
"Введи этот код на странице входа. Он подойдёт только в том браузере, где ты запросил вход.",
"Введите этот код на странице входа. Он подойдёт только в том браузере, где вы запросили вход.",
"Код действует 10 минут и срабатывает один раз.",
"Не запрашивал вход? Просто проигнорируй письмо и никому не сообщай код.",
"Не запрашивали вход? Просто проигнорируйте письмо и никому не сообщайте код.",
"Vnox: код для входа",
"Код",
),

View file

@ -106,6 +106,7 @@ async fn index() -> Html<&'static str> {
async fn headers(request: Request<Body>, next: Next) -> Response {
let mut response = next.run(request).await;
// Handlers that set their own cache policy or CSP (avatar delivery) keep them.
for (name, value) in [
("cache-control", "no-store"),
("x-content-type-options", "nosniff"),
@ -115,6 +116,10 @@ async fn headers(request: Request<Body>, next: Next) -> Response {
"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'",
),
] {
let present = response.headers().contains_key(name);
if present && matches!(name, "cache-control" | "content-security-policy") {
continue;
}
response
.headers_mut()
.insert(name, HeaderValue::from_static(value));

742
hub/tests/avatar.rs Normal file
View file

@ -0,0 +1,742 @@
use axum::{
Router,
body::{Body, to_bytes},
http::{Method, Request, Response, StatusCode},
};
use image::{ExtendedColorType, ImageEncoder, RgbImage};
use std::sync::Arc;
use tower::ServiceExt;
use vnox_hub::{
auth::{
self,
provider::GitHubProfile,
store::{self, User},
},
database,
identity::Issuer,
web::{self, HubState},
};
const ORIGIN: &str = "https://central.loki-code.dev";
const GITHUB_AVATAR: &str = "https://avatars.githubusercontent.com/u/123?v=4";
struct Session {
user: User,
token: String,
csrf: String,
}
struct Fixture {
_dir: tempfile::TempDir,
state: Arc<HubState>,
app: Router,
}
async fn fixture() -> Fixture {
let dir = tempfile::tempdir().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
}
let issuer = Issuer::load_or_create(dir.path()).unwrap();
let pool = database::open(dir.path(), &issuer).await.unwrap();
let auth = auth::AuthService::with_provider(pool.clone(), ORIGIN.parse().unwrap(), None);
let state = Arc::new(HubState {
database: pool,
auth: Arc::new(auth),
issuer,
smtp_configured: false,
started: std::time::Instant::now(),
});
Fixture {
_dir: dir,
app: web::router(state.clone()),
state,
}
}
impl Fixture {
async fn email_user(&self, address: &str) -> Session {
let user = store::upsert_email_identity(&self.state.database, address)
.await
.unwrap();
self.session(user).await
}
async fn github_user(&self) -> Session {
let profile = GitHubProfile {
id: 123,
login: "person".into(),
name: Some("Person".into()),
avatar_url: Some(GITHUB_AVATAR.into()),
};
let user = store::upsert_identity(&self.state.database, &profile)
.await
.unwrap();
self.session(user).await
}
async fn session(&self, user: User) -> Session {
let (token, csrf) = store::create_session(&self.state.database, &user.user_id)
.await
.unwrap();
Session { user, token, csrf }
}
async fn send(&self, request: Request<Body>) -> Response<Body> {
self.app.clone().oneshot(request).await.unwrap()
}
/// A well-formed request; callers override pieces to break it.
fn change<'a>(
&'a self,
method: Method,
session: Option<&Session>,
csrf: Option<&str>,
origin: Option<&str>,
content_type: &str,
body: Vec<u8>,
) -> impl std::future::Future<Output = Response<Body>> + use<'a> {
let mut request = Request::builder()
.method(method)
.uri("/v1/account/avatar")
.header("content-type", content_type);
if let Some(session) = session {
request = request.header("cookie", format!("__Host-vnox_session={}", session.token));
}
if let Some(csrf) = csrf {
request = request.header("x-csrf-token", csrf);
}
if let Some(origin) = origin {
request = request.header("origin", origin);
}
self.send(request.body(Body::from(body)).unwrap())
}
async fn upload(&self, session: &Session, content_type: &str, body: Vec<u8>) -> Response<Body> {
self.change(
Method::POST,
Some(session),
Some(&session.csrf),
Some(ORIGIN),
content_type,
body,
)
.await
}
async fn remove(&self, session: &Session) -> Response<Body> {
self.change(
Method::DELETE,
Some(session),
Some(&session.csrf),
Some(ORIGIN),
"application/json",
Vec::new(),
)
.await
}
async fn get(&self, path: &str) -> Response<Body> {
self.send(Request::builder().uri(path).body(Body::empty()).unwrap())
.await
}
async fn session_avatar(&self, session: &Session) -> serde_json::Value {
let response = self
.send(
Request::builder()
.uri("/v1/auth/session")
.header("cookie", format!("__Host-vnox_session={}", session.token))
.body(Body::empty())
.unwrap(),
)
.await;
json(response).await["user"]["avatar_url"].clone()
}
async fn avatar_rows(&self) -> i64 {
sqlx::query_scalar("SELECT COUNT(*) FROM avatars")
.fetch_one(&self.state.database)
.await
.unwrap()
}
}
async fn json(response: Response<Body>) -> serde_json::Value {
serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap()).unwrap()
}
async fn bytes(response: Response<Body>) -> Vec<u8> {
to_bytes(response.into_body(), 1 << 22)
.await
.unwrap()
.to_vec()
}
fn picture(width: u32, height: u32) -> RgbImage {
RgbImage::from_fn(width, height, |x, y| {
image::Rgb([(x % 256) as u8, (y % 256) as u8, ((x + y) % 256) as u8])
})
}
fn png(width: u32, height: u32) -> Vec<u8> {
let mut out = Vec::new();
image::codecs::png::PngEncoder::new(&mut out)
.write_image(
picture(width, height).as_raw(),
width,
height,
ExtendedColorType::Rgb8,
)
.unwrap();
out
}
fn jpeg(width: u32, height: u32) -> Vec<u8> {
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut out)
.write_image(
picture(width, height).as_raw(),
width,
height,
ExtendedColorType::Rgb8,
)
.unwrap();
out
}
fn webp(width: u32, height: u32) -> Vec<u8> {
let mut out = Vec::new();
image::codecs::webp::WebPEncoder::new_lossless(&mut out)
.write_image(
picture(width, height).as_raw(),
width,
height,
ExtendedColorType::Rgb8,
)
.unwrap();
out
}
/// Inserts an EXIF APP1 segment carrying `marker` right after the JPEG start marker.
fn with_exif(jpeg: &[u8], marker: &str) -> Vec<u8> {
let mut payload = b"Exif\0\0".to_vec();
payload.extend_from_slice(marker.as_bytes());
let mut out = jpeg[..2].to_vec();
out.extend_from_slice(&[0xFF, 0xE1]);
out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
out.extend_from_slice(&payload);
out.extend_from_slice(&jpeg[2..]);
out
}
fn crc32(data: &[u8]) -> u32 {
let mut crc = !0u32;
for byte in data {
crc ^= u32::from(*byte);
for _ in 0..8 {
crc = if crc & 1 == 1 {
(crc >> 1) ^ 0xEDB8_8320
} else {
crc >> 1
};
}
}
!crc
}
/// Inserts an ancillary chunk before IEND.
fn with_chunk(png: &[u8], kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
let end = png.len() - 12;
let mut out = png[..end].to_vec();
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
let mut body = kind.to_vec();
body.extend_from_slice(data);
out.extend_from_slice(&body);
out.extend_from_slice(&crc32(&body).to_be_bytes());
out.extend_from_slice(&png[end..]);
out
}
/// Rewrites the IHDR size of a PNG and fixes its CRC: a tiny file that claims huge pixels.
fn claim_size(png: &[u8], width: u32, height: u32) -> Vec<u8> {
let mut out = png.to_vec();
out[16..20].copy_from_slice(&width.to_be_bytes());
out[20..24].copy_from_slice(&height.to_be_bytes());
let crc = crc32(&out[12..29]);
out[29..33].copy_from_slice(&crc.to_be_bytes());
out
}
fn chunk_names(png: &[u8]) -> Vec<String> {
let mut names = Vec::new();
let mut at = 8;
while at + 8 <= png.len() {
let length = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
names.push(String::from_utf8_lossy(&png[at + 4..at + 8]).into_owned());
at += 12 + length;
}
names
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack.windows(needle.len()).any(|w| w == needle)
}
async fn assert_error(response: Response<Body>, status: StatusCode, code: &str) {
assert_eq!(response.status(), status);
assert_eq!(response.headers()["cache-control"], "no-store");
assert_eq!(json(response).await["error"], code);
}
#[tokio::test]
async fn upload_reencodes_to_a_square_png_and_serves_it_with_safe_headers() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
assert_eq!(fx.session_avatar(&alice).await, serde_json::Value::Null);
let response = fx.upload(&alice, "image/png", png(600, 300)).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["cache-control"], "no-store");
let url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
assert!(url.starts_with("/v1/avatars/"));
assert_eq!(url.len(), "/v1/avatars/".len() + 64);
assert_eq!(fx.session_avatar(&alice).await, url);
let served = fx.get(&url).await;
assert_eq!(served.status(), StatusCode::OK);
let h = served.headers();
assert_eq!(h["content-type"], "image/png");
assert_eq!(h["x-content-type-options"], "nosniff");
assert_eq!(h["cache-control"], "public, max-age=31536000, immutable");
assert!(
h["content-security-policy"]
.to_str()
.unwrap()
.contains("default-src 'none'")
);
assert!(h.get("set-cookie").is_none());
let body = bytes(served).await;
let decoded = image::load_from_memory(&body).unwrap();
assert_eq!((decoded.width(), decoded.height()), (256, 256));
// The id is the content hash.
assert_eq!(
url,
format!("/v1/avatars/{}", vnox_hub::avatar::content_id(&body))
);
}
#[tokio::test]
async fn jpeg_and_webp_are_accepted_and_exif_and_png_text_chunks_are_removed() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let tagged = with_exif(&jpeg(200, 200), "SECRET-GPS-48.8566N");
assert!(contains(&tagged, b"SECRET-GPS"));
let response = fx.upload(&alice, "image/jpeg", tagged).await;
assert_eq!(response.status(), StatusCode::OK);
let url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
let body = bytes(fx.get(&url).await).await;
assert!(!contains(&body, b"SECRET"));
assert!(!contains(&body, b"Exif"));
assert_eq!(chunk_names(&body), ["IHDR", "IDAT", "IEND"]);
let marked = with_chunk(&png(100, 100), b"tEXt", b"Comment\0SECRET-AUTHOR");
let marked = with_chunk(&marked, b"eXIf", b"SECRET-EXIF");
assert!(contains(&marked, b"SECRET-AUTHOR"));
let response = fx.upload(&alice, "image/png", marked).await;
assert_eq!(response.status(), StatusCode::OK);
let url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
let body = bytes(fx.get(&url).await).await;
assert!(!contains(&body, b"SECRET"));
assert_eq!(chunk_names(&body), ["IHDR", "IDAT", "IEND"]);
let response = fx.upload(&alice, "image/webp", webp(120, 90)).await;
assert_eq!(response.status(), StatusCode::OK);
let url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
let served = fx.get(&url).await;
assert_eq!(served.headers()["content-type"], "image/png");
let decoded = image::load_from_memory(&bytes(served).await).unwrap();
assert_eq!((decoded.width(), decoded.height()), (256, 256));
}
#[tokio::test]
async fn changes_need_session_csrf_and_exact_origin() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let image = png(64, 64);
for method in [Method::POST, Method::DELETE] {
let go = |session, csrf: Option<&str>, origin: Option<&str>| {
fx.change(
method.clone(),
session,
csrf,
origin,
"image/png",
image.clone(),
)
};
assert_error(
go(None, Some(&alice.csrf), Some(ORIGIN)).await,
StatusCode::UNAUTHORIZED,
"not_authenticated",
)
.await;
assert_error(
go(Some(&alice), None, Some(ORIGIN)).await,
StatusCode::FORBIDDEN,
"invalid_csrf",
)
.await;
assert_error(
go(Some(&alice), Some("0".repeat(64).as_str()), Some(ORIGIN)).await,
StatusCode::FORBIDDEN,
"invalid_csrf",
)
.await;
for origin in [
None,
Some("https://evil.example"),
Some("http://central.loki-code.dev"),
Some("https://central.loki-code.dev:8443"),
Some("null"),
] {
assert_error(
go(Some(&alice), Some(&alice.csrf), origin).await,
StatusCode::FORBIDDEN,
"invalid_origin",
)
.await;
}
}
assert_eq!(fx.avatar_rows().await, 0);
}
#[tokio::test]
async fn another_account_cannot_change_or_remove_my_avatar() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let bob = fx.email_user("bob@example.com").await;
let response = fx.upload(&alice, "image/png", png(64, 64)).await;
let alice_url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
// Bob's session with Alice's CSRF token, and Alice's cookie with Bob's token.
let mixed = [
fx.change(
Method::DELETE,
Some(&bob),
Some(&alice.csrf),
Some(ORIGIN),
"x/y",
vec![],
)
.await,
fx.change(
Method::POST,
Some(&bob),
Some(&alice.csrf),
Some(ORIGIN),
"image/png",
png(64, 64),
)
.await,
fx.change(
Method::DELETE,
Some(&alice),
Some(&bob.csrf),
Some(ORIGIN),
"x/y",
vec![],
)
.await,
];
for response in mixed {
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
assert_eq!(fx.session_avatar(&alice).await, alice_url);
assert_eq!(fx.session_avatar(&bob).await, serde_json::Value::Null);
// Bob acting as himself only affects Bob.
assert_eq!(
fx.upload(&bob, "image/png", png(80, 80)).await.status(),
StatusCode::OK
);
assert_eq!(fx.remove(&bob).await.status(), StatusCode::OK);
assert_eq!(fx.session_avatar(&alice).await, alice_url);
assert_eq!(fx.get(&alice_url).await.status(), StatusCode::OK);
}
#[tokio::test]
async fn wrong_types_and_swapped_extensions_are_refused() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let gif = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;".to_vec();
let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><script>alert(1)</script></svg>"#.to_vec();
for (declared, body, code) in [
("image/gif", gif.clone(), "unsupported_type"),
("image/png", gif, "unsupported_type"),
("image/svg+xml", svg.clone(), "unsupported_type"),
("image/png", svg, "unsupported_type"),
("text/plain", b"hello".to_vec(), "unsupported_type"),
("application/json", b"{}".to_vec(), "unsupported_type"),
(
"image/png",
b"not an image at all".to_vec(),
"unsupported_type",
),
// A JPEG sent as a PNG, a PNG sent as a JPEG, WebP sent as PNG: the name does not matter.
("image/png", jpeg(64, 64), "type_mismatch"),
("image/jpeg", png(64, 64), "type_mismatch"),
("image/png", webp(64, 64), "type_mismatch"),
] {
assert_error(
fx.upload(&alice, declared, body).await,
StatusCode::UNSUPPORTED_MEDIA_TYPE,
code,
)
.await;
}
// No content type at all.
let response = fx
.send(
Request::builder()
.method(Method::POST)
.uri("/v1/account/avatar")
.header("cookie", format!("__Host-vnox_session={}", alice.token))
.header("x-csrf-token", &alice.csrf)
.header("origin", ORIGIN)
.body(Body::from(png(64, 64)))
.unwrap(),
)
.await;
assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
assert_eq!(fx.avatar_rows().await, 0);
}
#[tokio::test]
async fn oversized_bodies_are_refused() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let mut big = png(64, 64);
big.resize(2 * 1024 * 1024 + 1, 0);
// Without a Content-Length (chunked), the read itself stops at the limit.
assert_error(
fx.upload(&alice, "image/png", big.clone()).await,
StatusCode::PAYLOAD_TOO_LARGE,
"too_large",
)
.await;
// With an announced length, it is refused before reading.
let response = fx
.send(
Request::builder()
.method(Method::POST)
.uri("/v1/account/avatar")
.header("cookie", format!("__Host-vnox_session={}", alice.token))
.header("x-csrf-token", &alice.csrf)
.header("origin", ORIGIN)
.header("content-type", "image/png")
.header("content-length", big.len())
.body(Body::from(big))
.unwrap(),
)
.await;
assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
// Unauthenticated callers never get their body read or decoded.
let response = fx
.change(
Method::POST,
None,
None,
Some(ORIGIN),
"image/png",
vec![0; 3 << 20],
)
.await;
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
assert_eq!(fx.avatar_rows().await, 0);
}
#[tokio::test]
async fn decompression_bomb_and_odd_dimensions_are_refused_before_decoding() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
// Tiny files whose headers claim huge or oversized pictures.
for (w, h) in [(60_000, 60_000), (4097, 64), (64, 4097), (u32::MAX >> 1, 1)] {
let lie = claim_size(&png(64, 64), w, h);
assert!(lie.len() < 100_000);
assert_error(
fx.upload(&alice, "image/png", lie).await,
StatusCode::UNPROCESSABLE_ENTITY,
"bad_dimensions",
)
.await;
}
// Real, merely oversized or undersized pictures.
assert_error(
fx.upload(&alice, "image/png", png(4097, 40)).await,
StatusCode::UNPROCESSABLE_ENTITY,
"bad_dimensions",
)
.await;
assert_error(
fx.upload(&alice, "image/jpeg", jpeg(16, 16)).await,
StatusCode::UNPROCESSABLE_ENTITY,
"bad_dimensions",
)
.await;
// Truncated and corrupted data.
let mut cut = png(300, 300);
cut.truncate(cut.len() / 2);
assert_error(
fx.upload(&alice, "image/png", cut).await,
StatusCode::UNPROCESSABLE_ENTITY,
"invalid_image",
)
.await;
let mut cut = jpeg(300, 300);
cut.truncate(60);
let response = fx.upload(&alice, "image/jpeg", cut).await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(fx.avatar_rows().await, 0);
}
#[tokio::test]
async fn a_new_upload_replaces_the_old_one() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let first = json(fx.upload(&alice, "image/png", png(100, 100)).await).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
let second = json(fx.upload(&alice, "image/jpeg", jpeg(150, 150)).await).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
assert_ne!(first, second);
assert_eq!(fx.avatar_rows().await, 1);
assert_eq!(fx.get(&first).await.status(), StatusCode::NOT_FOUND);
assert_eq!(fx.get(&second).await.status(), StatusCode::OK);
assert_eq!(fx.session_avatar(&alice).await, second);
}
#[tokio::test]
async fn delete_returns_the_provider_avatar_or_the_default() {
let fx = fixture().await;
let github = fx.github_user().await;
assert_eq!(fx.session_avatar(&github).await, GITHUB_AVATAR);
let url = json(fx.upload(&github, "image/png", png(64, 64)).await).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
assert_ne!(fx.session_avatar(&github).await, GITHUB_AVATAR);
let response = fx.remove(&github).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["cache-control"], "no-store");
assert_eq!(json(response).await["avatar_url"], GITHUB_AVATAR);
assert_eq!(fx.session_avatar(&github).await, GITHUB_AVATAR);
assert_eq!(fx.get(&url).await.status(), StatusCode::NOT_FOUND);
assert_eq!(fx.avatar_rows().await, 0);
// Removing again is harmless, and an email account falls back to the default (null).
assert_eq!(fx.remove(&github).await.status(), StatusCode::OK);
let alice = fx.email_user("alice@example.com").await;
fx.upload(&alice, "image/png", png(64, 64)).await;
let response = fx.remove(&alice).await;
assert_eq!(json(response).await["avatar_url"], serde_json::Value::Null);
assert_eq!(fx.session_avatar(&alice).await, serde_json::Value::Null);
}
#[tokio::test]
async fn avatar_urls_are_validated_and_unknown_ids_are_not_found() {
let fx = fixture().await;
for path in [
"/v1/avatars/".to_owned(),
"/v1/avatars/abc".to_owned(),
format!("/v1/avatars/{}", "0".repeat(64)),
format!("/v1/avatars/{}", "G".repeat(64)),
format!("/v1/avatars/{}", "A".repeat(64)),
"/v1/avatars/..%2F..%2Fhub.sqlite3".to_owned(),
] {
let response = fx.get(&path).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND, "{path}");
assert_eq!(response.headers()["cache-control"], "no-store");
}
}
#[tokio::test]
async fn upload_rate_limit_applies_per_account() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let bob = fx.email_user("bob@example.com").await;
let image = png(64, 64);
for _ in 0..10 {
assert_eq!(
fx.upload(&alice, "image/png", image.clone()).await.status(),
StatusCode::OK
);
}
assert_error(
fx.upload(&alice, "image/png", image.clone()).await,
StatusCode::TOO_MANY_REQUESTS,
"try_later",
)
.await;
assert_error(
fx.remove(&alice).await,
StatusCode::TOO_MANY_REQUESTS,
"try_later",
)
.await;
// Another account from the same source still has its own budget.
assert_eq!(
fx.upload(&bob, "image/png", image).await.status(),
StatusCode::OK
);
}
#[tokio::test]
async fn upload_rate_limit_applies_per_source() {
let fx = fixture().await;
let image = png(64, 64);
let mut accepted = 0;
for n in 0..40 {
let user = fx.email_user(&format!("user{n}@example.com")).await;
let response = fx
.send(
Request::builder()
.method(Method::POST)
.uri("/v1/account/avatar")
.header("cookie", format!("__Host-vnox_session={}", user.token))
.header("x-csrf-token", &user.csrf)
.header("origin", ORIGIN)
.header("x-forwarded-for", "203.0.113.9")
.header("content-type", "image/png")
.body(Body::from(image.clone()))
.unwrap(),
)
.await;
match response.status() {
StatusCode::OK => accepted += 1,
StatusCode::TOO_MANY_REQUESTS => break,
other => panic!("unexpected {other}"),
}
}
assert_eq!(accepted, 30);
}
#[tokio::test]
async fn deleting_an_account_removes_its_avatar() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
fx.upload(&alice, "image/png", png(64, 64)).await;
sqlx::query("DELETE FROM accounts WHERE user_id=?")
.bind(&alice.user.user_id)
.execute(&fx.state.database)
.await
.unwrap();
assert_eq!(fx.avatar_rows().await, 0);
}

View file

@ -258,7 +258,9 @@ async fn full_flow_creates_neutral_account_and_session() {
{
assert_eq!(url, ORIGIN);
}
assert!(!html.contains(&format!("{ORIGIN}/")) || html.contains("/assets/vnox-mark.png"));
assert!(
!html.contains(&format!("{ORIGIN}/")) || html.contains("/assets/vnox-mark-email.png")
);
}
// Only keyed MACs are stored.
let row: (String, String) = sqlx::query_as("SELECT email_mac,code_mac FROM email_attempts")

View file

@ -8,8 +8,11 @@ message Hello {
bytes server_pubkey = 2;
bytes challenge_nonce = 3;
string node_name = 4;
bytes server_eph_pubkey = 5;
// LNEx v3: the ephemeral X25519 exchange was replaced by TLS 1.3.
reserved 5;
reserved "server_eph_pubkey";
bool private_mode = 6;
// Ed25519 over "VNOX-LNEx-v3-server-hello\0" || tls_exporter || Hello(signature empty).
bytes server_signature = 7;
}
@ -17,8 +20,10 @@ message Auth {
bytes client_pubkey = 1;
string nickname = 2;
string lnex_version = 3;
// Ed25519 over the client-auth transcript bound to the TLS exporter (see docs/02-protocol/tls.md).
bytes signature = 4;
bytes client_eph_pubkey = 5;
reserved 5;
reserved "client_eph_pubkey";
}
message Session {