diff --git a/Cargo.toml b/Cargo.toml index b342207..ce3fceb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2024" rust-version.workspace = true license = "AGPL-3.0-only" -description = "Self-hosted Signal service for Polymorfa zero-knowledge sessions" +description = "Self-hosted Signal service for Polymorfa zero-knowledge connections" repository = "https://github.com/polymorfa/signal-node" publish = false diff --git a/README.md b/README.md index 85e3999..1508e8d 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,21 @@ # signal-node -`signal-node` is the customer-operated Signal service for Polymorfa zero-knowledge sessions. It owns the linked device's keys, decrypts incoming messages in the customer's process, and delivers them directly to the customer's server application. Its outbound WebSocket carries encrypted stanzas and protocol operations to Polymorfa. The application sends messages through this service's local API. +`signal-node` is the customer-operated Signal service for Polymorfa zero-knowledge connections. It owns the linked device's keys, decrypts incoming messages in the customer's process, and delivers them directly to the customer's server application. Its outbound WebSocket carries encrypted stanzas and protocol operations to Polymorfa. The application sends messages through this service's local API. -This repository is private. The implementation is under review and has not been published or accepted against a real WhatsApp account. Deployment also requires the corresponding Polymorfa runner/API support and session eligibility. Starting this binary does not enable zero-knowledge sessions or grant permissions. +This repository is private. The implementation is under review and has not been published or accepted against a real WhatsApp account. Deployment also requires the corresponding Polymorfa runner/API support and connection eligibility. Starting this binary does not enable zero-knowledge connections or grant permissions. ## Contracts and dependency status - Runner protocol: [`proto/polymorfa/signal/v1/signal_service.proto`](proto/polymorfa/signal/v1/signal_service.proto), version `1`, subprotocol `polymorfa.signal.v1`, originating at `b6d5f5f`. - Application API: [`docs/app-api.openapi.json`](docs/app-api.openapi.json). JSON field names use snake_case. Event and message timestamps use Unix seconds; lease expiry uses Unix milliseconds internally. -- Signal libraries: exact `polymorfa/whatsapp-rust` revision `4b3b13cacd40a27573d0246386db553ef887539b`, the unmerged [recordstore/Signal operations producer PR](https://github.com/polymorfa/whatsapp-rust/pull/5). All five normal/dev crate families use this same source. A successful local build does not make that producer a released dependency. +- Signal libraries: `wacore`, `wacore-binary` and `waproto` use exact `oxidezap/whatsapp-rust` revision `2671430db6161c01c507587d0e3c90dcf153aa85`. `wacore-recordstore` and `wacore-signal-ops` are workspace crates under `crates/`. A successful local build does not establish published dependencies or live-provider acceptance. - Rust MSRV: `1.95`. The checked-in toolchain selects `1.95.0`. The server connection uses a project credential in `Authorization`, never in a URL or browser. The local API uses a separate application bearer secret. It rejects every authenticated request with an `Origin` header, including `Origin: null`, and supplies no CORS permission. Browser/WASM remote transport is unavailable until Polymorfa provides a distinct, short-lived client grant backed by live authorization. Never put the project credential or application secret in a browser. ## Durable public prekey uploads -The additive runner operations `PreparePreKeyUpload` and `AcknowledgePreKeyUpload` retain protocol version `1`. Prepare accepts 1..812 and returns the entire surviving pending batch under one opaque token, including after a process or database reopen. A later request for 50 can return the outstanding 812 keys; it never truncates or tops up that batch. Only public keys, IDs and the token cross the runner protocol. Counter, private keys and pending metadata commit atomically in the customer store. Keep one `SignalOps` instance per held session scope, as the service does. +The additive runner operations `PreparePreKeyUpload` and `AcknowledgePreKeyUpload` retain protocol version `1`. Prepare accepts 1..812 and returns the entire surviving pending batch under one opaque token, including after a process or database reopen. A later request for 50 can return the outstanding 812 keys; it never truncates or tops up that batch. Only public keys, IDs and the token cross the runner protocol. Counter, private keys and pending metadata commit atomically in the customer store. Keep one `SignalOps` instance per held connection scope, as the service does. The runner acknowledges only after its upload succeeds, using that token and unique original IDs covering every surviving key. Consumed originals may remain in an in-flight ACK; they stay deleted. Flags, the exact replay receipt and pending retirement commit together. The most recent exact ACK can be repeated after a lost response or restart without changing a newer pending batch. A timeout does not establish whether WhatsApp accepted an upload. Fresh retry-receipt keys still use `GeneratePreKeys` and `MarkPreKeysUploaded`; the legacy mark rejects the entire request if it includes an original pending-batch member, including a consumed member. Uploaded counts describe surviving local flags, not WhatsApp's remaining pool. @@ -31,11 +31,11 @@ cargo build --release --locked ./target/release/signal-node --config /etc/signal-node/signal-node.toml ``` -Copy [`signal-node.example.toml`](signal-node.example.toml) to a private configuration directory. Set the actual runner URL and eligible session IDs. Give every node a unique `node_id`. Place the project credential, application secret, master key and optional webhook secret in separately mounted secret files. Secret file paths resolve against the process working directory; use absolute paths in deployments. Keep the master key and its recovery copy outside the database. +Copy [`signal-node.example.toml`](signal-node.example.toml) to a private configuration directory. Set the actual runner URL and eligible connection IDs. Give every node a unique `node_id`. Place the project credential, application secret, master key and optional webhook secret in separately mounted secret files. Secret file paths resolve against the process working directory; use absolute paths in deployments. Keep the master key and its recovery copy outside the database. The operator can generate a random master key with `signal-node generate-key`, redirecting its output directly to a private secret file. The value is base64 of 32 random bytes. Do not print it in logs, paste it into a support ticket, or commit it. Application secrets require at least 16 visible ASCII characters without spaces; webhook secrets require at least 16 characters; provision independent random secrets. -Environment variables override inline file settings. An inline override and a configured `*_file` for the same secret are rejected, so remove the file setting before switching sources. Supported overrides are `SIGNAL_NODE_ID`, `SIGNAL_NODE_POLYMORFA_URL`, `SIGNAL_NODE_POLYMORFA_CREDENTIAL`, `SIGNAL_NODE_SESSIONS` (comma-separated), `SIGNAL_NODE_STORAGE_DRIVER`, `SIGNAL_NODE_STORAGE_URL`, `SIGNAL_NODE_MASTER_KEY`, `SIGNAL_NODE_HTTP_LISTEN`, `SIGNAL_NODE_HTTP_SECRET`, `SIGNAL_NODE_WEBHOOK_URL`, `SIGNAL_NODE_WEBHOOK_SECRET`, `SIGNAL_NODE_HISTORY_DELIVER` and `SIGNAL_NODE_APP_STATE_SHARE_KEYS`. `SIGNAL_NODE_CONFIG` selects the file when `--config` is absent. `SIGNAL_NODE_LOG_FORMAT=json` selects structured logs; `SIGNAL_NODE_LOG` sets the log filter. Avoid verbose dependency logging in production. +Environment variables override inline file settings. An inline override and a configured `*_file` for the same secret are rejected, so remove the file setting before switching sources. Supported overrides are `SIGNAL_NODE_ID`, `SIGNAL_NODE_POLYMORFA_URL`, `SIGNAL_NODE_POLYMORFA_CREDENTIAL`, `SIGNAL_NODE_CONNECTIONS` (comma-separated), `SIGNAL_NODE_STORAGE_DRIVER`, `SIGNAL_NODE_STORAGE_URL`, `SIGNAL_NODE_MASTER_KEY`, `SIGNAL_NODE_HTTP_LISTEN`, `SIGNAL_NODE_HTTP_SECRET`, `SIGNAL_NODE_WEBHOOK_URL`, `SIGNAL_NODE_WEBHOOK_SECRET`, `SIGNAL_NODE_HISTORY_DELIVER` and `SIGNAL_NODE_APP_STATE_SHARE_KEYS`. `SIGNAL_NODE_CONFIG` selects the file when `--config` is absent. `SIGNAL_NODE_LOG_FORMAT=json` selects structured logs; `SIGNAL_NODE_LOG` sets the log filter. Avoid verbose dependency logging in production. The runner URL requires `wss`; loopback `ws` is available for local testing. It cannot contain URL credentials, a query or a fragment. Webhooks require HTTPS, with loopback HTTP allowed for tests. The service does not follow webhook redirects or forward either bearer credential to the webhook. @@ -51,19 +51,19 @@ docker run --rm --read-only --cap-drop ALL --security-opt no-new-privileges \ signal-node:local --config /etc/signal-node/signal-node.toml ``` -The image runs as UID/GID `10001`. Grant that identity read access to secret/config files and write access to the state directory. Use `http.listen = "0.0.0.0:8787"` inside the container, while binding the host port to loopback or a private network. The HTTP API carries plaintext and descriptors with media keys; use authenticated TLS termination if it crosses a host boundary. The default binary listener is `127.0.0.1:8787`. `/healthz` is public and returns only `{"status":"ok"}`. It reports process liveness, not upstream connectivity or session readiness. Authenticated `/v1/sessions` supplies local ownership and claim state. +The image runs as UID/GID `10001`. Grant that identity read access to secret/config files and write access to the state directory. Use `http.listen = "0.0.0.0:8787"` inside the container, while binding the host port to loopback or a private network. The HTTP API carries plaintext and descriptors with media keys; use authenticated TLS termination if it crosses a host boundary. The default binary listener is `127.0.0.1:8787`. `/healthz` is public and returns only `{"status":"ok"}`. It reports process liveness, not upstream connectivity or connection readiness. Authenticated `/v1/connections` supplies local ownership and claim state. SIGINT/SIGTERM stop renewal and release held leases. HTTP shutdown waits for open requests and SSE streams, then aborts remaining tasks after a ten-second deadline. Unreleased leases expire after a forced stop; configure the supervisor to allow at least that shutdown period. ## Application API -All `/v1/*` requests require `Authorization: Bearer `. The secret authorizes every configured local session; deploy separate services/secrets for applications that must not share that authority. Do not pass a Polymorfa project credential to these endpoints. +All `/v1/*` requests require `Authorization: Bearer `. The secret authorizes every configured local connection; deploy separate services/secrets for applications that must not share that authority. Do not pass a Polymorfa project credential to these endpoints. | Method | Path | Result | | --- | --- | --- | -| GET | `/v1/sessions` | Node ID and locally held sessions, each with `id`, `lease_generation`, `claimed`, `has_device_keys`, `state`, nullable `pn` and `lid` | -| POST | `/v1/sessions/{id}/messages` | Send text or one encrypted-media descriptor; returns `message_id`, `server_timestamp`, `resent` | -| GET | `/v1/events?session_id={id}` | SSE stream of decrypted `message` events and explicitly enabled `history.sync` descriptors | +| GET | `/v1/connections` | Node ID and locally held connections, each with `id`, `lease_generation`, `claimed`, `has_device_keys`, `state`, nullable `pn` and `lid` | +| POST | `/v1/connections/{id}/messages` | Send text or one encrypted-media descriptor; returns `message_id`, `server_timestamp`, `resent` | +| GET | `/v1/events?connection_id={id}` | SSE stream of decrypted `message` events and explicitly enabled `history.sync` descriptors | | POST | `/v1/events/{id}/ack` | `204` for a pending event; `404` when no delivery awaits that ID | A text send has this body: @@ -72,20 +72,20 @@ A text send has this body: {"to":"15551234567@s.whatsapp.net","text":"Hello"} ``` -Supply exactly one of `text` or `media`. A media send provides an already encrypted/uploaded descriptor; the service does not upload plaintext or fetch media. The OpenAPI schema defines image, video, audio and document descriptors, required hashes/key/path/size fields, and optional metadata. An unknown configured session returns `404`; an unowned or unpaired session returns `409`; disconnected/storage-unavailable operations return `503`; runner rate refusal returns `429`. Local pacing queues sends rather than rejecting them solely because the five-per-second window is full. Invalid input returns `400`. Error envelopes use `{"error":{"code":"...","message":"..."}}`. +Supply exactly one of `text` or `media`. A media send provides an already encrypted/uploaded descriptor; the service does not upload plaintext or fetch media. The OpenAPI schema defines image, video, audio and document descriptors, required hashes/key/path/size fields, and optional metadata. An unknown configured connection returns `404`; an unowned or unpaired connection returns `409`; disconnected/storage-unavailable operations return `503`; runner rate refusal returns `429`. Local pacing queues sends rather than rejecting them solely because the five-per-second window is full. Invalid input returns `400`. Error envelopes use `{"error":{"code":"...","message":"..."}}`. If a queued send loses its reply through timeout or connection loss, the service returns `504 send_unconfirmed` with `error.message_id`. This also applies when a participant-hash mismatch acknowledgment requires a resend and that resend fails, even before the second stanza is queued. The first stanza may already have reached some participants. The ordinary `503` response applies only before a send acknowledgment. Retain the ID and reconcile the outcome before sending again. Do not automatically retry: a new POST generates another message ID and can duplicate delivery. The returned ID is neither an idempotency key nor an application-API status lookup. -A sender-key distribution write failure preserves the acknowledgment and permits the one same-ID mismatch resend. Without a mismatch, the confirmed send returns `200`. Fence loss retires the old session and returns the confirmed result without a resend. +A sender-key distribution write failure preserves the acknowledgment and permits the one same-ID mismatch resend. Without a mismatch, the confirmed send returns `200`. Fence loss retires the old connection and returns the confirmed result without a resend. -Events contain a stable `id`, `type`, `session_id`, routing metadata, `message_id`, `timestamp`, `is_from_me`, `redelivered`, `identity_changed` and `message_proto`. Optional fields include `sender_alt`, `text`, `media` and `history`. `message_proto` is a base64 WhatsApp message protobuf for ordinary messages. History events use an empty `message_proto` and expose only the history notification descriptor (including any inline payload already contained in that notification). Descriptor keys are sensitive application data. +Events contain a stable `id`, `type`, `connection_id`, routing metadata, `message_id`, `timestamp`, `is_from_me`, `redelivered`, `identity_changed` and `message_proto`. Optional fields include `sender_alt`, `text`, `media` and `history`. `message_proto` is a base64 WhatsApp message protobuf for ordinary messages. History events use an empty `message_proto` and expose only the history notification descriptor (including any inline payload already contained in that notification). Descriptor keys are sensitive application data. ### Acknowledgment and replay A receive that produces an application event succeeds only after one application acknowledgment. With both channels enabled, the first successful webhook or SSE acknowledgment wins. - Webhook: any `2xx` response acknowledges the event. Persist/deduplicate the event before responding. Non-`2xx`, redirects, timeouts and connection failures do not acknowledge it. -- SSE: persist/deduplicate the event, then POST its `id` to the ACK route. Multiple subscribers receive the same event; one acknowledgment completes all pending receives for that ID. IDs are unique per session: two sessions that receive the same group message get different IDs. Keep authorization headers on the stream and ACK request. +- SSE: persist/deduplicate the event, then POST its `id` to the ACK route. Multiple subscribers receive the same event; one acknowledgment completes all pending receives for that ID. IDs are unique per connection: two connections that receive the same group message get different IDs. Keep authorization headers on the stream and ACK request. The webhook signs the exact request body bytes. Headers are `Signal-Node-Timestamp` (Unix seconds), `Signal-Node-Event-Id`, and `Signal-Node-Signature: v1=`. The signed bytes are `timestamp + "." + rawBody`. Verify the MAC in constant time and reject timestamps outside a bounded window, such as five minutes, before parsing or processing. The Rust helpers `delivery::verify` and `delivery::verify_recent` implement the MAC and timestamp checks. Deduplicate by event ID in durable application storage; a valid signature alone does not prevent replay. @@ -95,7 +95,7 @@ An enabled own-device app-state key share is sealed separately before that deliv Protocol-only messages such as sender-key distributions and app-state shares do not produce application events; the Signal core processes them locally and marks them consumed without an application ACK. Disabled or foreign-device history notifications also produce no application event. The service never sends decrypted message content in the runner receive response. The service returns app-state key shares to the runner only after explicit operator opt-in and only from the account's own devices. Mixed protocol/text or media messages preserve ordinary application content; their application protobuf omits protocol fields, and history metadata is included only with consent. -SSE uses one shared buffer of at most 1,024 events per session filter. All subscribers with the same filter share that buffer. A lagging subscriber can miss an event, but it cannot acknowledge an event it never processes. There is no SSE cursor replay or `Last-Event-ID` recovery. Reconnect the stream and rely on runner ciphertext retry plus the sealed buffer for unacknowledged messages. With no webhook and no stream subscriber, receive fails immediately instead of silently dropping an application message. The default acknowledgment timeout is ten seconds. +SSE uses one shared buffer of at most 1,024 events per connection filter. All subscribers with the same filter share that buffer. A lagging subscriber can miss an event, but it cannot acknowledge an event it never processes. There is no SSE cursor replay or `Last-Event-ID` recovery. Reconnect the stream and rely on runner ciphertext retry plus the sealed buffer for unacknowledged messages. With no webhook and no stream subscriber, receive fails immediately instead of silently dropping an application message. The default acknowledgment timeout is ten seconds. ## App-state key sharing consent @@ -111,7 +111,7 @@ runner to decrypt synchronized metadata, including contact names, labels and mute/archive/pin state. Message-plaintext custody does not imply metadata opacity; Polymorfa can also see operational metadata such as blocklists. Disabling the setting stops future key forwarding; it cannot recall keys or metadata already -shared. This operator setting grants no session eligibility or hosted-history access. +shared. This operator setting grants no connection eligibility or hosted-history access. Shipped-client evidence is Cellar bundle `whatsapp-1049950004`, `WAWebSyncdDecryptMutations.js:24-35` (key-based mutation decryption) and @@ -121,9 +121,9 @@ blocklists use those app-state keys. ## History consent and content limits -`history.deliver` defaults to `false`. Enabling it is an explicit deployment-level consent decision by the customer operator; it does not grant Polymorfa session eligibility, hosted-history storage, or a backend entitlement. Even with consent, only notifications marked `is_from_me` are delivered. The service forwards descriptors and optional inline notification payloads. It never downloads, inflates, stores or MMS-deletes history chunks. The application SDK owns those actions and its own retention decision. +`history.deliver` defaults to `false`. Enabling it is an explicit deployment-level consent decision by the customer operator; it does not grant Polymorfa connection eligibility, hosted-history storage, or a backend entitlement. Even with consent, only notifications marked `is_from_me` are delivered. The service forwards descriptors and optional inline notification payloads. It never downloads, inflates, stores or MMS-deletes history chunks. The application SDK owns those actions and its own retention decision. -Zero-knowledge sessions do not use hosted message history or content-dependent Campaigns. Polymorfa still sees routing and operational metadata required for transport. The customer service and application see plaintext. A compromised customer host or application bearer can expose it. This service does not remove the need to protect the customer runtime, backups and application database. +Zero-knowledge connections do not use hosted message history or content-dependent Campaigns. Polymorfa still sees routing and operational metadata required for transport. The customer service and application see plaintext. A compromised customer host or application bearer can expose it. This service does not remove the need to protect the customer runtime, backups and application database. Polymorfa holds the WhatsApp connection, so this service learns recipients' devices and public keys from Polymorfa, much as a WhatsApp client learns them from WhatsApp's servers. It checks that each key bundle is well formed and signed by the identity key the bundle presents, but it cannot independently verify that the identity key belongs to the intended recipient. Polymorfa is trusted to relay device lists, prekey bundles and identity-change notices faithfully. A Polymorfa runner that substituted a key or added a device could read messages encrypted to that key. That affects first contact with a recipient, newly listed devices, and contacts whose stored identity it caused this service to forget. It does not expose this service's stored keys or other recipients' sessions. Independent key verification is not implemented. @@ -131,19 +131,19 @@ Polymorfa holds the WhatsApp connection, so this service learns recipients' devi Use SQLite for a deployment on one host, or PostgreSQL for multiple hosts. SQLite uses WAL and `BEGIN IMMEDIATE` for atomic fence checks and write batches. Multiple processes can share one local file; do not place that file on a network filesystem for multi-host failover. PostgreSQL locks the lease row and commits each fence check with its write batch. Startup runs the checked-in driver migrations; the database identity needs schema/migration permissions. Use a dedicated customer-owned database and network/TLS policy. The `memory` driver loses state on restart and is for tests only. -Each session gets a random 256-bit data key. An exclusive, fenced insert stores it wrapped with AES-256-GCM under the operator's master key. The wrap authenticates the session scope. Every Signal record then uses the session key and authenticates a length-prefixed domain, scope, namespace and record key. Copying ciphertext to another slot fails authentication. Record keys, namespace tags, session scopes and lease metadata remain readable. Sealing does not detect a rollback to an older valid value in the same slot. +Each connection gets a random 256-bit data key. An exclusive, fenced insert stores it wrapped with AES-256-GCM under the operator's master key. The wrap authenticates the connection scope. Every Signal record then uses the connection key and authenticates a length-prefixed domain, scope, namespace and record key. Copying ciphertext to another slot fails authentication. Record keys, namespace tags, connection scopes and lease metadata remain readable. Sealing does not detect a rollback to an older valid value in the same slot. -All nodes sharing a deployment need the same master key and database. A wrong key fails session activation without resetting state. Back up the database and master key separately, retain a protected recovery copy, and test restoration in an isolated deployment that cannot compete with production claims. Losing the master key loses access to the sealed device state. Online master/data-key rotation and a sealed cross-mode handoff are not implemented; never overwrite an existing key to simulate rotation. Set an operational rotation plan before approaching AES-GCM's per-key nonce limits. +All nodes sharing a deployment need the same master key and database. A wrong key fails connection activation without resetting state. Back up the database and master key separately, retain a protected recovery copy, and test restoration in an isolated deployment that cannot compete with production claims. Losing the master key loses access to the sealed device state. Online master/data-key rotation and a sealed cross-mode handoff are not implemented; never overwrite an existing key to simulate rotation. Set an operational rotation plan before approaching AES-GCM's per-key nonce limits. -The sealed decrypt buffer defaults to 14 days; sealed sent-message retry records default to seven days. The pruner runs hourly for locally held sessions. Expired records in inactive/logged-out scopes persist until an owning node prunes them or the operator removes that scope. A retention window bounds replay/retry support, not delivery latency. Retention applies to customer-owned sealed protocol state and is distinct from optional hosted history. +The sealed decrypt buffer defaults to 14 days; sealed sent-message retry records default to seven days. The pruner runs hourly for locally held connections. Expired records in inactive/logged-out scopes persist until an owning node prunes them or the operator removes that scope. A retention window bounds replay/retry support, not delivery latency. Retention applies to customer-owned sealed protocol state and is distinct from optional hosted history. ## Scale and failover -Give each replica a unique stable node ID, the same session list, the same master key, and access to the same PostgreSQL store. Each process uses a fresh random incarnation token for its database lease holder, so even a replacement with the same configured node ID cannot share the old fence. Every replica attempts free sessions. The first successful lease holder claims that session over its outbound connection. Polymorfa routes to its highest accepted generation. A closed transport releases its fences, and a new socket claims only after acquiring higher durable generations. A crash leaves the lease to expire; another node then takes a higher generation. The old generation cannot commit record writes after takeover. +Give each replica a unique stable node ID, the same connection list, the same master key, and access to the same PostgreSQL store. Each process uses a fresh random incarnation token for its database lease holder, so even a replacement with the same configured node ID cannot share the old fence. Every replica attempts free connections. The first successful lease holder claims that connection over its outbound connection. Polymorfa routes to its highest accepted generation. A closed transport releases its fences, and a new socket claims only after acquiring higher durable generations. A crash leaves the lease to expire; another node then takes a higher generation. The old generation cannot commit record writes after takeover. Defaults are a 30-second lease TTL and renewal every ten seconds. Keep renewal at most half the TTL. A node stops serving on loss, expiry, or a renewal failure close to expiry. A resumed process checks its deadline before requests and again after send pacing or application ACK. Generation-specific callbacks cannot evict a newer local holder. Keep host clocks synchronized; lease timestamps come from the service clock, so this implementation does not solve arbitrary clock skew. Store loss fails closed; it does not create a new in-memory key store. -The service clamps the upstream send limit to at most five `SendStanza` operations per second per session, including its own participant-hash resend. The runner independently enforces its transport admission limit. Lookups/prekey operations do not consume the service's SendStanza pacing window. The ceiling is not a throughput guarantee or a WhatsApp safety approval. +The service clamps the upstream send limit to at most five `SendStanza` operations per second per connection, including its own participant-hash resend. The runner independently enforces its transport admission limit. Lookups/prekey operations do not consume the service's SendStanza pacing window. The ceiling is not a throughput guarantee or a WhatsApp safety approval. After a participant-hash mismatch, the service refreshes routing and rebuilds once with the same message ID. WhatsApp Web excludes previously addressed devices; this implementation re-encrypts for all current devices. Real-provider acceptance of that broader resend is unresolved. Source evidence is Cellar bundle `whatsapp-1049950004`, `WAWebSendUserMsgJob.js:53-79` and `WAWebSendGroupSkmsgJob.js:194-213`. Protocol-message dispatch evidence is `WAWebHandleMsgProcess.js:201-228`. Those shipped-client observations do not prove current server behavior. @@ -151,11 +151,11 @@ After a participant-hash mismatch, the service refreshes routing and rebuilds on ```sh cargo fmt --all --check -cargo clippy --all-targets --locked -- -D warnings +cargo clippy --workspace --all-targets --locked -- -D warnings # Use a dedicated fixture database; do not point tests at production. SIGNAL_NODE_TEST_POSTGRES_URL=postgres://fixture@127.0.0.1/signal_node_tests \ - cargo test --all-targets --locked -cargo test --doc --locked + cargo test --workspace --all-targets --locked +cargo test --workspace --doc --locked cargo build --release --locked ``` diff --git a/docs/app-api.openapi.json b/docs/app-api.openapi.json index 7e3187a..aff4931 100644 --- a/docs/app-api.openapi.json +++ b/docs/app-api.openapi.json @@ -34,16 +34,16 @@ } } }, - "/v1/sessions": { + "/v1/connections": { "get": { - "operationId": "listSessions", + "operationId": "listConnections", "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Sessions" + "$ref": "#/components/schemas/Connections" } } } @@ -57,7 +57,7 @@ } } }, - "/v1/sessions/{id}/messages": { + "/v1/connections/{id}/messages": { "post": { "operationId": "sendMessage", "parameters": [ @@ -95,10 +95,10 @@ "description": "Invalid request" }, "404": { - "description": "Unknown configured session" + "description": "Unknown configured connection" }, "409": { - "description": "Not lease holder, unpaired or unavailable session" + "description": "Not lease holder, unpaired or unavailable connection" }, "429": { "description": "Runner send ceiling reached" @@ -130,7 +130,7 @@ "operationId": "events", "parameters": [ { - "name": "session_id", + "name": "connection_id", "in": "query", "schema": { "type": "string" @@ -356,7 +356,7 @@ "required": [ "id", "type", - "session_id", + "connection_id", "chat", "sender", "message_id", @@ -377,7 +377,7 @@ "history.sync" ] }, - "session_id": { + "connection_id": { "type": "string" }, "chat": { @@ -496,7 +496,7 @@ } } }, - "SessionInfo": { + "ConnectionInfo": { "type": "object", "required": [ "id", @@ -538,20 +538,20 @@ } } }, - "Sessions": { + "Connections": { "type": "object", "required": [ "node_id", - "sessions" + "connections" ], "properties": { "node_id": { "type": "string" }, - "sessions": { + "connections": { "type": "array", "items": { - "$ref": "#/components/schemas/SessionInfo" + "$ref": "#/components/schemas/ConnectionInfo" } } } diff --git a/docs/integration-status.md b/docs/integration-status.md index 7051485..5316809 100644 --- a/docs/integration-status.md +++ b/docs/integration-status.md @@ -1,43 +1,96 @@ -# Producer integration status +# Signal service integration status -This service implements the accepted server-mode contract. It does not establish deployed zero-knowledge availability or browser remote transport support. Source revisions remain explicit: runner protocol originates at signal-node `b6d5f5f` and adds durable public upload requests 20/21 and response 18 without changing protocol version 1; all Signal library families are pinned to `4b3b13cacd40a27573d0246386db553ef887539b` in unmerged whatsapp-rust PR #5. The unchanged service OpenAPI artifact is the application/native-client contract. +The service is private and unmerged. Local verification does not establish live +WhatsApp, hosted transport, deployment or package availability. This Connection +candidate preserves rename source `61209057729b002a2122b898d744a8813a702fc7` and +implementation PR [#1](https://github.com/polymorfa/signal-node/pull/1) target +`4d9694eaf97deca34c78990d1293b2b533e19d17`. Its existing PR +[#3](https://github.com/polymorfa/signal-node/pull/3) targets +`feat/signal-service-completion-20261014`, not `main`. Attribution PR #2 is separate. -## Mandatory six-part assessment +## Producer and client ABI -| Part | Status | Evidence / remaining owner | -| --- | --- | --- | -| API | Updated locally; upstream integration blocked | Additive protobuf upload prepare/ACK and full-batch response; local HTTP/OpenAPI, Origin rejection and SSE/ACK contract unchanged by this checkpoint. Backend PR #593 and HyperMeow own exact wire consumption, live authorization and real runner acceptance. | -| SDKs | Application HTTP unaffected by this wire addition; program integration remains coordinated | Native application clients do not implement private runner prekey operations or import the AGPL core. Parent coordinates TypeScript and five handwritten native consumers against exact application pins. The separate WASM producer shares the guarded core API; no private service proto belongs in MIT SDKs. | -| CLI | Updated service CLI; Polymorfa CLI blocked | `--config`, `--help`, `--version`, private operator key generation and SIGINT/SIGTERM shutdown. Customer CLI must consume accepted SDK/backend revisions; this producer does not edit that repository. | -| Docs | Updated operator/API docs; public release docs blocked | README, example configuration, OpenAPI and this integration record. Parent owns Mintlify guides, language pages, Help Center and release-appropriate changelog. No local draft date is presented as a shipped release. | -| Feature releases | Blocked for release | Backend owns beta eligibility/flag/enrollment/entitlement enforcement. Service does not grant access or change rollout controls. No publication, visibility, tags or production flag edits. Unmerged library producer, real-provider acceptance and legal review remain gates. | -| Admin controls | Unaffected within service authority; backend integration blocked | No customer/control-plane state or staff action is added here. Keys/plaintext remain customer-side. Backend PR #593 owns counts-only transport diagnostics and existing eligibility/disable controls; no new admin credential or direct database authority. | +| Boundary | Current source and contract | +| --- | --- | +| Signal core | `wacore`, `wacore-binary` and `waproto` use oxidezap/whatsapp-rust `2671430db6161c01c507587d0e3c90dcf153aa85`. | +| Record store and Signal operations | Workspace crates under `crates/recordstore` and `crates/signal-ops`, preserved from target4d9694e. Their cryptographic sessions, trust/cancellation/prekey behavior and storage domains are not account-resource aliases. | +| Toolchain and native checks | Rust1.95.0; accepted workspace/lock, CI matrix and Docker inputs remain. | +| Runner protocol | `proto/polymorfa/signal/v1/signal_service.proto`, protocol1 and subprotocol `polymorfa.signal.v1`. Account symbols change; numeric tags, types, enum values and oneof positions remain. | +| Companion identity | Accepted target adds `Receive.device_identity` tag10 and `Bundle.device_identity` tag8. Bytes are forwarded to existing verification; they are not synthesized or substituted from the service's own identity. | +| Application API | `docs/app-api.openapi.json`; `/v1/connections`, `connection_id` events/filter and canonical account errors. Actual phone and per-peer Signal session fields retain their meanings. | +| Configuration | `polymorfa.connections`, `SIGNAL_NODE_CONNECTIONS`; stable configured selector values and local lease generations retain their values. | -## All fourteen program layers +Account messages are `ClaimConnection`, `ReleaseConnection`, `ConnectionClaimed` +and `ConnectionEvent`. The complete descriptor matches target4d9694e after only +the exact account-name mapping, including the accepted companion additions. +Two native wire regressions pin lease/event tags and companion byte fields. +The unavailable-account enum remains numeric8. No account compatibility alias, +retired HTTP route or permissive old event-filter reader is added. -| Layer | Service slice status / dependency | -| --- | --- | -| 1. Libraries | All normal/dev families repinned to exact `4b3b13c`; PR #5 unmerged. Durable atomic upload batches, exact replay ACK and fresh-only legacy marks consumed without a private-format parser. No library rewrite or publication here. | -| 1b. Signal service | Additive durable upload dispatch and core-backed local uploaded count; real framed SQLite/PostgreSQL recovery and rollback tests. HTTP routes, consent, key custody and runtime policy unchanged. | -| 2. Runners / Bartender | HyperMeow explicit batch interface and backend PR #593 wire/vendor integration remain pending. Unknown operations fail Unsupported without fresh-generation fallback. Fake WS is not a live runner; Bartender unchanged. | -| 3. Temporal | Parent/backend owner assesses workflows and transport recovery; this process creates no Temporal workflow or control-plane command. | -| 4. Customer API | Backend PR #593 owns mode, consent, refusal and project authority. Local API cannot bypass them. | -| 5. Admin API | Backend owns bounded diagnostics/capabilities. Service does not expose customer keys to staff. | -| 6. Inspector | Parent owns real-account acceptance scenarios; local two-device fixture is not Inspector acceptance. | -| 7. Console UI | Parent owns customer mode/consent/trade-off flow and backend integration. | -| 8. Admin UI | Parent/backend owner integrates diagnostics through API-owned authority. No service management UI added. | -| 9. SDKs | Parent coordinates TS + Go/Python/PHP/Rust/C# media/history/storage and sidecar clients against exact producer pins. | -| 10. CLI | Service CLI updated. Polymorfa CLI integration remains with its owner. | -| 11. Docs | Operator/API documentation updated here. Public Mintlify guides/references/language pages remain coordinated by parent. | -| 12. Help Center | Parent owns consent and operational trade-off article; no shipped availability claim in this producer. | -| 13. Marketing | Parent owns release-aligned copy; no announcement or availability claim authorized here. | - -## Verification limits - -Native checks use Rust 1.95 and a dedicated real PostgreSQL fixture plus SQLite. The integration transport is a fake Polymorfa peer; actual Signal encryption/decryption runs on both devices. Tests cover application ACK before durable delivery, HMAC over exact bytes, webhook rejection/redirect, SSE duplicate waiters, sealed replay after crash, old-generation writes, expiry/reacquisition, slot authentication, history consent and send pacing. - -Durable-upload tests additionally prepare 812, reopen the service/store and request 50 while retaining the full original batch. Real SQL failures at pending publication and ACK receipt insertion roll back counter/private-key or uploaded-flag changes. An actual encrypted receive consumes a pending key, the app fsyncs its receipt before ACK, and the subsequent batch ACK cannot resurrect that key. Discarding a serialized ACK response, reopening and repeating the exact ACK leaves a newer pending batch unchanged. Partial, duplicate, foreign, malformed and stale acknowledgments fail; legacy marks refuse mixed/consumed pending members. Wire-tag fixtures preserve additive version-1 decoding. Malformed frames allocate nothing; a frame above the existing 16 MiB transport ceiling reconnects with a higher fence and recovers the pending batch. - -The existing `[app_state].share_keys` opt-in remains false by default and requires own-device evidence when enabled. That exception permits contact-name, label and mute/archive/pin metadata decryption; message plaintext custody does not promise metadata opacity. QuickLink admission, short-lived tunnel/grant authority, Temporal, standard-custody behavior, billing/metering, logging and hosted retention are unchanged. No public release record or feature-flag change is warranted for an unmerged private protocol producer; parent owns coordinated release documentation and availability gates. - -Real WhatsApp pairing, media/history download, group resend, retry receipts and server redelivery have not been exercised. The participant-hash resend addresses every current device rather than WA Web's exclusion list; provider acceptance remains unresolved. Arbitrary clock skew, key rotation and same-slot rollback protection are not implemented. Browser remote relay is blocked pending distinct short-lived client grant authority. AGPL/legal review and owner approval are required before making this repository or artifacts public. +Signal ratchets, `Namespace::Session`, upstream Signal errors, +`peer_data_request_session_id`, stored record keys, sealing domains, IDs and +fences retain their meanings and bytes. Retry-receipt bundles establish a fresh +Signal session, not a fresh account Connection. Application event IDs retain the +accepted target's domain and length-prefixed account selector, so an ACK cannot +complete another Connection's event. + +## Companion producer dependencies + +The pinned backend HyperMeow `c858e73f841a` does not carry these identity bytes +through `RemoteReceive`, and its existing `prekey.Bundle` conversion does not +supply the companion identity. Regeneration alone cannot populate them. + +Existing counterpart [HyperMeow #69](https://github.com/polymorfa/hypermeow/pull/69), +head `4792d8dfc24c793711dd563079bba8fae787ec98`, adds +`RemoteReceive.DeviceIdentity` for prekey messages and +`FetchPreKeysWithIdentityNoError` / `FetchedPreKey.DeviceIdentity`. Existing bundle +APIs stay unchanged; its shadow relay still has no identity bytes. This source +has a separate human-maintainer and native/provider acceptance boundary. + +The existing backend counterpart is [Polymorfa #1037](https://github.com/polymorfa/polymorfa/pull/1037), +source `e8ab3e02b00f76b63c6918232e3ca7c6ddd8d6c0`, supplied by the family owner. +It carries the narrow HyperMeow companion producer, receive/bundle projections, +WebSocket regression and generated bindings. Root owns preserved integration into +[Backend #1022](https://github.com/polymorfa/polymorfa/pull/1022) and regeneration +against this exact final Signal proto. No monorepo/library pin, binding or runtime +producer was edited in this service lane. Consumer composition remains pending; +this document does not claim that the published backend already carries it. + +Cellar shipped-client evidence is bundle `whatsapp-1054794655`, indexed2026-11-16, +with zero chunk/codegen failures and5719 unresolved dependencies. +`WAWebMsgProcessingDecryptApi.js:24-39` passes received device identity into +companion verification before decryption. `WAWebAdvSignatureApi.js:42-59,80-91` +checks account/device signatures and selects the prekey verification path. +These are shipped-client observations, not current server or live-provider +acceptance. The service retains the target's verification and refusal gates; +missing data does not justify bypassing them. + +## Verification and availability + +The preserved candidate passes178 workspace/all-target native tests with zero +failed or ignored cases, including two new binary contract regressions. Tests +use a dedicated real PostgreSQL16.14 instance, real SQLite, sealed state and +actual synthetic-device Signal crypto with a framed fixture peer. Authentication, +Origin rejection, canonical routes, rejected old filters, claim/generation fences, +trust/cancellation, consent, prekey batch recovery and ACK isolation remain tested. +Strict workspace/all-target Clippy, formatting and Buf lint/build pass. + +The actual debug binary reports `signal-node/0.1.0`. Release compilation is not +attempted at the observed1.6GiB free disk. Docker runtime is unavailable locally; +container/TLS/native provider acceptance remains hosted. Official MBX Cargo is +used without manual cache, target, profile, cap or authentication changes. +Automatic MBX collection is host-managed and remains in the command receipts. + +The customer API, six SDKs, CLI, integrations, Inspector, Console, Connect, +Admin, docs and Help Center remain in the same coordinated family. This producer +adds no eligibility, enrollment, feature flag, metering/financial authority, +QuickLink/browser tunnel grant, staff authority or hosted history access. Existing +app-state/history opt-ins and customer custody boundaries remain. Source API date +and public-spec availability are owned by the family release record. + +Real pairing, send/receive/media/history/group/retry and retained/signed-state +acceptance remain separate gates. Private AGPL/legal review, human notice/approval, +exact merged source cohorts and owner publication authority remain. No merge, +deployment, publication, provider configuration or main-only cutover occurs here. +Rollback must preserve sealed/device/prekey state, event identity and fences; +never reset keys or weaken verification to fit an older consumer. diff --git a/internal/agent-sessions/sessions/purpshell-t3-codex/connections-rename-20261114/2026-11-17-signal-target-merge.md b/internal/agent-sessions/sessions/purpshell-t3-codex/connections-rename-20261114/2026-11-17-signal-target-merge.md new file mode 100644 index 0000000..ecd4703 --- /dev/null +++ b/internal/agent-sessions/sessions/purpshell-t3-codex/connections-rename-20261114/2026-11-17-signal-target-merge.md @@ -0,0 +1,61 @@ +# Signal Connection target merge + +Registration511. Rajeh Taher, Codex/T3 Code/OpenAI/gpt-6.1-sol/xhigh, +writer on rajeh/connection-rename-signal-node. No new delegate or checkout. +Selected visible evidence is manual; complete event/tool/timestamp/attachment +capture has gaps. Thread ID is not exposed. No credentials, customer content, +authentication screens or hidden reasoning are included. + +The user assigned existing Signal PR3 conflict repair in the task-owned checkout. +The clean accepted head61209057729b002a2122b898d744a8813a702fc7 is preserve-merged +with actual target4d9694eaf97deca34c78990d1293b2b533e19d17 on +feat/signal-service-completion-20261014. Target main is not substituted. The +three conflicted files are the proto and two boundary-test files. Accepted +workspace crates, lock, toolchain, Docker/workflow inputs and all target authors +remain intact. New account event-ID/trace/test bindings use Connection while +preserving the target's exact hash domain, selector bytes and ACK isolation. +Target trust/vouch, cancellation, refusal, companion and prekey behavior remains. + +Full descriptors compare equal to target4d after only the exact account-symbol +mapping:135 top-level fields, all tags/types/enum numbers/oneofs and protocol1. +Receive.device_identity retains tag10; Bundle.device_identity retains tag8. +Proto SHA256 is1bbda926d7e3ae251bcb18abe14bc516c795a670b7cad65c2aacea0c7f1e118a. +Two native wire regressions pin claims/events and additive opaque identity bytes. +Signal cryptographic sessions, Namespace::Session, upstream errors, stored keys, +sealing domains and peer_data_request_session_id retain their meanings/bytes. +The retry-bundle comment correctly refers to a fresh Signal session. + +Official /Users/purpshell/Library/Application Support/mbx/bin/cargo is the only +Cargo route used, version1.95.0. All178 workspace/all-target tests pass with zero +failed/ignored cases and a dedicated real PostgreSQL16.14 fixture, plus real +SQLite/crypto and framed synthetic peer. Final strict workspace Clippy, formatting, +Buf lint/build and the workspace documentation-test command pass; docs contain +zero executable examples. The debug binary reports signal-node/0.1.0. +Owned PostgreSQL PID31614 is stopped. All own local commands are terminal. + +Disk fell to117MiB. No further build/docs/Cargo/PG process is started. Release +build is unrun for capacity; Docker runtime is unavailable locally. These are +genuine remaining gates, not replaced by tests. Official MBX automatic collection +appears in logs; no manual shared-cache/target/profile/cap/auth change occurred. + +Current README/integration-status now identify the actual accepted local crates, +oxidezap2671430d source, Rust1.95 and client ABI dependencies. Existing HyperMeow +PR69 head4792d8dfc24c793711dd563079bba8fae787ec98 and backend PR1037 sourcee8ab3e02 +are counterparts. The current old Go producer lacks receive/bundle companion +identity propagation. Root owns exact integration and regeneration in Backend1022; +no monorepo, library pin or binding is edited here. Missing identity is not filled +with an empty/own identity and verification is never weakened. + +Cellar latest stored1054794655 is checked: zero parse/codegen failures and5719 +unresolved dependencies. WAWebMsgProcessingDecryptApi24-39 and +WAWebAdvSignatureApi42-59/80-91 show received companion identity verification. +This is shipped-client evidence, not current server acceptance. Full paths/hashes +and owner/counterpart links are retained in the external source receipt. + +Four application heads remain untouched. No live Signal credentials, real pairing, +provider/browser action, CI cancellation/rerun, merge/deploy/publication or legal/ +main-only action. Preserve own executing jobs before a qualified PR3 push and +immediately link it. Current-head Codex correctness/security and available scoped +CodeRabbit are authorized; old/unavailable reviews are never counted as a pass. +Family readiness, native/retained/product, human-maintainer, legal approval/notice, +source/API-date and publication gates remain. Child never watches PRs. diff --git a/proto/polymorfa/signal/v1/signal_service.proto b/proto/polymorfa/signal/v1/signal_service.proto index 07d545a..fe642a7 100644 --- a/proto/polymorfa/signal/v1/signal_service.proto +++ b/proto/polymorfa/signal/v1/signal_service.proto @@ -1,5 +1,5 @@ // Contract between Polymorfa's WhatsApp runner and a customer-run Signal -// service for zero-knowledge (ZK) sessions. +// service for zero-knowledge (ZK) connections. // // The Signal service holds a linked device's Signal private keys, sessions // and message plaintext. Polymorfa keeps the WhatsApp connection and asks the @@ -13,18 +13,18 @@ // Authorization header. Polymorfa never connects to the service. // - Each binary WebSocket message is exactly one Frame. // - Both sides send requests. A request carries an id unique per sender per -// connection; its response or Error carries the same id. Requests may be +// WebSocket link; its response or Error carries the same id. Requests may be // answered out of order. -// - One connection serves any number of sessions. Every session-scoped -// request names the session and the lease generation it was sent under. +// - One WebSocket link serves any number of Connections. Every account-scoped +// request names the Connection and the lease generation it was sent under. // // Leases and fencing -// - Before Polymorfa routes a session's operations to a connection, the -// service claims the session with ClaimSession, giving the generation of -// the lease it holds in its own store. Polymorfa routes the session to the +// - Before Polymorfa routes a Connection's operations to a service link, the +// service claims the Connection with ClaimConnection and its stored lease +// generation. Polymorfa routes the Connection to the // highest generation it has accepted and rejects claims and requests at a // lower generation with CODE_NOT_LEASE_HOLDER. -// - While no connection holds a session, the session is paused: Polymorfa +// - While no service link holds a Connection, the Connection is paused: Polymorfa // stops reading messages for it and resumes when a service claims it. // // Versioning @@ -40,7 +40,7 @@ option go_package = "github.com/polymorfa/polymorfa/apps/api/gen/proto/polymorfa // Frame is one WebSocket message. message Frame { // Request id, or the id of the request this frame answers. Zero for - // Hello, Welcome and SessionEvent. + // Hello, Welcome and ConnectionEvent. uint64 id = 1; oneof body { @@ -59,7 +59,7 @@ message Frame { // Either direction. Answers a request that failed. Error error = 8; // Polymorfa → service. Unsolicited; never answered. - SessionEvent session_event = 9; + ConnectionEvent connection_event = 9; } } @@ -74,18 +74,18 @@ message Hello { message Welcome { uint32 protocol_version = 1; - // Project the credential belongs to. Sessions outside it are refused. + // Project the credential belongs to. Connections outside it are refused. string project_id = 2; // The service sends a Ping at least this often; Polymorfa closes a silent // connection after three intervals. uint32 heartbeat_interval_ms = 3; - // Ceiling on SendStanza requests per session per second. + // Ceiling on SendStanza requests per connection per second. uint32 max_sends_per_second = 4; } // RunnerRequest is an operation Polymorfa's runner needs from the service. message RunnerRequest { - string session_id = 1; + string connection_id = 1; uint64 lease_generation = 2; oneof op { @@ -122,13 +122,13 @@ message ServiceResponse { // ServiceRequest is something the service needs from Polymorfa, chiefly to // send messages it built. message ServiceRequest { - string session_id = 1; - // Zero for ClaimSession and Ping. + string connection_id = 1; + // Zero for ClaimConnection and Ping. uint64 lease_generation = 2; oneof op { - ClaimSession claim_session = 10; - ReleaseSession release_session = 11; + ClaimConnection claim_connection = 10; + ReleaseConnection release_connection = 11; SendStanza send_stanza = 12; ResolveDevices resolve_devices = 13; FetchPreKeys fetch_pre_keys = 14; @@ -140,7 +140,7 @@ message ServiceRequest { message RunnerResponse { oneof result { Ok ok = 10; - SessionClaimed session_claimed = 11; + ConnectionClaimed connection_claimed = 11; SendResult send = 12; Devices devices = 13; Bundles bundles = 14; @@ -156,7 +156,7 @@ message Error { // A dependency is down (database, WhatsApp connection). Retry later. CODE_UNAVAILABLE = 2; CODE_INVALID_ARGUMENT = 3; - // The request's lease generation is not the current one for the session. + // The request's lease generation is not the current one for the connection. CODE_NOT_LEASE_HOLDER = 4; // Receive only: the payload could not be decrypted. See decrypt_failure. CODE_DECRYPT_FAILED = 5; @@ -164,9 +164,9 @@ message Error { CODE_UNSUPPORTED = 6; // SendStanza exceeded Welcome.max_sends_per_second. CODE_RATE_LIMITED = 7; - // The session is not paired, logged out, or not in this project. - CODE_SESSION_UNAVAILABLE = 8; - // The operation is refused: for zero-knowledge sessions (for example a + // The connection is not paired, logged out, or not in this project. + CODE_CONNECTION_UNAVAILABLE = 8; + // The operation is refused: for zero-knowledge connections (for example a // Campaign send), or because a recipient device's identity did not verify // against its account. CODE_REFUSED = 9; @@ -181,7 +181,7 @@ message Error { enum DecryptFailure { // Any other failure; the runner sends a retry receipt. DECRYPT_FAILURE_UNSPECIFIED = 0; - // Older than the session can decrypt; ignore the payload. + // Older than the Signal session can decrypt; ignore the payload. DECRYPT_FAILURE_OLD_COUNTER = 1; // Group message without a sender key. DECRYPT_FAILURE_NO_SENDER_KEY = 2; @@ -324,7 +324,7 @@ message Resend { // "pn" or "lid"; empty when not a group. string addressing_mode = 8; uint32 retry_count = 9; - // Keys carried by the retry receipt, to start a fresh session. + // Keys carried by the retry receipt, to start a fresh Signal session. Bundle bundle = 10; } @@ -349,25 +349,25 @@ message MigrateResult { // ─── Service → runner operations ──────────────────────────────────────── -message ClaimSession { +message ClaimConnection { // Generation of the lease the service holds in its own store. Must be // greater than or equal to any generation Polymorfa accepted before. uint64 generation = 1; } -message SessionClaimed { - // Polymorfa's view of the session when the claim was accepted. - SessionEvent.State state = 1; +message ConnectionClaimed { + // Polymorfa's view of the connection when the claim was accepted. + ConnectionEvent.State state = 1; // This device's JIDs once paired. string pn = 2; string lid = 3; } -message ReleaseSession {} +message ReleaseConnection {} // SendStanza transmits a message stanza the service built. Polymorfa checks -// the stanza is a for this session, applies the send ceiling and -// session safety pacing, and waits for the server acknowledgement. +// the stanza is a for this connection, applies the send ceiling and +// connection safety pacing, and waits for the server acknowledgement. message SendStanza { bytes node = 1; // Participant hash the stanza was built for (groups), to report a @@ -431,7 +431,7 @@ message Ping {} // ─── Notifications ────────────────────────────────────────────────────── -message SessionEvent { +message ConnectionEvent { enum State { STATE_UNSPECIFIED = 0; // Waiting for the QR code to be scanned. @@ -439,12 +439,12 @@ message SessionEvent { STATE_CONNECTED = 2; // Reconnecting to WhatsApp. STATE_DISCONNECTED = 3; - // No Signal service holds the session; messages are held by WhatsApp. + // No Signal service holds the connection; messages are held by WhatsApp. STATE_PAUSED = 4; - // Unlinked. The service may delete the session's state. + // Unlinked. The service may delete the connection's state. STATE_LOGGED_OUT = 5; } - string session_id = 1; + string connection_id = 1; State state = 2; string pn = 3; string lid = 4; diff --git a/signal-node.example.toml b/signal-node.example.toml index 194083f..dd04fd8 100644 --- a/signal-node.example.toml +++ b/signal-node.example.toml @@ -1,10 +1,10 @@ -# Operator example. Replace the URL and session IDs with eligible real values. +# Operator example. Replace the URL and connection IDs with eligible real values. node_id = "customer-node-1" [polymorfa] url = "wss://api.example.invalid/api/zk/signal" credential_file = "/run/secrets/polymorfa-project-credential" -sessions = ["replace-with-session-id"] +connections = ["replace-with-connection-id"] request_timeout_ms = 15000 reconnect_min_ms = 500 reconnect_max_ms = 30000 @@ -33,7 +33,7 @@ ack_timeout_ms = 10000 # webhook_secret_file = "/run/secrets/signal-webhook-secret" [history] -# Explicit operator consent. This never grants backend session eligibility. +# Explicit operator consent. This never grants backend connection eligibility. deliver = false [app_state] diff --git a/src/config.rs b/src/config.rs index a3ff5bd..7624b71 100644 --- a/src/config.rs +++ b/src/config.rs @@ -94,11 +94,11 @@ pub struct PolymorfaConfig { pub credential: Secret, #[serde(default)] pub credential_file: Option, - /// Zero-knowledge session IDs this deployment serves. Every node of a - /// deployment lists the same sessions; leases decide which node serves + /// Zero-knowledge connection IDs this deployment serves. Every node of a + /// deployment lists the same connections; leases decide which node serves /// each one. #[serde(default)] - pub sessions: Vec, + pub connections: Vec, /// Longest wait for a response to a request this node sends. #[serde(default = "default_request_timeout_ms")] pub request_timeout_ms: u64, @@ -127,7 +127,7 @@ pub struct StorageConfig { pub url: Secret, #[serde(default)] pub url_file: Option, - /// Base64 of 32 random bytes. Wraps each session's data key. + /// Base64 of 32 random bytes. Wraps each connection's data key. #[serde(default)] pub master_key: Secret, #[serde(default)] @@ -143,7 +143,7 @@ pub struct LeaseConfig { /// long after a node stops. #[serde(default = "default_lease_ttl_ms")] pub ttl_ms: u64, - /// How often leases are renewed and free sessions are tried. + /// How often leases are renewed and free connections are tried. #[serde(default = "default_lease_renew_ms")] pub renew_interval_ms: u64, } @@ -287,7 +287,7 @@ pub struct Resolved { pub node_id: String, pub polymorfa_url: String, pub credential: Secret, - pub sessions: Vec, + pub connections: Vec, pub request_timeout: Duration, pub reconnect_min: Duration, pub reconnect_max: Duration, @@ -314,7 +314,7 @@ impl std::fmt::Debug for Resolved { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Resolved") .field("node_id", &self.node_id) - .field("sessions", &self.sessions) + .field("connections", &self.connections) .field("storage_driver", &self.storage_driver) .field("master_key", &"") .field("credential", &self.credential) @@ -329,7 +329,7 @@ pub const ENV_VARS: &[&str] = &[ "SIGNAL_NODE_ID", "SIGNAL_NODE_POLYMORFA_URL", "SIGNAL_NODE_POLYMORFA_CREDENTIAL", - "SIGNAL_NODE_SESSIONS", + "SIGNAL_NODE_CONNECTIONS", "SIGNAL_NODE_STORAGE_DRIVER", "SIGNAL_NODE_STORAGE_URL", "SIGNAL_NODE_MASTER_KEY", @@ -365,8 +365,8 @@ impl Config { if let Some(v) = env("SIGNAL_NODE_POLYMORFA_CREDENTIAL") { self.polymorfa.credential = Secret::new(v); } - if let Some(v) = env("SIGNAL_NODE_SESSIONS") { - self.polymorfa.sessions = v + if let Some(v) = env("SIGNAL_NODE_CONNECTIONS") { + self.polymorfa.connections = v .split(',') .map(str::trim) .filter(|s| !s.is_empty()) @@ -522,9 +522,9 @@ impl Config { "leases.renew_interval_ms must be at most half of leases.ttl_ms", )); } - for id in &self.polymorfa.sessions { + for id in &self.polymorfa.connections { if id.is_empty() || id.len() > 200 { - return Err(invalid("session IDs must be 1 to 200 characters")); + return Err(invalid("connection IDs must be 1 to 200 characters")); } } let node_id = if self.node_id.is_empty() { @@ -552,7 +552,7 @@ impl Config { node_id, polymorfa_url: self.polymorfa.url, credential, - sessions: self.polymorfa.sessions, + connections: self.polymorfa.connections, request_timeout: Duration::from_millis(self.polymorfa.request_timeout_ms), reconnect_min: Duration::from_millis(self.polymorfa.reconnect_min_ms), reconnect_max: Duration::from_millis(self.polymorfa.reconnect_max_ms), @@ -620,7 +620,7 @@ mod tests { [polymorfa] url = "wss://example.invalid/signal" credential = "pk_test_credential" - sessions = ["sess_a", "sess_b"] + connections = ["sess_a", "sess_b"] [storage] driver = "memory" @@ -633,7 +633,7 @@ mod tests { #[test] fn a_minimal_file_resolves_with_defaults() { let resolved = Config::from_toml(MINIMAL).unwrap().resolve().unwrap(); - assert_eq!(resolved.sessions, ["sess_a", "sess_b"]); + assert_eq!(resolved.connections, ["sess_a", "sess_b"]); assert_eq!(resolved.lease_ttl_ms, 30_000); assert!(!resolved.deliver_history, "history must be off by default"); assert!( @@ -661,14 +661,14 @@ mod tests { let mut config = Config::from_toml(MINIMAL).unwrap(); config .apply_env(|name| match name { - "SIGNAL_NODE_SESSIONS" => Some("one, two".into()), + "SIGNAL_NODE_CONNECTIONS" => Some("one, two".into()), "SIGNAL_NODE_HISTORY_DELIVER" => Some("true".into()), "SIGNAL_NODE_ID" => Some("node-9".into()), _ => None, }) .unwrap(); let resolved = config.resolve().unwrap(); - assert_eq!(resolved.sessions, ["one", "two"]); + assert_eq!(resolved.connections, ["one", "two"]); assert!(resolved.deliver_history); assert_eq!(resolved.node_id, "node-9"); } diff --git a/src/delivery.rs b/src/delivery.rs index 7fa6648..fa52fff 100644 --- a/src/delivery.rs +++ b/src/delivery.rs @@ -114,10 +114,10 @@ impl Delivery { self.subscribe_for(None) } - /// Subscribe to one session, or all sessions when the filter is absent. + /// Subscribe to one connection, or all connections when the filter is absent. pub fn subscribe_for( &self, - session_id: Option, + connection_id: Option, ) -> Option>> { let mut streams = self .streams @@ -127,7 +127,7 @@ impl Delivery { streams.retain(|_, stream| stream.receiver_count() > 0); Some( streams - .entry(session_id) + .entry(connection_id) .or_insert_with(|| broadcast::channel(STREAM_BUFFER).0) .subscribe(), ) @@ -158,7 +158,9 @@ impl Delivery { registry.retain(|_, stream| stream.receiver_count() > 0); registry .iter() - .filter(|(filter, _)| filter.as_ref().is_none_or(|id| *id == event.session_id)) + .filter(|(filter, _)| { + filter.as_ref().is_none_or(|id| *id == event.connection_id) + }) .map(|(_, stream)| stream.clone()) .collect() }) @@ -255,7 +257,7 @@ mod tests { Event { id: id.into(), kind: "message", - session_id: "s".into(), + connection_id: "s".into(), chat: "c".into(), sender: "x".into(), sender_alt: None, diff --git a/src/http.rs b/src/http.rs index 7b3a9fb..a935159 100644 --- a/src/http.rs +++ b/src/http.rs @@ -32,8 +32,8 @@ fn error(status: StatusCode, code: &str, message: impl Into) -> Response pub fn router(node: Arc) -> Router { let api = Router::new() - .route("/v1/sessions", get(list_sessions)) - .route("/v1/sessions/{id}/messages", post(send_message)) + .route("/v1/connections", get(list_connections)) + .route("/v1/connections/{id}/messages", post(send_message)) .route("/v1/events", get(events)) .route("/v1/events/{id}/ack", post(ack)) .layer(middleware::from_fn_with_state(node.clone(), authenticate)); @@ -75,20 +75,20 @@ async fn health(State(node): State>) -> Response { } #[derive(Serialize)] -struct SessionInfo { +struct ConnectionInfo { id: String, lease_generation: u64, claimed: bool, has_device_keys: bool, #[serde(flatten)] - view: crate::node::SessionView, + view: crate::node::ConnectionView, } -async fn list_sessions(State(node): State>) -> Response { - let sessions: Vec = node - .sessions() +async fn list_connections(State(node): State>) -> Response { + let connections: Vec = node + .connections() .into_iter() - .map(|s| SessionInfo { + .map(|s| ConnectionInfo { id: s.id.clone(), lease_generation: s.generation, claimed: s.is_claimed(), @@ -96,7 +96,7 @@ async fn list_sessions(State(node): State>) -> Response { view: s.view(), }) .collect(); - Json(json!({ "node_id": node.cfg.node_id, "sessions": sessions })).into_response() + Json(json!({ "node_id": node.cfg.node_id, "connections": connections })).into_response() } async fn send_message( @@ -111,18 +111,18 @@ async fn send_message( if !node.is_configured(&id) { return error( StatusCode::NOT_FOUND, - "unknown_session", - "session is not configured", + "unknown_connection", + "connection is not configured", ); } - let Some(session) = node.session(&id) else { + let Some(connection) = node.connection(&id) else { return error( StatusCode::CONFLICT, "not_lease_holder", - "another node serves this session; send through that node", + "another node serves this connection; send through that node", ); }; - match send::send(&node, &session, request).await { + match send::send(&node, &connection, request).await { Ok(outcome) => (StatusCode::OK, Json(outcome)).into_response(), Err(SendError::Unconfirmed { message_id }) => ( StatusCode::GATEWAY_TIMEOUT, @@ -137,12 +137,12 @@ async fn send_message( let (status, code) = match &e { SendError::Invalid(_) => (StatusCode::BAD_REQUEST, "invalid_request"), SendError::NotLeaseHolder => (StatusCode::CONFLICT, "not_lease_holder"), - SendError::NotPaired => (StatusCode::CONFLICT, "session_not_paired"), + SendError::NotPaired => (StatusCode::CONFLICT, "connection_not_paired"), SendError::Disconnected => (StatusCode::SERVICE_UNAVAILABLE, "disconnected"), SendError::RateLimited => (StatusCode::TOO_MANY_REQUESTS, "rate_limited"), SendError::Refused(err) => match err.code_enum() { - crate::proto::Code::SessionUnavailable => { - (StatusCode::CONFLICT, "session_unavailable") + crate::proto::Code::ConnectionUnavailable => { + (StatusCode::CONFLICT, "connection_unavailable") } crate::proto::Code::Refused => (StatusCode::FORBIDDEN, "refused"), crate::proto::Code::Unavailable => { @@ -162,8 +162,9 @@ async fn send_message( } #[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct EventFilter { - session_id: Option, + connection_id: Option, } // An error Response is the standard axum handler shape; it is built only on refusal. @@ -172,7 +173,7 @@ async fn events( State(node): State>, Query(filter): Query, ) -> Result>>, Response> { - let Some(rx) = node.delivery.subscribe_for(filter.session_id) else { + let Some(rx) = node.delivery.subscribe_for(filter.connection_id) else { return Err(error( StatusCode::NOT_FOUND, "stream_disabled", diff --git a/src/keys.rs b/src/keys.rs index 00cfb3b..9a9caea 100644 --- a/src/keys.rs +++ b/src/keys.rs @@ -2,16 +2,16 @@ //! Key custody for server mode. //! -//! The operator supplies one 256-bit master key. Each session has its own -//! random 256-bit data key, stored in the session's records wrapped +//! The operator supplies one 256-bit master key. Each connection has its own +//! random 256-bit data key, stored in the connection's records wrapped //! (AES-256-GCM) by the master key. A node unwraps the data key once, when it -//! takes the session's lease, and seals every record with it from then on. +//! takes the connection's lease, and seals every record with it from then on. //! The master key never touches the database, and the data key is never //! stored unwrapped. //! -//! The wrapped data key lives in the session's `device` namespace under +//! The wrapped data key lives in the connection's `device` namespace under //! [`DATA_KEY_RECORD`]. It is written with an exclusive, fenced insert, so -//! two nodes that race to initialise a session cannot both pick a key. +//! two nodes that race to initialise a connection cannot both pick a key. use aes_gcm::aead::{Aead, KeyInit, Payload}; use aes_gcm::{Aes256Gcm, Nonce}; @@ -28,9 +28,9 @@ const NONCE_LEN: usize = 12; #[derive(Debug, thiserror::Error)] pub enum KeyError { - #[error("the session's data key does not open with this master key")] + #[error("the connection's data key does not open with this master key")] WrongMasterKey, - #[error("the session's wrapped data key is malformed")] + #[error("the connection's wrapped data key is malformed")] Malformed, #[error("storage: {0}")] Store(#[from] wacore::store::error::StoreError), diff --git a/src/lib.rs b/src/lib.rs index 3392ffb..35bfd14 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only //! signal-node: the self-hosted Signal service for Polymorfa -//! zero-knowledge sessions. +//! zero-knowledge connections. pub mod config; pub mod delivery; @@ -33,7 +33,7 @@ pub struct Running { } impl Running { - /// Release every session, then stop. + /// Release every connection, then stop. pub async fn shutdown(mut self) { // Open SSE streams or a stalled peer cannot hold shutdown forever. // Aborting after this deadline leaves any unreleased lease to expire. diff --git a/src/link.rs b/src/link.rs index 1fff6c6..f4c84ba 100644 --- a/src/link.rs +++ b/src/link.rs @@ -8,7 +8,7 @@ //! failure the link reconnects with jittered exponential backoff. use crate::proto::{ - self, Code, Frame, Hello, RunnerRequest, ServiceRequest, ServiceResponse, SessionEvent, + self, Code, ConnectionEvent, Frame, Hello, RunnerRequest, ServiceRequest, ServiceResponse, Welcome, frame::Body, runner_response, service_request, }; use async_trait::async_trait; @@ -113,7 +113,7 @@ impl Link { /// Send a request and wait for its response. pub async fn request( &self, - session_id: &str, + connection_id: &str, lease_generation: u64, op: service_request::Op, ) -> Result { @@ -126,7 +126,7 @@ impl Link { let frame = Frame::with( id, Body::ServiceRequest(ServiceRequest { - session_id: session_id.to_owned(), + connection_id: connection_id.to_owned(), lease_generation, op: Some(op), }), @@ -169,7 +169,7 @@ pub trait Handler: Send + Sync + 'static { -> Result; /// `origin` is the link that delivered the event; a handler must ignore /// events from a link that is no longer current. - async fn session_event(&self, event: SessionEvent, origin: Arc); + async fn connection_event(&self, event: ConnectionEvent, origin: Arc); /// A link finished its handshake. Claims go out from here. async fn connected(&self, link: Arc); async fn disconnected(&self); @@ -434,10 +434,10 @@ async fn dispatch(link: &Arc, handler: &Arc, frame: Frame) { link.complete(id, Err(error)).await; } } - Some(Body::SessionEvent(event)) => { + Some(Body::ConnectionEvent(event)) => { let handler = handler.clone(); let origin = link.clone(); - tokio::spawn(async move { handler.session_event(event, origin).await }); + tokio::spawn(async move { handler.connection_event(event, origin).await }); } Some(Body::Welcome(_)) => {} Some(Body::Hello(_) | Body::ServiceRequest(_) | Body::ServiceResponse(_)) => { diff --git a/src/main.rs b/src/main.rs index daa770a..041fe01 100644 --- a/src/main.rs +++ b/src/main.rs @@ -53,7 +53,7 @@ async fn main() -> anyhow::Result<()> { let running = signal_node::start(resolved, backend).await?; wait_for_stop().await; - tracing::info!("stopping: releasing sessions"); + tracing::info!("stopping: releasing connections"); running.shutdown().await; Ok(()) } diff --git a/src/message.rs b/src/message.rs index 409d828..323464e 100644 --- a/src/message.rs +++ b/src/message.rs @@ -24,7 +24,7 @@ pub struct Event { /// `message` or `history.sync`. #[serde(rename = "type")] pub kind: &'static str, - pub session_id: String, + pub connection_id: String, pub chat: String, pub sender: String, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/src/node.rs b/src/node.rs index 9ff3ae7..01932ad 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: AGPL-3.0-only -//! The node: which sessions it holds, its link to Polymorfa, and the loops +//! The node: which connections it holds, its link to Polymorfa, and the loops //! that keep both current. //! -//! Every configured session is tried on each lease tick. A node serves a -//! session only while it holds the session's lease in the shared store. -//! Holding the lease, it claims the session from Polymorfa at that lease's +//! Every configured connection is tried on each lease tick. A node serves a +//! connection only while it holds the connection's lease in the shared store. +//! Holding the lease, it claims the connection from Polymorfa at that lease's //! generation; Polymorfa routes to the highest generation it accepted. If //! the node stops renewing (crash, partition), the lease expires and another //! node takes it at a higher generation. Any write the old node still @@ -16,8 +16,8 @@ use crate::delivery::{Delivery, Webhook}; use crate::keys::MasterKey; use crate::link::{self, Handler, Link, LinkError, LinkSettings}; use crate::proto::{ - self, ClaimSession, Code, ReleaseSession, RunnerRequest, ServiceResponse, SessionEvent, - runner_response, service_request, session_event::State, + self, ClaimConnection, Code, ConnectionEvent, ReleaseConnection, RunnerRequest, + ServiceResponse, connection_event::State, runner_response, service_request, }; use crate::ratelimit::SendLimiter; use crate::share_replay::ShareReplay; @@ -41,9 +41,9 @@ pub fn now_ms() -> u64 { .map_or(0, |d| d.as_millis() as u64) } -/// What the application sees about a session on this node. +/// What the application sees about a connection on this node. #[derive(Debug, Clone, Default, Serialize)] -pub struct SessionView { +pub struct ConnectionView { pub state: String, pub pn: Option, pub lid: Option, @@ -57,8 +57,8 @@ fn state_name(state: i32) -> String { .to_ascii_lowercase() } -/// A session this node holds the lease for. -pub struct ActiveSession { +/// A connection this node holds the lease for. +pub struct ActiveConnection { pub id: String, pub generation: u64, lease: Mutex, @@ -69,10 +69,10 @@ pub struct ActiveSession { claiming: AtomicBool, lost: AtomicBool, pub limiter: SendLimiter, - view: RwLock, + view: RwLock, } -impl ActiveSession { +impl ActiveConnection { /// The Signal operations, if the device keys exist. pub fn ops(&self) -> Option> { self.ops.get().cloned() @@ -129,7 +129,7 @@ impl ActiveSession { !self.is_lost() && now_ms() < self.lease.lock().await.expires_at_ms } - pub fn view(&self) -> SessionView { + pub fn view(&self) -> ConnectionView { self.view.read().expect("view lock").clone() } @@ -156,8 +156,8 @@ pub struct Node { master: MasterKey, /// Unique process incarnation; stable diagnostic node IDs cannot share a fence. lease_holder: String, - sessions: RwLock>>, - /// Sessions Polymorfa reported logged out; not taken again until restart. + connections: RwLock>>, + /// Connections Polymorfa reported logged out; not taken again until restart. retired: RwLock>, /// Highest generation this process stopped serving without a confirmed /// release. A reacquired lease at or below it shares the old fence, so it is @@ -185,7 +185,7 @@ impl Node { ), cfg: Arc::new(cfg), backend: Arc::new(backend), - sessions: RwLock::new(HashMap::new()), + connections: RwLock::new(HashMap::new()), retired: RwLock::new(HashSet::new()), abandoned: RwLock::new(HashMap::new()), link: RwLock::new(None), @@ -198,19 +198,19 @@ impl Node { &self.backend } - pub fn session(&self, id: &str) -> Option> { - self.sessions + pub fn connection(&self, id: &str) -> Option> { + self.connections .read() - .expect("sessions lock") + .expect("connections lock") .get(id) .cloned() } - pub fn sessions(&self) -> Vec> { + pub fn connections(&self) -> Vec> { let mut all: Vec<_> = self - .sessions + .connections .read() - .expect("sessions lock") + .expect("connections lock") .values() .cloned() .collect(); @@ -219,7 +219,7 @@ impl Node { } pub fn is_configured(&self, id: &str) -> bool { - self.cfg.sessions.iter().any(|s| s == id) + self.cfg.connections.iter().any(|s| s == id) } pub fn link(&self) -> Option> { @@ -238,70 +238,71 @@ impl Node { /// released: it is no longer ours. pub fn lose(&self, id: &str, generation: u64, why: &str) { let removed = { - let mut sessions = self.sessions.write().expect("sessions lock"); - let Some(session) = sessions.get(id).filter(|s| s.generation == generation) else { + let mut connections = self.connections.write().expect("connections lock"); + let Some(connection) = connections.get(id).filter(|s| s.generation == generation) + else { return; }; // A lease tick must see the refused fence before the missing - // session, even when the later durable release fails. - session.lost.store(true, Ordering::SeqCst); + // connection, even when the later durable release fails. + connection.lost.store(true, Ordering::SeqCst); self.remember_abandoned(id, generation); - sessions.remove(id) + connections.remove(id) }; - if let Some(session) = removed { + if let Some(connection) = removed { tracing::warn!( - session = id, - generation = session.generation, + connection = id, + generation = connection.generation, reason = why, - "stopped serving session" + "stopped serving connection" ); } } - /// Give a session up voluntarily: tell Polymorfa, then release the lease + /// Give a connection up voluntarily: tell Polymorfa, then release the lease /// so another node can take it at once. pub async fn release(&self, id: &str) { let removed = { - let mut sessions = self.sessions.write().expect("sessions lock"); - let removed = sessions.remove(id); - if let Some(session) = &removed { - session.lost.store(true, Ordering::SeqCst); + let mut connections = self.connections.write().expect("connections lock"); + let removed = connections.remove(id); + if let Some(connection) = &removed { + connection.lost.store(true, Ordering::SeqCst); // Publish the refusal before a lease tick can observe the - // missing session, and before either release can suspend. - self.remember_abandoned(id, session.generation); + // missing connection, and before either release can suspend. + self.remember_abandoned(id, connection.generation); } removed }; - let Some(session) = removed else { return }; + let Some(connection) = removed else { return }; if let Some(link) = self.link() - && session.is_claimed() + && connection.is_claimed() { - let op = service_request::Op::ReleaseSession(ReleaseSession {}); - if let Err(e) = link.request(id, session.generation, op).await { - tracing::debug!(session = id, error = %e, "ReleaseSession was not acknowledged"); + let op = service_request::Op::ReleaseConnection(ReleaseConnection {}); + if let Err(e) = link.request(id, connection.generation, op).await { + tracing::debug!(connection = id, error = %e, "ReleaseConnection was not acknowledged"); } } - let lease = session.lease().await; + let lease = connection.lease().await; self.abandon(id, &lease).await; tracing::info!( - session = id, - generation = session.generation, - "released session" + connection = id, + generation = connection.generation, + "released connection" ); } - /// Map an operation error to a contract error, dropping the session if + /// Map an operation error to a contract error, dropping the connection if /// the store says another node took it. - pub fn ops_error(&self, session: &ActiveSession, error: &OpsError) -> proto::Error { + pub fn ops_error(&self, connection: &ActiveConnection, error: &OpsError) -> proto::Error { if error.is_fence_lost() { self.lose( - &session.id, - session.generation, + &connection.id, + connection.generation, "store refused a write: lease moved to another node", ); return proto::Error::new( Code::NotLeaseHolder, - "this node no longer holds the session", + "this node no longer holds the connection", ); } match error { @@ -310,7 +311,7 @@ impl Node { proto::Error::new(Code::InvalidArgument, message.clone()) } OpsError::NotInitialised => proto::Error::new( - Code::SessionUnavailable, + Code::ConnectionUnavailable, "device keys do not exist yet; GetIdentity creates them", ), OpsError::Pairing { code, text } => proto::Error::new( @@ -326,7 +327,7 @@ impl Node { } } - async fn activate(&self, lease: Lease) -> anyhow::Result> { + async fn activate(&self, lease: Lease) -> anyhow::Result> { let data_key = self .master .data_key_for(self.backend.as_ref(), &lease.fence) @@ -344,9 +345,13 @@ impl Node { let _ = ops.set(Arc::new(opened)); } Err(OpsError::NotInitialised) => {} - Err(e) => return Err(anyhow::anyhow!("opening the session's Signal state: {e}")), + Err(e) => { + return Err(anyhow::anyhow!( + "opening the connection's Signal state: {e}" + )); + } } - Ok(Arc::new(ActiveSession { + Ok(Arc::new(ActiveConnection { id: lease.fence.scope.to_string(), generation: lease.fence.generation, lease: Mutex::new(lease), @@ -357,7 +362,7 @@ impl Node { claiming: AtomicBool::new(false), lost: AtomicBool::new(false), limiter: SendLimiter::new(), - view: RwLock::new(SessionView { + view: RwLock::new(ConnectionView { state: "unclaimed".into(), ..Default::default() }), @@ -366,8 +371,13 @@ impl Node { /// Publish only while the connection that began acquisition is current. /// Holding the link read lock through insertion orders publication before - /// disconnect's link removal and subsequent session snapshot. - fn publish_acquired(&self, id: &str, session: Arc, origin: &Arc) -> bool { + /// disconnect's link removal and subsequent connection snapshot. + fn publish_acquired( + &self, + id: &str, + connection: Arc, + origin: &Arc, + ) -> bool { let current = self.link.read().expect("link lock"); if *self.shutdown.borrow() || !current @@ -376,47 +386,47 @@ impl Node { { return false; } - self.sessions + self.connections .write() - .expect("sessions lock") - .insert(id.to_owned(), session); + .expect("connections lock") + .insert(id.to_owned(), connection); true } - /// One pass over every configured session: renew what we hold, try to + /// One pass over every configured connection: renew what we hold, try to /// take what is free, and claim anything Polymorfa has not accepted yet. pub async fn tick_leases(self: &Arc) { let ttl = self.cfg.lease_ttl_ms; - for id in &self.cfg.sessions { + for id in &self.cfg.connections { if *self.shutdown.borrow() { return; } if self.retired.read().expect("retired lock").contains(id) { continue; } - match self.session(id) { - Some(session) => { - let lease = session.lease().await; + match self.connection(id) { + Some(connection) => { + let lease = connection.lease().await; let now = now_ms(); if now >= lease.expires_at_ms { - self.lose(id, session.generation, "lease expired before renewal"); + self.lose(id, connection.generation, "lease expired before renewal"); self.abandon(id, &lease).await; continue; } match self.backend.renew(&lease, now, ttl).await { - Ok(Some(renewed)) => *session.lease.lock().await = renewed, + Ok(Some(renewed)) => *connection.lease.lock().await = renewed, Ok(None) => { - self.lose(id, session.generation, "lease taken over"); + self.lose(id, connection.generation, "lease taken over"); continue; } Err(e) => { - tracing::warn!(session = %id, error = %e, "lease renewal failed"); + tracing::warn!(connection = %id, error = %e, "lease renewal failed"); // Stop before another node can take it. let margin = self.cfg.lease_renew.as_millis() as u64; if now.saturating_add(margin) >= lease.expires_at_ms { self.lose( id, - session.generation, + connection.generation, "lease could not be renewed before it expired", ); self.abandon(id, &lease).await; @@ -424,8 +434,8 @@ impl Node { } } } - if !session.is_claimed() { - self.spawn_claim(session); + if !connection.is_claimed() { + self.spawn_claim(connection); } } None => { @@ -448,41 +458,43 @@ impl Node { // Same holder, same fence: release so the next // acquisition increments the generation. if self.backend.release(&lease).await.is_ok() { - tracing::info!(session = %id, generation, "released an abandoned fence before reacquiring"); + tracing::info!(connection = %id, generation, "released an abandoned fence before reacquiring"); } continue; } match self.activate(lease.clone()).await { - Ok(session) => { - if !self.publish_acquired(id, session.clone(), &origin) { + Ok(connection) => { + if !self.publish_acquired(id, connection.clone(), &origin) { self.abandon(id, &lease).await; continue; } - tracing::info!(session = %id, generation, "took session lease"); - self.spawn_claim(session); + tracing::info!(connection = %id, generation, "took connection lease"); + self.spawn_claim(connection); } Err(e) => { - tracing::error!(session = %id, error = %e, "cannot serve session; releasing its lease"); + tracing::error!(connection = %id, error = %e, "cannot serve connection; releasing its lease"); self.abandon(id, &lease).await; } } } Ok(None) => {} - Err(e) => tracing::warn!(session = %id, error = %e, "lease acquire failed"), + Err(e) => { + tracing::warn!(connection = %id, error = %e, "lease acquire failed") + } } } } } } - /// Polymorfa refused this session's generation, for example after a + /// Polymorfa refused this connection's generation, for example after a /// runner-side pause. Stop serving it and release the durable lease, so the /// next acquisition claims a strictly higher generation instead of /// retrying the refused one forever. - pub(crate) async fn refused_generation(&self, session: &ActiveSession, why: &str) { - let lease = session.lease().await; - self.lose(&session.id, session.generation, why); - self.abandon(&session.id, &lease).await; + pub(crate) async fn refused_generation(&self, connection: &ActiveConnection, why: &str) { + let lease = connection.lease().await; + self.lose(&connection.id, connection.generation, why); + self.abandon(&connection.id, &lease).await; } /// Stop owning `lease` after serving stopped without a renewal. Release it so @@ -492,7 +504,7 @@ impl Node { let generation = lease.fence.generation; self.remember_abandoned(id, generation); if let Err(e) = self.backend.release(lease).await { - tracing::warn!(session = id, generation, error = %e, "abandoned lease release failed; its fence stays refused"); + tracing::warn!(connection = id, generation, error = %e, "abandoned lease release failed; its fence stays refused"); } } @@ -502,67 +514,69 @@ impl Node { *entry = (*entry).max(generation); } - fn spawn_claim(&self, session: Arc) { + fn spawn_claim(&self, connection: Arc) { let Some(link) = self.link() else { return }; let Some(node) = self.me.upgrade() else { return; }; - if session.claiming.swap(true, Ordering::SeqCst) { + if connection.claiming.swap(true, Ordering::SeqCst) { return; } tokio::spawn(async move { - node.claim(&session, &link).await; - session.claiming.store(false, Ordering::SeqCst); + node.claim(&connection, &link).await; + connection.claiming.store(false, Ordering::SeqCst); }); } - async fn claim(&self, session: &Arc, link: &Arc) { - if !session.can_serve().await { + async fn claim(&self, connection: &Arc, link: &Arc) { + if !connection.can_serve().await { return; } - let op = service_request::Op::ClaimSession(ClaimSession { - generation: session.generation, + let op = service_request::Op::ClaimConnection(ClaimConnection { + generation: connection.generation, }); - match link.request(&session.id, 0, op).await { - Ok(runner_response::Result::SessionClaimed(claimed)) => { - if !session.can_serve().await { + match link.request(&connection.id, 0, op).await { + Ok(runner_response::Result::ConnectionClaimed(claimed)) => { + if !connection.can_serve().await { return; } - session.claimed.store(true, Ordering::SeqCst); - session.set_view(claimed.state, &claimed.pn, &claimed.lid); + connection.claimed.store(true, Ordering::SeqCst); + connection.set_view(claimed.state, &claimed.pn, &claimed.lid); tracing::info!( - session = %session.id, - generation = session.generation, + connection = %connection.id, + generation = connection.generation, state = %state_name(claimed.state), "Polymorfa accepted the claim" ); if claimed.state == State::LoggedOut as i32 { - self.retire(&session.id).await; + self.retire(&connection.id).await; return; } if !claimed.pn.is_empty() - && let Some(ops) = session.ops() + && let Some(ops) = connection.ops() { let lid = Some(claimed.lid.as_str()).filter(|l| !l.is_empty()); if let Err(e) = ops.set_own_jids(&claimed.pn, lid).await { - let error = self.ops_error(session, &e); - tracing::warn!(session = %session.id, error = %error, "could not record own JIDs"); + let error = self.ops_error(connection, &e); + tracing::warn!(connection = %connection.id, error = %error, "could not record own JIDs"); } } } - Ok(_) => tracing::warn!(session = %session.id, "unexpected answer to ClaimSession"), + Ok(_) => { + tracing::warn!(connection = %connection.id, "unexpected answer to ClaimConnection") + } Err(LinkError::Remote(error)) => match error.code_enum() { Code::NotLeaseHolder => { - self.refused_generation(session, "Polymorfa refused this claim generation") + self.refused_generation(connection, "Polymorfa refused this claim generation") .await; } - Code::SessionUnavailable => tracing::warn!( - session = %session.id, - "Polymorfa refused the claim: the session is not in this project or is logged out" + Code::ConnectionUnavailable => tracing::warn!( + connection = %connection.id, + "Polymorfa refused the claim: the connection is not in this project or is logged out" ), - _ => tracing::warn!(session = %session.id, error = %error, "claim refused"), + _ => tracing::warn!(connection = %connection.id, error = %error, "claim refused"), }, - Err(e) => tracing::warn!(session = %session.id, error = %e, "claim failed"), + Err(e) => tracing::warn!(connection = %connection.id, error = %e, "claim failed"), } } @@ -572,8 +586,8 @@ impl Node { .expect("retired lock") .insert(id.to_owned()); tracing::warn!( - session = id, - "session is logged out; stopped serving it. Its sealed state is kept; remove it from the configuration and delete its records when no longer needed" + connection = id, + "connection is logged out; stopped serving it. Its sealed state is kept; remove it from the configuration and delete its records when no longer needed" ); self.release(id).await; } @@ -583,26 +597,28 @@ impl Node { let buffer_cutoff = now.saturating_sub(self.cfg.decrypt_buffer_retention.as_millis() as u64); let sent_cutoff = now.saturating_sub(self.cfg.sent_message_retention.as_millis() as u64); - for session in self.sessions() { - if !session.can_serve().await { + for connection in self.connections() { + if !connection.can_serve().await { continue; } - let Some(ops) = session.ops() else { continue }; + let Some(ops) = connection.ops() else { + continue; + }; let result = async { let buffered = ops.prune_decrypt_buffer(buffer_cutoff).await?; let sent = ops.prune_sent_messages(sent_cutoff).await?; - let shares = session.shares.prune(buffer_cutoff).await?; + let shares = connection.shares.prune(buffer_cutoff).await?; Ok::<_, OpsError>((buffered, sent, shares)) } .await; match result { Ok((buffered, sent, shares)) if buffered + sent + shares > 0 => { - tracing::info!(session = %session.id, buffered, sent, shares, "pruned expired records") + tracing::info!(connection = %connection.id, buffered, sent, shares, "pruned expired records") } Ok(_) => {} Err(e) => { - let error = self.ops_error(&session, &e); - tracing::warn!(session = %session.id, error = %error, "pruning failed"); + let error = self.ops_error(&connection, &e); + tracing::warn!(connection = %connection.id, error = %error, "pruning failed"); } } } @@ -654,15 +670,15 @@ impl Node { vec![link_task, leases, pruner] } - /// Release every session, then stop the loops. + /// Release every connection, then stop the loops. pub async fn shutdown(&self) { - // Prevent renewal/reacquisition while releasing sessions. Socket closure - // removes routing claims even if ReleaseSession races the stop signal. + // Prevent renewal/reacquisition while releasing connections. Socket closure + // removes routing claims even if ReleaseConnection races the stop signal. self.shutdown.send_replace(true); // Wait for publications that read the previous flag before taking the - // session snapshot. Later publications observe shutdown and refuse. + // connection snapshot. Later publications observe shutdown and refuse. drop(self.link.write().expect("link lock")); - let ids: Vec = self.sessions().iter().map(|s| s.id.clone()).collect(); + let ids: Vec = self.connections().iter().map(|s| s.id.clone()).collect(); for id in ids { self.release(&id).await; } @@ -675,48 +691,48 @@ impl Handler for Node { &self, request: RunnerRequest, ) -> Result { - let Some(session) = self.session(&request.session_id) else { + let Some(connection) = self.connection(&request.connection_id) else { return Err(proto::Error::new( Code::NotLeaseHolder, - "this node does not hold the session", + "this node does not hold the connection", )); }; - if request.lease_generation != session.generation || !session.can_serve().await { + if request.lease_generation != connection.generation || !connection.can_serve().await { return Err(proto::Error::new( Code::NotLeaseHolder, format!( "request generation {} is not this node's generation {}", - request.lease_generation, session.generation + request.lease_generation, connection.generation ), )); } let Some(op) = request.op else { return Err(proto::Error::new(Code::Unsupported, "unknown operation")); }; - crate::serve::handle(self, &session, op).await + crate::serve::handle(self, &connection, op).await } - async fn session_event(&self, event: SessionEvent, origin: Arc) { + async fn connection_event(&self, event: ConnectionEvent, origin: Arc) { // Events carry no generation. One from a replaced link describes the // old connection and must not retire or reclaim its successor. if !self .link() .is_some_and(|current| Arc::ptr_eq(¤t, &origin)) { - tracing::debug!(session = %event.session_id, "ignored a session event from a previous link"); + tracing::debug!(connection = %event.connection_id, "ignored a connection event from a previous link"); return; } - let Some(session) = self.session(&event.session_id) else { + let Some(connection) = self.connection(&event.connection_id) else { return; }; - session.set_view(event.state, &event.pn, &event.lid); - tracing::info!(session = %session.id, state = %state_name(event.state), "session state changed"); + connection.set_view(event.state, &event.pn, &event.lid); + tracing::info!(connection = %connection.id, state = %state_name(event.state), "connection state changed"); match State::try_from(event.state).unwrap_or(State::Unspecified) { - State::LoggedOut => self.retire(&session.id).await, + State::LoggedOut => self.retire(&connection.id).await, // Polymorfa no longer routes to us; claim again. State::Paused => { - session.claimed.store(false, Ordering::SeqCst); - self.spawn_claim(session); + connection.claimed.store(false, Ordering::SeqCst); + self.spawn_claim(connection); } _ => {} } @@ -724,8 +740,8 @@ impl Handler for Node { async fn connected(&self, link: Arc) { *self.link.write().expect("link lock") = Some(link); - for session in self.sessions() { - self.spawn_claim(session); + for connection in self.connections() { + self.spawn_claim(connection); } } @@ -733,7 +749,7 @@ impl Handler for Node { *self.link.write().expect("link lock") = None; // A new socket must claim a strictly higher generation. Relinquish // these fences before reconnect so the durable store increments them. - let ids: Vec<_> = self.sessions().iter().map(|s| s.id.clone()).collect(); + let ids: Vec<_> = self.connections().iter().map(|s| s.id.clone()).collect(); for id in ids { self.release(&id).await; } @@ -748,7 +764,7 @@ mod tests { use std::task::{Context, Poll, Waker}; use wacore_recordstore::MemoryRecordStore; - const SESSION: &str = "fixture-session"; + const CONNECTION: &str = "fixture-session"; fn node() -> Arc { let cfg = Config::from_toml( @@ -757,7 +773,7 @@ node_id = "fixture-node" [polymorfa] url = "ws://127.0.0.1:1/signal" credential = "fixture-project-principal" -sessions = ["fixture-session"] +connections = ["fixture-session"] [storage] driver = "memory" master_key = "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk=" @@ -772,39 +788,44 @@ secret = "fixture-application-secret" Node::new(cfg, Backend::Memory(Arc::new(MemoryRecordStore::new()))) } - async fn acquired(node: &Node) -> (Lease, Arc) { + async fn acquired(node: &Node) -> (Lease, Arc) { let lease = node .backend - .acquire(SESSION, &node.lease_holder, now_ms(), node.cfg.lease_ttl_ms) + .acquire( + CONNECTION, + &node.lease_holder, + now_ms(), + node.cfg.lease_ttl_ms, + ) .await .unwrap() .unwrap(); - let session = node.activate(lease.clone()).await.unwrap(); - (lease, session) + let connection = node.activate(lease.clone()).await.unwrap(); + (lease, connection) } #[tokio::test] async fn release_refuses_the_fence_before_waiting_for_storage() { let node = node(); - let (lease, session) = acquired(&node).await; - node.sessions + let (lease, connection) = acquired(&node).await; + node.connections .write() .unwrap() - .insert(SESSION.into(), session.clone()); + .insert(CONNECTION.into(), connection.clone()); // Suspend release before durable storage can acknowledge it. Even if // that operation later fails, acquisition must already refuse the fence. - let held = session.lease.lock().await; - let mut release = std::pin::pin!(node.release(SESSION)); + let held = connection.lease.lock().await; + let mut release = std::pin::pin!(node.release(CONNECTION)); assert!(matches!( release .as_mut() .poll(&mut Context::from_waker(Waker::noop())), Poll::Pending )); - assert!(session.is_lost()); - assert!(node.session(SESSION).is_none()); + assert!(connection.is_lost()); + assert!(node.connection(CONNECTION).is_none()); assert_eq!( - node.abandoned.read().unwrap().get(SESSION), + node.abandoned.read().unwrap().get(CONNECTION), Some(&lease.fence.generation) ); drop(held); @@ -814,49 +835,49 @@ secret = "fixture-application-secret" } #[tokio::test] - async fn losing_a_fence_records_refusal_before_exposing_a_missing_session() { + async fn losing_a_fence_records_refusal_before_exposing_a_missing_connection() { let node = node(); - let (lease, session) = acquired(&node).await; - node.sessions + let (lease, connection) = acquired(&node).await; + node.connections .write() .unwrap() - .insert(SESSION.into(), session.clone()); + .insert(CONNECTION.into(), connection.clone()); let removal_is_locked = { let held = node.abandoned.write().unwrap(); let losing = { let node = node.clone(); std::thread::spawn(move || { - node.lose(SESSION, lease.fence.generation, "fixture refusal") + node.lose(CONNECTION, lease.fence.generation, "fixture refusal") }) }; let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - while !session.is_lost() { + while !connection.is_lost() { if std::time::Instant::now() >= deadline { break; } std::thread::yield_now(); } // Refusal is waiting for the held map. No lease tick may observe a - // missing session until that refusal has become visible. - let locked = session.is_lost() && node.sessions.try_read().is_err(); + // missing connection until that refusal has become visible. + let locked = connection.is_lost() && node.connections.try_read().is_err(); drop(held); losing.join().unwrap(); locked }; assert!(removal_is_locked); - assert!(node.session(SESSION).is_none()); + assert!(node.connection(CONNECTION).is_none()); assert_eq!( - node.abandoned.read().unwrap().get(SESSION), - Some(&session.generation) + node.abandoned.read().unwrap().get(CONNECTION), + Some(&connection.generation) ); *node.link.write().unwrap() = Some(Link::fixture()); node.tick_leases().await; assert!( - node.session(SESSION).is_none(), + node.connection(CONNECTION).is_none(), "the refused generation was served again" ); let (next, _) = acquired(&node).await; - assert!(next.fence.generation > session.generation); + assert!(next.fence.generation > connection.generation); } #[tokio::test] @@ -864,12 +885,12 @@ secret = "fixture-application-secret" let node = node(); let origin = Link::fixture(); *node.link.write().unwrap() = Some(origin.clone()); - let (lease, session) = acquired(&node).await; + let (lease, connection) = acquired(&node).await; node.shutdown().await; assert!(*node.shutdown.borrow()); - assert!(!node.publish_acquired(SESSION, session, &origin)); - assert!(node.session(SESSION).is_none()); - node.abandon(SESSION, &lease).await; + assert!(!node.publish_acquired(CONNECTION, connection, &origin)); + assert!(node.connection(CONNECTION).is_none()); + node.abandon(CONNECTION, &lease).await; } #[tokio::test] @@ -877,21 +898,21 @@ secret = "fixture-application-secret" let node = node(); let origin = Link::fixture(); *node.link.write().unwrap() = Some(origin.clone()); - let (lease, session) = acquired(&node).await; + let (lease, connection) = acquired(&node).await; // Acquisition/activation awaited storage while disconnect took its - // session snapshot. The late result must never become a live session. + // connection snapshot. The late result must never become a live connection. node.disconnected().await; - assert!(!node.publish_acquired(SESSION, session.clone(), &origin)); - assert!(node.session(SESSION).is_none()); + assert!(!node.publish_acquired(CONNECTION, connection.clone(), &origin)); + assert!(node.connection(CONNECTION).is_none()); let successor = Link::fixture(); *node.link.write().unwrap() = Some(successor.clone()); - assert!(!node.publish_acquired(SESSION, session.clone(), &origin)); - node.abandon(SESSION, &lease).await; + assert!(!node.publish_acquired(CONNECTION, connection.clone(), &origin)); + node.abandon(CONNECTION, &lease).await; let (_, next) = acquired(&node).await; - assert!(node.publish_acquired(SESSION, next, &successor)); + assert!(node.publish_acquired(CONNECTION, next, &successor)); node.disconnected().await; - assert!(node.session(SESSION).is_none()); + assert!(node.connection(CONNECTION).is_none()); } } diff --git a/src/ratelimit.rs b/src/ratelimit.rs index 2a4f6ff..19d0a78 100644 --- a/src/ratelimit.rs +++ b/src/ratelimit.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only //! Client-side send ceiling: at most `limit` sends in any one-second window -//! per session, matching `Welcome.max_sends_per_second`. Polymorfa enforces +//! per connection, matching `Welcome.max_sends_per_second`. Polymorfa enforces //! the same ceiling and answers `CODE_RATE_LIMITED` past it; pacing here //! keeps a burst from the application from turning into refused sends. diff --git a/src/resolver.rs b/src/resolver.rs index d4f4199..e90d7d0 100644 --- a/src/resolver.rs +++ b/src/resolver.rs @@ -50,7 +50,7 @@ impl Runtime for TokioRuntime { pub struct RemoteResolver { pub link: Arc, - pub session_id: String, + pub connection_id: String, pub generation: u64, } @@ -93,7 +93,7 @@ pub fn remote_bundle(bundle: &proto::Bundle) -> anyhow::Result { impl RemoteResolver { async fn ask(&self, op: service_request::Op) -> anyhow::Result { self.link - .request(&self.session_id, self.generation, op) + .request(&self.connection_id, self.generation, op) .await .map_err(|e: LinkError| anyhow::Error::new(e)) } diff --git a/src/send.rs b/src/send.rs index 4e83d03..ee00280 100644 --- a/src/send.rs +++ b/src/send.rs @@ -5,7 +5,7 @@ //! The node builds the encrypted stanza itself (device lists, prekeys and //! group routing come from Polymorfa through [`RemoteResolver`]), then asks //! Polymorfa to transmit it with `SendStanza`. Every `SendStanza`, including -//! a resend, first waits for the per-session ceiling. +//! a resend, first waits for the per-connection ceiling. //! //! When the server reports a participant-hash mismatch, the device list //! changed while the message was in flight. WhatsApp Web then refreshes the @@ -18,7 +18,7 @@ use crate::link::LinkError; use crate::message::{self, BuildError, SendRequest}; -use crate::node::{ActiveSession, Node}; +use crate::node::{ActiveConnection, Node}; use crate::proto::{self, Code, SendStanza, runner_response, service_request}; use crate::resolver::{RemoteResolver, TokioRuntime}; use serde::Serialize; @@ -38,9 +38,9 @@ pub struct SendOutcome { pub enum SendError { #[error("{0}")] Invalid(String), - #[error("this node does not hold the session")] + #[error("this node does not hold the connection")] NotLeaseHolder, - #[error("the session is not paired yet")] + #[error("the connection is not paired yet")] NotPaired, #[error("not connected to Polymorfa")] Disconnected, @@ -50,7 +50,7 @@ pub enum SendError { Refused(proto::Error), #[error("send ceiling reached")] RateLimited, - #[error("session storage is unavailable")] + #[error("connection storage is unavailable")] StorageUnavailable, #[error("building the stanza failed")] Build, @@ -75,9 +75,9 @@ enum Built { }, } -fn ops_failure(node: &Node, session: &ActiveSession, error: &OpsError) -> SendError { +fn ops_failure(node: &Node, connection: &ActiveConnection, error: &OpsError) -> SendError { if error.is_fence_lost() { - node.ops_error(session, error); + node.ops_error(connection, error); return SendError::NotLeaseHolder; } match error { @@ -93,7 +93,7 @@ fn ops_failure(node: &Node, session: &ActiveSession, error: &OpsError) -> SendEr pub async fn send( node: &Node, - session: &Arc, + connection: &Arc, request: SendRequest, ) -> Result { let to: Jid = request @@ -102,8 +102,8 @@ pub async fn send( .map_err(|_| SendError::Invalid("to is not a valid JID".into()))?; let now = crate::delivery::now_secs(); let message = message::build_message(&request, now)?; - let ops = session.ops().ok_or(SendError::NotPaired)?; - let own = session.view().pn.and_then(|pn| pn.parse::().ok()); + let ops = connection.ops().ok_or(SendError::NotPaired)?; + let own = connection.view().pn.and_then(|pn| pn.parse::().ok()); let message_id = wacore::request::RequestUtils::message_id_at(own.as_ref(), u64::try_from(now).unwrap_or(0)); @@ -111,19 +111,19 @@ pub async fn send( let outcome = async { loop { let link = node.link().ok_or(SendError::Disconnected)?; - if !session.can_serve().await || !session.is_claimed() { + if !connection.can_serve().await || !connection.is_claimed() { return Err(SendError::NotLeaseHolder); } let resolver = RemoteResolver { link: link.clone(), - session_id: session.id.clone(), - generation: session.generation, + connection_id: connection.id.clone(), + generation: connection.generation, }; let built = if to.is_group() { let prepared = ops .send_group(&TokioRuntime, &resolver, &to, &message, &message_id) .await - .map_err(|e| ops_failure(node, session, &e))?; + .map_err(|e| ops_failure(node, connection, &e))?; Built::Group { stanza: prepared.stanza, phash: prepared.phash, @@ -134,7 +134,7 @@ pub async fn send( let prepared = ops .send_direct(&TokioRuntime, &resolver, &to, &message, &message_id) .await - .map_err(|e| ops_failure(node, session, &e))?; + .map_err(|e| ops_failure(node, connection, &e))?; Built::Direct { stanza: prepared.stanza, phash: prepared.phash, @@ -146,15 +146,15 @@ pub async fn send( } }; - session.limiter.acquire(link.max_sends_per_second()).await; - if !session.can_serve().await || !session.is_claimed() { + connection.limiter.acquire(link.max_sends_per_second()).await; + if !connection.can_serve().await || !connection.is_claimed() { return Err(SendError::NotLeaseHolder); } let op = service_request::Op::SendStanza(SendStanza { node: stanza, phash, }); - let result = match link.request(&session.id, session.generation, op).await { + let result = match link.request(&connection.id, connection.generation, op).await { Ok(runner_response::Result::Send(result)) => result, Ok(_) => { return Err(SendError::Unconfirmed { @@ -166,7 +166,7 @@ pub async fn send( Code::RateLimited => SendError::RateLimited, Code::NotLeaseHolder => { node.refused_generation( - session, + connection, "Polymorfa refused a send at this generation", ) .await; @@ -193,13 +193,13 @@ pub async fn send( Ok(true) => {} // The group's sender key rotated after this send was built, // so its targets hold the old key; the next send redistributes. - Ok(false) => tracing::debug!(session = %session.id, message_id = %message_id, "sender key rotated before the send was acknowledged"), + Ok(false) => tracing::debug!(connection = %connection.id, message_id = %message_id, "sender key rotated before the send was acknowledged"), Err(e) => { // The runner has already confirmed the send. A failed local // distribution mark must not invite a new message ID. Only fence - // loss stops the same-ID mismatch resend and retires this session. - node.ops_error(session, &e); - tracing::warn!(session = %session.id, message_id = %message_id, "send accepted; sender-key distribution was not recorded"); + // loss stops the same-ID mismatch resend and retires this connection. + node.ops_error(connection, &e); + tracing::warn!(connection = %connection.id, message_id = %message_id, "send accepted; sender-key distribution was not recorded"); if e.is_fence_lost() { return Ok(SendOutcome { message_id: message_id.clone(), @@ -210,9 +210,9 @@ pub async fn send( } } } - tracing::info!(session = %session.id, message_id = %message_id, resent, "sent"); + tracing::info!(connection = %connection.id, message_id = %message_id, resent, "sent"); if result.participant_hash_mismatch && !resent { - tracing::info!(session = %session.id, message_id = %message_id, "device list changed; resending once"); + tracing::info!(connection = %connection.id, message_id = %message_id, "device list changed; resending once"); resent = true; continue; } diff --git a/src/serve.rs b/src/serve.rs index f48e065..91d4193 100644 --- a/src/serve.rs +++ b/src/serve.rs @@ -7,7 +7,7 @@ //! Error messages name the failure, never content or key material. use crate::message::{self, Event}; -use crate::node::{ActiveSession, Node}; +use crate::node::{ActiveConnection, Node}; use crate::proto::{ self, Code, DecryptFailure, Identity, MigrateResult, PreKey, PreKeyCount, PreKeyUploadBatch, PreKeys, ReceiveResult, ServiceResponse, SignedPairing, Stanza, runner_request::Op, @@ -42,14 +42,14 @@ fn jid(value: &str, field: &str) -> Result { pub async fn handle( node: &Node, - session: &Arc, + connection: &Arc, op: Op, ) -> Result { if let Op::GetIdentity(_) = op { - let ops = session + let ops = connection .ops_or_create() .await - .map_err(|e| node.ops_error(session, &e))?; + .map_err(|e| node.ops_error(connection, &e))?; let identity = ops.public_identity().await; return respond(Out::Identity(Identity { registration_id: identity.registration_id, @@ -60,16 +60,16 @@ pub async fn handle( adv_secret: identity.adv_secret.to_vec(), })); } - let Some(ops) = session.ops() else { + let Some(ops) = connection.ops() else { return Err(proto::Error::new( - Code::SessionUnavailable, + Code::ConnectionUnavailable, "device keys do not exist yet; GetIdentity creates them", )); }; - let fail = |e: OpsError| node.ops_error(session, &e); + let fail = |e: OpsError| node.ops_error(connection, &e); match op { Op::GetIdentity(_) => unreachable!("handled above"), - Op::Receive(receive) => self::receive(node, session, &ops, receive).await, + Op::Receive(receive) => self::receive(node, connection, &ops, receive).await, Op::GeneratePreKeys(request) => { let keys = ops .generate_prekeys(&TokioRuntime, request.count) @@ -115,7 +115,7 @@ pub async fn handle( respond(Out::Ok(proto::Ok {})) } Op::UploadedPreKeyCount(_) => { - let count = uploaded_prekey_count(node, session).await?; + let count = uploaded_prekey_count(node, connection).await?; respond(Out::PreKeyCount(PreKeyCount { count })) } Op::SignPairing(request) => { @@ -169,8 +169,8 @@ pub async fn handle( }; let resolver = RemoteResolver { link, - session_id: session.id.clone(), - generation: session.generation, + connection_id: connection.id.clone(), + generation: connection.generation, }; let node_bytes = ops .resend( @@ -210,9 +210,9 @@ pub async fn handle( } /// Map a receive failure to the contract's decrypt failures. -pub fn receive_error(node: &Node, session: &ActiveSession, error: &OpsError) -> proto::Error { +pub fn receive_error(node: &Node, connection: &ActiveConnection, error: &OpsError) -> proto::Error { if error.is_fence_lost() { - return node.ops_error(session, error); + return node.ops_error(connection, error); } match error { OpsError::Store(_) | OpsError::Signal(SignalProtocolError::BackendError(..)) => { @@ -233,14 +233,14 @@ pub fn receive_error(node: &Node, session: &ActiveSession, error: &OpsError) -> "decrypted payload is not a message", ) } - OpsError::NotInitialised => node.ops_error(session, error), + OpsError::NotInitialised => node.ops_error(connection, error), _ => proto::Error::decrypt_failed(DecryptFailure::Unspecified, "decryption failed"), } } async fn receive( node: &Node, - session: &Arc, + connection: &Arc, ops: &crate::node::Ops, receive: proto::Receive, ) -> Result { @@ -267,9 +267,9 @@ async fn receive( }) .await .map_err(|e| { - let error = receive_error(node, session, &e); + let error = receive_error(node, connection, &e); tracing::info!( - session = %session.id, + connection = %connection.id, message_id = %receive.message_id, kind = %receive.kind, code = error.code_enum().as_str_name(), @@ -282,14 +282,14 @@ async fn receive( let app_state_key_share = if node.cfg.share_app_state_keys && receive.is_from_me { let cutoff = crate::node::now_ms() .saturating_sub(node.cfg.decrypt_buffer_retention.as_millis() as u64); - session + connection .replay_app_state_share(&receipt_key, cutoff) .await - .map_err(|e| node.ops_error(session, &e))? + .map_err(|e| node.ops_error(connection, &e))? } else { Vec::new() }; - if !session.can_serve().await { + if !connection.can_serve().await { return Err(proto::Error::new( Code::NotLeaseHolder, "the lease expired before receive replay", @@ -314,20 +314,20 @@ async fn receive( } else { Vec::new() }; - if let Some(event) = event_for(node, session, &receive, &message) { + if let Some(event) = event_for(node, connection, &receive, &message) { let kind = event.kind; if let Err(e) = node.delivery.deliver(event).await { tracing::info!( - session = %session.id, + connection = %connection.id, message_id = %receive.message_id, error = %e, "delivery not acknowledged; the message stays sealed in the buffer for redelivery" ); return Err(proto::Error::new(Code::Unavailable, e.to_string())); } - tracing::debug!(session = %session.id, message_id = %receive.message_id, kind, "delivered"); + tracing::debug!(connection = %connection.id, message_id = %receive.message_id, kind, "delivered"); } - if !session.can_serve().await { + if !connection.can_serve().await { return Err(proto::Error::new( Code::NotLeaseHolder, "the lease expired before delivery was recorded", @@ -336,14 +336,14 @@ async fn receive( // The runner has not acknowledged this response. Preserve only the share // before dropping buffered plaintext, so a lost reply remains replayable. if !app_state_key_share.is_empty() { - session + connection .save_app_state_share(&message.receipt_key, &app_state_key_share) .await - .map_err(|e| node.ops_error(session, &e))?; + .map_err(|e| node.ops_error(connection, &e))?; } ops.mark_delivered(&message.receipt_key) .await - .map_err(|e| node.ops_error(session, &e))?; + .map_err(|e| node.ops_error(connection, &e))?; respond(Out::Receive(ReceiveResult { already_delivered: false, redelivered: message.redelivered, @@ -353,16 +353,16 @@ async fn receive( } /// The application event ID for a received payload. The receipt key keys -/// the session's own decrypt buffer and is identical for every session that -/// receives the same ciphertext (two sessions in one group), so the event ID -/// also binds the session: acknowledging one session's event never completes -/// another's. Stable across redelivery to the same session. -pub fn event_id(session_id: &str, receipt_key: &str) -> String { +/// the connection's own decrypt buffer and is identical for every connection that +/// receives the same ciphertext (two connections in one group), so the event ID +/// also binds the connection: acknowledging one connection's event never completes +/// another's. Stable across redelivery to the same connection. +pub fn event_id(connection_id: &str, receipt_key: &str) -> String { use sha2::{Digest, Sha256}; let mut hash = Sha256::new(); hash.update(b"signal-node app event v1\0"); - hash.update((session_id.len() as u64).to_be_bytes()); - hash.update(session_id.as_bytes()); + hash.update((connection_id.len() as u64).to_be_bytes()); + hash.update(connection_id.as_bytes()); hash.update(receipt_key.as_bytes()); hex::encode(hash.finalize()) } @@ -372,7 +372,7 @@ pub fn event_id(session_id: &str, receipt_key: &str) -> String { /// operations) or is history and history delivery is off. fn event_for( node: &Node, - session: &ActiveSession, + connection: &ActiveConnection, receive: &proto::Receive, received: &wacore_signal_ops::ReceivedMessage, ) -> Option { @@ -380,11 +380,11 @@ fn event_for( if content.is_skdm_only { return None; } - let id = event_id(&session.id, &received.receipt_key); + let id = event_id(&connection.id, &received.receipt_key); let base = |kind: &'static str| Event { id: id.clone(), kind, - session_id: session.id.clone(), + connection_id: connection.id.clone(), chat: receive.chat.clone(), sender: receive.sender.clone(), sender_alt: Some(receive.sender_alt.clone()).filter(|s| !s.is_empty()), @@ -428,7 +428,7 @@ fn event_for( { // History comes only from this account's own devices. if !node.cfg.deliver_history || !receive.is_from_me { - tracing::debug!(session = %session.id, "history notification not delivered (history delivery is off)"); + tracing::debug!(connection = %connection.id, "history notification not delivered (history delivery is off)"); return None; } return Some(Event { @@ -470,12 +470,12 @@ fn base64_of(bytes: &[u8]) -> String { /// Surviving uploaded keys in customer-local state, not a provider pool count. pub async fn uploaded_prekey_count( node: &Node, - session: &ActiveSession, + connection: &ActiveConnection, ) -> Result { - session + connection .uploaded_prekey_count() .await - .map_err(|error| node.ops_error(session, &error)) + .map_err(|error| node.ops_error(connection, &error)) } #[cfg(test)] @@ -483,12 +483,12 @@ mod tests { use super::event_id; #[test] - fn event_ids_are_stable_per_session_and_distinct_across_sessions() { + fn event_ids_are_stable_per_connection_and_distinct_across_connections() { let receipt = "same-group-ciphertext"; assert_eq!(event_id("alpha", receipt), event_id("alpha", receipt)); assert_ne!(event_id("alpha", receipt), event_id("beta", receipt)); assert_ne!(event_id("alpha", receipt), event_id("alpha", "other")); - // Length-prefixing the session keeps ("ab", "c…") apart from ("a", "bc…"). + // Length-prefixing the connection keeps ("ab", "c…") apart from ("a", "bc…"). assert_ne!(event_id("ab", "cd"), event_id("a", "bcd")); assert_eq!(event_id("alpha", receipt).len(), 64); } diff --git a/tests/prekey_upload_boundary.rs b/tests/prekey_upload_boundary.rs index 5268262..2ec6ee8 100644 --- a/tests/prekey_upload_boundary.rs +++ b/tests/prekey_upload_boundary.rs @@ -58,7 +58,7 @@ impl Database { } } // Inject a real SQL error at pending publication or ACK receipt insertion. - // Conditions isolate this trigger to the test's random session scope. + // Conditions isolate this trigger to the test's random connection scope. async fn fail_on(&self, scope: &str, key: &str) { let token = scope.strip_prefix("upload_").unwrap(); let key = hex::encode(key); @@ -129,7 +129,7 @@ impl Database { fn request(scope: &str, generation: u64, op: Op) -> proto::RunnerRequest { proto::RunnerRequest { - session_id: scope.into(), + connection_id: scope.into(), lease_generation: generation, op: Some(op), } @@ -142,13 +142,19 @@ async fn start( ttl: u64, ) -> signal_node::Running { let mut cfg = config(name, &hub.url, false); - cfg.sessions = vec![scope.into()]; + cfg.connections = vec![scope.into()]; cfg.lease_ttl_ms = ttl; // Keep fixture reacquisition within Hub's five-second test deadline; // bulk SQL work still gets the configured, unchanged lease TTL. cfg.lease_renew = Duration::from_millis((ttl / 4).min(100)); let running = signal_node::start(cfg, backend).await.unwrap(); - wait(|| running.node.session(scope).is_some_and(|s| s.is_claimed())).await; + wait(|| { + running + .node + .connection(scope) + .is_some_and(|s| s.is_claimed()) + }) + .await; running } fn result(frame: proto::Frame) -> Out { @@ -234,7 +240,7 @@ fn ack(batch: &proto::PreKeyUploadBatch, ids: Vec) -> Op { #[derive(prost::Message)] struct FutureRequest { #[prost(string, tag = "1")] - session_id: String, + connection_id: String, #[prost(uint64, tag = "2")] lease_generation: u64, #[prost(bytes = "vec", tag = "99")] @@ -245,7 +251,7 @@ struct FutureRequest { #[derive(prost::Message)] struct OldRequest { #[prost(string, tag = "1")] - session_id: String, + connection_id: String, #[prost(uint64, tag = "2")] lease_generation: u64, #[prost(message, optional, tag = "11")] @@ -260,11 +266,11 @@ async fn consume_pending( batch: &proto::PreKeyUploadBatch, identity: proto::Identity, ) { - let generation = running.node.session(scope).unwrap().generation; + let generation = running.node.connection(scope).unwrap().generation; let (sender, sender_bundle) = peer("upload-sender-fixture").await; let target: wacore_binary::Jid = "222:1@s.whatsapp.net".parse().unwrap(); // The node is a paired companion; each side pins the other's account. - let node_ops = running.node.session(scope).unwrap().ops().unwrap(); + let node_ops = running.node.connection(scope).unwrap().ops().unwrap(); let node = pair(&*node_ops).await; vouch(&sender, "222:1@s.whatsapp.net", &node.device_identity).await; vouch( @@ -378,7 +384,7 @@ async fn exercise_database(db: Database) { let hub = Hub::start().await; let backend = db.reopen().await; let first = start(&hub, "upload-first", &scope, backend.clone(), 30_000).await; - let generation = first.node.session(&scope).unwrap().generation; + let generation = first.node.connection(&scope).unwrap().generation; let init = hub .request( "upload-first", @@ -448,7 +454,7 @@ async fn exercise_database(db: Database) { let backend = db.reopen().await; let second = start(&hub, "upload-second", &scope, backend.clone(), 30_000).await; - let generation2 = second.node.session(&scope).unwrap().generation; + let generation2 = second.node.connection(&scope).unwrap().generation; assert!(generation2 > generation); assert_eq!( prepare(&hub, "upload-second", &scope, generation2, 50).await, @@ -490,7 +496,7 @@ async fn exercise_database(db: Database) { hub.raw_request( "upload-second", FutureRequest { - session_id: scope.clone(), + connection_id: scope.clone(), lease_generation: generation2, future_operation: vec![1], } @@ -641,7 +647,7 @@ async fn exercise_database(db: Database) { let backend = db.reopen().await; let third = start(&hub, "upload-third", &scope, backend.clone(), 30_000).await; - let generation3 = third.node.session(&scope).unwrap().generation; + let generation3 = third.node.connection(&scope).unwrap().generation; assert!(generation3 > generation2); let next = prepare(&hub, "upload-third", &scope, generation3, 2).await; assert_ne!(next.batch_id, batch.batch_id); @@ -699,7 +705,7 @@ async fn durable_batch_survives_process_crash_and_refuses_the_old_holder() { let hub = Hub::start().await; let backend = db.reopen().await; let first = start(&hub, "upload-crash-first", &scope, backend.clone(), 500).await; - let generation = first.node.session(&scope).unwrap().generation; + let generation = first.node.connection(&scope).unwrap().generation; result( hub.request( "upload-crash-first", @@ -708,11 +714,11 @@ async fn durable_batch_survives_process_crash_and_refuses_the_old_holder() { .await, ); let batch = prepare(&hub, "upload-crash-first", &scope, generation, 3).await; - let stale_ops = first.node.session(&scope).unwrap().ops().unwrap(); + let stale_ops = first.node.connection(&scope).unwrap().ops().unwrap(); first.abort(); tokio::time::sleep(Duration::from_millis(650)).await; let second = start(&hub, "upload-crash-second", &scope, db.reopen().await, 500).await; - let generation2 = second.node.session(&scope).unwrap().generation; + let generation2 = second.node.connection(&scope).unwrap().generation; assert!(generation2 > generation); assert_eq!( prepare(&hub, "upload-crash-second", &scope, generation2, 1).await, @@ -788,7 +794,7 @@ async fn malformed_and_oversized_frames_do_not_allocate_or_lose_the_pending_batc let hub = Hub::start().await; let backend = db.reopen().await; let running = start(&hub, "upload-framing", &scope, backend.clone(), 30_000).await; - let generation = running.node.session(&scope).unwrap().generation; + let generation = running.node.connection(&scope).unwrap().generation; result( hub.request( "upload-framing", @@ -810,11 +816,11 @@ async fn malformed_and_oversized_frames_do_not_allocate_or_lose_the_pending_batc wait(|| { running .node - .session(&scope) + .connection(&scope) .is_some_and(|s| s.generation > generation && s.is_claimed()) }) .await; - let successor = running.node.session(&scope).unwrap().generation; + let successor = running.node.connection(&scope).unwrap().generation; assert_eq!( prepare(&hub, "upload-framing", &scope, successor, 50).await, batch diff --git a/tests/protocol_contract.rs b/tests/protocol_contract.rs new file mode 100644 index 0000000..a813107 --- /dev/null +++ b/tests/protocol_contract.rs @@ -0,0 +1,70 @@ +use prost::Message; +use signal_node::proto::{self, frame::Body, service_request::Op}; + +#[test] +fn connection_lease_names_preserve_version_one_wire_tags() { + assert_eq!(proto::PROTOCOL_VERSION, 1); + assert_eq!(proto::SUBPROTOCOL, "polymorfa.signal.v1"); + assert_eq!(proto::Code::ConnectionUnavailable as i32, 8); + let request = proto::ServiceRequest { + connection_id: "stable".into(), + lease_generation: 9, + op: Some(Op::ClaimConnection(proto::ClaimConnection { + generation: 7, + })), + }; + // Root selector tag1, generation tag2 and claim tag10 are unchanged. + let wire = b"\x0a\x06stable\x10\x09\x52\x02\x08\x07"; + assert_eq!(request.encode_to_vec(), wire); + assert_eq!( + proto::ServiceRequest::decode(wire.as_slice()).unwrap(), + request + ); + + let event = proto::Frame::with( + 0, + Body::ConnectionEvent(proto::ConnectionEvent { + connection_id: "stable".into(), + state: proto::connection_event::State::Connected as i32, + ..Default::default() + }), + ); + // The unsolicited account event retains frame tag9 and state value2. + let wire = b"\x4a\x0a\x0a\x06stable\x10\x02"; + assert_eq!(event.encode_to_vec(), wire); + assert_eq!(proto::Frame::decode(wire.as_slice()).unwrap(), event); +} + +#[test] +fn companion_identity_fields_preserve_additive_tags_and_opaque_bytes() { + let receive = proto::Receive { + device_identity: vec![1, 2, 3], + ..Default::default() + }; + let bundle = proto::Bundle { + device_identity: vec![1, 2, 3], + ..Default::default() + }; + assert_eq!(receive.encode_to_vec(), [0x52, 3, 1, 2, 3]); + assert_eq!(bundle.encode_to_vec(), [0x42, 3, 1, 2, 3]); + assert_eq!( + proto::Receive::decode(&[0x52, 3, 1, 2, 3][..]).unwrap(), + receive + ); + assert_eq!( + proto::Bundle::decode(&[0x42, 3, 1, 2, 3][..]).unwrap(), + bundle + ); + assert!( + proto::Receive::decode(&[][..]) + .unwrap() + .device_identity + .is_empty() + ); + assert!( + proto::Bundle::decode(&[][..]) + .unwrap() + .device_identity + .is_empty() + ); +} diff --git a/tests/service_boundary.rs b/tests/service_boundary.rs index 61d3e66..661cda0 100644 --- a/tests/service_boundary.rs +++ b/tests/service_boundary.rs @@ -31,12 +31,12 @@ async fn encrypted( body: wa::Message, from_me: bool, ) -> proto::Receive { - let session = running.node.session(SESSION).unwrap(); - let identity = identity(hub, node, session.generation).await; + let connection = running.node.connection(CONNECTION).unwrap(); + let identity = identity(hub, node, connection.generation).await; let response = hub .command( node, - session.generation, + connection.generation, Op::GeneratePreKeys(proto::GeneratePreKeys { count: 1 }), ) .await; @@ -49,7 +49,7 @@ async fn encrypted( // The node is a paired companion of its own account. The sender is either // a companion of another account the node has pinned, or, for an own // device message, another device paired under the node's own account. - let node_ops = session.ops().unwrap(); + let node_ops = connection.ops().unwrap(); let node = pair(&*node_ops).await; // The hub's claim reply names this account's phone number; the service // cannot apply it before the device keys exist. @@ -155,7 +155,7 @@ async fn app_auth_origin_and_public_liveness_keep_private_state_hidden() { assert_eq!(health, serde_json::json!({"status":"ok"})); assert_eq!( client - .get(format!("{url}/v1/sessions")) + .get(format!("{url}/v1/connections")) .send() .await .unwrap() @@ -164,7 +164,7 @@ async fn app_auth_origin_and_public_liveness_keep_private_state_hidden() { ); assert_eq!( client - .get(format!("{url}/v1/sessions")) + .get(format!("{url}/v1/connections")) .bearer_auth(APP_SECRET) .header("Origin", "null") .send() @@ -173,8 +173,8 @@ async fn app_auth_origin_and_public_liveness_keep_private_state_hidden() { .status(), 403 ); - let sessions = client - .get(format!("{url}/v1/sessions")) + let connections = client + .get(format!("{url}/v1/connections")) .bearer_auth(APP_SECRET) .send() .await @@ -182,13 +182,36 @@ async fn app_auth_origin_and_public_liveness_keep_private_state_hidden() { .json::() .await .unwrap(); - assert_eq!(sessions["sessions"][0]["claimed"], true); - assert!(!sessions.to_string().contains("master_key")); + assert_eq!(connections["connections"][0]["claimed"], true); + assert_eq!(connections["connections"][0]["id"], CONNECTION); + assert!(connections.get("sessions").is_none()); + assert!(!connections.to_string().contains("master_key")); + assert_eq!( + client + .get(format!("{url}/v1/sessions")) + .bearer_auth(APP_SECRET) + .send() + .await + .unwrap() + .status(), + 404 + ); + // A retired filter must fail instead of silently subscribing to every Connection. + assert_eq!( + client + .get(format!("{url}/v1/events?session_id=other")) + .bearer_auth(APP_SECRET) + .send() + .await + .unwrap() + .status(), + 400 + ); running.shutdown().await; } #[tokio::test] -async fn an_unrelated_sse_filter_does_not_make_a_session_wait_for_an_ack() { +async fn an_unrelated_sse_filter_does_not_make_a_connection_wait_for_an_ack() { let hub = Hub::start().await; let running = start( &hub, @@ -197,7 +220,7 @@ async fn an_unrelated_sse_filter_does_not_make_a_session_wait_for_an_ack() { false, ) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; let receive = encrypted( &hub, "node-filter", @@ -210,7 +233,7 @@ async fn an_unrelated_sse_filter_does_not_make_a_session_wait_for_an_ack() { .await; let response = reqwest::Client::new() .get(format!( - "http://{}/v1/events?session_id=other", + "http://{}/v1/events?connection_id=other", running.http_addr )) .bearer_auth(APP_SECRET) @@ -239,7 +262,7 @@ async fn real_encrypted_receive_requires_app_ack_then_is_durable_and_sealed() { false, ) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; let receive = encrypted( &hub, "node-receive", @@ -303,8 +326,8 @@ async fn real_encrypted_receive_requires_app_ack_then_is_durable_and_sealed() { })) )); for ns in Namespace::ALL { - for key in records.scan_keys(SESSION, ns, "", None).await.unwrap() { - let value = records.get(SESSION, ns, &key).await.unwrap().unwrap(); + for key in records.scan_keys(CONNECTION, ns, "", None).await.unwrap() { + let value = records.get(CONNECTION, ns, &key).await.unwrap().unwrap(); assert!( !value .windows(b"application-private-text".len()) @@ -339,7 +362,7 @@ async fn unacknowledged_receive_replays_across_crash_and_old_holder_is_fenced() false, ) .await; - let old = first.node.session(SESSION).unwrap(); + let old = first.node.connection(CONNECTION).unwrap(); let generation = old.generation; let receive = encrypted( &hub, @@ -361,7 +384,7 @@ async fn unacknowledged_receive_replays_across_crash_and_old_holder_is_fenced() first.abort(); tokio::time::sleep(std::time::Duration::from_millis(650)).await; let second = start(&hub, "node-crash-b", Backend::Memory(records), false).await; - let generation2 = second.node.session(SESSION).unwrap().generation; + let generation2 = second.node.connection(CONNECTION).unwrap().generation; assert!(generation2 > generation); let old_write = stale .generate_prekeys(&signal_node::resolver::TokioRuntime, 1) @@ -435,11 +458,11 @@ async fn app_state_keys_require_separate_consent_and_an_own_device() { wait(|| { running .node - .session(SESSION) + .connection(CONNECTION) .is_some_and(|s| s.is_claimed()) }) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; let expected = app_state_share(); let receive = encrypted( &hub, @@ -512,11 +535,11 @@ async fn app_state_share_survives_a_lost_reply_and_restart_with_live_consent_che wait(|| { running .node - .session(SESSION) + .connection(CONNECTION) .is_some_and(|s| s.is_claimed()) }) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; let share = app_state_share(); let receive = encrypted( &hub, @@ -556,11 +579,11 @@ async fn app_state_share_survives_a_lost_reply_and_restart_with_live_consent_che wait(|| { replacement .node - .session(SESSION) + .connection(CONNECTION) .is_some_and(|s| s.is_claimed()) }) .await; - let generation = replacement.node.session(SESSION).unwrap().generation; + let generation = replacement.node.connection(CONNECTION).unwrap().generation; for from_me in [true, false] { let mut retry = receive.clone(); retry.is_from_me = from_me; @@ -598,7 +621,7 @@ async fn history_stays_off_until_explicit_consent_and_delivers_only_the_notifica consent, ) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; let message = proto!(wa::Message { protocol_message: proto!(wa::message::ProtocolMessage { r#type: Some(wa::message::protocol_message::Type::HistorySyncNotification), @@ -674,9 +697,9 @@ async fn http_send_stanza_round_trips_into_the_other_device_and_never_exceeds_fi false, ) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; identity(&hub, "node-send", generation).await; - let ops = running.node.session(SESSION).unwrap().ops().unwrap(); + let ops = running.node.connection(CONNECTION).unwrap().ops().unwrap(); let node = pair(&*ops).await; ops.set_own_jids("222:1@s.whatsapp.net", None) .await @@ -687,7 +710,7 @@ async fn http_send_stanza_round_trips_into_the_other_device_and_never_exceeds_fi hub.bundle("111:1@s.whatsapp.net", bundle).await; let client = reqwest::Client::new(); let url = format!( - "http://{}/v1/sessions/{SESSION}/messages", + "http://{}/v1/connections/{CONNECTION}/messages", running.http_addr ); for _ in 0..7 { @@ -770,9 +793,9 @@ async fn a_lost_send_reply_reports_the_original_unconfirmed_message_without_retr false, ) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; identity(&hub, "node-uncertain", generation).await; - let ops = running.node.session(SESSION).unwrap().ops().unwrap(); + let ops = running.node.connection(CONNECTION).unwrap().ops().unwrap(); pair(&*ops).await; ops.set_own_jids("222:1@s.whatsapp.net", Some("22201:1@lid")) .await @@ -783,7 +806,7 @@ async fn a_lost_send_reply_reports_the_original_unconfirmed_message_without_retr hub.lose_send_reply(disconnect); let response = reqwest::Client::new() .post(format!( - "http://{}/v1/sessions/{SESSION}/messages", + "http://{}/v1/connections/{CONNECTION}/messages", running.http_addr )) .bearer_auth(APP_SECRET) @@ -822,9 +845,9 @@ async fn a_failed_mismatch_resend_keeps_the_original_message_unconfirmed() { false, ) .await; - let session = running.node.session(SESSION).unwrap(); - identity(&hub, "node-resend", session.generation).await; - let ops = session.ops().unwrap(); + let connection = running.node.connection(CONNECTION).unwrap(); + identity(&hub, "node-resend", connection.generation).await; + let ops = connection.ops().unwrap(); pair(&*ops).await; ops.set_own_jids("222:1@s.whatsapp.net", Some("22201:1@lid")) .await @@ -835,7 +858,7 @@ async fn a_failed_mismatch_resend_keeps_the_original_message_unconfirmed() { hub.fail_resend(failure); let response = reqwest::Client::new() .post(format!( - "http://{}/v1/sessions/{SESSION}/messages", + "http://{}/v1/connections/{CONNECTION}/messages", running.http_addr )) .bearer_auth(APP_SECRET) @@ -881,9 +904,9 @@ async fn an_accepted_group_send_survives_distribution_storage_failure_or_fence_l let pool = sqlx::SqlitePool::connect(&url).await.unwrap(); let hub = Hub::start().await; let running = start(&hub, "node-mark-failure", Backend::Sqlite(backend), false).await; - let session = running.node.session(SESSION).unwrap(); - identity(&hub, "node-mark-failure", session.generation).await; - let ops = session.ops().unwrap(); + let connection = running.node.connection(CONNECTION).unwrap(); + identity(&hub, "node-mark-failure", connection.generation).await; + let ops = connection.ops().unwrap(); pair(&*ops).await; ops.set_own_jids("222:1@s.whatsapp.net", Some("22201:1@lid")) .await @@ -901,7 +924,7 @@ async fn an_accepted_group_send_survives_distribution_storage_failure_or_fence_l let (observed, release) = hub.gate_next_send().await; let send = reqwest::Client::new() .post(format!( - "http://{}/v1/sessions/{SESSION}/messages", + "http://{}/v1/connections/{CONNECTION}/messages", running.http_addr )) .bearer_auth(APP_SECRET) @@ -913,7 +936,7 @@ async fn an_accepted_group_send_survives_distribution_storage_failure_or_fence_l .expect("send never reached the runner"); if fence_lost { sqlx::query("UPDATE signal_leases SET generation = generation + 1 WHERE scope = ?") - .bind(SESSION) + .bind(CONNECTION) .execute(&pool) .await .unwrap(); @@ -946,12 +969,12 @@ async fn an_accepted_group_send_survives_distribution_storage_failure_or_fence_l } if fence_lost { assert!( - !session.can_serve().await, - "fence loss must still retire the old session" + !connection.can_serve().await, + "fence loss must still retire the old connection" ); } drop(ops); - drop(session); + drop(connection); running.shutdown().await; pool.close().await; std::fs::remove_file(&path).unwrap(); @@ -1038,11 +1061,11 @@ async fn webhook_signature_failure_and_ack_gate_durable_delivery() { wait(|| { running .node - .session(SESSION) + .connection(CONNECTION) .is_some_and(|s| s.is_claimed()) }) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; let ciphertext = encrypted( &hub, "node-webhook", @@ -1116,15 +1139,15 @@ async fn expired_holder_refuses_requests_and_old_callbacks_preserve_new_generati false, ) .await; - let old_session = old.node.session(SESSION).unwrap(); + let old_connection = old.node.connection(CONNECTION).unwrap(); old.abort(); tokio::time::sleep(std::time::Duration::from_millis(650)).await; - assert!(!old_session.can_serve().await); + assert!(!old_connection.can_serve().await); let error = old .node .runner_request(proto::RunnerRequest { - session_id: SESSION.into(), - lease_generation: old_session.generation, + connection_id: CONNECTION.into(), + lease_generation: old_connection.generation, op: Some(Op::GetIdentity(proto::GetIdentity {})), }) .await @@ -1132,13 +1155,13 @@ async fn expired_holder_refuses_requests_and_old_callbacks_preserve_new_generati assert_eq!(error.code_enum(), proto::Code::NotLeaseHolder); old.node.tick_leases().await; // Releases the expired generation. old.node.tick_leases().await; // Same holder ID must take a new generation. - let new_session = old.node.session(SESSION).unwrap(); - assert!(new_session.generation > old_session.generation); + let new_connection = old.node.connection(CONNECTION).unwrap(); + assert!(new_connection.generation > old_connection.generation); old.node - .lose(SESSION, old_session.generation, "late old callback"); + .lose(CONNECTION, old_connection.generation, "late old callback"); assert_eq!( - old.node.session(SESSION).unwrap().generation, - new_session.generation + old.node.connection(CONNECTION).unwrap().generation, + new_connection.generation ); old.node.shutdown().await; } @@ -1155,7 +1178,7 @@ async fn process_incarnations_with_the_same_node_id_cannot_share_a_fence() { false, ) .await; - let old = first.node.session(SESSION).unwrap(); + let old = first.node.connection(CONNECTION).unwrap(); let ops = old.ops_or_create().await.unwrap(); let replacement = signal_node::start( config("same-stable-node", &hub.url, false), @@ -1165,14 +1188,14 @@ async fn process_incarnations_with_the_same_node_id_cannot_share_a_fence() { .unwrap(); tokio::time::sleep(std::time::Duration::from_millis(250)).await; assert!( - replacement.node.session(SESSION).is_none(), + replacement.node.connection(CONNECTION).is_none(), "an active lease cannot be reacquired by another process with the same node ID" ); first.abort(); wait(|| { replacement .node - .session(SESSION) + .connection(CONNECTION) .is_some_and(|s| s.generation > old.generation) }) .await; @@ -1196,7 +1219,7 @@ async fn group_retry_rejects_unknown_or_missing_addressing_mode() { false, ) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; identity(&hub, "node-group-validation", generation).await; for mode in ["", "unknown"] { let response = hub @@ -1280,7 +1303,7 @@ async fn mixed_protocol_text_is_delivered_without_foreign_keys_or_unconsented_hi false, ) .await; - let generation = running.node.session(SESSION).unwrap().generation; + let generation = running.node.connection(CONNECTION).unwrap().generation; let ciphertext = encrypted( &hub, "node-mixed", @@ -1360,27 +1383,27 @@ async fn reconnect_claims_a_strictly_higher_durable_generation() { false, ) .await; - let first = running.node.session(SESSION).unwrap().generation; + let first = running.node.connection(CONNECTION).unwrap().generation; hub.disconnect("node-reconnect").await; wait(|| { running .node - .session(SESSION) + .connection(CONNECTION) .is_some_and(|s| s.generation > first && s.is_claimed()) }) .await; - assert!(running.node.session(SESSION).unwrap().generation > first); + assert!(running.node.connection(CONNECTION).unwrap().generation > first); running.shutdown().await; } #[tokio::test] async fn a_node_without_a_live_link_takes_no_leases() { - // A partitioned replica must leave free sessions to a connected one. + // A partitioned replica must leave free connections to a connected one. let node = signal_node::node::Node::new( config("partitioned", "ws://127.0.0.1:1/signal", false), Backend::Memory(Arc::new(MemoryRecordStore::new())), ); node.tick_leases().await; - assert!(node.session(SESSION).is_none()); + assert!(node.connection(CONNECTION).is_none()); node.shutdown().await; } diff --git a/tests/support/mod.rs b/tests/support/mod.rs index af9b38e..4363b53 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -34,7 +34,7 @@ use tokio::{ use tokio_tungstenite::tungstenite; pub const APP_SECRET: &str = "fixture-application-secret"; -pub const SESSION: &str = "session-fixture"; +pub const CONNECTION: &str = "connection-fixture"; type SendGate = (Arc, Arc); struct State { connections: Mutex>>>, @@ -165,7 +165,7 @@ impl Hub { }; assert_eq!(hello.protocol_version, 1); let node_id = hello.node_id; - let connection_id = + let link_id = format!("{node_id}:{}", state.next.fetch_add(1, Ordering::SeqCst)); let (disconnect_tx, mut disconnect_rx) = oneshot::channel(); state @@ -209,14 +209,14 @@ impl Hub { let op = request.op.unwrap(); let mut failure = None; let result = match op { - service_request::Op::ClaimSession(claim) => { + service_request::Op::ClaimConnection(claim) => { let mut claims = state.claims.lock().await; - if claims.get(&request.session_id).is_some_and(|(generation, owner)| *generation > claim.generation || *generation == claim.generation && *owner != connection_id) { + if claims.get(&request.connection_id).is_some_and(|(generation, owner)| *generation > claim.generation || *generation == claim.generation && *owner != link_id) { failure = Some(proto::Error::new(proto::Code::NotLeaseHolder, "stale claim")); } else { - claims.insert(request.session_id.clone(), (claim.generation, connection_id.clone())); + claims.insert(request.connection_id.clone(), (claim.generation, link_id.clone())); } - runner_response::Result::SessionClaimed(proto::SessionClaimed { state: proto::session_event::State::Connected as i32, pn: "222:1@s.whatsapp.net".into(), lid: String::new() }) + runner_response::Result::ConnectionClaimed(proto::ConnectionClaimed { state: proto::connection_event::State::Connected as i32, pn: "222:1@s.whatsapp.net".into(), lid: String::new() }) } service_request::Op::ResolveDevices(_) => runner_response::Result::Devices(proto::Devices { jids: state.bundles.lock().await.keys().cloned().collect() }), service_request::Op::FetchPreKeys(query) => runner_response::Result::Bundles(proto::Bundles { bundles: state.bundles.lock().await.iter().filter(|(jid, _)| query.jids.contains(jid)).map(|(jid, bundle)| (jid.clone(), bundle.clone())).collect() }), @@ -255,7 +255,7 @@ impl Hub { } runner_response::Result::Send(proto::SendResult { server_timestamp: 1720000000, participant_hash_mismatch: state.mismatch_next_send.swap(false, Ordering::SeqCst) }) } - service_request::Op::Ping(_) | service_request::Op::ReleaseSession(_) => runner_response::Result::Ok(proto::Ok {}), + service_request::Op::Ping(_) | service_request::Op::ReleaseConnection(_) => runner_response::Result::Ok(proto::Ok {}), }; let body = match failure { Some(error) => Body::Error(error), None => Body::RunnerResponse(proto::RunnerResponse { result: Some(result) }) }; tx.send(proto::Frame::with(frame.id, body).encode_to_vec()).unwrap(); @@ -285,7 +285,7 @@ impl Hub { self.request( node, proto::RunnerRequest { - session_id: SESSION.into(), + connection_id: CONNECTION.into(), lease_generation: generation, op: Some(op), }, @@ -404,7 +404,7 @@ pub fn config(node: &str, url: &str, history: bool) -> signal_node::config::Reso [polymorfa] url="{url}" credential="fixture-project-principal" - sessions=["{SESSION}"] + connections=["{CONNECTION}"] request_timeout_ms=1000 reconnect_min_ms=10 reconnect_max_ms=50 @@ -432,7 +432,7 @@ pub async fn start(hub: &Hub, node: &str, backend: Backend, history: bool) -> si wait(|| { running .node - .session(SESSION) + .connection(CONNECTION) .is_some_and(|s| s.is_claimed()) }) .await;