diff --git a/plans/2026-07-11-service-rpc-implementation.md b/plans/2026-07-11-service-rpc-implementation.md new file mode 100644 index 000000000..d3529f141 --- /dev/null +++ b/plans/2026-07-11-service-rpc-implementation.md @@ -0,0 +1,205 @@ +# Service RPC implementation plan + +RFC: [../rfcs/2026-07-11-service-rpc.md](../rfcs/2026-07-11-service-rpc.md) + +Depends on: [2026-07-12-address-dr-implementation.md](2026-07-12-address-dr-implementation.md). RPC establishes the double ratchet from the service address exactly as the address-DR plan does; this plan is the RPC layer on top of it. Steps named R2'/O2'/O3' below are from that plan. Constructor, event, table and function names are provisional. + +RPC is a one-directional short-lived DR exchange: the client establishes the ratchet from the address (address-DR requester), sends one request, receives one or more responses on its reply queue, and both sides tear the ratchet down after the final response. Unlike a connection, the service does not send a reply queue back and no persistent connection remains. + +## Versions + +- `VersionSMPA` (agent protocol): the new `AgentServiceRequest`/`AgentServiceResponse` messages and the service address subtype. RPC requires the address-DR agent version, whose ratchet establishment it reuses. + +`SSND` (SMP protocol) and the hybrid queue header (SMP client) are not used here - they are separate RFCs (combined secure-send; queue-layer PQ). The ratchet provides post-quantum encryption, and the reply queue is secured with `SKEY` as in the address-DR owner path (O3'). + +## Service address + +A service address is a DR-advertising contact address (address-DR plan: `linkRatchetKey` in fixed data, `RatchetKeys` in mutable data) with a service subtype. There is no separate `ServiceKeyBundle` - requests are encrypted by establishing the ratchet against the advertised keys. + +The subtype distinguishes RPC from a normal connection and drives the owner's handling. Reuse the `ContactConnType` char slot: + +```haskell +data ContactConnType = CCTContact | CCTChannel | CCTGroup | CCTRelay | CCTService +ctTypeChar CCTService = 'S' -- 's' in links +ctTypeP 'S' = pure CCTService +``` + +Stored on the address receive queue as `link_contact_type` (NULL means the current contact type). A service address rejects `AgentInvitation` and connection `AgentConfirmation`; a non-service address rejects service requests. + +## RPC messages + +RPC adds two `AgentMessage` variants (Protocol.hs:883-889, parsed by `parseMessage`), parallel to `AgentConnInfoReply`, not new top-level envelopes. They are the decrypted content of the existing per-queue-e2e envelopes: the request is the `encConnInfo` of the address-DR `AgentConfirmation`; each response is the `encConnInfo` of an `AgentConfirmation` (first message to the reply queue) or the `encAgentMessage` of an `AgentMsgEnvelope` (later messages), all double-ratchet-encrypted. Their tags `Q`/`P` are the RFC's `agentRequest`/`agentResponse`. + +```haskell +data AgentMessage + = ... -- AgentConnInfo 'I', AgentConnInfoReply 'D', AgentRatchetInfo 'R', AgentMessage 'M' + | AgentServiceRequest (NonEmpty SMPQueueInfo) MsgBody -- 'Q': reply queue(s) + opaque request payload + | AgentServiceResponse Bool (NonEmpty MsgBody) -- 'P': final flag + one or more response payloads + +-- encoding (extends AgentMessage Encoding) +AgentServiceRequest qs body -> smpEncode ('Q', qs, Tail body) +AgentServiceResponse final bodies -> smpEncode ('P', final) <> smpEncodeList (map Large (L.toList bodies)) +``` + +One response message carries one or more response payloads, so responses known together are one message; responses over time are separate messages, each with `final = False` until the last. There is no signature and no previous-message hash: the ratchet, established against the `linkRatchetKey` committed by the link hash (address-DR authentication), authenticates each message and its message numbering detects dropping and reordering. The request payload is opaque application bytes (the chat command); the reply queue fields are outside it. + +The request hash used for idempotency is `SHA3-256` of the decrypted request payload (the `MsgBody` in `AgentServiceRequest`). + +The `AgentMsgEnvelope` receive path (`agentClientMsg`, Agent.hs:3289) today expects only `AgentMessage APrivHeader aMessage`; it is extended to accept `AgentServiceResponse` for the stream after the first response. + +## Ratchet establishment - reuse of the address-DR flow + +Request (client), reusing the address-DR requester path (R2'/R3'): + +- Retrieve link data, reconstruct and negotiate the advertised `RcvE2ERatchetParamsUri`, create the reply queue Q_A (messaging mode, subscribed), establish the send ratchet (`generateSndE2EParams`, `pqX3dhSnd`, `initSndRatchet`, `createSndRatchet`). +- Send `AgentConfirmation {e2eEncryption_ = Just sndParams, ratchetKeyId = Just ratchetKeyId, encConnInfo = ratchetEncrypt(AgentServiceRequest (Q_A :| []) payload)}` to the address queue, unauthenticated (`agentCbEncryptOnce`). The client connection is `RcvConnection` (Q_A) with the send ratchet. + +Request (service), reusing the address-DR owner path (O1'/O2'): + +- `smpAddressConfirmation` selects the private keys by `ratchetKeyId`, `pqX3dhRcv`, `initRcvRatchet`, and `rcDecrypt` of `encConnInfo`, which also gives the connection its send side. The decrypted message is `AgentServiceRequest` (not `AgentConnInfoReply`), so the owner takes the RPC branch: create a `SndConnection` to Q_A (no Q_B, unidirectional) holding the ratchet, run idempotency (below), and either deliver `SREQ` or replay stored responses. This is receive-time establishment on unauthenticated input - the abuse bound of the address-DR plan ("Receive-time establishment, state, and abuse") applies unchanged. + +Response (service): send each response to Q_A under the ratchet. The first message to Q_A is `AgentConfirmation {e2eEncryption_ = Nothing, encConnInfo = ratchetEncrypt(AgentServiceResponse final bodies)}` (per-queue e2e is unestablished on Q_A - the address-DR first-message constraint), securing Q_A with `SKEY` using the service's own key (`agentSecureSndQueue`, Q_A is messaging mode); later messages are `AgentMsgEnvelope {encAgentMessage = ratchetEncrypt(AgentServiceResponse …)}`. After the `final = True` message, delete the send connection and its ratchet. + +Response (client): a message on Q_A (its `snd_service_requests` row marks it an RPC reply queue). The first is `AgentConfirmation … Nothing` and takes the address-DR `RcvConnection … Nothing` branch (R5'), extended to accept `AgentServiceResponse`; later ones are `AgentMsgEnvelope` and take the standard message path, extended to accept `AgentServiceResponse`. Each `agentRatchetDecrypt` advances the ratchet. The first response returns from the call; later responses go to the callback. On `final`, the deadline, or `cancelServiceRequest`, delete Q_A (`DEL`) and the reply connection. + +## Reply queue - the requester's DR connection + +The reply queue is the address-DR requester connection: an `RcvConnection` whose receive queue is Q_A, with a ratchet. No `reply_kem_priv_key`/`reply_secret` columns (those were the queue-layer hybrid secret, not used here). A `snd_service_requests` row referencing this connection marks it an RPC reply queue for dispatch and cleanup; there is no new connection type. + +## Database schema + +One migration (`M20260712_service_rpc`), on top of the address-DR migration. SQLite shown, PostgreSQL mirrors it. + +```sql +-- service subtype on the address receive queue (address-DR adds the ratchet key columns) +ALTER TABLE rcv_queues ADD COLUMN link_contact_type TEXT; -- NULL = current contact type + +-- client side: one pending request per reply queue connection. +CREATE TABLE snd_service_requests( + snd_service_request_id INTEGER PRIMARY KEY AUTOINCREMENT, + conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE, -- reply queue (RcvConnection) with the ratchet + deadline TEXT NOT NULL, + created_at TEXT NOT NULL +); + +-- service side: one record per distinct request hash on a service address. +CREATE TABLE rcv_service_requests( + rcv_service_request_id INTEGER PRIMARY KEY AUTOINCREMENT, + address_conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE, -- the service address connection + request_hash BLOB NOT NULL, + ended INTEGER NOT NULL DEFAULT 0, -- a response with final = True was produced + expires_at TEXT NOT NULL, -- created + retention + created_at TEXT NOT NULL +); +CREATE UNIQUE INDEX idx_rcv_service_requests ON rcv_service_requests(address_conn_id, request_hash); + +-- service side: ordered response payloads (plaintext) for a request; re-encrypted per reply +-- connection because each request establishes its own ratchet, so ciphertext is not reusable. +CREATE TABLE rcv_service_responses( + rcv_service_response_id INTEGER PRIMARY KEY AUTOINCREMENT, + rcv_service_request_id INTEGER NOT NULL REFERENCES rcv_service_requests ON DELETE CASCADE, + response_seq INTEGER NOT NULL, + final INTEGER NOT NULL, + response_bodies BLOB NOT NULL -- plaintext response payloads for this message (encoded NonEmpty MsgBody) +); +CREATE UNIQUE INDEX idx_rcv_service_responses ON rcv_service_responses(rcv_service_request_id, response_seq); + +-- service side: reply connections subscribed under a request (the first, and any repeat while pending +-- or after completion). Each is a SndConnection to a reply queue with its own ratchet (in ratchets table). +CREATE TABLE rcv_service_reply_conns( + rcv_service_reply_conn_id INTEGER PRIMARY KEY AUTOINCREMENT, + rcv_service_request_id INTEGER NOT NULL REFERENCES rcv_service_requests ON DELETE CASCADE, + conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE, -- SndConnection to the reply queue, holds the ratchet + last_sent_seq INTEGER NOT NULL DEFAULT 0 +); +``` + +The service's address ratchet keys are the address-DR `address_ratchet_keys` table - not duplicated here. + +## Agent API - `Simplex.Messaging.Agent` + +Service side: + +```haskell +-- Creates a DR-advertising contact address with CCTService subtype (address-DR createServiceAddress +-- plus the subtype), generating the link ratchet key and the first RatchetKeys row. +createServiceAddress :: AgentClient -> UserId -> UserLinkData -> AE (ConnId, ConnShortLink 'CMContact) + +-- Sends one response message with one or more payloads (final = True ends the exchange). The first +-- message to each reply connection secures the reply queue with SKEY; later ones use SEND. Appends to +-- rcv_service_responses. +sendServiceReply :: AgentClient -> ServiceRequestRef -> Bool -> NonEmpty MsgBody -> AE () +``` + +Key rotation and update use the address-DR `rotateRatchetKeys`/link-data update; address deletion is `deleteConnection`. + +Client side (name resolution to a link is an existing API; the link must be a `CCTService` DR-advertising address): + +```haskell +-- Establishes the ratchet from the address, creates the reply queue, sends the request, and waits for +-- the first response up to the deadline. The callback receives later responses while the process runs. +sendServiceRequest :: + AgentClient -> UserId -> ConnShortLink 'CMContact -> UTCTime -> + MsgBody -> (ServiceResponse -> IO ()) -> AE ServiceResponse + +cancelServiceRequest :: AgentClient -> ConnId -> AE () + +data ServiceResponse = ServiceResponse {bodies :: NonEmpty MsgBody, final :: Bool} +``` + +The waiting call and the callback are held in an in-memory map in `AgentClient`, keyed by the reply queue connection, filled by the receive path; they do not survive a restart. + +Service side event (`AEvent`, entity is the service address connection): + +```haskell +SREQ :: ServiceRequestRef -> MsgBody -> AEvent AEConn -- request payload for the bot +``` + +`ServiceRequestRef` identifies the `rcv_service_requests` record; the bot passes it to `sendServiceReply`. + +Rejection reuses `AgentRejection` (communicating-rejection RFC) as an `AgentServiceResponse`-level refusal or a dedicated variant - decided with that RFC. + +## Agent processing + +Client side: + +- `sendServiceRequest`: retrieve link data per request (proxied per config); establish the ratchet and create Q_A (address-DR R2'); write the `snd_service_requests` row; send the `AgentServiceRequest` confirmation (proxied per config); wait on the in-memory sink for the first response until the deadline. +- Response processing in `processSMPTransmissions`: a message on a queue with a `snd_service_requests` row is a response; `agentRatchetDecrypt` (advancing the ratchet), parse `AgentServiceResponse`, deliver to the waiting call or the callback. On `final`/deadline/cancel, delete Q_A and the reply connection. +- `cleanupManager`: delete `snd_service_requests` past the deadline and mark their reply connections deleted; the existing deleted-connections step sends `DEL`. After a restart every row is stale, so this removes reply queues left behind. + +Service side: + +- Address-queue dispatch on `link_contact_type`: a service address routes `AgentConfirmation` with `ratchetKeyId` to the RPC handler (address-DR `smpAddressConfirmation` producing `AgentServiceRequest`); it rejects `AgentInvitation` and connection confirmations. +- On `AgentServiceRequest`: establish the ratchet (address-DR O2'), create the `SndConnection` to Q_A, compute the request hash, look up `rcv_service_requests` by (address conn, hash): + - new: insert the request, insert a `rcv_service_reply_conns` row, deliver `SREQ` to the bot. + - existing: insert a `rcv_service_reply_conns` row and send it every stored `rcv_service_responses` in order, each `AgentServiceResponse` re-encrypted under this connection's ratchet. +- `sendServiceReply`: append a `rcv_service_responses` row, then send `AgentServiceResponse` to every reply connection of the request under its ratchet (`SKEY`+`SEND` for the first message to a connection, `SEND` after); set `ended` on `final`. +- `cleanupManager`: delete `rcv_service_requests` past `expires_at` (cascading to responses and reply connections, and their ratchets/queues). + +Configuration (`AgentConfig`): default request deadline, request retention period (1 to 24 hours). Ratchet key rotation interval is the address-DR config. + +Errors reuse `AgentErrorType` (e.g. `CMD PROHIBITED` for a link that is not a service address). + +## Idempotency + +The service identifies a request by its hash and keeps, for the retention period (config, not in link data), the ordered response payloads (`rcv_service_responses`) and the reply connections under that hash (`rcv_service_reply_conns`). A repeat request (same payload, therefore same hash) establishes its own ratchet and reply connection and does not reach the bot: while pending it is added and receives the responses so far and each later one; after completion it receives the whole stored sequence. Responses are stored as plaintext and re-encrypted per reply connection because each request has its own ratchet. This gives single execution over at-least-once delivery, bounded by the retention period. + +## Correlation and chat + +A response is connected to its request by the reply queue (one request, one reply queue, one ratchet). The request hash is only the idempotency key. The application ID is content inside the request payload, used only by the application to make two requests equal or different; the agent does not read it. + +Both ends are chat bots on the chat library, which serializes a service command into the request payload and deserializes the responses; the agent transports them and correlates by reply queue. The chat framework's `chatServiceCalls` correlation is not used. + +## Tests + +- Encoding roundtrips: `AgentServiceRequest`, `AgentServiceResponse` in `AgentMessage` (one and several response bodies); the service subtype in `UserContactData`/link. +- End to end (on the address-DR machinery): a request with one response; several responses streamed to the callback; `pqEncryption` on (hybrid) and off (X448-only) per the advertised keys; the request payload never travels under per-queue-only encryption. +- Idempotency: a repeat while pending coalesces onto the same operation; a repeat after completion receives the stored responses without a second `SREQ`; both under fresh ratchets. +- Lifecycle: the reply connection and the service ratchet are deleted after `final`; deadline; cancellation; a restart deletes client reply queues. +- Rejection and rejection of the wrong envelope on a service vs non-service address. + +## Phases + +1. Service address subtype and dispatch on top of the address-DR flow; `AgentServiceRequest`/`AgentServiceResponse` messages; `createServiceAddress`. +2. Client: `sendServiceRequest`, reply-queue reception and callback, cleanup. +3. Service: request store, `sendServiceReply`, idempotency (coalescing and repeats under fresh ratchets), end-to-end and idempotency tests. diff --git a/plans/2026-07-12-address-dr-implementation.md b/plans/2026-07-12-address-dr-implementation.md new file mode 100644 index 000000000..6ba55b159 --- /dev/null +++ b/plans/2026-07-12-address-dr-implementation.md @@ -0,0 +1,282 @@ +# Establishing the double ratchet from address data - implementation plan + +RFC: [../rfcs/2026-07-12-address-pqdr-keys.md](../rfcs/2026-07-12-address-pqdr-keys.md) + +All references are to the current tree. Names of new constructors, fields, tables and functions are provisional. + +Goal: a contact address advertises the owner's X3DH parameters in link data; a requester establishes the double ratchet in its first message, so that message and the profile in it are under the ratchet with post-quantum protection. The change reuses the invitation/confirmation machinery, with the requester in the joiner role and the owner in the initiator role - opposite to today's contact flow, but every message and code path below is reused. + +Version: `addressDRVersion = VersionSMPA 8`, a plain agent-layer bump; `currentSMPAgentVersion` goes 7 → 8 (Agent/Protocol.hs:317-324). It gates the `AgentConfirmation.ratchetKeyId` field and the DR-from-address behavior. The receive-at-address path relies on ratchet-on-confirmation, already present since `ratchetOnConfSMPAgentVersion = 7` (Agent/Protocol.hs:317), so there is no cross-layer version dependency; the SMP and e2e-encryption versions are unchanged. + +Scope of this change: the **synchronous** DR handshake in join, gated on the address advertising `ratchetKeys`. `joinConnection`/`joinConn`/`joinConnSrv` gain an optional `Maybe AddressRatchetKeys` (the advertised `RcvE2ERatchetParamsUri` + `ratchetKeyId`), passed in from the link data the caller fetched at plan time (`LGET`); present → DR path (R2'/R3'), absent → the classic `AgentInvitation`. Chat wires that argument later (a chat change); the agent supports it now and tests pass it directly. Making the send **async** (worker retry, a "connecting" UX, the `CreatedConnLink` LGET-gate) is **deferred** - kept below under "Deferred" as future work, not part of this change. + +### Implementation status (as built; `lib:simplexmq` compiles) + +**Done** (compiles): version bump; `RatchetKeyId`/`AddressRatchetKeys` types + `Encoding`, `UserContactData.ratchetKeys` (appended, backward-compatible); `AgentConfirmation.ratchetKeyId` (version-gated encode/decode); `ContactRequest`/`DRRequest` sum with tagged `Encoding` + `cr_invitation` `ToField`/`FromField` (legacy-URI fallback); `address_ratchet_keys` table + `createAddressRatchetKeys`/`getAddressRatchetKeys` (SQLite + Postgres migrations `M20260712_address_dr`); join threading (`Maybe AddressRatchetKeys`); requester R2'/R3' (`joinAddressDR` + `sendConfirmationToAddress`); owner O1' dispatch, O2' `smpAddressConfirmation`, O3' (`acceptContact'` continue-ratchet branch), all three `connReq` readers (`acceptContact'`, `acceptContactAsync'` → `CMD PROHIBITED` for DR, `newConnToAccept` → shell from `drAgentVersion`/`drPQSupport`); requester R5' (`smpConfirmation` `RcvConnection … Nothing` branch, guarded on a ratchet existing); address-creation bundle generation (`mkAddressRatchetKeys`) wired into `createConnectionForLink'` (`IKUsePQ`-for-`SCMContact` prohibition lifted there). + +**Deltas from the plan discovered while building:** +- **R5' emits `CONF` and reuses the allow step** (not auto-complete). The DR requester is a `RcvConnection` receiving the owner's reply - the same position as the classic contact requester, which goes `CONF` → `allowConnection'` → `connectReplyQueues` (msg 3). R5' mirrors that (differing only in that the ratchet already exists, so it `getRatchet` + `rcDecrypt` instead of building it), so the app supplies `ownConnInfo` for msg 3 at allow, exactly as today. No new storage. +- **`DRRequest` carries `drAgentVersion` + `drPQSupport`** (Part 3): the sync accept creates the connection shell via `newConnToAccept`→`newConnToJoin` before O3', and there is no URI to derive the version/PQ from. +- `cr_invitation` serialization is downgrade-safe: `CRInvitation` keeps the legacy URI (`strEncode`, byte-identical to before), so an older agent still reads classic invitations; `CRConfirmation` is JSON (`DRRequest` has manual `ToJSON`/`FromJSON`), told apart on read by the leading `{` (a URI never starts with it). JSON keeps `DRRequest` extensible. `SMPQueueInfo` gained a base64 `StrEncoding` + JSON (it only had `Encoding`) so it can sit in the JSON. +- **DR is opt-in per address**: `createConnectionForLink'`/`createConnectionForLink` gain a `Maybe InitialKeys` DR parameter (separate from the existing connection-PQ `InitialKeys`) - `Nothing` = no DR (old behavior, existing callers), `Just ik` = advertise the bundle with `ik`. The `IKUsePQ`-for-`SCMContact` prohibition stays on the connection-PQ parameter and is lifted only for the DR bundle. + +**Test-matrix consequence of the version bump:** `currentSMPAgentVersion` 7 → 8 moves the version-matrix "prev" (`current − 1`) from v6 to v7. v7 ≥ `ratchetOnConfSMPAgentVersion (7)`, so a joiner/acceptor at "prev" now secures the send queue on confirmation - the `sqSecured` expectation for the prev variants in `testMatrix2`/`testMatrix2Stress`/`testBasicMatrix2` flips `False → True`. (Standard version-bump maintenance; the pre-`ratchetOnConf` unsecured path is now two versions back and no longer exercised by these matrices.) + +**Not yet done:** rotation (`rotateRatchetKeys`, Part 4), cleanup step (Part 4), the app-driven `LSET` upgrade API (Part 5), wiring the DR parameter into the non-prepared-link `newRcvConnSrv` path, DR-specific tests (Part 6), regenerating `agent_schema.sql` if a schema-consistency test requires it, and chat wiring (deferred by design). + +## Part 1 - the current contact-address handshake, step by step + +Requester Alice connects to owner Bob's contact address. Q_A is Alice's receive queue (Bob to Alice), Q_B is Bob's receive queue (Alice to Bob). + +Requester side, in `joinConnSrv … CRContactUri` (Agent.hs:1398-1428): + +- R1. `compatibleContactUri` (Agent.hs:1370) - version check, yields the address queue `SMPQueueInfo`. +- R2. `mkJoinInvitation` (Agent.hs:1411): creates or reuses the receive queue Q_A; `getRatchetX3dhKeys` or `generateRcvE2EParams` produces Alice's Rcv X3DH parameters, stored by `createRatchetX3dhKeys` (Agent.hs:1424); builds `cReq = CRInvitationUri crData aliceRcvParams` (Agent.hs:1426). +- R3. `sendInvitation` (Agent.hs:1408; Agent/Client.hs:1924-1934): sends `AgentInvitation {connReq = cReq, connInfo = aliceProfile}` to the address queue, per-queue encrypted with a fresh ephemeral key by `agentCbEncryptOnce` (Agent/Client.hs:1929-1934), unauthenticated. **`connInfo` (Alice's profile) is under the per-queue X25519 layer only - the gap this plan closes.** + +Owner side, receiving on the contact address: + +- O1. `processClientMsg` dispatch (Agent.hs:3185): state `(Nothing, Just e2ePubKey)`, `(PHEmpty, AgentInvitation {connReq, connInfo})` -> `smpInvitation` (Agent.hs:3186). +- O2. `smpInvitation` (Agent.hs:3610): stores an `Invitation`, emits `REQ` with Alice's `connInfo`. +- O3. `acceptContact'` (Agent.hs:1477): `getInvitation`, then `joinConn` with Alice's `connReq` (Agent.hs:1480). +- O4. `joinConnSrv … CRInvitationUri` (Agent.hs:1383) -> `startJoinInvitation` (Agent.hs:1395). +- O5. `startJoinInvitation` (Agent.hs:1310-1350): creates Bob's send queue to Q_A (`newSndQueue`, Agent.hs:1335); `createRatchet_` (Agent.hs:1343-1350) runs `generateSndE2EParams`, `pqX3dhSnd` against Alice's Rcv parameters, `initSndRatchet`, `createSndRatchet`. +- O6. `secureConfirmQueue` (Agent.hs:1396, 3747-3765): `agentSecureSndQueue` secures Q_A with `SKEY` (Agent.hs:3749); `mkAgentConfirmation` (Agent.hs:3780-3785) calls `createReplyQueue` to create Bob's receive queue Q_B and returns `AgentConnInfoReply (Q_B :| []) bobInfo`; `mkConfirmation` ratchet-encrypts it and wraps `AgentConfirmation {e2eEncryption_ = Just bobSndParams, encConnInfo}`; `sendConfirmation` sends it to Q_A. This is confirmation #1. + +Requester side, receiving confirmation #1 on Q_A: + +- R4. dispatch (Agent.hs:3181-3183): state `(Nothing, Just e2ePubKey)`, `AgentConfirmation` -> `smpConfirmation`. +- R5. `smpConfirmation`, initiating-party branch `RcvConnection … Just e2eEncryption` (Agent.hs:3405-3444): `getRatchetX3dhKeys`, `pqX3dhRcv` (Agent.hs:3408), `initRcvRatchet` (Agent.hs:3411), `createRatchet` (Agent.hs:3436), `setRcvQueueConfirmedE2E` (Agent.hs:3440); decrypts `AgentConnInfoReply` (Agent.hs:3420); `processConf` emits `CONF` (Agent.hs:3444). +- R6. `allowConnection'` (Agent.hs:1467-1474): `acceptConfirmation`, then `ICAllowSecure` secures Q_A with Bob's sender key. +- R7. `connectReplyQueues` (Agent.hs:3724-3737): `upgradeConn` creates Alice's send queue to Q_B; `agentSecureSndQueue` secures Q_B; `enqueueConfirmation … Nothing` (Agent.hs:3733) stores `AgentConnInfo aliceInfo` and sends `AgentConfirmation {e2eEncryption_ = Nothing, encConnInfo}` to Q_B. This is confirmation #2. + +Owner side, receiving confirmation #2 on Q_B: + +- O7. dispatch (Agent.hs:3182): `AgentConfirmation` -> `smpConfirmation`. +- O8. `smpConfirmation`, accepting-party branch `DuplexConnection … Nothing` (Agent.hs:3447-3462): `agentRatchetDecrypt` with the established ratchet; `AgentConnInfo` -> `INFO` (Agent.hs:3452); `ICDuplexSecure` or `CON`. + +Completion is direct `CON` on `senderCanSecure` (SKEY) messaging-mode queues (the sender on `AgentConnInfo`, Agent.hs:2252; the receiver with no `senderKey`, Agent.hs:3459-3461); the separate `HELLO` via `helloMsg` (Agent.hs:3466) is the older non-`senderCanSecure` (duplexHandshake v2, in-band-securing) path. + +## Part 2 - the DR-from-address handshake, mapped to Part 1 + +The address advertises Bob's Rcv X3DH parameters in link data (Part 3). Alice, when the address advertises them and versions are compatible, takes the joiner role; Bob takes the initiator role. + +Requester side - a new branch in `joinConnSrv … CRContactUri`, taken when the passed `Maybe AddressRatchetKeys` is present (the caller's plan-time `LGET`): + +- R2'. Replaces R2/R3. Read the passed bundle - `ratchetKeyId` and `e2eParams :: RcvE2ERatchetParamsUri 'C.X448` - and negotiate the concrete version with `compatibleVersion` against the client e2e range, as `compatibleInvitationUri` does (Agent.hs:1362-1368). Create the receive queue Q_A subscribed (`newRcvQueue` with `subMode`), messaging mode so Bob can secure it. Choose the requester's KEM with `replyKEM_ v ownerKem_ pqSup` (Ratchet.hs:839): if the bundle advertises a KEM (owner `IKUsePQ`) the requester `AcceptKEM` - a **double KEM**: it both encapsulates to the address KEM (ciphertext) and includes its own new KEM public key (`generateSndE2EParams` → `sntrup761Enc` + a fresh keypair, Ratchet.hs:433-435), so PQ is bidirectional from message 1; if the bundle has no KEM and the requester wants PQ, it `ProposeKEM` (its own key only, PQ from message 2 if the owner supports it). Run `generateSndE2EParams g v (replyKEM_ …)`, `pqX3dhSnd` against the negotiated parameters, `initSndRatchet`, `createSndRatchet` - the body of `createRatchet_` (Agent.hs:1343-1350), with parameters from the passed bundle rather than a received invitation. +- R3'. Build `AgentConfirmation {e2eEncryption_ = Just aliceSndParams, ratchetKeyId = Just ratchetKeyId, encConnInfo = ratchetEncrypt(AgentConnInfoReply (Q_A :| []) aliceProfile)}` - the `mkAgentConfirmation`/`mkConfirmation` bodies (Agent.hs:3780-3765) with the reply queue being Alice's own Q_A. Send it to the address queue unauthenticated with `agentCbEncryptOnce`, one-shot (as `sendInvitation` sends, Agent/Client.hs:1929-1934) - **synchronous**, with the same send-failure UX as today's classic contact join. Nothing is stored: a retry (chat re-invokes the join → `mkJoinInvitation` reuses Q_A + keys, 1418) re-builds the confirmation, advancing the send ratchet, and the owner absorbs the advance - a **failed send** is skipped when the owner establishes the ratchet (`maxSkip = 512`, Ratchet.hs:988), and a **lost reply** carries the current content and updates the owner's request by `XContactId` (ContactRequest.hs:99-101, 269); both testable. The requester does **not** SKEY the address (`QMContact`, not `senderCanSecure`); rotation is handled because the passed params are the current advertised keys. **Alice's profile is now inside `encConnInfo`, under the ratchet.** Alice's connection is `RcvConnection` (Q_A) with a send ratchet, until she receives Q_B. This "New `RcvConnection` + `ratchets` row" is a new state (today a New `RcvConnection` holds x3dh keys but no ratchet - the classic initiator builds the ratchet only at R5, `createRatchet` Agent.hs:3436), and it composes: connection type is derived from queue rows alone while the `ratchets` table is keyed independently by `conn_id`, so subscription (Agent.hs:1551), `connectionStats` (2658), and `allowConnectionAsync'` (888) never read the ratchet for a `RcvConnection`; the only handshake reader on it is `smpConfirmation` (R5'). + +### Deferred (future work): async delivery + connect UX + +The synchronous send above fails in the user's face on a lost reply (the same wart as today's classic contact join), even though the request may have been delivered. Making it async is a separate, later change, not part of this DR work: + +- Delivery cannot use the message-delivery worker: a `SndQueue` is unique per `(host, port, snd_id)` and belongs to one connection (schema PK), while a contact address is one queue that many connections send to, so no per-connection SndQueue to it can exist. It would go through the **async command worker**, keyed by `(connId, server)` (`getAsyncCmdWorker`, Agent.hs:1856-1858), which already retries the `JOIN` command (`tryMoveableCommand` → `retrySndOp`, 2016-2024); each retry re-runs `joinConnSrv` (re-build + ratchet advance, which the owner absorbs - above), so nothing is stored. (`joinConnSrvAsync` for `CRContactUri` is `CMD PROHIBITED` today, Agent.hs:1452, and the `JOIN` handler falls back to sync `joinConnSrv`, 1899-1902; the `TBC` at Agent.hs:1897 is about async *receive*-queue creation - Q_A - and is orthogonal.) +- The async join returns "connecting" early and completes via the events chat already handles (`joinContact` sets `ConnJoined`; the DR requester emits `CONF` in R5' and the chat allows it, exactly as the classic contact requester, driving msg 3 → `CON`; a permanent send failure still surfaces as `ERR → ConnFailed`). +- This needs a chat change: the join API takes a `CreatedConnLink` (full + short link), not the bare `ConnectionRequestUri` it takes today, so the agent can LGET-gate on the owner's server (a real reachability check) and verify the fetched `linkConnReq` equals the passed full link before reporting success. Used only for DR addresses (link data advertises `ratchetKeys`); old / non-DR addresses stay on the current sync path. + +Owner side - a new dispatch branch and a new receive handler: + +- O1'. In `processClientMsg` (Agent.hs:3176-3187), add a branch in state `(Nothing, Just e2ePubKey)`: an `AgentConfirmation` with `ratchetKeyId = Just _` **and** `e2eEncryption_ = Just _` on a `ContactConnection` -> `smpAddressConfirmation` (new). A `ratchetKeyId` without `e2eEncryption_` is ignored (it does not match this branch and falls through as a non-DR confirmation). It must be placed **before** the existing `(PHEmpty, AgentConfirmation) | senderCanSecure queueMode` case (Agent.hs:3182-3184), because a contact-address queue is `QMContact` (not `senderCanSecure`) and would otherwise fall into `prohibited "handshake: missing sender key"` (Agent.hs:3184). The address queue's `e2eDhSecret` stays `Nothing` (it is never set for a contact address - `smpInvitation` does not set it, Agent.hs:3609-3622), so every request is decrypted with its own ephemeral key via this `(Nothing, Just e2ePubKey)` path. +- O2'. `smpAddressConfirmation` (new, modeled on `smpConfirmation` initiating branch, Agent.hs:3405-3444): select the private triple `(pk1, pk2, pKem)` by `ratchetKeyId` from `address_ratchet_keys`; `pqX3dhRcv pk1 pk2 pKem aliceSndParams`; `initRcvRatchet` with the address connection's stored `PQSupport` (`connPQEncryption` of the address `InitialKeys` - `On` for `IKUsePQ` and `IKPQOn`, `Off` for `IKPQOff`; this is what lets `IKPQOn` accept the requester's proposed KEM), combined with version compatibility as `smpConfirmation` derives `pqSupport'` (Agent.hs:3410); `rcDecrypt` of `encConnInfo` performs the first ratchet step, giving the ratchet its send side too (as it does for the initiator today), so the owner can later reply. Parse `AgentConnInfoReply (Q_A :| []) aliceProfile`. Store the request with `createInvitation` on the address connection (`contact_conn_id`), exactly as a classic invitation - except the request value is the `CRConfirmation` variant (Part 3) carrying the post-decrypt ratchet state and Q_A, and `recipient_conn_info` is `aliceProfile` - so **no connection or `ratchets` row is created at receive**, as with a classic invitation. Emit `REQ` with the `invitation_id`. A resend is not deduplicated: like a resent classic invitation it produces another `REQ` (the connect-UX fix for that is separate chat work). An unknown or expired `ratchetKeyId`, or a decryption failure: discard and acknowledge, as an undecryptable message is dropped today. This establishes ratchet state on unauthenticated input before the user accepts - see "Receive-time establishment, state, and abuse". +- O3'. `acceptContact'` for a DR request - a new branch that continues the ratchet instead of `joinConn`. `getInvitation` returns the request; its `CRConfirmation` variant gives the stored ratchet state and Q_A. Create the connection now (as `joinConn` does for a classic invitation) and `createRatchet` (AgentStore.hs:1419) from the stored ratchet state. Reuse `mkAgentConfirmation` (Agent.hs:3780-3785) to create Bob's receive queue Q_B and return `AgentConnInfoReply (Q_B :| []) bobInfo`; create Bob's send queue to Q_A (`newSndQueue`, generating Bob's own sender key) and secure Q_A with `SKEY` using that key (`agentSecureSndQueue`, valid because Q_A is messaging mode) - the securing key is Bob's own, not taken from Alice's message; send the response to Q_A as `AgentConfirmation {e2eEncryption_ = Nothing, ratchetKeyId = Nothing, encConnInfo = ratchetEncrypt(AgentConnInfoReply (Q_B :| []) bobInfo)}` via `sendConfirmation` (`agentCbEncrypt` over Bob's send queue to Q_A, `PHEmpty` because Q_A is `senderCanSecure`) - exactly the current contact msg 2 path (Client.hs:1916), not `agentCbEncryptOnce`. The reply content is `AgentConnInfoReply`, not `AgentConnInfo`: it takes the `mkAgentConfirmation` path with `e2eEncryption_ = Nothing`, not the `enqueueConfirmation` path (which produces `AgentConnInfo`, Agent.hs:3789). `rejectContact'` deletes the `conn_invitations` row (the current behaviour), discarding the inline ratchet; no connection was created, so there is nothing else to clean up. + +Requester side, receiving the response on Q_A: + +- R5'. `smpConfirmation` needs a new branch `RcvConnection … Nothing` (today only `RcvConnection … Just` and `DuplexConnection … Nothing` exist, Agent.hs:3403-3447). It looks up the ratchet first (`getRatchet`) and, if there is none, falls through to `prohibited "conf: incorrect state"` - so a classic initiator (a New `RcvConnection` with x3dh keys but no ratchet) that receives a stray `Nothing`-confirmation keeps today's exact outcome; only a DR requester, which holds a send ratchet, takes the new path. Alice already holds the send ratchet, so `rcDecrypt` advances it and creates the receive side; parse `AgentConnInfoReply (Q_B :| []) bobInfo`. **This mirrors the classic contact requester exactly**: `setRcvQueueConfirmedE2E` on Q_A, `createRatchet` the advanced ratchet, store the reply as a `NewConfirmation`, and emit **`CONF`** - the app then calls `allowConnection'` (supplying `ownConnInfo` for msg 3), which drives `connectReplyQueues` (create Alice's send queue to Q_B, `SKEY`, upgrade to `DuplexConnection`, `enqueueConfirmation` the `AgentConnInfo` msg 3). Because Q_B is sender-securable, sending `AgentConnInfo` completes Alice with `CON` (Agent.hs:2252) - no `HELLO`. The only difference from the classic requester is that the ratchet is pre-built (from R2') rather than built from Bob's Snd params here, so there is no `CONF`-less auto-completion and no separate storage of Alice's own info. +- R6'/completion. Unchanged from the current contact handshake, and modern (no `HELLO`). The exchange is three agent↔agent wire messages - Alice → address queue (msg 1), Bob → Q_A (msg 2, an `AgentConfirmation` carrying `AgentConnInfoReply` with Q_B), Alice → Q_B (msg 3, an `AgentConfirmation` carrying `AgentConnInfo`) - the same shape as the current contact flow, where msg 1 was `AgentInvitation`; here it is the ratchet-establishing `AgentConfirmation`. (`CON` is not a wire message - it is the agent→app event; `HELLO` and `AgentConnInfo` are the wire messages.) `HELLO` belongs to the older non-`senderCanSecure` path (duplexHandshake v2, before SKEY): there the confirmation secures the queue in-band (`PHConfirmation` carries the sender key, Client.hs:1918) and the receiver replies with `HELLO` (`ICDuplexSecure` → `enqueueDuplexHello`, Agent.hs:3457-3458). Both Q_A and Q_B here are messaging-mode - Q_A by R2', Q_B via `createReplyQueue` → `SCMInvitation` → `QMMessaging` (Agent.hs:1233,1458,3783) - so the sender secures with SKEY and sends `PHEmpty` (Client.hs:1918), the dispatch takes the `senderCanSecure` branch (Agent.hs:3182-3184), and each agent raises the `CON` app event locally off msg 3 - Bob on receiving it (`senderKey = Nothing`, Agent.hs:3459-3461), Alice on sending it (Agent.hs:2252) - with no separate `HELLO` wire message. (msg 2's `AgentConnInfoReply` only sets Q_A `Confirmed`, Agent.hs:2254.) Invitations are two messages because the initiator's queue is already in the link; a contact address needs three because Bob's receive queue Q_B is only delivered in msg 2. The third message no longer has a ratchet role: Bob's X3DH params are pre-published, so the agreement is complete once Bob receives msg 1 (in the current flow Bob's Snd params instead arrive in msg 2). msg 2 and msg 3 are queue setup - msg 2 delivers Q_B, msg 3 secures Q_B so Alice can send to Bob and signals Bob's `CON`; neither negotiates the ratchet. A one-directional exchange (the RPC) needs no Q_B and is two messages. + +Net code touch points: `joinConnSrv` (new requester branch), `processClientMsg` (new owner dispatch), `smpConfirmation` (new `RcvConnection … Nothing` branch and `AgentConnInfoReply` acceptance), `acceptContact'` (new continue-ratchet branch), a new `smpAddressConfirmation` reusing `createInvitation`/`getInvitation` with the sum request value, and the link data and storage of Part 3-4. `rejectContact'` is unchanged (it deletes the `conn_invitations` row either way). + +### Receive-time establishment, state, and abuse + +This is the substantive departure from the current flow. Today `smpInvitation` creates only a lightweight `NewInvitation` and emits `REQ` (Agent.hs:3618-3621); no connection or ratchet exists until the user accepts. For DR the request is under the ratchet, so to show the requester's profile in `REQ` the owner must decrypt it, which means establishing the ratchet at **receive**, before accept. + +Design decision (Q1): decrypt at receive. Both use cases need the request content at `REQ` - a person decides to accept from the profile, and a service bot needs the request payload to act. Deferring decryption to accept would make `REQ` contentless and does not fit the service case, so it is not done. + +Consequences: + +- No connection is created at receive, exactly as for a classic invitation. O2' stores the request with `createInvitation` on the address connection; the post-decrypt ratchet state and Q_A live inline in the `CRConfirmation` request value (`cr_invitation`). O3' (accept) creates the connection, `createRatchet` from the stored state, and adds Bob's queues, becoming a `DuplexConnection`; `rejectContact'` deletes the `conn_invitations` row. +- Per incoming `AgentConfirmation` the owner does one `pqX3dhRcv` (three DH plus, with PQ, one `sntrup761` decapsulation) and one `rcDecrypt`, on unauthenticated input, and writes one `conn_invitations` row - more CPU than the current `NewInvitation`, the same order of state (no connection, no `ratchets` row until accept). + +Abuse (Q2): a contact address already accepts and processes unauthenticated invitations today, so this is a degree-worse version of an existing surface, not a new class. It is bounded by the address queue quota (an attacker fills it, the owner drains and acknowledges) and, optionally, by basic auth on the address (already supported for contact addresses, `optBasicAuth`). The per-request state is a single `conn_invitations` row - the same class as a classic contact request - so it is subject to the same limits and lifecycle, with no DR-specific dedup or TTL. Proof-of-work or a stricter gate can be added later; it is out of scope here and noted as a follow-up. + +`acceptContact'`/`rejectContact'` keep taking the `invitation_id` from `REQ` unchanged; the only difference is that `getInvitation` returns a request that is either a `CRInvitation` URI (current `joinConn` path, O3-O6) or a `CRConfirmation` (continue-ratchet path, O3'). Nothing in the `REQ`/accept/reject flow or the chat client changes - the change is contained in the agent. + +### The four communication layers, per message (verified against code) + +Layers, outermost (server-visible) first: + +- **L1 `ClientMsgEnvelope`** (Protocol.hs:1089), `PubHeader {phVersion, phE2ePubDhKey :: Maybe PublicKeyX25519}` (1096) - **this is where per-queue encryption is agreed** (not L2). `phE2ePubDhKey` is the sender's e2e DH public key; the recipient combines it with the queue's e2e private key: `(e2eDhSecret, e2ePubKey_) -> (Nothing, Just e2ePubKey) -> e2eDh = dh' e2ePubKey e2ePrivKey` (Agent.hs:3172-3178). `agentCbEncryptOnce` (Client.hs:2214) puts a **fresh ephemeral** pubkey (generated 2217, set 2223) - used when the sender has no send queue (the address queue), whose `e2eDhSecret` stays `Nothing`, so it decrypts every message with the per-message ephemeral. `agentCbEncrypt` (Client.hs:2203) puts the **send queue's persistent** e2e pubkey (`Just` on a confirmation, 2210); the recipient stores the secret via `setRcvQueueConfirmedE2E`, and *later* messages send `phE2ePubDhKey = Nothing` (`sendAgentMessage`, 2080). +- **L2 `ClientMessage PrivHeader`** (Protocol.hs:1113), `PrivHeader = PHConfirmation APublicAuthKey | PHEmpty` (1115) - **queue securing / authorization, not encryption**. `PHConfirmation` carries the sender's AUTH key for in-band securing (v2, non-`senderCanSecure`); `PHEmpty` when the sender secured the queue with SKEY out-of-band. `PHEmpty` on every message here is about securing, and says nothing about encryption (that is L1). Set in `sendConfirmation` (Client.hs:1918), `sendInvitation` (1934), `sendAgentMessage` (2079). +- **L3 `AgentMsgEnvelope`** (Agent/Protocol.hs:829, encoding 851) - outside the ratchet. `AgentConfirmation` ('C') carries `e2eEncryption_` (Snd X3DH params, agrees DR) + `encConnInfo`; `AgentInvitation` ('I') carries `connReq` (Rcv X3DH params) + plaintext `connInfo` (no DR); `AgentMsgEnvelope` ('M') carries `encAgentMessage`. +- **L4 `AgentMessage`** (Agent/Protocol.hs:883, encoding 893) - inside the ratchet. `AgentConnInfo` ('I'), `AgentConnInfoReply` ('D', reply queues + info), `AgentMessage APrivHeader AMessage` ('M'; `AMessage` includes `HELLO`, Agent/Protocol.hs:1018-1020). **Absent when L3 is `AgentInvitation`** (that profile is per-queue-only - the gap this plan closes). + +Send routing: msg 1 (to address) → `sendInvitation` today / a new `agentCbEncryptOnce` confirmation send for DR; msg 2 → `secureConfirmQueue` → `sendConfirmation` (Agent.hs:3747); msg 3 → `connectReplyQueues` → `enqueueConfirmation` → delivery worker `AM_CONN_INFO` → `sendConfirmation` (Agent.hs:3733,3789,2183). `AM_CONN_INFO`/`AM_CONN_INFO_REPLY` both go through `sendConfirmation` (2183-2184); other `AMessage`s go through `sendAgentMessage` wrapping `AgentMsgEnvelope` 'M' (2192-2193). + +Current contact handshake (address does **not** advertise DR): + +| msg | L1 `PubHeader.phE2ePubDhKey` (per-queue enc) | L2 `PrivHeader` (securing) | L3 `AgentMsgEnvelope` | L4 `AgentMessage` | +|---|---|---|---|---| +| 1 Alice→addr | `Just` fresh ephemeral, `agentCbEncryptOnce` (Client.hs:1933,2223) | `PHEmpty` (1934) | `AgentInvitation` {connReq = Alice Rcv params, connInfo = profile} (Client.hs:1932) | — none (profile per-queue only) | +| 2 Bob→Q_A | `Just` Bob's send-queue e2e pubkey, `agentCbEncrypt` (1920,2210) | `PHEmpty` [`senderCanSecure`] (1918) | `AgentConfirmation` {e2eEncryption_ = **Just Bob Snd params**, encConnInfo} (Agent.hs:3765) | `AgentConnInfoReply` (Q_B) bobInfo, DR-enc (Agent.hs:3785) | +| 3 Alice→Q_B | `Just` Alice's send-queue e2e pubkey, `agentCbEncrypt` (1920,2210) | `PHEmpty` [`senderCanSecure`] (1918) | `AgentConfirmation` {e2eEncryption_ = **Nothing**, encConnInfo} (Agent.hs:3802) | `AgentConnInfo` aliceInfo, DR-enc (Agent.hs:3789) | + +New DR handshake (address advertises DR): + +| msg | L1 `PubHeader.phE2ePubDhKey` (per-queue enc) | L2 `PrivHeader` (securing) | L3 `AgentMsgEnvelope` | L4 `AgentMessage` | +|---|---|---|---|---| +| 1 Alice→addr | `Just` fresh ephemeral, `agentCbEncryptOnce` [same] | `PHEmpty` [same] | **`AgentConfirmation`** {e2eEncryption_ = **Just Alice Snd params**, **ratchetKeyId = Just**, encConnInfo} [was `AgentInvitation`] | **`AgentConnInfoReply`** (Q_A) aliceProfile, **DR-enc** [was plaintext connInfo] | +| 2 Bob→Q_A | `Just` Bob's send-queue e2e pubkey, `agentCbEncrypt` [same] | `PHEmpty` [same] | `AgentConfirmation` {e2eEncryption_ = **Nothing**, ratchetKeyId = Nothing, encConnInfo} [was Just Bob Snd params] | `AgentConnInfoReply` (Q_B) bobInfo, DR-enc [same] | +| 3 Alice→Q_B | `Just` Alice's send-queue e2e pubkey, `agentCbEncrypt` [same] | `PHEmpty` [same] | `AgentConfirmation` {e2eEncryption_ = Nothing, encConnInfo} [same] | `AgentConnInfo` aliceInfo, DR-enc [same] | + +Net difference: **only msg 1 and msg 2's L3/L4 change.** msg 1's L3 becomes `AgentConfirmation` (was `AgentInvitation`) carrying Alice's Snd params + `ratchetKeyId`, and the profile moves from plaintext L3 to DR-encrypted L4 (`AgentConnInfoReply`) - the whole point of the change. msg 2 drops `e2eEncryption_` (Bob no longer sends Snd params - the ratchet is agreed from msg 1). msg 3 is unchanged. L1 (per-queue encryption - each queue agrees its own secret via the sender's e2e pubkey in the `PubHeader` on the first message to it) and L2 (securing, `PHEmpty` because SKEY is used) are unchanged throughout; the DR change is entirely at L3/L4. The only new send code is msg 1 (an `AgentConfirmation` fired to the address with `agentCbEncryptOnce`, like `sendInvitation` but with a confirmation envelope). + +## Part 3 - types and link data + +### Fixed data - unchanged + +`FixedLinkData` (Protocol.hs:1824) is not touched. The double-ratchet keys go entirely in mutable data, so an existing address advertises them without a new link (the fixed data is hash-committed and cannot change). Fixed data keeps only `agentVRange`, `rootKey`, `linkConnReq`, `linkEntityId`. + +### Mutable data - ratchet keys bundle + +Appended to `UserContactData` (Protocol.hs:1840); the encoding stops at a trailing tail (Protocol.hs:1981), so earlier versions ignore it: + +```haskell +newtype RatchetKeyId = RatchetKeyId ByteString -- opaque short id; one Encoding instance, shared below + +data AddressRatchetKeys = AddressRatchetKeys + { ratchetKeyId :: RatchetKeyId, -- identifies this bundle; changes on rotation, echoed in the request + e2eParams :: CR.RcvE2ERatchetParamsUri 'C.X448 -- version range + both X3DH keys + optional KEM + } +instance Encoding AddressRatchetKeys where ... -- the key-bundle instance; both fields required + +data UserContactData = UserContactData + { direct :: Bool, owners :: [OwnerAuth], relays :: [ConnShortLink 'CMContact], + userData :: UserLinkData, + ratchetKeys :: Maybe AddressRatchetKeys -- whole bundle optional, one Encoding instance + } +``` + +`e2eParams` is the existing `RcvE2ERatchetParamsUri 'C.X448` (`E2ERatchetParamsUri VersionRangeE2E k1 k2 (Maybe (RKEMParams s))`, Ratchet.hs:282-286) - the same type a `CRInvitationUri` advertises - with `StrEncoding`/`Encoding` already defined (Ratchet.hs:302-374). There is no bespoke key type and no reconstruction: the requester negotiates the concrete version with `compatibleVersion` against its own e2e range, exactly as `compatibleInvitationUri` does for an invitation (Agent.hs:1362-1368), giving `RcvE2ERatchetParams` for `pqX3dhSnd`. The KEM is optional: `Nothing` gives an X448-only ratchet (as when `PQSupport` is off), `Just` a hybrid one, matching `generateRcvE2EParams`'s `PQSupport` gate (Ratchet.hs:439-445). + +The address-creation parameter is `InitialKeys` (Ratchet.hs:864) - the same 3-way choice as invitations, not a bare `PQSupport`. Currently `IKUsePQ` is prohibited for `SCMContact` (Agent.hs:990,1198) because a contact address carries no owner keys; this change lifts that prohibition. The bundle plays the published-contact-request role, so its KEM follows `initialPQEncryption False pqInitKeys` (Ratchet.hs:882) - exactly as the requester's contact request does today (Agent.hs:1422): + +- `IKUsePQ` - the bundle advertises the KEM; the requester encapsulates to it, so PQ from message 1. +- `IKPQOn` (`IKLinkPQ PQSupportOn`) - the bundle is X448-only (no KEM advertised), but the owner's ratchet supports PQ (`connPQEncryption` = On, Ratchet.hs:888); the requester proposes its own KEM (R2'), so PQ from message 2. +- `IKPQOff` (`IKLinkPQ PQSupportOff`) - X448-only, and the owner's ratchet does not support PQ even if the requester proposes it. + +Advertising the KEM adds ~1158 B to the rotated, widely-fetched link data, which is why `IKPQOn` exists (PQ one round later, without the size cost). The owner generates the bundle with `generateRcvE2EParams g v (initialPQEncryption False pqInitKeys)` (Ratchet.hs:439), stores the private triple `(pk1, pk2, pKem)` (Part 4), and advertises `e2eParams` by wrapping the public `E2ERatchetParams` in the address's e2e version range (`toVersionRangeT`; or `mkRcvE2ERatchetParams` from the stored privates, Ratchet.hs:412) - the same private-key shape `createRatchetX3dhKeys`/`getRatchetX3dhKeys` already store (AgentStore.hs:1362-1367). `ratchetKeys` is set by the agent when it signs mutable link data (`Crypto.ShortLink.encodeSignUserData`), not by the application. + +### Authentication of the advertised keys + +No signature is added on the keys: the mutable link data already signs them. `decryptLinkData` (Crypto/ShortLink.hs:106-114) verifies `sig2` over the mutable `UserContactData` by `rootKey`, so `ratchetKeys` is root-signed. This is the X3DH anti-substitution property: an SMP server cannot substitute the keys without forging the root signature. The signer is the root Ed25519 key (the address's signing identity); the X3DH keys are separate DH keys (X448, which cannot sign). A single owner signs address data ("we don't use multiple owners"), so the root signature alone is sufficient - no per-key signature. A malicious server can still serve an older but validly-signed `UserContactData` (rollback to a retired bundle); this is bounded by the retention window and by the ratchet advancing after the first message, and a signature does not prevent it. Inline ratchet params in a `CRInvitationUri` contact request are not in signed link data and remain unsigned - a separate change, out of scope here. + +### Request envelope + +`AgentConfirmation` (Protocol.hs:830-834) gains an optional `ratchetKeyId` - the `ratchetKeyId` of the `AddressRatchetKeys` bundle the requester used, so the owner selects the matching private keys: + +```haskell +AgentConfirmation + { agentVersion :: VersionSMPA, + e2eEncryption_ :: Maybe (SndE2ERatchetParams 'C.X448), -- reused: Alice's Snd params in DR msg 1 + ratchetKeyId :: Maybe RatchetKeyId, -- selects the owner's key generation + encConnInfo :: ByteString + } +``` + +`ratchetKeyId` is a separate optional selector (the shared `RatchetKeyId` newtype), not the bundle - the owner already holds the published public bundle and looks up its private keys by this id. It reuses the existing `e2eEncryption_` for Alice's Snd params rather than a new combined bundle; the minor cost is two correlated `Maybe`s (`ratchetKeyId = Just` is only meaningful with `e2eEncryption_ = Just`). **A `ratchetKeyId` with `e2eEncryption_ = Nothing` is ignored** - O2' requires both (there are no Snd params to run `pqX3dhRcv`), so such a message falls through to the current dispatch as if it had no `ratchetKeyId`. + +Encoding (extends Protocol.hs:853-866): from `addressDRVersion`, `smpEncode (agentVersion, 'C', e2eEncryption_, ratchetKeyId, Tail encConnInfo)`; `ratchetKeyId` is `Just` for an address-DR confirmation and `Nothing` for the current joiner-to-initiator and initiator-to-joiner confirmations; earlier versions omit the field entirely and use `smpEncode (agentVersion, 'C', e2eEncryption_, Tail encConnInfo)`. Parsing gates the field on `agentVersion`. `CRInvitationUri` is unchanged - a connection request URI holds Rcv parameters and must not hold Snd parameters. + +### Stored request - the invitation record + +The `conn_invitations` record stays; only the type of the stored request widens. From chat's point of view a DR request is still an invitation - it "contains a confirmation" instead of an invitation URI - so `REQ`, `acceptContact'`/`rejectContact'`, and the chat side are unchanged; the change is contained in the agent. The `NewInvitation`/`Invitation` request field (`cr_invitation`, stays `NOT NULL`) becomes a sum: + +```haskell +data ContactRequest + = CRInvitation (ConnectionRequestUri 'CMInvitation) -- classic: joinConn on accept (O3-O6) + | CRConfirmation DRRequest -- DR: continue the ratchet on accept (O3') + +data DRRequest = DRRequest + { drRatchet :: RatchetX448, -- post-decrypt receiving ratchet (with send side), stored inline + drReplyQueue :: SMPQueueInfo, -- Q_A, where the owner replies + drAgentVersion :: VersionSMPA, -- negotiated at receive; needed to build the connection shell at accept + drPQSupport :: PQSupport -- the address's PQ setting for this connection + } +``` + +`recipient_conn_info` holds the profile in both cases. `getInvitation`/`createInvitation` carry `ContactRequest`; `acceptContact'` branches on the constructor. There is no dedup column: a resent request produces another `REQ`, exactly as a resent classic invitation does. + +`drAgentVersion`/`drPQSupport` are stored because the accept flow creates the connection **shell** through `newConnToAccept` → `newConnToJoin` (via `prepareConnectionToAccept`, called by chat's sync accept before `acceptContact'`, Internal.hs:914,925) and `newConnToJoin` today derives `connAgentVersion`/`pqSupport` from the `ConnectionRequestUri` (Agent.hs:1277-1293); a `CRConfirmation` has no URI, so the values negotiated at receive (O2') are stored and used to build the shell. + +Three readers of the widened `connReq` field (all via `getInvitation`) branch on the constructor: +- `acceptContact'` (Agent.hs:1479, sync): `CRInvitation cr` → `joinConn … cr` (classic, unchanged); `CRConfirmation dr` → the O3' continue-ratchet path. +- `newConnToAccept` (Agent.hs:1296, via `prepareConnectionToAccept`): `CRInvitation cr` → `newConnToJoin … cr` (unchanged); `CRConfirmation dr` → create the `NewConnection` shell from `drAgentVersion`/`drPQSupport` (`createNewConn`, generating the connId). +- `acceptContactAsync'` (Agent.hs:900): `CRInvitation cr` → `joinConnAsync … cr` (unchanged); `CRConfirmation _` → `throwE $ CMD PROHIBITED` (async DR accept is deferred; DR requests accept synchronously). Chat's REQ/accept is unaffected either way - it only ever passes `invId`, never the `ContactRequest`, which stays internal to the agent. + +Storage: `cr_invitation`'s `ToField`/`FromField` encode `CRInvitation` as the legacy `strEncode` URI (unchanged from before, so the format is downgrade-safe) and `CRConfirmation` as JSON (`J.encode` of `DRRequest`). `FromField` peeks the first byte: `{` → JSON `CRConfirmation`, else `strDecode` → `CRInvitation` (a URI never starts with `{`). `DRRequest` uses manual `ToJSON`/`FromJSON` (extensible), and `SMPQueueInfo` gets a base64 `StrEncoding` + JSON to sit inside it. `smpInvitation` (Agent.hs:3618) wraps its `connReq` in `CRInvitation`; `smpAddressConfirmation` (O2') writes `CRConfirmation`. + +## Part 4 - key rotation (separate concern) + +Rotation is required but independent of the handshake above. The whole ratchet-keys bundle - both X448 keys and the KEM - rotates on a schedule, generated fresh each time. + +### Schema + +```sql +-- one row per ratchet-keys generation for an address; current plus retired-within-window. +-- private side of the advertised RcvE2ERatchetParamsUri - same shape as the ratchets x3dh +-- columns and createRatchetX3dhKeys (AgentStore.hs:1362-1367). +CREATE TABLE address_ratchet_keys( + address_ratchet_key_id INTEGER PRIMARY KEY AUTOINCREMENT, + conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE, + ratchet_key_id BLOB NOT NULL, -- the published id echoed by requests + x3dh_priv_key_1 BLOB NOT NULL, -- X448 + x3dh_priv_key_2 BLOB NOT NULL, -- X448 + pq_priv_kem BLOB, -- RcvPrivRKEMParams (sntrup761 keypair); NULL when PQ is off for this address + created_at TEXT NOT NULL, + retired_at TEXT -- set on rotation +); +CREATE UNIQUE INDEX idx_address_ratchet_keys ON address_ratchet_keys(conn_id, ratchet_key_id); + +-- a DR request stays in conn_invitations with NO schema change: cr_invitation now holds a ContactRequest +-- sum (an invitation URI or a confirmation carrying the post-decrypt ratchet + reply queue), so it stays +-- NOT NULL - no nullable change, no new column on conn_invitations, no new table for the request. +``` + +`cr_invitation` stays `NOT NULL` - only its decoded value gains a variant (Part 3), so the invitations flow, `REQ`, and chat are unchanged; the only new storage is the `address_ratchet_keys` table. The link signing key is already on the address queue (`rcv_queues.link_priv_sig_key`, M20250322), so nothing is added there - rotation and retrofit re-sign mutable data with it. PostgreSQL mirrors this. Migration `M20260712_address_dr`. + +### Rotation logic + +`rotateRatchetKeys` (new), run on address subscription, at most every 2 weeks (skip if the current generation is younger): + +1. `generateRcvE2EParams` (Ratchet.hs:439) for a fresh generation - two X448 keys, and an sntrup761 keypair only if PQ is on for this address - with a fresh `ratchetKeyId`. +2. Recompute mutable link data with the new `AddressRatchetKeys` (the public `e2eParams`), re-sign with the root key (`encodeSignUserData`, key from `rcv_queues.link_priv_sig_key`), and `LSET` it to the address queue (`setConnShortLink` path). +3. Insert the new `address_ratchet_keys` row (`x3dh_priv_key_1`, `x3dh_priv_key_2`, `pq_priv_kem`); set `retired_at` on the previous row. + +Retention window equals queue message retention (`storedMsgDataTTL`, Env/SQLite.hs:237), covering a request that used a just-retired bundle and is still in the address queue. The 2-week cadence bounds how long a recorded first message stays decryptable after a compromise of the current private keys - a retired generation is deleted after the window and then decrypts nothing. + +### Cleanup + +`cleanupManager` (Agent.hs:2994) gains one step: delete `address_ratchet_keys` rows with `retired_at` older than the window, batched like `deleteRcvMsgHashesExpired` (Agent.hs:3001). Unaccepted DR request rows in `conn_invitations` are handled exactly like unaccepted classic invitation requests - no DR-specific cleanup (a DR request is one `conn_invitations` row, the same class of state as a classic contact request). + +## Part 5 - backward compatibility + +- A requester older than `addressDRVersion`, or an address without `ratchetKeys`, uses R2/R3 (`AgentInvitation`); the owner uses O1-O8. Unchanged. +- The owner dispatches on the envelope: `AgentInvitation` -> `smpInvitation` (current); `AgentConfirmation` with `ratchetKeyId` on a `ContactConnection` -> `smpAddressConfirmation` (new). Both coexist. +- `AgentConfirmation` without `ratchetKeyId` remains the current confirmation on established connections. +- An existing address gains `ratchetKeys` via a new agent API (e.g. `updateContactAddressLink`) that the app calls with the mutable link data (profile/badge and any other short-link data): the agent generates the DR bundle if absent (the first `address_ratchet_keys` row and its stored private keys), adds `ratchetKeys` to `UserContactData`, re-signs with `rcv_queues.link_priv_sig_key`, and `LSET`s it. **Only mutable data changes - the address (link) is unchanged**, because the keys are in mutable, not fixed, data. Requesters that fetch the updated data use DR; older ones still use `AgentInvitation`. The agent does not do this on its own (it lacks the profile and the user's intent); the app drives it, combined with the full→short address migration. + +## Part 6 - tests + +- Encoding roundtrips: `UserContactData` with and without `ratchetKeys`, and with the KEM present and absent; `AgentConfirmation` with and without `ratchetKeyId`, across versions. +- Address creation advertises `ratchetKeys` (the `RcvE2ERatchetParamsUri`); `decryptLinkData` (Crypto/ShortLink.hs:100) verifies signatures and the requester negotiates the advertised params to a concrete version, with and without the KEM. +- Both PQ modes: an address whose bundle carries a KEM gives a hybrid ratchet (`pqEncryption` on); one without gives an X448-only ratchet. +- End to end: a DR-advertising address; a new requester establishes the ratchet, sends its profile under it, owner emits `REQ`, accepts, both reach `CON`; assert the profile never travels under per-queue-only encryption; assert `pqEncryption` on. +- Rotation and retrofit: request against the current bundle; against a just-retired bundle within the window still decrypts; against a bundle past the window is discarded and the requester times out; an address that adds `ratchetKeys` via `LSET` is then reached by DR while an old requester still uses `AgentInvitation`. +- Backward compatibility: old requester against a DR address connects via `AgentInvitation`; new requester against a non-DR address falls back to `AgentInvitation`. + +## Part 7 - phases + +1. Link data: `AddressRatchetKeys` in `UserContactData` (reusing `RcvE2ERatchetParamsUri`), encoding, `encodeSignUserData`; `AgentConfirmation.ratchetKeyId`; address creation taking `InitialKeys` (lifting the `IKUsePQ`-for-`SCMContact` prohibition), generating (`generateRcvE2EParams`, KEM per `initialPQEncryption False`) and storing the first `address_ratchet_keys` row. +2. Handshake: thread the optional `Maybe AddressRatchetKeys` through `joinConnection`/`joinConn`/`joinConnSrv` (present → DR branch, absent → classic); requester R2'/R3' (synchronous one-shot send); owner O1'/O2'/O3' storing the DR request as a `conn_invitations` row whose request value is the `CRConfirmation` variant; `smpConfirmation` `RcvConnection … Nothing` branch and `AgentConnInfoReply` acceptance; end-to-end connection with the profile under the ratchet. Tests pass `AddressRatchetKeys` directly (chat wiring is later work). +3. Rotation and retrofit: schema migration, `rotateRatchetKeys`, retention window, cleanup step, app-driven `LSET` retrofit (with the full→short address migration), rotation/retrofit tests. diff --git a/rfcs/2026-07-11-service-rpc.md b/rfcs/2026-07-11-service-rpc.md new file mode 100644 index 000000000..2fc18520c --- /dev/null +++ b/rfcs/2026-07-11-service-rpc.md @@ -0,0 +1,114 @@ +--- +Proposed: 2026-07-11 +Protocol: agent-protocol (new version) +Depends on: 2026-07-12-address-pqdr-keys +--- + +# One-off requests to service addresses + +Implementation plan: to follow, after this and the address-DR RFC are reviewed. + +## Problem + +Client applications need to interact with services, for example: badge issuance, directory requests, telemetry submissions, blockchain reads and writes, LLM calls. The only communication primitive available today is a duplex connection, so each of these interactions requires the full connection procedure - creating queues, key agreement, double ratchet initialization - and leaves persistent state on both sides: queues, ratchet state, connection records, message history. + +This is the wrong primitive for most service interactions: + +1. Cost. To send the first request to a not yet connected service, the client and the service exchange multiple commands across two servers. For "search the directory" all of it is overhead. The setup cost also creates an incentive to keep connections open, and a service with N users who used it once permanently holds N sets of queues and ratchet states. + +2. Privacy. A connection is a stable pairwise pseudonym. If a service were to use a duplex connection, it could link all requests made over it into a profile: search history in the directory, blockchain operations linked even when different on-chain keys are used, telemetry that becomes longitudinal tracking. The client also accumulates history that can be recovered from the device. Where continuity is needed, it can be provided in the application protocol (e.g., a token included in requests), without a transport-level identity. + +3. Encryption. Messages sent to contact addresses outside an established connection have a single layer of X25519 encryption, with no post-quantum protection and no forward secrecy. This is not acceptable for service requests. + +In-app service addresses should be stored as names resolving to links via the existing addressing layer (server host in the link authority, current link data retrieved with `LGET`), so that service links can be changed without redeploying the apps. Name resolution is already supported, and out of scope. + +## Security objectives + +1. Requests from the same client must not be linkable to each other by the service or by servers, and no long term state is created on either side in the transport layer. +2. Post-quantum resistant end-to-end encryption of requests and replies. +3. Reply authenticity must be verifiable against the link; substitution, replay, dropping or reordering of replies by servers must be detectable. +4. A repeated request for the same operation must not be executed twice. + +## Solution + +A service address is an ordinary short-link contact address. The client sends one request to the address queue and receives replies in a reply queue it creates for the request. The double ratchet is established from the address's published keys (see the address-DR RFC): the request is the first ratchet message, and replies are subsequent ratchet messages. So a request-response exchange is a short-lived one-directional double ratchet connection, established from the first message and removed after the last. + +The exchange: + +1. Retrieve the address link data (`LGET`, via proxy when IP protection is needed): the root key, the identity key, the prekey with its id, and the KEM key. +2. Create a reply queue (`NEW`, subscribed). +3. Establish the sending ratchet from the published keys (`pqX3dhSnd`, `initSndRatchet`). Build the request: the reply queue, the requester's X3DH parameters, and the payload encrypted under the ratchet. Encrypt the whole request to the address queue and send it once (unauthenticated `SEND`, via proxy when IP protection is needed). There is no transport retry; a reply is the success signal, and a hard error fails the request. +4. The service establishes the receiving ratchet from its private keys and the request's X3DH parameters (`pqX3dhRcv`, `initRcvRatchet`), decrypts the payload, and delivers it to the service application. To reply it creates a send connection with the ratchet and sends reply messages to the reply queue, each encrypted under the ratchet. +5. The client decrypts and delivers each reply message to the application. The first reply message returns from the request; later reply messages are delivered through a callback the application registered. The exchange ends on a reply marked final. The client deletes the reply queue and the ratchet on the final message, the deadline, or when the application cancels. + +How this meets the objectives: + +1. Unlinkability: fresh X3DH keys and a fresh reply queue per request; the sender's IP address and session are protected by existing private routing; the reply queue and both ratchets are removed after the exchange; nothing is shared between two requests. +2. Encryption: the double ratchet with its sntrup761 KEM, from the first message. +3. Authenticity: the ratchet is established against the identity key committed by the link hash, so a decryptable reply proves it came from the address owner; the ratchet message numbering detects dropped and reordered replies. No separate signature is needed. +4. Single execution: the service identifies a request by the hash of its decrypted payload and, within a fixed retention period, re-sends the stored replies for a repeated request without running the operation again. + +## Design + +Syntax uses [ABNF][1] with [case-sensitive strings extension][2]. `SMPQueueInfo`, `agentVersion`, and the X3DH and ratchet types are as in the [agent protocol](../protocol/agent-protocol.md) and `Crypto.Ratchet`. + +### Correlation and chat + +A reply is connected to its request by the reply queue: each request has its own reply queue, and every message in that queue is a reply to that request. The request hash (of the decrypted payload) is used only for idempotency. The application sets an id inside the payload to make two requests the same operation or different ones; the agent does not read it. + +Both ends are chat bots on the chat library over the agent. The chat library serializes a service command into the request payload and deserializes the responses; the agent transports them, establishes and removes the ratchet, and correlates by reply queue. + +### Request + +A new agent envelope, shaped like `AgentConfirmation` (X3DH parameters to establish the ratchet, plus a body encrypted under it): + +```abnf +agentRequest = agentVersion %s"Q" replyQueues prekeyId sndE2EParams encRequest +replyQueues = length 1*SMPQueueInfo ; the first is used; more are for redundancy +prekeyId = shortString ; the published prekey used, from link data +sndE2EParams = +encRequest = +``` + +The whole `agentRequest` is encrypted to the address queue with the per-queue layer and sent with `SEND`, as an invitation is today. The reply queue keys and the X3DH parameters are not visible to servers. A request must fit one message; a larger payload is an XFTP file description in the payload. + +The request hash is the SHA3-256 of the decrypted payload - the same bytes on both sides. There is no transport retry; a hard error (`AUTH`, `QUOTA`) fails the request, and the application decides whether to send a new one. + +### Replies + +The service creates a send connection with the ratchet and sends reply messages to the reply queue, each encrypted under the ratchet. A reply message uses a new agent envelope: + +```abnf +agentResponse = agentVersion %s"P" final responses +final = %s"T" / %s"F" ; T - no more reply messages follow +responses = length 1*responseItem ; non-empty list of application responses +responseItem = largeString ; opaque application response +``` + +Each message includes a list of responses, so responses known together are sent in one message and responses that become known over time are sent in separate messages. The message is encrypted and numbered by the ratchet, which authenticates it against the committed identity key and detects dropped or reordered messages; no separate signature is used. + +The first reply message returns from the request. Later reply messages are delivered through the callback the application registered with the request, while the process runs. The exchange ends on a message with `final = T`. The client deletes the reply queue and the ratchet on that message, on the deadline, or when the application cancels. Deleting the reply queue stops further replies. The transport keeps no exchange across a client restart; the application keeps its own state and sends a new request when it needs to. + +### Rejection + +The service refuses a request with the `AgentRejection` envelope from the [communicating rejection RFC](../../simplex-chat/docs/rfcs/2024-03-22-communicating-reject.md), sent to the reply queue under the ratchet, with an opaque application reason. The same envelope communicates refusal of a connection request, where today it is dropped silently. A rejection ends the exchange like a final reply. + +### Idempotency + +The service keeps, for a fixed retention period it chooses (1 to 24 hours, in service configuration, not in link data), the request hash, the ordered response messages it produced, and the reply queues and ratchets subscribed under that hash. A repeat request with the same hash does not reach the service application: + +- while the first request is being answered, the repeat establishes its own ratchet and reply queue, is added to the record, receives the responses already produced, and receives each later response too. +- after the operation completed, the repeat receives the whole stored sequence of responses, re-encrypted under its own ratchet. + +The stored responses are the application response bytes, not the ratchet ciphertext, because a repeat establishes a new ratchet and the responses are re-encrypted for it. This gives single execution over at-least-once delivery. After the retention period a request with the same hash is a new operation and runs again. + +### Out of scope + +- Recovery across restart: the transport keeps no exchange across a client restart; the application persists its own state and sends a new request when it needs to. +- Service-initiated messages: there is no standing channel; use a connection where the service must reach the client without a request. +- Abuse protection beyond existing queue quotas: services can require application-level credentials (e.g., a badge) in the request payload; rate limiting is a separate discussion. +- Scaling request reception: a single address queue bounds service throughput; distributing reception across multiple queues or relays (the existing `relays` field in contact link data) is a separate question, but it would fit well with name resolving to multiple addresses, both for redundancy, reliability and higher throughput. +- Name resolution: existing addressing layer. + +[1]: https://tools.ietf.org/html/rfc5234 +[2]: https://tools.ietf.org/html/rfc7405 diff --git a/rfcs/2026-07-12-address-pqdr-keys.md b/rfcs/2026-07-12-address-pqdr-keys.md new file mode 100644 index 000000000..dad2bb76d --- /dev/null +++ b/rfcs/2026-07-12-address-pqdr-keys.md @@ -0,0 +1,83 @@ +--- +Proposed: 2026-07-12 +Protocol: agent-protocol (new version) +--- + +# Establishing the double ratchet from address data + +## Problem + +A contact address receives a connection request as an `AgentInvitation` message, encrypted only with the per-queue X25519 layer. The double ratchet is established later: the address owner joins the requester's connection request, generates its X3DH keys, and sends them in the confirmation. So the first message to an address - the invitation and the profile in it - is not under the double ratchet, and has no post-quantum protection. + +The cause is that the address owner's X3DH contribution is generated per request and sent in the confirmation, so it cannot exist before the requester's first message. + +## Solution + +Publish the address owner's X3DH contribution in the address link data, so a requester can establish the double ratchet in its first message. The requester runs the existing `pqX3dhSnd` against the published keys, initializes a sending ratchet, and encrypts its first message under it. The owner runs the existing `pqX3dhRcv` against its stored private keys and the requester's X3DH keys from the message, initializes a receiving ratchet, and decrypts it. + +Publish the owner's X3DH contribution - two X448 keys and an optional sntrup761 KEM key, with the e2e version range - as one bundle in the mutable contact user data, signed by the root key. The bundle is the existing `RcvE2ERatchetParamsUri` type that a one-time invitation already advertises, with an id for rotation. + +This is backward compatible. A requester that does not use the published bundle sends a current `AgentInvitation` with its own X3DH keys, and the owner does what it does today: generates fresh X3DH keys and sends them in the confirmation. The owner branches on whether the incoming message uses the published bundle. + +Three properties follow. The first message, including the profile, is under the double ratchet, which closes the profile gap and gives it post-quantum protection through the ratchet's sntrup761 KEM. A decryptable message proves the sender established X3DH against the root-signed keys, so it authenticates the address owner without a separate signature. And because the bundle is in mutable data, an existing address can advertise the double ratchet by updating its mutable data - no new link. + +## Design + +Syntax uses [ABNF][1] with [case-sensitive strings extension][2]. Key and ratchet types are as in `Crypto.Ratchet` and the [agent protocol](../protocol/agent-protocol.md); all DH keys are X448, the KEM is sntrup761. + +### Published keys in link data + +The owner's X3DH contribution is a ratchet-keys bundle appended to the mutable contact user data, signed by the root key. Nothing is added to the immutable fixed link data: + +```abnf +userContactData =/ ratchetKeys ; appended, ignored by earlier versions +ratchetKeys = %s"0" / (%s"1" ratchetKeyId e2eParams) +ratchetKeyId = shortString ; identifies this bundle, changes on rotation, echoed in the request +e2eParams = +``` + +`e2eParams` is the existing `RcvE2ERatchetParamsUri` - the same type a one-time invitation advertises - so a requester reads it, negotiates the concrete e2e version against its own range, and runs `pqX3dhSnd` against it, exactly as it does for an invitation. The KEM key is optional (the params' KEM field is a `Maybe`), controlled by the address's initial-keys mode, the same 3-way choice as invitations: advertise the KEM (post-quantum from the first message), advertise X448-only but still support post-quantum if the requester proposes its own KEM (one message later, avoiding the ~1158-byte key in link data), or no post-quantum. + +The owner keeps the private side of each bundle - the two X448 private keys and, when PQ is on, the KEM keypair - indexed by `ratchetKeyId`. On rotation with `LSET` it publishes a new bundle with a new `ratchetKeyId` and keeps the previous private keys for a window covering queue message retention, so a request that used a just-rotated bundle still decrypts. Because the bundle is in mutable data, an existing address advertises the double ratchet by updating its mutable data - no new link, no re-creation. + +### Request confirmation + +A requester that uses the published keys establishes the sending ratchet before its first message, so it sends that message as a confirmation, not an invitation - the same envelope a joining party sends in a connection. The confirmation gains an optional `ratchetKeyId` naming the bundle the requester used, so the owner selects the matching private keys: + +```abnf +agentConfirmation =/ ratchetKeyId ; the bundle the requester used, echoed; absent on other confirmations +``` + +The confirmation holds the requester's Snd X3DH parameters (so the owner runs `pqX3dhRcv`) and, encrypted under the ratchet, the first message. A confirmation with `ratchetKeyId` on a contact address takes the published-key path; an `AgentInvitation`, as today, takes the current path where the owner generates fresh X3DH keys and returns them in its own confirmation. A connection-request URI is unchanged: it advertises the requester's Rcv parameters and must not include Snd parameters. + +### Establishing the ratchet + +Requester: + +1. Retrieve link data (`LGET`), read the bundle - its `ratchetKeyId` and `e2eParams` (`RcvE2ERatchetParamsUri`) - and negotiate the concrete e2e version against its own range. +2. `generateSndE2EParams` for its own X3DH contribution - encapsulating to the bundle's KEM if it advertises one, or proposing its own KEM if the requester wants post-quantum and the bundle is X448-only. +3. `pqX3dhSnd` against the bundle's parameters, then `initSndRatchet` - the sending ratchet. +4. Encrypt the first message under the ratchet, and send a confirmation with its Snd parameters and `ratchetKeyId`. + +Owner: + +1. On a confirmation with `ratchetKeyId` on a contact address, select the private X3DH keys and, if any, KEM keypair by `ratchetKeyId` (current or a retained previous generation). +2. `pqX3dhRcv` against the requester's Snd parameters with those private keys, then `initRcvRatchet` - the receiving ratchet. Decrypting the first message advances the ratchet and gives it a send side, so the owner can reply. +3. Decrypt, and reply under the ratchet. + +A request whose `ratchetKeyId` is no longer retained cannot be decrypted; the owner does not learn the requester or its reply address, and the requester's attempt fails at its own timeout. + +### Authentication + +The ratchet-keys bundle is in the mutable link data, signed by the root key. A decryptable message proves the sender established X3DH against those root-signed keys: an SMP server cannot substitute them without forging the root signature (`decryptLinkData` verifies it), which is the X3DH anti-substitution property. Where a message today relies on a separate signature over its content for authenticity, this establishment provides it, and the signature is not needed. The root Ed25519 key is the address's signing identity; the X3DH keys are separate DH keys (X448), and X3DH is over crypto_box, so deniability is preserved. A malicious server can still serve an older but validly-signed bundle (rollback to a retired generation); this is bounded by the retention window and by the ratchet advancing after the first message, and a per-key signature would not prevent it. Reusing a bundle across requesters is consistent with the address already being a shared identifier. + +## Uses + +- Invitations to an address, and the profile in them, are under the double ratchet from the first message. +- An existing address gains the double ratchet when the app updates its mutable link data (`LSET`, with the user's confirmation and current profile, combined with the full→short address migration); no new link is issued. +- The service RPC (see the RPC RFC) establishes the ratchet this way to send the request as the first ratchet message. + +This RFC depends on nothing else here. It replaces the need for the PQ-queue RFC in the address case, because the ratchet provides post-quantum protection for the first message; the PQ-queue RFC remains for first messages that do not establish a ratchet. + +[1]: https://tools.ietf.org/html/rfc5234 +[2]: https://tools.ietf.org/html/rfc7405 diff --git a/rfcs/2026-07-12-queue-pq-encryption.md b/rfcs/2026-07-12-queue-pq-encryption.md new file mode 100644 index 000000000..f82092323 --- /dev/null +++ b/rfcs/2026-07-12-queue-pq-encryption.md @@ -0,0 +1,42 @@ +--- +Proposed: 2026-07-12 +Protocol: smp-client (new version) +--- + +# Post-quantum encryption of the SMP queue layer + +## Problem + +A message sent to a queue outside an established double ratchet has one layer of end-to-end encryption: NaCl crypto_box over an X25519 DH secret. The sender generates an ephemeral X25519 key, computes the secret with the recipient's per-queue DH key, and puts its ephemeral key in the message public header (`agentCbEncryptOnce`). This layer protects invitations, confirmations, and the profile sent with them. + +It is not post-quantum. An adversary that records this traffic and later has a quantum computer can recover the X25519 secret and decrypt it. The double ratchet adds a post-quantum KEM once it is established, but the first message to a queue, before the ratchet, has only X25519. + +This RFC adds post-quantum protection to the single-shot queue encryption itself, for cases that do not establish a double ratchet from the first message. Where a double ratchet is established from the first message (see the address-DR RFC), the ratchet provides post-quantum protection and this layer is not needed. + +## Solution + +Extend the single-shot queue encryption to a hybrid X25519 + sntrup761 scheme, in a new SMP client version. The recipient publishes a KEM encapsulation key alongside its per-queue DH key. The sender encapsulates to it, combines the KEM shared secret with the X25519 DH secret, and encrypts the body with the combined secret. The KEM ciphertext travels in the message public header next to the ephemeral X25519 key. + +Recording the traffic and breaking X25519 later is not sufficient: without breaking sntrup761 as well, the combined secret is not recoverable. + +## Design + +The message public header (`PubHeader`) gains a hybrid variant, selected by a version and a tag, so older senders and the empty-header case are unchanged: + +```abnf +smpPubHeaderHybrid = smpClientVersion %s"2" senderPublicDhKey kemCiphertext +senderPublicDhKey = length x509encoded ; sender ephemeral X25519 key +kemCiphertext = largeString ; sntrup761 ciphertext, 1039 bytes +``` + +The secret combines both shared secrets, and the body is encrypted with NaCl secret_box (the DH-only path uses crypto_box today; the combined secret is no longer a plain DH result, so it is used as a secret_box key), padded to the same lengths: + +``` +secret = HKDF(dh(recipient key, sender ephemeral key) || KEM shared secret) +``` + +The recipient's KEM encapsulation key is distributed the same way its per-queue DH key is today - in the queue address for a connection request, and in link data for a short link. The KEM ciphertext is stored the same way the ephemeral DH key is: in the public header, readable by the destination server (and not by the proxy with proxied sending), which cannot derive the secret without the recipient's KEM private key. + +The recipient stores the computed secret the way the per-queue DH secret is stored on receiving the first message (`setRcvQueueConfirmedE2E`), and reuses it for later messages on the queue. + +Sizes: the KEM ciphertext is 1039 bytes and the encapsulation key 1158 bytes. Link data user data is padded to 13784 bytes, so the key fits with application data. This RFC is independent of the RPC, SSND, and address-DR RFCs. diff --git a/rfcs/2026-07-12-smp-secure-send.md b/rfcs/2026-07-12-smp-secure-send.md new file mode 100644 index 000000000..6bb444b09 --- /dev/null +++ b/rfcs/2026-07-12-smp-secure-send.md @@ -0,0 +1,55 @@ +--- +Proposed: 2026-07-12 +Protocol: smp (new version) +--- + +# SSND: combined secure-and-send command + +## Problem + +Two SMP flows secure a messaging queue and then immediately send the first message to it, as two commands and two round trips: + +- The fast connection handshake: the joining party secures the queue with `SKEY`, then sends the confirmation with `SEND`. +- Any first send to a sender-securable queue where the sender both secures it and delivers the first message. + +The two commands express one intent - "this is my key, and here is my first message" - so they can be one command and one round trip. The combination must be idempotent, because the first send is retried on network failure and a queue is often secured before the response is known. `SKEY` is already idempotent (a repeat with the same key succeeds). `SEND` is not, so a naive combination would deliver a duplicate message on retry. + +## Solution + +A new command `SSND` combines `SKEY` and `SEND` in one transmission, idempotent in both parts: + +- Key part: as `SKEY` - a repeat with the same key succeeds, a different key fails with `AUTH`. +- Send part: the server keeps the hash of the message until it is acknowledged, and reports a repeat of the same message as delivered without delivering it again. + +The server-side hash covers the common case, when the retry arrives before the message is acknowledged. A retry that arrives after the acknowledgement is delivered as a duplicate and discarded by the receiving agent by message hash, as duplicate messages are discarded today. + +## Design + +Syntax uses [ABNF][1] with [case-sensitive strings extension][2]. `senderAuthPublicKey`, `msgFlags` and `smpEncMessage` are as in the [SMP protocol](../protocol/simplex-messaging.md). + +```abnf +secureSend = %s"SSND " senderAuthPublicKey SP msgFlags SP smpEncMessage +senderAuthPublicKey = length x509encoded +``` + +`SSND` is a sender command, authorized with the key it sets, and accepted only on messaging-mode queues (`QMMessaging`), where the sender can secure the queue. The server responds `OK` or `ERR`. + +Server processing: + +1. Secure the queue with the key, as `SKEY`. A repeat with the same key succeeds; a different key returns `AUTH`. +2. If the queue holds an unacknowledged message whose stored hash equals the hash of this message, respond `OK` without storing it again. +3. Otherwise store the message, keep its hash with the queue until the message is acknowledged, and deliver it. + +The stored hash is one value per not-yet-acknowledged queue message. It is removed when the message is acknowledged. All queue store backends (in-memory, journal, PostgreSQL) keep it. + +`SSND` composes with the proxy protocol without change: `proxySMPCommand` forwards any sender command through `PFWD`/`RFWD`, so `SSND` is proxied as `SEND` and `SKEY` are today. + +## Uses + +- The fast connection handshake replaces `SKEY` then the `SEND` confirmation with one `SSND`. +- The service RPC response (see the RPC RFC) secures the reply queue and sends the first reply with one `SSND`. + +This RFC is independent of the RPC, PQ-queue, and address-DR RFCs and can be implemented on its own. + +[1]: https://tools.ietf.org/html/rfc5234 +[2]: https://tools.ietf.org/html/rfc7405 diff --git a/simplexmq.cabal b/simplexmq.cabal index b017dc706..dededf68b 100644 --- a/simplexmq.cabal +++ b/simplexmq.cabal @@ -190,6 +190,7 @@ library Simplex.Messaging.Agent.Store.Postgres.Migrations.M20251230_strict_tables Simplex.Messaging.Agent.Store.Postgres.Migrations.M20260410_receive_attempts Simplex.Messaging.Agent.Store.Postgres.Migrations.M20260411_service_certs + Simplex.Messaging.Agent.Store.Postgres.Migrations.M20260712_address_dr else exposed-modules: Simplex.Messaging.Agent.Store.SQLite @@ -242,6 +243,7 @@ library Simplex.Messaging.Agent.Store.SQLite.Migrations.M20251230_strict_tables Simplex.Messaging.Agent.Store.SQLite.Migrations.M20260410_receive_attempts Simplex.Messaging.Agent.Store.SQLite.Migrations.M20260411_service_certs + Simplex.Messaging.Agent.Store.SQLite.Migrations.M20260712_address_dr Simplex.Messaging.Agent.Store.SQLite.Util if flag(client_postgres) || flag(server_postgres) exposed-modules: diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index c53e8ba5d..8d433b4d1 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -430,8 +430,8 @@ prepareConnectionLink c userId rootKey linkEntityId checkNotices clientData srv_ -- | Create connection for prepared link (single network call). -- Validates that server response matches the prepared link. -createConnectionForLink :: AgentClient -> NetworkRequestMode -> UserId -> Bool -> CreatedConnLink 'CMContact -> PreparedLinkParams -> UserConnLinkData 'CMContact -> CR.InitialKeys -> SubscriptionMode -> AE ConnId -createConnectionForLink c nm userId enableNtfs = withAgentEnv c .::. createConnectionForLink' c nm userId enableNtfs +createConnectionForLink :: AgentClient -> NetworkRequestMode -> UserId -> Bool -> CreatedConnLink 'CMContact -> PreparedLinkParams -> UserConnLinkData 'CMContact -> CR.InitialKeys -> Maybe CR.InitialKeys -> SubscriptionMode -> AE ConnId +createConnectionForLink c nm userId enableNtfs = withAgentEnv c .::: createConnectionForLink' c nm userId enableNtfs {-# INLINE createConnectionForLink #-} -- | Create or update user's contact connection short link @@ -484,8 +484,8 @@ prepareConnectionToAccept c userId enableNtfs = withAgentEnv c .: newConnToAccep {-# INLINE prepareConnectionToAccept #-} -- | Join SMP agent connection (JOIN command). -joinConnection :: AgentClient -> NetworkRequestMode -> UserId -> ConnId -> Bool -> ConnectionRequestUri c -> ConnInfo -> PQSupport -> SubscriptionMode -> AE SndQueueSecured -joinConnection c nm userId connId enableNtfs = withAgentEnv c .:: joinConn c nm userId connId enableNtfs +joinConnection :: AgentClient -> NetworkRequestMode -> UserId -> ConnId -> Bool -> ConnectionRequestUri c -> ConnInfo -> Maybe AddressRatchetKeys -> PQSupport -> SubscriptionMode -> AE SndQueueSecured +joinConnection c nm userId connId enableNtfs = withAgentEnv c .::. joinConn c nm userId connId enableNtfs {-# INLINE joinConnection #-} -- | Allow connection to continue after CONF notification (LET command) @@ -899,10 +899,13 @@ allowConnectionAsync' c corrId connId confId ownConnInfo = acceptContactAsync' :: AgentClient -> ACorrId -> ConnId -> Bool -> InvitationId -> ConnInfo -> PQSupport -> SubscriptionMode -> AM () acceptContactAsync' c corrId connId enableNtfs invId ownConnInfo pqSupport subMode = do Invitation {connReq} <- withStore c $ \db -> getInvitation db "acceptContactAsync'" invId - withStore' c $ \db -> acceptInvitation db invId ownConnInfo - joinConnAsync c corrId False connId enableNtfs connReq ownConnInfo pqSupport subMode `catchAllErrors` \err -> do - withStore' c (`unacceptInvitation` invId) - throwE err + case connReq of + CRConfirmation _ -> throwE $ CMD PROHIBITED "acceptContactAsync: address DR requires sync accept" + CRInvitation cReq -> do + withStore' c $ \db -> acceptInvitation db invId ownConnInfo + joinConnAsync c corrId False connId enableNtfs cReq ownConnInfo pqSupport subMode `catchAllErrors` \err -> do + withStore' c (`unacceptInvitation` invId) + throwE err ackMessageAsync' :: AgentClient -> ACorrId -> ConnId -> AgentMsgId -> Maybe MsgReceiptInfo -> AM () ackMessageAsync' c corrId connId msgId rcptInfo_ = do @@ -983,16 +986,34 @@ prepareConnectionLink' c userId rootKey@(_, plpRootPrivKey) linkEntityId checkNo pure (ccLink, params) -- | Create connection for prepared link (single network call). -createConnectionForLink' :: AgentClient -> NetworkRequestMode -> UserId -> Bool -> CreatedConnLink 'CMContact -> PreparedLinkParams -> UserConnLinkData 'CMContact -> CR.InitialKeys -> SubscriptionMode -> AM ConnId -createConnectionForLink' c nm userId enableNtfs (CCLink connReq _) PreparedLinkParams {plpNonce, plpQueueE2EKeys, plpLinkKey, plpRootPrivKey, plpSignedFixedData, plpSrvWithAuth} userLinkData pqInitKeys subMode = do +mkAddressRatchetKeys :: AgentClient -> ConnId -> CR.InitialKeys -> AM AddressRatchetKeys +mkAddressRatchetKeys c connId pqInitKeys = do + g <- asks random + e2eVR <- asks $ e2eEncryptVRange . config + let pqEnc = CR.initialPQEncryption False pqInitKeys + (pk1, pk2, pKem, e2eRcvParams) <- liftIO $ CR.generateRcvE2EParams g (maxVersion e2eVR) pqEnc + rkId <- RatchetKeyId <$> atomically (C.randomBytes 16 g) + now <- liftIO getCurrentTime + withStore' c $ \db -> createAddressRatchetKeys db connId rkId pk1 pk2 pKem now + pure AddressRatchetKeys {ratchetKeyId = rkId, e2eParams = toVersionRangeT e2eRcvParams e2eVR} + +addAddressRatchetKeys :: AgentClient -> ConnId -> Maybe CR.InitialKeys -> UserConnLinkData 'CMContact -> AM (UserConnLinkData 'CMContact) +addAddressRatchetKeys _ _ Nothing uld = pure uld +addAddressRatchetKeys c connId (Just pqInitKeys) (UserContactLinkData ucd) = do + bundle <- mkAddressRatchetKeys c connId pqInitKeys + pure $ UserContactLinkData ucd {ratchetKeys = Just bundle} + +createConnectionForLink' :: AgentClient -> NetworkRequestMode -> UserId -> Bool -> CreatedConnLink 'CMContact -> PreparedLinkParams -> UserConnLinkData 'CMContact -> CR.InitialKeys -> Maybe CR.InitialKeys -> SubscriptionMode -> AM ConnId +createConnectionForLink' c nm userId enableNtfs (CCLink connReq _) PreparedLinkParams {plpNonce, plpQueueE2EKeys, plpLinkKey, plpRootPrivKey, plpSignedFixedData, plpSrvWithAuth} userLinkData pqInitKeys drInitKeys_ subMode = do g <- asks random AgentConfig {smpAgentVRange} <- asks config case pqInitKeys of CR.IKUsePQ -> throwE $ CMD PROHIBITED "createConnectionForLink" _ -> pure () connId <- newConnNoQueues c userId enableNtfs SCMContact (CR.connPQEncryption pqInitKeys) + userLinkData' <- addAddressRatchetKeys c connId drInitKeys_ userLinkData let CRContactUri ConnReqUriData {crSmpQueues = SMPQueueUri _ SMPQueueAddress {senderId = sndId} :| _} = connReq - md = SL.encodeSignUserData SCMContact plpRootPrivKey smpAgentVRange userLinkData + md = SL.encodeSignUserData SCMContact plpRootPrivKey smpAgentVRange userLinkData' linkData = (plpSignedFixedData, md) qd <- encryptContactLinkData g plpRootPrivKey plpLinkKey sndId linkData (_, qUri) <- @@ -1301,12 +1322,17 @@ newConnToJoin c userId connId enableNtfs cReq pqSup = case cReq of newConnToAccept :: AgentClient -> UserId -> ConnId -> Bool -> ConfirmationId -> PQSupport -> AM ConnId newConnToAccept c userId connId enableNtfs invId pqSup = do Invitation {connReq} <- withStore c $ \db -> getInvitation db "newConnToAccept" invId - newConnToJoin c userId connId enableNtfs connReq pqSup + case connReq of + CRInvitation cReq -> newConnToJoin c userId connId enableNtfs cReq pqSup + CRConfirmation DRRequest {agentVersion, pqSupport} -> do + g <- asks random + let cData = ConnData {userId, connId, connAgentVersion = agentVersion, enableNtfs, lastExternalSndId = 0, deleted = False, ratchetSyncState = RSOk, pqSupport} + withStore c $ \db -> createNewConn db g cData SCMInvitation -joinConn :: AgentClient -> NetworkRequestMode -> UserId -> ConnId -> Bool -> ConnectionRequestUri c -> ConnInfo -> PQSupport -> SubscriptionMode -> AM SndQueueSecured -joinConn c nm userId connId enableNtfs cReq cInfo pqSupport subMode = do +joinConn :: AgentClient -> NetworkRequestMode -> UserId -> ConnId -> Bool -> ConnectionRequestUri c -> ConnInfo -> Maybe AddressRatchetKeys -> PQSupport -> SubscriptionMode -> AM SndQueueSecured +joinConn c nm userId connId enableNtfs cReq cInfo addrKeys_ pqSupport subMode = do srv <- getNextSMPServer c userId [qServer $ connReqQueue cReq] - joinConnSrv c nm userId connId enableNtfs cReq cInfo pqSupport subMode srv + joinConnSrv c nm userId connId enableNtfs cReq cInfo addrKeys_ pqSupport subMode srv connReqQueue :: ConnectionRequestUri c -> SMPQueueUri connReqQueue = \case @@ -1331,7 +1357,7 @@ startJoinInvitation c userId connId sq_ enableNtfs cReqUri pqSup = Right r -> pure $ Right $ snd r Left e -> do nonBlockingWriteTBQueue (subQ c) ("", connId, AEvt SAEConn (ERR $ INTERNAL $ "no snd ratchet " <> show e)) - runExceptT $ createRatchet_ db g maxSupported pqSupport e2eRcvParams + runExceptT $ createRatchet_ db g connId maxSupported pqSupport e2eRcvParams pure (cData, sq, e2eSndParams, Nothing) _ -> do let Compatible SMPQueueInfo {queueAddress = SMPQueueAddress {smpServer, senderId}} = qInfo @@ -1341,19 +1367,37 @@ startJoinInvitation c userId connId sq_ enableNtfs cReqUri pqSup = (q, _) <- lift $ newSndQueue userId "" qInfo sndKey_ withStore c $ \db -> runExceptT $ do liftIO $ lockConnForUpdate db connId - e2eSndParams <- createRatchet_ db g maxSupported pqSupport e2eRcvParams + e2eSndParams <- createRatchet_ db g connId maxSupported pqSupport e2eRcvParams sq' <- maybe (ExceptT $ updateNewConnSnd db connId q) pure sq_ pure (cData, sq', e2eSndParams, lnkId_) Nothing -> throwE $ AGENT A_VERSION - where - createRatchet_ db g maxSupported pqSupport e2eRcvParams@(CR.E2ERatchetParams v _ rcDHRr kem_) = do - (pk1, pk2, pKem, e2eSndParams) <- liftIO $ CR.generateSndE2EParams g v (CR.replyKEM_ v kem_ pqSupport) - (_, rcDHRs) <- atomically $ C.generateKeyPair g - rcParams <- liftEitherWith (SEAgentError . cryptoError) $ CR.pqX3dhSnd pk1 pk2 pKem e2eRcvParams - let rcVs = CR.RatchetVersions {current = v, maxSupported} - rc = CR.initSndRatchet rcVs rcDHRr rcDHRs rcParams - liftIO $ createSndRatchet db connId rc e2eSndParams - pure e2eSndParams + +createRatchet_ :: DB.Connection -> TVar ChaChaDRG -> ConnId -> CR.VersionE2E -> PQSupport -> CR.RcvE2ERatchetParams 'C.X448 -> ExceptT StoreError IO (CR.SndE2ERatchetParams 'C.X448) +createRatchet_ db g connId maxSupported pqSupport e2eRcvParams@(CR.E2ERatchetParams v _ rcDHRr kem_) = do + (pk1, pk2, pKem, e2eSndParams) <- liftIO $ CR.generateSndE2EParams g v (CR.replyKEM_ v kem_ pqSupport) + (_, rcDHRs) <- atomically $ C.generateKeyPair g + rcParams <- liftEitherWith (SEAgentError . cryptoError) $ CR.pqX3dhSnd pk1 pk2 pKem e2eRcvParams + let rcVs = CR.RatchetVersions {current = v, maxSupported} + rc = CR.initSndRatchet rcVs rcDHRr rcDHRs rcParams + liftIO $ createSndRatchet db connId rc e2eSndParams + pure e2eSndParams + +-- initializes the receive ratchet from X3DH keys and decrypts the confirmation reply (first ratchet message); +-- shared by the connection initiator and the address DR owner, which differ only in the key source. +initRcvRatchetDecrypt :: VersionSMPA -> PQSupport -> (C.PrivateKeyX448, C.PrivateKeyX448, Maybe CR.RcvPrivRKEMParams) -> CR.SndE2ERatchetParams 'C.X448 -> ByteString -> AM (Either C.CryptoError ByteString, CR.RatchetX448, PQSupport) +initRcvRatchetDecrypt agentVersion pqSupport (pk1, pk2, pKem) (CR.AE2ERatchetParams _ e2eSndParams@(CR.E2ERatchetParams e2eVersion _ _ _)) encConnInfo = do + e2eEncryptVRange <- asks $ e2eEncryptVRange . config + unless (e2eVersion `isCompatible` e2eEncryptVRange) $ throwE $ AGENT A_VERSION + rcParams <- liftError cryptoError $ CR.pqX3dhRcv pk1 pk2 pKem e2eSndParams + let rcVs = CR.RatchetVersions {current = e2eVersion, maxSupported = maxVersion e2eEncryptVRange} + pqSupport' = pqSupport `CR.pqSupportAnd` versionPQSupport_ agentVersion (Just e2eVersion) + rc = CR.initRcvRatchet rcVs pk2 rcParams pqSupport' + g <- asks random + (agentMsgBody_, rc', skipped) <- liftError cryptoError $ CR.rcDecrypt g rc M.empty encConnInfo + case skipped of + CR.SMDNoChange -> pure () + _ -> logWarn "conf: skipped confirmations" + pure (agentMsgBody_, rc', pqSupport') connRequestPQSupport :: AgentClient -> PQSupport -> ConnectionRequestUri c -> IO (Maybe (VersionSMPA, PQSupport)) connRequestPQSupport c pqSup cReq = withAgentEnv' c $ case cReq of @@ -1385,8 +1429,8 @@ versionPQSupport_ :: VersionSMPA -> Maybe CR.VersionE2E -> PQSupport versionPQSupport_ agentV e2eV_ = PQSupport $ agentV >= pqdrSMPAgentVersion && maybe True (>= CR.pqRatchetE2EEncryptVersion) e2eV_ {-# INLINE versionPQSupport_ #-} -joinConnSrv :: AgentClient -> NetworkRequestMode -> UserId -> ConnId -> Bool -> ConnectionRequestUri c -> ConnInfo -> PQSupport -> SubscriptionMode -> SMPServerWithAuth -> AM SndQueueSecured -joinConnSrv c nm userId connId enableNtfs inv@CRInvitationUri {} cInfo pqSup subMode srv = +joinConnSrv :: AgentClient -> NetworkRequestMode -> UserId -> ConnId -> Bool -> ConnectionRequestUri c -> ConnInfo -> Maybe AddressRatchetKeys -> PQSupport -> SubscriptionMode -> SMPServerWithAuth -> AM SndQueueSecured +joinConnSrv c nm userId connId enableNtfs inv@CRInvitationUri {} cInfo _addrKeys pqSup subMode srv = withInvLock c (strEncode inv) "joinConnSrv" $ do SomeConn cType conn <- withStore c (`getConn` connId) case conn of @@ -1401,18 +1445,20 @@ joinConnSrv c nm userId connId enableNtfs inv@CRInvitationUri {} cInfo pqSup sub (cData, sq, e2eSndParams, lnkId_) <- startJoinInvitation c userId connId sq_ enableNtfs inv pqSup secureConfirmQueue c nm cData rq_ sq srv cInfo (Just e2eSndParams) subMode >>= (mapM_ (delInvSL c connId srv) lnkId_ $>) -joinConnSrv c nm userId connId enableNtfs cReqUri@CRContactUri {} cInfo pqSup subMode srv = +joinConnSrv c nm userId connId enableNtfs cReqUri@CRContactUri {} cInfo addrKeys_ pqSup subMode srv = lift (compatibleContactUri cReqUri) >>= \case Just (qInfo, vrsn@(Compatible v)) -> - withInvLock c (strEncode cReqUri) "joinConnSrv" $ do - SomeConn cType conn <- withStore c (`getConn` connId) - let pqInitKeys = CR.joinContactInitialKeys (v >= pqdrSMPAgentVersion) pqSup - CCLink cReq _ <- case conn of - NewConnection _ -> newRcvConnSrv c NRMBackground userId connId enableNtfs SCMInvitation Nothing Nothing pqInitKeys subMode srv - RcvConnection _ rq -> mkJoinInvitation rq pqInitKeys - _ -> throwE $ CMD PROHIBITED $ "joinConnSrv: bad connection " <> show cType - void $ sendInvitation c nm userId connId qInfo vrsn cReq cInfo - pure False + withInvLock c (strEncode cReqUri) "joinConnSrv" $ case addrKeys_ of + Just addrKeys -> joinAddressDR addrKeys + Nothing -> do + SomeConn cType conn <- withStore c (`getConn` connId) + let pqInitKeys = CR.joinContactInitialKeys (v >= pqdrSMPAgentVersion) pqSup + CCLink cReq _ <- case conn of + NewConnection _ -> newRcvConnSrv c NRMBackground userId connId enableNtfs SCMInvitation Nothing Nothing pqInitKeys subMode srv + RcvConnection _ rq -> mkJoinInvitation rq pqInitKeys + _ -> throwE $ CMD PROHIBITED $ "joinConnSrv: bad connection " <> show cType + void $ sendInvitation c nm userId connId qInfo vrsn cReq cInfo + pure False where mkJoinInvitation rq pqInitKeys = do g <- asks random @@ -1431,6 +1477,28 @@ joinConnSrv c nm userId connId enableNtfs cReqUri@CRContactUri {} cInfo pqSup su pure e2eRcvParams let cReq = CRInvitationUri crData $ toVersionRangeT e2eRcvParams e2eVR pure $ CCLink cReq Nothing + joinAddressDR AddressRatchetKeys {ratchetKeyId = addrRKId, e2eParams} = do + g <- asks random + e2eVR <- asks $ e2eEncryptVRange . config + case e2eParams `compatibleVersion` e2eVR of + Nothing -> throwE $ AGENT A_VERSION + Just (Compatible e2eRcvParams@(CR.E2ERatchetParams e2eV _ _ _)) -> do + let pqSupport = pqSup `CR.pqSupportAnd` versionPQSupport_ v (Just e2eV) + e2eKeys <- atomically $ C.generateKeyPair g + (rq, _) <- createRcvQueue c NRMBackground userId connId srv enableNtfs subMode Nothing (CQRMessaging Nothing) e2eKeys + SomeConn _ conn <- withStore c (`getConn` connId) + let RcvQueue {smpClientVersion = rqV} = rq + cData = (toConnData conn) {pqSupport} :: ConnData + qAInfo = SMPQueueInfo rqV (rcvSMPQueueAddress rq) + aliceReply = AgentConnInfoReply (qAInfo :| []) cInfo + (aliceSndParams, encConnInfo) <- withStore c $ \db -> runExceptT $ do + aliceSndParams <- createRatchet_ db g connId (maxVersion e2eVR) pqSupport e2eRcvParams + liftIO $ setConnPQSupport db connId pqSupport + encConnInfo <- fst <$> agentRatchetEncrypt db cData (smpEncode aliceReply) e2eEncConnInfoLength (Just $ CR.pqSupportToEnc pqSupport) (maxVersion e2eVR) + pure (aliceSndParams, encConnInfo) + let agentEnvelope = AgentConfirmation {agentVersion = v, e2eEncryption_ = Just aliceSndParams, ratchetKeyId = Just addrRKId, encConnInfo} + void $ sendConfirmationToAddress c nm userId connId qInfo agentEnvelope + pure False Nothing -> throwE $ AGENT A_VERSION delInvSL :: AgentClient -> ConnId -> SMPServerWithAuth -> SMP.LinkId -> AM () @@ -1483,7 +1551,20 @@ allowConnection' c connId confId ownConnInfo = withConnLock c connId "allowConne acceptContact' :: AgentClient -> NetworkRequestMode -> UserId -> ConnId -> Bool -> InvitationId -> ConnInfo -> PQSupport -> SubscriptionMode -> AM SndQueueSecured acceptContact' c nm userId connId enableNtfs invId ownConnInfo pqSupport subMode = withConnLock c connId "acceptContact" $ do Invitation {connReq} <- withStore c $ \db -> getInvitation db "acceptContact'" invId - r <- joinConn c nm userId connId enableNtfs connReq ownConnInfo pqSupport subMode + r <- case connReq of + CRInvitation cReq -> joinConn c nm userId connId enableNtfs cReq ownConnInfo Nothing pqSupport subMode + CRConfirmation DRRequest {ratchetState, replyQueue} -> do + SomeConn _ conn <- withStore c (`getConn` connId) + let cData = toConnData conn + srv <- getNextSMPServer c userId [qServer replyQueue] + clientVRange <- asks $ smpClientVRange . config + qInfo <- maybe (throwE $ AGENT A_VERSION) pure $ replyQueue `proveCompatible` clientVRange + (q, _) <- lift $ newSndQueue userId connId qInfo Nothing + sq <- withStore c $ \db -> runExceptT $ do + liftIO $ lockConnForUpdate db connId + liftIO $ createRatchet db connId ratchetState + ExceptT $ updateNewConnSnd db connId q + secureConfirmQueue c nm cData Nothing sq srv ownConnInfo Nothing subMode withStore' c $ \db -> acceptInvitation db invId ownConnInfo pure r @@ -1905,7 +1986,7 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do JOIN enableNtfs (ACR _ cReq@(CRContactUri ConnReqUriData {crSmpQueues = q :| _})) pqEnc subMode connInfo -> noServer $ do triedHosts <- newTVarIO S.empty tryCommand . withNextSrv c userId storageSrvs triedHosts [qServer q] $ \srv -> do - sqSecured <- joinConnSrv c NRMBackground userId connId enableNtfs cReq connInfo pqEnc subMode srv + sqSecured <- joinConnSrv c NRMBackground userId connId enableNtfs cReq connInfo Nothing pqEnc subMode srv notify $ JOINED sqSecured LET confId ownCInfo -> withServer' . tryCommand $ allowConnection' c connId confId ownCInfo >> notify OK ACK msgId rcptInfo_ -> withServer' . tryCommand $ ackMessage' c connId msgId rcptInfo_ >> notify OK @@ -3185,6 +3266,8 @@ processSMPTransmissions c@AgentClient {subQ} (tSess@(userId, srv, _), THandlePar decryptClientMessage e2eDh clientMsg >>= \case (SMP.PHConfirmation senderKey, AgentConfirmation {e2eEncryption_, encConnInfo, agentVersion}) -> smpConfirmation srvMsgId conn (Just senderKey) e2ePubKey e2eEncryption_ encConnInfo phVer agentVersion >> ack + (SMP.PHEmpty, AgentConfirmation {e2eEncryption_ = Just e2eSndParams, ratchetKeyId = Just rkId, encConnInfo, agentVersion}) -> + smpAddressConfirmation srvMsgId conn e2ePubKey rkId e2eSndParams encConnInfo phVer agentVersion >> ack (SMP.PHEmpty, AgentConfirmation {e2eEncryption_, encConnInfo, agentVersion}) | senderCanSecure queueMode -> smpConfirmation srvMsgId conn Nothing e2ePubKey e2eEncryption_ encConnInfo phVer agentVersion >> ack | otherwise -> prohibited "handshake: missing sender key" >> ack @@ -3395,59 +3478,33 @@ processSMPTransmissions c@AgentClient {subQ} (tSess@(userId, srv, _), THandlePar parseMessage :: Encoding a => ByteString -> AM a parseMessage = liftEither . parse smpP (AGENT A_MESSAGE) + -- checking agreed versions to continue connection in case of client/agent version downgrades + checkConfVersions :: VersionSMPA -> VersionSMPC -> AM () + checkConfVersions agentVersion phVer = do + AgentConfig {smpClientVRange, smpAgentVRange} <- asks config + let compatible = + (agentVersion `isCompatible` smpAgentVRange || agentVersion <= agreedAgentVersion) + && (phVer `isCompatible` smpClientVRange || phVer <= agreedClientVerion) + unless compatible $ throwE $ AGENT A_VERSION + smpConfirmation :: SMP.MsgId -> Connection c -> Maybe C.APublicAuthKey -> C.PublicKeyX25519 -> Maybe (CR.SndE2ERatchetParams 'C.X448) -> ByteString -> VersionSMPC -> VersionSMPA -> AM () smpConfirmation srvMsgId conn' senderKey e2ePubKey e2eEncryption encConnInfo phVer agentVersion = do logServer "<--" c srv rId $ "MSG :" <> logSecret' srvMsgId - AgentConfig {smpClientVRange, smpAgentVRange, e2eEncryptVRange} <- asks config + checkConfVersions agentVersion phVer let ConnData {pqSupport} = toConnData conn' - -- checking agreed versions to continue connection in case of client/agent version downgrades - compatible = - (agentVersion `isCompatible` smpAgentVRange || agentVersion <= agreedAgentVersion) - && (phVer `isCompatible` smpClientVRange || phVer <= agreedClientVerion) - unless compatible $ throwE $ AGENT A_VERSION case status of New -> case (conn', e2eEncryption) of -- party initiating connection - (RcvConnection _ _, Just (CR.AE2ERatchetParams _ e2eSndParams@(CR.E2ERatchetParams e2eVersion _ _ _))) -> do - unless (e2eVersion `isCompatible` e2eEncryptVRange) (throwE $ AGENT A_VERSION) - (pk1, rcDHRs, pKem) <- withStore c (`getRatchetX3dhKeys` connId) - rcParams <- liftError cryptoError $ CR.pqX3dhRcv pk1 rcDHRs pKem e2eSndParams - let rcVs = CR.RatchetVersions {current = e2eVersion, maxSupported = maxVersion e2eEncryptVRange} - pqSupport' = pqSupport `CR.pqSupportAnd` versionPQSupport_ agentVersion (Just e2eVersion) - rc = CR.initRcvRatchet rcVs rcDHRs rcParams pqSupport' - g <- asks random - (agentMsgBody_, rc', skipped) <- liftError cryptoError $ CR.rcDecrypt g rc M.empty encConnInfo - case skipped of - CR.SMDNoChange -> pure () - _ -> logWarn "conf: skipped confirmations" + (RcvConnection _ _, Just e2eSndParams) -> do + keys <- withStore c (`getRatchetX3dhKeys` connId) + (agentMsgBody_, rc', pqSupport') <- initRcvRatchetDecrypt agentVersion pqSupport keys e2eSndParams encConnInfo case agentMsgBody_ of Right agentMsgBody -> parseMessage agentMsgBody >>= \case AgentConnInfoReply smpQueues connInfo -> do - processConf connInfo SMPConfirmation {senderKey, e2ePubKey, connInfo, smpReplyQueues = L.toList smpQueues, smpClientVersion = phVer} + processReplyConf agentVersion pqSupport pqSupport' rc' SMPConfirmation {senderKey, e2ePubKey, connInfo, smpReplyQueues = L.toList smpQueues, smpClientVersion = phVer} connInfo withStore' c $ \db -> updateRcvMsgHash db connId 1 (InternalRcvId 0) (C.sha256Hash agentMsgBody) _ -> prohibited "conf: not AgentConnInfoReply" -- including AgentConnInfo, that is prohibited here in v2 - where - processConf connInfo senderConf = do - let newConfirmation = NewConfirmation {connId, senderConf, ratchetState = rc'} - confId <- withStore c $ \db -> do - setConnAgentVersion db connId agentVersion - when (pqSupport /= pqSupport') $ setConnPQSupport db connId pqSupport' - -- / - -- Starting with agent version 7 (ratchetOnConfSMPAgentVersion), - -- initiating party initializes ratchet on processing confirmation; - -- previously, it initialized ratchet on allowConnection; - -- this is to support decryption of messages that may be received before allowConnection - liftIO $ do - createRatchet db connId rc' - let RcvQueue {smpClientVersion = v, e2ePrivKey = e2ePrivKey'} = rq - SMPConfirmation {smpClientVersion = v', e2ePubKey = e2ePubKey'} = senderConf - dhSecret = C.dh' e2ePubKey' e2ePrivKey' - setRcvQueueConfirmedE2E db rq dhSecret $ min v v' - -- / - createConfirmation db g newConfirmation - let srvs = map qServer $ smpReplyQueues senderConf - notify $ CONF confId pqSupport' srvs connInfo _ -> prohibited "conf: decrypt error" -- party accepting connection (DuplexConnection _ (rq'@RcvQueue {smpClientVersion = v'} :| _) _, Nothing) -> do @@ -3466,9 +3523,69 @@ processSMPTransmissions c@AgentClient {subQ} (tSess@(userId, srv, _), THandlePar notify $ CON pqEncryption withStore' c $ \db -> setRcvQueueStatus db rq' Active _ -> prohibited "conf: not AgentConnInfo" + -- DR requester: the reply arrives with the ratchet already established (built in join) + (RcvConnection _ _, Nothing) -> + withStore' c (`getRatchet` connId) >>= \case + Left _ -> prohibited "conf: incorrect state" + Right rc -> do + g <- asks random + (agentMsgBody_, rc', _) <- liftError cryptoError $ CR.rcDecrypt g rc M.empty encConnInfo + case agentMsgBody_ of + Right agentMsgBody -> + parseMessage agentMsgBody >>= \case + AgentConnInfoReply smpQueues connInfo -> do + processReplyConf agentVersion pqSupport pqSupport rc' SMPConfirmation {senderKey, e2ePubKey, connInfo, smpReplyQueues = L.toList smpQueues, smpClientVersion = phVer} connInfo + withStore' c $ \db -> updateRcvMsgHash db connId 1 (InternalRcvId 0) (C.sha256Hash agentMsgBody) + _ -> prohibited "conf: not AgentConnInfoReply" + _ -> prohibited "conf: decrypt error" _ -> prohibited "conf: incorrect state" _ -> prohibited "conf: status /= new" + -- persists a confirmation reply and its ratchet, then notifies CONF; shared by the connection + -- initiator (ratchet built here) and the address DR requester (ratchet built during join). + processReplyConf :: VersionSMPA -> PQSupport -> PQSupport -> CR.RatchetX448 -> SMPConfirmation -> ConnInfo -> AM () + processReplyConf agentVersion pqSupport pqSupport' rc' senderConf connInfo = do + let newConfirmation = NewConfirmation {connId, senderConf, ratchetState = rc'} + g <- asks random + confId <- withStore c $ \db -> do + setConnAgentVersion db connId agentVersion + when (pqSupport /= pqSupport') $ setConnPQSupport db connId pqSupport' + -- Starting with agent version 7 (ratchetOnConfSMPAgentVersion), the ratchet is initialized + -- on processing confirmation (previously on allowConnection), to decrypt messages that may + -- be received before allowConnection. + liftIO $ do + createRatchet db connId rc' + let RcvQueue {smpClientVersion = v, e2ePrivKey = e2ePrivKey'} = rq + SMPConfirmation {smpClientVersion = v', e2ePubKey = e2ePubKey'} = senderConf + dhSecret = C.dh' e2ePubKey' e2ePrivKey' + setRcvQueueConfirmedE2E db rq dhSecret $ min v v' + createConfirmation db g newConfirmation + notify $ CONF confId pqSupport' (map qServer $ smpReplyQueues senderConf) connInfo + + smpAddressConfirmation :: SMP.MsgId -> Connection c -> C.PublicKeyX25519 -> RatchetKeyId -> CR.SndE2ERatchetParams 'C.X448 -> ByteString -> VersionSMPC -> VersionSMPA -> AM () + smpAddressConfirmation srvMsgId conn' _e2ePubKey rkId e2eSndParams encConnInfo phVer agentVersion = do + logServer "<--" c srv rId $ "MSG :" <> logSecret' srvMsgId + checkConfVersions agentVersion phVer + let ConnData {pqSupport} = toConnData conn' + case conn' of + ContactConnection {} -> + withStore' c (\db -> getAddressRatchetKeys db connId rkId) >>= \case + Left _ -> prohibited "addr conf: unknown ratchetKeyId" + Right keys -> do + (agentMsgBody_, rc', pqSupport') <- initRcvRatchetDecrypt agentVersion pqSupport keys e2eSndParams encConnInfo + case agentMsgBody_ of + Right agentMsgBody -> + parseMessage agentMsgBody >>= \case + AgentConnInfoReply (qA :| _) aliceProfile -> do + g <- asks random + let dr = DRRequest {ratchetState = rc', replyQueue = qA, agentVersion, pqSupport = pqSupport'} + newInv = NewInvitation {contactConnId = connId, connReq = CRConfirmation dr, recipientConnInfo = aliceProfile} + invId <- withStore c $ \db -> createInvitation db g newInv + notify $ REQ invId pqSupport' (qServer qA :| []) aliceProfile + _ -> prohibited "addr conf: not AgentConnInfoReply" + _ -> prohibited "addr conf: decrypt error" + _ -> prohibited "addr conf: not a contact address" + helloMsg :: SMP.MsgId -> MsgMeta -> Connection c -> AM () helloMsg srvMsgId MsgMeta {pqEncryption} conn' = do logServer "<--" c srv rId $ "MSG :" <> logSecret' srvMsgId @@ -3621,7 +3738,7 @@ processSMPTransmissions c@AgentClient {subQ} (tSess@(userId, srv, _), THandlePar -- in case invitation not compatible, assume there is no PQ encryption support. pqSupport <- lift $ maybe PQSupportOff pqSupported <$> compatibleInvitationUri connReq g <- asks random - let newInv = NewInvitation {contactConnId = connId, connReq, recipientConnInfo = cInfo} + let newInv = NewInvitation {contactConnId = connId, connReq = CRInvitation connReq, recipientConnInfo = cInfo} invId <- withStore c $ \db -> createInvitation db g newInv let srvs = L.map qServer $ crSmpQueues crData notify $ REQ invId pqSupport srvs cInfo @@ -3768,7 +3885,7 @@ secureConfirmQueue c nm cData@ConnData {connId, connAgentVersion, pqSupport} rq_ liftIO $ updateSndMsgHash db connId internalSndId (C.sha256Hash agentMsgBody) let pqEnc = CR.pqSupportToEnc pqSupport (encConnInfo, _) <- agentRatchetEncrypt db cData agentMsgBody e2eEncConnInfoLength (Just pqEnc) currentE2EVersion - pure . smpEncode $ AgentConfirmation {agentVersion = connAgentVersion, e2eEncryption_, encConnInfo} + pure . smpEncode $ AgentConfirmation {agentVersion = connAgentVersion, e2eEncryption_, ratchetKeyId = Nothing, encConnInfo} agentSecureSndQueue :: AgentClient -> NetworkRequestMode -> ConnData -> SndQueue -> AM SndQueueSecured agentSecureSndQueue c nm ConnData {connAgentVersion} sq@SndQueue {queueMode, status} @@ -3805,7 +3922,7 @@ storeConfirmation c cData@ConnData {connId, pqSupport, connAgentVersion = v} sq internalHash = C.sha256Hash agentMsgStr pqEnc = CR.pqSupportToEnc pqSupport (encConnInfo, pqEncryption) <- agentRatchetEncrypt db cData agentMsgStr e2eEncConnInfoLength (Just pqEnc) currentE2EVersion - let msgBody = smpEncode $ AgentConfirmation {agentVersion = v, e2eEncryption_, encConnInfo} + let msgBody = smpEncode $ AgentConfirmation {agentVersion = v, e2eEncryption_, ratchetKeyId = Nothing, encConnInfo} msgType = agentMessageType agentMsg msgData = SndMsgData {internalId, internalSndId, internalTs, msgType, msgBody, pqEncryption, msgFlags = SMP.MsgFlags {notification = True}, internalHash, prevMsgHash, sndMsgPrepData_ = Nothing} liftIO $ createSndMsg db connId msgData diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index bb4f1a950..be9330e9e 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -59,6 +59,7 @@ module Simplex.Messaging.Agent.Client getSubscriptions, sendConfirmation, sendInvitation, + sendConfirmationToAddress, temporaryAgentError, temporaryOrHostError, serverHostError, @@ -1925,6 +1926,11 @@ sendInvitation c nm userId connId (Compatible (SMPQueueInfo v SMPQueueAddress {s agentCbEncryptOnce v dhPublicKey . smpEncode $ SMP.ClientMessage SMP.PHEmpty (smpEncode agentEnvelope) +sendConfirmationToAddress :: AgentClient -> NetworkRequestMode -> UserId -> ConnId -> Compatible SMPQueueInfo -> AgentMsgEnvelope -> AM (Maybe SMPServer) +sendConfirmationToAddress c nm userId connId (Compatible (SMPQueueInfo v SMPQueueAddress {smpServer, senderId, dhPublicKey})) agentEnvelope = do + msg <- agentCbEncryptOnce v dhPublicKey . smpEncode $ SMP.ClientMessage SMP.PHEmpty (smpEncode agentEnvelope) + sendOrProxySMPMessage c nm userId smpServer connId "" Nothing senderId (MsgFlags {notification = True}) msg + getQueueMessage :: AgentClient -> RcvQueue -> AM (Maybe SMPMsgMeta) getQueueMessage c rq@RcvQueue {server, rcvId, rcvPrivateKey} = do atomically createTakeGetLock diff --git a/src/Simplex/Messaging/Agent/Protocol.hs b/src/Simplex/Messaging/Agent/Protocol.hs index c4310414e..c22c64b3d 100644 --- a/src/Simplex/Messaging/Agent/Protocol.hs +++ b/src/Simplex/Messaging/Agent/Protocol.hs @@ -1,6 +1,7 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingStrategies #-} +{-# LANGUAGE DerivingVia #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} @@ -46,6 +47,7 @@ module Simplex.Messaging.Agent.Protocol pqdrSMPAgentVersion, sndAuthKeySMPAgentVersion, ratchetOnConfSMPAgentVersion, + addressDRSMPAgentVersion, currentSMPAgentVersion, supportedSMPAgentVRange, e2eEncConnInfoLength, @@ -118,6 +120,8 @@ module Simplex.Messaging.Agent.Protocol UserConnLinkData (..), UserContactData (..), UserLinkData (..), + AddressRatchetKeys (..), + RatchetKeyId (..), OwnerAuth (..), OwnerId, ConnectionLink (..), @@ -319,11 +323,16 @@ sndAuthKeySMPAgentVersion = VersionSMPA 6 ratchetOnConfSMPAgentVersion :: VersionSMPA ratchetOnConfSMPAgentVersion = VersionSMPA 7 +-- | The address advertises the owner's X3DH keys in link data, and a requester +-- establishes the double ratchet from its first message (a confirmation with ratchetKeyId). +addressDRSMPAgentVersion :: VersionSMPA +addressDRSMPAgentVersion = VersionSMPA 8 + minSupportedSMPAgentVersion :: VersionSMPA minSupportedSMPAgentVersion = duplexHandshakeSMPAgentVersion currentSMPAgentVersion :: VersionSMPA -currentSMPAgentVersion = VersionSMPA 7 +currentSMPAgentVersion = VersionSMPA 8 supportedSMPAgentVRange :: VersionRangeSMPA supportedSMPAgentVRange = mkVersionRange minSupportedSMPAgentVersion currentSMPAgentVersion @@ -832,6 +841,7 @@ data AgentMsgEnvelope = AgentConfirmation { agentVersion :: VersionSMPA, e2eEncryption_ :: Maybe (SndE2ERatchetParams 'C.X448), + ratchetKeyId :: Maybe RatchetKeyId, encConnInfo :: ByteString } | AgentMsgEnvelope @@ -852,8 +862,11 @@ data AgentMsgEnvelope instance Encoding AgentMsgEnvelope where smpEncode = \case - AgentConfirmation {agentVersion, e2eEncryption_, encConnInfo} -> - smpEncode (agentVersion, 'C', e2eEncryption_, Tail encConnInfo) + AgentConfirmation {agentVersion, e2eEncryption_, ratchetKeyId, encConnInfo} + | agentVersion >= addressDRSMPAgentVersion -> + smpEncode (agentVersion, 'C', e2eEncryption_, ratchetKeyId, Tail encConnInfo) + | otherwise -> + smpEncode (agentVersion, 'C', e2eEncryption_, Tail encConnInfo) AgentMsgEnvelope {agentVersion, encAgentMessage} -> smpEncode (agentVersion, 'M', Tail encAgentMessage) AgentInvitation {agentVersion, connReq, connInfo} -> @@ -864,8 +877,10 @@ instance Encoding AgentMsgEnvelope where agentVersion <- smpP smpP >>= \case 'C' -> do - (e2eEncryption_, Tail encConnInfo) <- smpP - pure AgentConfirmation {agentVersion, e2eEncryption_, encConnInfo} + e2eEncryption_ <- smpP + ratchetKeyId <- if agentVersion >= addressDRSMPAgentVersion then smpP else pure Nothing + Tail encConnInfo <- smpP + pure AgentConfirmation {agentVersion, e2eEncryption_, ratchetKeyId, encConnInfo} 'M' -> do Tail encAgentMessage <- smpP pure AgentMsgEnvelope {agentVersion, encAgentMessage} @@ -1328,6 +1343,7 @@ sameQueue addr q = sameQAddress addr (qAddress q) data SMPQueueInfo = SMPQueueInfo {clientVersion :: VersionSMPC, queueAddress :: SMPQueueAddress} deriving (Eq, Show) + deriving (ToJSON, FromJSON) via (StrJSON "SMPQueueInfo" SMPQueueInfo) instance Encoding SMPQueueInfo where smpEncode (SMPQueueInfo clientVersion SMPQueueAddress {smpServer, senderId, dhPublicKey, queueMode}) @@ -1396,42 +1412,52 @@ sameQAddress :: (SMPServer, SMP.QueueId) -> (SMPServer, SMP.QueueId) -> Bool sameQAddress (srv, qId) (srv', qId') = sameSrvAddr srv srv' && qId == qId' {-# INLINE sameQAddress #-} +strEncodeSMPQueue :: StrEncoding v => (v -> VersionSMPC) -> v -> SMPQueueAddress -> ByteString +strEncodeSMPQueue minVer v SMPQueueAddress {smpServer = srv, senderId = qId, dhPublicKey, queueMode} + | minVer v >= srvHostnamesSMPClientVersion = strEncode srv <> "/" <> strEncode qId <> "#/?" <> query queryParams + | otherwise = legacyStrEncodeServer srv <> "/" <> strEncode qId <> "#/?" <> query (queryParams <> srvParam) + where + query = strEncode . QSP QEscape + queryParams = [("v", strEncode v), ("dh", strEncode dhPublicKey)] <> queueModeParam <> sndSecureParam + where + queueModeParam = case queueMode of + Just QMMessaging -> [("q", "m")] + Just QMContact -> [("q", "c")] + Nothing -> [] + sndSecureParam = [("k", "s") | senderCanSecure queueMode && minVer v < shortLinksSMPClientVersion] + srvParam = [("srv", strEncode $ TransportHosts_ hs) | not (null hs)] + hs = L.tail $ host srv + +strPSMPQueue :: StrEncoding v => v -> (v -> VersionSMPC) -> A.Parser (v, SMPQueueAddress) +strPSMPQueue defaultVer maxVer = do + srv@ProtocolServer {host = h :| host} <- strP <* A.char '/' + senderId <- strP <* optional (A.char '/') <* A.char '#' + (ver, hs, dhPublicKey, queueMode) <- versioned <|> unversioned + let srv' = srv {host = h :| host <> hs} + smpServer = if maxVer ver < srvHostnamesSMPClientVersion then updateSMPServerHosts srv' else srv' + pure (ver, SMPQueueAddress {smpServer, senderId, dhPublicKey, queueMode}) + where + unversioned = (defaultVer,[],,Nothing) <$> strP <* A.endOfInput + versioned = do + dhKey_ <- optional strP + query <- optional (A.char '/') *> A.char '?' *> strP + ver <- queryParam "v" query + dhKey <- maybe (queryParam "dh" query) pure dhKey_ + hs_ <- queryParam_ "srv" query + let queueMode = case queryParamStr "q" query of + Just "m" -> Just QMMessaging + Just "c" -> Just QMContact + _ | queryParamStr "k" query == Just "s" -> Just QMMessaging + _ -> Nothing + pure (ver, maybe [] thList_ hs_, dhKey, queueMode) + instance StrEncoding SMPQueueUri where - strEncode (SMPQueueUri vr SMPQueueAddress {smpServer = srv, senderId = qId, dhPublicKey, queueMode}) - | minVersion vr >= srvHostnamesSMPClientVersion = strEncode srv <> "/" <> strEncode qId <> "#/?" <> query queryParams - | otherwise = legacyStrEncodeServer srv <> "/" <> strEncode qId <> "#/?" <> query (queryParams <> srvParam) - where - query = strEncode . QSP QEscape - queryParams = [("v", strEncode vr), ("dh", strEncode dhPublicKey)] <> queueModeParam <> sndSecureParam - where - queueModeParam = case queueMode of - Just QMMessaging -> [("q", "m")] - Just QMContact -> [("q", "c")] - Nothing -> [] - sndSecureParam = [("k", "s") | senderCanSecure queueMode && minVersion vr < shortLinksSMPClientVersion] - srvParam = [("srv", strEncode $ TransportHosts_ hs) | not (null hs)] - hs = L.tail $ host srv - strP = do - srv@ProtocolServer {host = h :| host} <- strP <* A.char '/' - senderId <- strP <* optional (A.char '/') <* A.char '#' - (vr, hs, dhPublicKey, queueMode) <- versioned <|> unversioned - let srv' = srv {host = h :| host <> hs} - smpServer = if maxVersion vr < srvHostnamesSMPClientVersion then updateSMPServerHosts srv' else srv' - pure $ SMPQueueUri vr SMPQueueAddress {smpServer, senderId, dhPublicKey, queueMode} - where - unversioned = (versionToRange initialSMPClientVersion,[],,Nothing) <$> strP <* A.endOfInput - versioned = do - dhKey_ <- optional strP - query <- optional (A.char '/') *> A.char '?' *> strP - vr <- queryParam "v" query - dhKey <- maybe (queryParam "dh" query) pure dhKey_ - hs_ <- queryParam_ "srv" query - let queueMode = case queryParamStr "q" query of - Just "m" -> Just QMMessaging - Just "c" -> Just QMContact - _ | queryParamStr "k" query == Just "s" -> Just QMMessaging - _ -> Nothing - pure (vr, maybe [] thList_ hs_, dhKey, queueMode) + strEncode (SMPQueueUri vr addr) = strEncodeSMPQueue minVersion vr addr + strP = uncurry SMPQueueUri <$> strPSMPQueue (versionToRange initialSMPClientVersion) maxVersion + +instance StrEncoding SMPQueueInfo where + strEncode (SMPQueueInfo v addr) = strEncodeSMPQueue id v addr + strP = uncurry SMPQueueInfo <$> strPSMPQueue initialSMPClientVersion id instance Encoding SMPQueueUri where smpEncode (SMPQueueUri clientVRange@(VersionRange minV maxV) SMPQueueAddress {smpServer, senderId, dhPublicKey, queueMode}) @@ -1785,6 +1811,27 @@ deriving instance Eq (ConnLinkData c) deriving instance Show (ConnLinkData c) +newtype RatchetKeyId = RatchetKeyId ByteString + deriving (Eq, Show) + +instance Encoding RatchetKeyId where + smpEncode (RatchetKeyId s) = smpEncode s + {-# INLINE smpEncode #-} + smpP = RatchetKeyId <$> smpP + {-# INLINE smpP #-} + +data AddressRatchetKeys = AddressRatchetKeys + { ratchetKeyId :: RatchetKeyId, + e2eParams :: RcvE2ERatchetParamsUri 'C.X448 + } + deriving (Eq, Show) + +instance Encoding AddressRatchetKeys where + smpEncode AddressRatchetKeys {ratchetKeyId, e2eParams} = smpEncode (ratchetKeyId, e2eParams) + smpP = do + (ratchetKeyId, e2eParams) <- smpP + pure AddressRatchetKeys {ratchetKeyId, e2eParams} + data UserContactData = UserContactData { -- direct connection via connReq in fixed data is allowed. direct :: Bool, @@ -1792,7 +1839,8 @@ data UserContactData = UserContactData owners :: [OwnerAuth], -- alternative addresses of chat relays that receive requests for this contact address. relays :: [ConnShortLink 'CMContact], - userData :: UserLinkData + userData :: UserLinkData, + ratchetKeys :: Maybe AddressRatchetKeys } deriving (Eq, Show) @@ -1920,14 +1968,15 @@ instance ConnectionModeI c => StrEncoding (UserConnLinkData c) where {-# INLINE strP #-} instance Encoding UserContactData where - smpEncode UserContactData {direct, owners, relays, userData} = - B.concat [smpEncode direct, smpEncodeList owners, smpEncodeList relays, smpEncode userData] + smpEncode UserContactData {direct, owners, relays, userData, ratchetKeys} = + B.concat [smpEncode direct, smpEncodeList owners, smpEncodeList relays, smpEncode userData, maybe "" smpEncode ratchetKeys] smpP = do direct <- smpP owners <- smpListP relays <- smpListP - userData <- smpP <* A.takeByteString -- ignoring tail for forward compatibility with the future link data encoding - pure UserContactData {direct, owners, relays, userData} + userData <- smpP + ratchetKeys <- optional smpP <* A.takeByteString -- ignoring tail for forward compatibility with the future link data encoding + pure UserContactData {direct, owners, relays, userData, ratchetKeys} instance Encoding UserLinkData where smpEncode (UserLinkData s) = if B.length s <= 254 then smpEncode s else smpEncode ('\255', Large s) diff --git a/src/Simplex/Messaging/Agent/Store.hs b/src/Simplex/Messaging/Agent/Store.hs index 605a07e78..98c1d6906 100644 --- a/src/Simplex/Messaging/Agent/Store.hs +++ b/src/Simplex/Messaging/Agent/Store.hs @@ -12,6 +12,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} +{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-unticked-promoted-constructors #-} module Simplex.Messaging.Agent.Store @@ -45,6 +46,8 @@ module Simplex.Messaging.Agent.Store AcceptedConfirmation (..), NewInvitation (..), Invitation (..), + ContactRequest (..), + DRRequest (..), PrevExternalSndId, PrevRcvMsgHash, PrevSndMsgHash, @@ -107,9 +110,11 @@ import Simplex.Messaging.Agent.Store.Entity import Simplex.Messaging.Agent.Store.Interface (createDBStore) import Simplex.Messaging.Agent.Store.Migrations.App (appMigrations) import Simplex.Messaging.Agent.Store.Shared (MigrationConfig (..), MigrationError (..)) +import qualified Data.Aeson.TH as J import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Crypto.Ratchet (MsgEncryptKeyX448, PQEncryption, PQSupport, RatchetX448) import Simplex.Messaging.Encoding.String +import Simplex.Messaging.Parsers (defaultJSON) import Simplex.Messaging.Protocol ( MsgBody, MsgFlags, @@ -626,19 +631,31 @@ data AcceptedConfirmation = AcceptedConfirmation data NewInvitation = NewInvitation { contactConnId :: ConnId, - connReq :: ConnectionRequestUri 'CMInvitation, + connReq :: ContactRequest, recipientConnInfo :: ConnInfo } data Invitation = Invitation { invitationId :: InvitationId, contactConnId_ :: Maybe ConnId, - connReq :: ConnectionRequestUri 'CMInvitation, + connReq :: ContactRequest, recipientConnInfo :: ConnInfo, ownConnInfo :: Maybe ConnInfo, accepted :: Bool } +-- | A classic connection request URI, or a double-ratchet confirmation received at a DR address. +data ContactRequest + = CRInvitation (ConnectionRequestUri 'CMInvitation) + | CRConfirmation DRRequest + +data DRRequest = DRRequest + { ratchetState :: RatchetX448, + replyQueue :: SMPQueueInfo, + agentVersion :: VersionSMPA, + pqSupport :: PQSupport + } + -- * Message integrity validation types -- | Corresponds to `last_external_snd_msg_id` in `connections` table @@ -828,3 +845,5 @@ instance AnyStoreError StoreError where SEWorkItemError {} -> True _ -> False mkWorkItemError errContext = SEWorkItemError {errContext} + +$(J.deriveJSON defaultJSON ''DRRequest) diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index e3ea1671b..0fb74c43f 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -152,6 +152,8 @@ module Simplex.Messaging.Agent.Store.AgentStore createRatchetX3dhKeys, getRatchetX3dhKeys, setRatchetX3dhKeys, + createAddressRatchetKeys, + getAddressRatchetKeys, createSndRatchet, getSndRatchet, createRatchet, @@ -278,9 +280,11 @@ import Control.Monad.IO.Class import Control.Monad.Trans.Except import Crypto.Random (ChaChaDRG) import Data.Bifunctor (first) +import qualified Data.Aeson as J import Data.ByteString (ByteString) import qualified Data.ByteString.Base64.URL as U import qualified Data.ByteString.Char8 as B +import qualified Data.ByteString.Lazy as LB import Data.Functor (($>)) import Data.Int (Int64) import Data.List (foldl', sortBy) @@ -1384,6 +1388,31 @@ setRatchetX3dhKeys db connId x3dhPrivKey1 x3dhPrivKey2 pqPrivKem = |] (x3dhPrivKey1, x3dhPrivKey2, pqPrivKem, connId) +createAddressRatchetKeys :: DB.Connection -> ConnId -> RatchetKeyId -> C.PrivateKeyX448 -> C.PrivateKeyX448 -> Maybe CR.RcvPrivRKEMParams -> UTCTime -> IO () +createAddressRatchetKeys db connId ratchetKeyId x3dhPrivKey1 x3dhPrivKey2 pqPrivKem createdAt = + DB.execute + db + [sql| + INSERT INTO address_ratchet_keys + (conn_id, ratchet_key_id, x3dh_priv_key_1, x3dh_priv_key_2, pq_priv_kem, created_at) + VALUES (?, ?, ?, ?, ?, ?) + |] + (connId, ratchetKeyId, x3dhPrivKey1, x3dhPrivKey2, pqPrivKem, createdAt) + +getAddressRatchetKeys :: DB.Connection -> ConnId -> RatchetKeyId -> IO (Either StoreError (C.PrivateKeyX448, C.PrivateKeyX448, Maybe CR.RcvPrivRKEMParams)) +getAddressRatchetKeys db connId ratchetKeyId = + firstRow' keys SEX3dhKeysNotFound $ + DB.query + db + [sql| + SELECT x3dh_priv_key_1, x3dh_priv_key_2, pq_priv_kem + FROM address_ratchet_keys + WHERE conn_id = ? AND ratchet_key_id = ? + |] + (connId, ratchetKeyId) + where + keys (k1, k2, pKem) = Right (k1, k2, pKem) + createSndRatchet :: DB.Connection -> ConnId -> RatchetX448 -> CR.AE2ERatchetParams 'C.X448 -> IO () createSndRatchet db connId ratchetState (CR.AE2ERatchetParams s (CR.E2ERatchetParams _ x3dhPubKey1 x3dhPubKey2 pqPubKem)) = DB.execute @@ -2075,6 +2104,22 @@ instance ConnectionModeI c => ToField (ConnectionRequestUri c) where toField = t instance (E.Typeable c, ConnectionModeI c) => FromField (ConnectionRequestUri c) where fromField = blobFieldDecoder strDecode +instance ToField RatchetKeyId where toField (RatchetKeyId s) = toField $ Binary s + +instance FromField RatchetKeyId where fromField = blobFieldDecoder $ Right . RatchetKeyId + +-- CRInvitation keeps the legacy URI (downgrade-safe); CRConfirmation is JSON, told apart by leading '{' +instance ToField ContactRequest where + toField = toField . Binary . \case + CRInvitation cr -> strEncode cr + CRConfirmation dr -> LB.toStrict $ J.encode dr + +instance FromField ContactRequest where + fromField = blobFieldDecoder $ \bs -> + if "{" `B.isPrefixOf` bs + then CRConfirmation <$> J.eitherDecodeStrict' bs + else CRInvitation <$> strDecode bs + instance ToField ConnectionMode where toField = toField . decodeLatin1 . strEncode instance FromField ConnectionMode where fromField = fromTextField_ connModeT diff --git a/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/App.hs b/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/App.hs index b2ac33a68..12bf3f183 100644 --- a/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/App.hs +++ b/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/App.hs @@ -13,6 +13,7 @@ import Simplex.Messaging.Agent.Store.Postgres.Migrations.M20251010_client_notice import Simplex.Messaging.Agent.Store.Postgres.Migrations.M20251230_strict_tables import Simplex.Messaging.Agent.Store.Postgres.Migrations.M20260410_receive_attempts import Simplex.Messaging.Agent.Store.Postgres.Migrations.M20260411_service_certs +import Simplex.Messaging.Agent.Store.Postgres.Migrations.M20260712_address_dr import Simplex.Messaging.Agent.Store.Shared (Migration (..)) schemaMigrations :: [(String, Text, Maybe Text)] @@ -25,7 +26,8 @@ schemaMigrations = ("20251010_client_notices", m20251010_client_notices, Just down_m20251010_client_notices), ("20251230_strict_tables", m20251230_strict_tables, Just down_m20251230_strict_tables), ("20260410_receive_attempts", m20260410_receive_attempts, Just down_m20260410_receive_attempts), - ("20260411_service_certs", m20260411_service_certs, Just down_m20260411_service_certs) + ("20260411_service_certs", m20260411_service_certs, Just down_m20260411_service_certs), + ("20260712_address_dr", m20260712_address_dr, Just down_m20260712_address_dr) ] -- | The list of migrations in ascending order by date diff --git a/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/M20260712_address_dr.hs b/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/M20260712_address_dr.hs new file mode 100644 index 000000000..3be969a46 --- /dev/null +++ b/src/Simplex/Messaging/Agent/Store/Postgres/Migrations/M20260712_address_dr.hs @@ -0,0 +1,31 @@ +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE QuasiQuotes #-} + +module Simplex.Messaging.Agent.Store.Postgres.Migrations.M20260712_address_dr where + +import Data.Text (Text) +import Text.RawString.QQ (r) + +m20260712_address_dr :: Text +m20260712_address_dr = + [r| +CREATE TABLE address_ratchet_keys( + address_ratchet_key_id BIGSERIAL PRIMARY KEY, + conn_id BYTEA NOT NULL REFERENCES connections ON DELETE CASCADE, + ratchet_key_id BYTEA NOT NULL, + x3dh_priv_key_1 BYTEA NOT NULL, + x3dh_priv_key_2 BYTEA NOT NULL, + pq_priv_kem BYTEA, + created_at TEXT NOT NULL, + retired_at TEXT +); + +CREATE UNIQUE INDEX idx_address_ratchet_keys ON address_ratchet_keys(conn_id, ratchet_key_id); + |] + +down_m20260712_address_dr :: Text +down_m20260712_address_dr = + [r| +DROP INDEX idx_address_ratchet_keys; +DROP TABLE address_ratchet_keys; + |] diff --git a/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/App.hs b/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/App.hs index bfdab2729..c17a191a9 100644 --- a/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/App.hs +++ b/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/App.hs @@ -49,6 +49,7 @@ import Simplex.Messaging.Agent.Store.SQLite.Migrations.M20251010_client_notices import Simplex.Messaging.Agent.Store.SQLite.Migrations.M20251230_strict_tables import Simplex.Messaging.Agent.Store.SQLite.Migrations.M20260410_receive_attempts import Simplex.Messaging.Agent.Store.SQLite.Migrations.M20260411_service_certs +import Simplex.Messaging.Agent.Store.SQLite.Migrations.M20260712_address_dr import Simplex.Messaging.Agent.Store.Shared (Migration (..)) schemaMigrations :: [(String, Query, Maybe Query)] @@ -97,7 +98,8 @@ schemaMigrations = ("m20251010_client_notices", m20251010_client_notices, Just down_m20251010_client_notices), ("m20251230_strict_tables", m20251230_strict_tables, Just down_m20251230_strict_tables), ("m20260410_receive_attempts", m20260410_receive_attempts, Just down_m20260410_receive_attempts), - ("m20260411_service_certs", m20260411_service_certs, Just down_m20260411_service_certs) + ("m20260411_service_certs", m20260411_service_certs, Just down_m20260411_service_certs), + ("m20260712_address_dr", m20260712_address_dr, Just down_m20260712_address_dr) ] -- | The list of migrations in ascending order by date diff --git a/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/M20260712_address_dr.hs b/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/M20260712_address_dr.hs new file mode 100644 index 000000000..e5634b6db --- /dev/null +++ b/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/M20260712_address_dr.hs @@ -0,0 +1,30 @@ +{-# LANGUAGE QuasiQuotes #-} + +module Simplex.Messaging.Agent.Store.SQLite.Migrations.M20260712_address_dr where + +import Database.SQLite.Simple (Query) +import Database.SQLite.Simple.QQ (sql) + +m20260712_address_dr :: Query +m20260712_address_dr = + [sql| +CREATE TABLE address_ratchet_keys( + address_ratchet_key_id INTEGER PRIMARY KEY, + conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE, + ratchet_key_id BLOB NOT NULL, + x3dh_priv_key_1 BLOB NOT NULL, + x3dh_priv_key_2 BLOB NOT NULL, + pq_priv_kem BLOB, + created_at TEXT NOT NULL, + retired_at TEXT +) STRICT; + +CREATE UNIQUE INDEX idx_address_ratchet_keys ON address_ratchet_keys(conn_id, ratchet_key_id); + |] + +down_m20260712_address_dr :: Query +down_m20260712_address_dr = + [sql| +DROP INDEX idx_address_ratchet_keys; +DROP TABLE address_ratchet_keys; + |] diff --git a/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/agent_schema.sql b/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/agent_schema.sql index e77582b92..195783cce 100644 --- a/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/agent_schema.sql +++ b/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/agent_schema.sql @@ -465,6 +465,16 @@ CREATE TABLE client_services( service_queue_ids_hash BLOB NOT NULL DEFAULT x'00000000000000000000000000000000', FOREIGN KEY(host, port) REFERENCES servers ON UPDATE CASCADE ON DELETE RESTRICT ) STRICT; +CREATE TABLE address_ratchet_keys( + address_ratchet_key_id INTEGER PRIMARY KEY, + conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE, + ratchet_key_id BLOB NOT NULL, -- published id echoed by requests + x3dh_priv_key_1 BLOB NOT NULL, -- X448 + x3dh_priv_key_2 BLOB NOT NULL, -- X448 + pq_priv_kem BLOB, -- sntrup761 keypair; NULL when PQ is off for this address + created_at TEXT NOT NULL, + retired_at TEXT -- set on rotation +) STRICT; CREATE UNIQUE INDEX idx_rcv_queues_ntf ON rcv_queues(host, port, ntf_id); CREATE UNIQUE INDEX idx_rcv_queue_id ON rcv_queues(conn_id, rcv_queue_id); CREATE UNIQUE INDEX idx_snd_queue_id ON snd_queues(conn_id, snd_queue_id); @@ -615,6 +625,10 @@ CREATE UNIQUE INDEX idx_server_certs_user_id_host_port ON client_services( server_key_hash ); CREATE INDEX idx_server_certs_host_port ON client_services(host, port); +CREATE UNIQUE INDEX idx_address_ratchet_keys ON address_ratchet_keys( + conn_id, + ratchet_key_id +); CREATE TRIGGER tr_rcv_queue_insert AFTER INSERT ON rcv_queues FOR EACH ROW diff --git a/src/Simplex/Messaging/Crypto/Ratchet.hs b/src/Simplex/Messaging/Crypto/Ratchet.hs index 7250a1d60..b1c28bda6 100644 --- a/src/Simplex/Messaging/Crypto/Ratchet.hs +++ b/src/Simplex/Messaging/Crypto/Ratchet.hs @@ -37,6 +37,7 @@ module Simplex.Messaging.Crypto.Ratchet AUseKEM (..), RatchetKEMState (..), SRatchetKEMState (..), + RatchetKEMStateI (..), RcvPrivRKEMParams, APrivRKEMParams (..), RcvE2ERatchetParamsUri, diff --git a/tests/AgentTests/ConnectionRequestTests.hs b/tests/AgentTests/ConnectionRequestTests.hs index 13ee3e156..a0ea929d1 100644 --- a/tests/AgentTests/ConnectionRequestTests.hs +++ b/tests/AgentTests/ConnectionRequestTests.hs @@ -256,26 +256,26 @@ connectionRequestTests = queueV1NoPort #== ("smp://1234-w==@smp.simplex.im/3456-w==#/?v=1-1&dh=" <> url testDhKeyStr <> "&srv=jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion") queueV1NoPort #== ("smp://1234-w==@smp.simplex.im,jjbyvoemxysm7qxap7m5d5m35jzv5qq6gnlv7s4rsn7tdwwmuqciwpid.onion/3456-w==#" <> testDhKeyStr) it "should serialize and parse connection invitations and contact addresses" $ do - connectionRequest #==# ("simplex:/invitation#/?v=2-7&smp=" <> url queueStr <> "&e2e=" <> testE2ERatchetParamsStrUri) - connectionRequest #== ("https://simplex.chat/invitation#/?v=2-7&smp=" <> url queueStr <> "&e2e=" <> testE2ERatchetParamsStrUri) - connectionRequestNoQM #==# ("simplex:/invitation#/?v=2-7&smp=" <> url queueStrNoQM <> "&e2e=" <> testE2ERatchetParamsStrUri) - connectionRequest1 #==# ("simplex:/invitation#/?v=2-7&smp=" <> url queue1Str <> "&e2e=" <> testE2ERatchetParamsStrUri) - connectionRequest2queues #==# ("simplex:/invitation#/?v=2-7&smp=" <> url (queueStr <> ";" <> queueStr) <> "&e2e=" <> testE2ERatchetParamsStrUri) - connectionRequestNew #==# ("simplex:/invitation#/?v=2-7&smp=" <> url queueNewStr <> "&e2e=" <> testE2ERatchetParamsStrUri) - connectionRequestNew1 #==# ("simplex:/invitation#/?v=2-7&smp=" <> url queueNew1Str <> "&e2e=" <> testE2ERatchetParamsStrUri) - connectionRequest2queuesNew #==# ("simplex:/invitation#/?v=2-7&smp=" <> url (queueNewStr <> ";" <> queueNewStr) <> "&e2e=" <> testE2ERatchetParamsStrUri) + connectionRequest #==# ("simplex:/invitation#/?v=2-8&smp=" <> url queueStr <> "&e2e=" <> testE2ERatchetParamsStrUri) + connectionRequest #== ("https://simplex.chat/invitation#/?v=2-8&smp=" <> url queueStr <> "&e2e=" <> testE2ERatchetParamsStrUri) + connectionRequestNoQM #==# ("simplex:/invitation#/?v=2-8&smp=" <> url queueStrNoQM <> "&e2e=" <> testE2ERatchetParamsStrUri) + connectionRequest1 #==# ("simplex:/invitation#/?v=2-8&smp=" <> url queue1Str <> "&e2e=" <> testE2ERatchetParamsStrUri) + connectionRequest2queues #==# ("simplex:/invitation#/?v=2-8&smp=" <> url (queueStr <> ";" <> queueStr) <> "&e2e=" <> testE2ERatchetParamsStrUri) + connectionRequestNew #==# ("simplex:/invitation#/?v=2-8&smp=" <> url queueNewStr <> "&e2e=" <> testE2ERatchetParamsStrUri) + connectionRequestNew1 #==# ("simplex:/invitation#/?v=2-8&smp=" <> url queueNew1Str <> "&e2e=" <> testE2ERatchetParamsStrUri) + connectionRequest2queuesNew #==# ("simplex:/invitation#/?v=2-8&smp=" <> url (queueNewStr <> ";" <> queueNewStr) <> "&e2e=" <> testE2ERatchetParamsStrUri) connectionRequestV1 #== ("https://simplex.chat/invitation#/?v=1&smp=" <> url queueStr <> "&e2e=" <> testE2ERatchetParamsStrUri) - connectionRequestClientDataEmpty #==# ("simplex:/invitation#/?v=2-7&smp=" <> url queueStr <> "&e2e=" <> testE2ERatchetParamsStrUri <> "&data=" <> url "{}") - contactAddress #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueStr) - contactAddress #== ("https://simplex.chat/contact#/?v=2-7&smp=" <> url queueStr) - contactAddress2queues #==# ("simplex:/contact#/?v=2-7&smp=" <> url (queueStr <> ";" <> queueStr)) - contactAddressNew #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueNewStr) - contactAddress2queuesNew #==# ("simplex:/contact#/?v=2-7&smp=" <> url (queueNewStr <> ";" <> queueNewStr)) + connectionRequestClientDataEmpty #==# ("simplex:/invitation#/?v=2-8&smp=" <> url queueStr <> "&e2e=" <> testE2ERatchetParamsStrUri <> "&data=" <> url "{}") + contactAddress #==# ("simplex:/contact#/?v=2-8&smp=" <> url queueStr) + contactAddress #== ("https://simplex.chat/contact#/?v=2-8&smp=" <> url queueStr) + contactAddress2queues #==# ("simplex:/contact#/?v=2-8&smp=" <> url (queueStr <> ";" <> queueStr)) + contactAddressNew #==# ("simplex:/contact#/?v=2-8&smp=" <> url queueNewStr) + contactAddress2queuesNew #==# ("simplex:/contact#/?v=2-8&smp=" <> url (queueNewStr <> ";" <> queueNewStr)) contactAddressV2 #==# ("simplex:/contact#/?v=2&smp=" <> url queueStr) contactAddressV2 #== ("https://simplex.chat/contact#/?v=1&smp=" <> url queueStr) -- adjusted to v2 contactAddressV2 #== ("https://simplex.chat/contact#/?v=1-2&smp=" <> url queueStr) -- adjusted to v2 contactAddressV2 #== ("https://simplex.chat/contact#/?v=2-2&smp=" <> url queueStr) - contactAddressClientData #==# ("simplex:/contact#/?v=2-7&smp=" <> url queueStr <> "&data=" <> url "{\"type\":\"group_link\", \"group_link_id\":\"abc\"}") + contactAddressClientData #==# ("simplex:/contact#/?v=2-8&smp=" <> url queueStr <> "&data=" <> url "{\"type\":\"group_link\", \"group_link_id\":\"abc\"}") it "should serialize / parse queue address, connection invitations and contact addresses as binary" $ do smpEncodingTest queue smpEncodingTest queueNoQM -- this passes, no queue mode patch in SMPQueueUri encoding diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 7b95c71bf..656be6914 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -290,7 +290,7 @@ createConnection c userId enableNtfs cMode clientData subMode = do joinConnection :: AgentClient -> UserId -> Bool -> ConnectionRequestUri c -> ConnInfo -> SubscriptionMode -> AE (ConnId, SndQueueSecured) joinConnection c userId enableNtfs cReq connInfo subMode = do connId <- A.prepareConnectionToJoin c userId enableNtfs cReq PQSupportOn - sndSecure <- A.joinConnection c NRMInteractive userId connId enableNtfs cReq connInfo PQSupportOn subMode + sndSecure <- A.joinConnection c NRMInteractive userId connId enableNtfs cReq connInfo Nothing PQSupportOn subMode pure (connId, sndSecure) acceptContact :: AgentClient -> UserId -> ConnId -> Bool -> ConfirmationId -> ConnInfo -> PQSupport -> SubscriptionMode -> AE SndQueueSecured @@ -347,6 +347,8 @@ functionalAPITests ps = do testRatchetMatrix2 ps runAgentClientContactTest describe "Establish duplex connection via contact address, different PQ settings" $ do testPQMatrix3 ps $ runAgentClientContactTestPQ3 True + describe "Establish duplex connection via contact address with DR" $ + testContactDRMatrix ps it "should support rejecting contact request" $ withSmpServer ps testRejectContactRequest describe "Changing connection user id" $ do @@ -586,18 +588,18 @@ testMatrix2 ps runTest = do it "current, via proxy" $ withSmpServerProxy ps $ runTestCfgServers2 agentCfg agentCfg initAgentServersProxy 1 $ runTest PQSupportOn True True it "v8, via proxy" $ withSmpServerProxy ps $ runTestCfgServers2 agentProxyCfgV8 agentProxyCfgV8 initAgentServersProxy 3 $ runTest PQSupportOn False True it "current" $ withSmpServer ps $ runTestCfg2 agentCfg agentCfg 1 $ runTest PQSupportOn True False - it "prev" $ withSmpServer ps $ runTestCfg2 agentCfgVPrev agentCfgVPrev 1 $ runTest PQSupportOff False False - it "prev to current" $ withSmpServer ps $ runTestCfg2 agentCfgVPrev agentCfg 1 $ runTest PQSupportOff False False - it "current to prev" $ withSmpServer ps $ runTestCfg2 agentCfg agentCfgVPrev 1 $ runTest PQSupportOff False False + it "prev" $ withSmpServer ps $ runTestCfg2 agentCfgVPrev agentCfgVPrev 1 $ runTest PQSupportOff True False + it "prev to current" $ withSmpServer ps $ runTestCfg2 agentCfgVPrev agentCfg 1 $ runTest PQSupportOff True False + it "current to prev" $ withSmpServer ps $ runTestCfg2 agentCfg agentCfgVPrev 1 $ runTest PQSupportOff True False testMatrix2Stress :: HasCallStack => (ASrvTransport, AStoreType) -> (PQSupport -> SndQueueSecured -> Bool -> AgentClient -> AgentClient -> AgentMsgId -> IO ()) -> Spec testMatrix2Stress ps runTest = do it "current, via proxy" $ withSmpServerProxy ps $ runTestCfgServers2 aCfg aCfg initAgentServersProxy 1 $ runTest PQSupportOn True True it "v8, via proxy" $ withSmpServerProxy ps $ runTestCfgServers2 aProxyCfgV8 aProxyCfgV8 initAgentServersProxy 1 $ runTest PQSupportOn False True it "current" $ withSmpServer ps $ runTestCfg2 aCfg aCfg 1 $ runTest PQSupportOn True False - it "prev" $ withSmpServer ps $ runTestCfg2 aCfgVPrev aCfgVPrev 1 $ runTest PQSupportOff False False - it "prev to current" $ withSmpServer ps $ runTestCfg2 aCfgVPrev aCfg 1 $ runTest PQSupportOff False False - it "current to prev" $ withSmpServer ps $ runTestCfg2 aCfg aCfgVPrev 1 $ runTest PQSupportOff False False + it "prev" $ withSmpServer ps $ runTestCfg2 aCfgVPrev aCfgVPrev 1 $ runTest PQSupportOff True False + it "prev to current" $ withSmpServer ps $ runTestCfg2 aCfgVPrev aCfg 1 $ runTest PQSupportOff True False + it "current to prev" $ withSmpServer ps $ runTestCfg2 aCfg aCfgVPrev 1 $ runTest PQSupportOff True False where aCfg = agentCfg {messageRetryInterval = fastMessageRetryInterval} aProxyCfgV8 = agentProxyCfgV8 {messageRetryInterval = fastMessageRetryInterval} @@ -606,9 +608,9 @@ testMatrix2Stress ps runTest = do testBasicMatrix2 :: HasCallStack => (ASrvTransport, AStoreType) -> (SndQueueSecured -> AgentClient -> AgentClient -> AgentMsgId -> IO ()) -> Spec testBasicMatrix2 ps runTest = do it "current" $ withSmpServer ps $ runTestCfg2 agentCfg agentCfg 1 $ runTest True - it "prev" $ withSmpServer ps $ runTestCfg2 agentCfgVPrevPQ agentCfgVPrevPQ 1 $ runTest False - it "prev to current" $ withSmpServer ps $ runTestCfg2 agentCfgVPrevPQ agentCfg 1 $ runTest False - it "current to prev" $ withSmpServer ps $ runTestCfg2 agentCfg agentCfgVPrevPQ 1 $ runTest False + it "prev" $ withSmpServer ps $ runTestCfg2 agentCfgVPrevPQ agentCfgVPrevPQ 1 $ runTest True + it "prev to current" $ withSmpServer ps $ runTestCfg2 agentCfgVPrevPQ agentCfg 1 $ runTest True + it "current to prev" $ withSmpServer ps $ runTestCfg2 agentCfg agentCfgVPrevPQ 1 $ runTest True testRatchetMatrix2 :: HasCallStack => (ASrvTransport, AStoreType) -> (PQSupport -> SndQueueSecured -> Bool -> AgentClient -> AgentClient -> AgentMsgId -> IO ()) -> Spec testRatchetMatrix2 ps runTest = do @@ -725,7 +727,7 @@ runAgentClientTestPQ sqSecured viaProxy (alice, aPQ) (bob, bPQ) baseId = runRight_ $ do (bobId, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive 1 True True SCMInvitation Nothing Nothing aPQ SMSubscribe aliceId <- A.prepareConnectionToJoin bob 1 True qInfo bPQ - sqSecured' <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" bPQ SMSubscribe + sqSecured' <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" Nothing bPQ SMSubscribe liftIO $ sqSecured' `shouldBe` sqSecured ("", _, A.CONF confId pqSup' _ "bob's connInfo") <- get alice liftIO $ pqSup' `shouldBe` CR.connPQEncryption aPQ @@ -954,7 +956,7 @@ runAgentClientContactTestPQ sqSecured viaProxy reqPQSupport (alice, aPQ) (bob, b runRight_ $ do (_, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive 1 True True SCMContact Nothing Nothing aPQ SMSubscribe aliceId <- A.prepareConnectionToJoin bob 1 True qInfo bPQ - sqSecuredJoin <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" bPQ SMSubscribe + sqSecuredJoin <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" Nothing bPQ SMSubscribe liftIO $ sqSecuredJoin `shouldBe` False -- joining via contact address connection ("", _, A.REQ invId pqSup' _ "bob's connInfo") <- get alice liftIO $ pqSup' `shouldBe` reqPQSupport @@ -994,6 +996,49 @@ runAgentClientContactTestPQ sqSecured viaProxy reqPQSupport (alice, aPQ) (bob, b where msgId = subtract baseId . fst +-- Establish a connection via a DR-advertising contact address (short-link data carries ratchetKeys). +-- addrIK drives the advertised bundle and the owner's PQ; useDR chooses the DR path (pass the fetched +-- keys) or the classic path (ignore them); bPQ is the joiner's PQSupport. +runAgentClientContactDRTest :: HasCallStack => InitialKeys -> Bool -> PQSupport -> (ASrvTransport, AStoreType) -> IO () +runAgentClientContactDRTest addrIK useDR bPQ ps = withSmpServer ps $ withAgentClients2 $ \alice bob -> do + g <- C.newRandom + rootKey <- atomically $ C.generateKeyPair g + linkEntId <- atomically $ C.randomBytes 32 g + let userCtData = UserContactData {direct = True, owners = [], relays = [], userData = UserLinkData "test user data", ratchetKeys = Nothing} + userLinkData = UserContactLinkData userCtData + connIK = IKLinkPQ (CR.connPQEncryption addrIK) -- owner connection PQ (never IKUsePQ) + pqEnc = PQEncryption $ pqConnectionMode addrIK bPQ + runRight_ $ do + (ccLink@(CCLink _ (Just shortLink)), preparedParams) <- A.prepareConnectionLink alice 1 rootKey linkEntId True Nothing Nothing + _ <- A.createConnectionForLink alice NRMInteractive 1 True ccLink preparedParams userLinkData connIK (Just addrIK) SMSubscribe + (FixedLinkData {linkConnReq = connReq'}, ContactLinkData _ userCtData') <- getConnShortLink bob 1 shortLink + let addrKeys_ = if useDR then ratchetKeys userCtData' else Nothing + aliceId <- A.prepareConnectionToJoin bob 1 True connReq' bPQ + sqSecuredJoin <- A.joinConnection bob NRMInteractive 1 aliceId True connReq' "bob's connInfo" addrKeys_ bPQ SMSubscribe + liftIO $ sqSecuredJoin `shouldBe` False + ("", _, A.REQ invId _ _ "bob's connInfo") <- get alice + bobId <- A.prepareConnectionToAccept alice 1 True invId (CR.connPQEncryption addrIK) + _ <- acceptContact alice 1 bobId True invId "alice's connInfo" (CR.connPQEncryption addrIK) SMSubscribe + ("", _, A.CONF confId _ _ "alice's connInfo") <- get bob + allowConnection bob aliceId confId "bob's connInfo" + get alice ##> ("", bobId, A.INFO (CR.connPQEncryption addrIK) "bob's connInfo") + get alice ##> ("", bobId, A.CON pqEnc) + get bob ##> ("", aliceId, A.CON pqEnc) + exchangeGreetings_ pqEnc alice bobId bob aliceId + +testContactDRMatrix :: HasCallStack => (ASrvTransport, AStoreType) -> Spec +testContactDRMatrix ps = do + describe "DR join (ratchet from the invitation)" $ do + it "IKPQOff, dh join" $ runAgentClientContactDRTest IKPQOff True PQSupportOff ps + it "IKPQOff, pq join" $ runAgentClientContactDRTest IKPQOff True PQSupportOn ps + it "IKPQOn, dh join" $ runAgentClientContactDRTest IKPQOn True PQSupportOff ps + it "IKPQOn, pq join" $ runAgentClientContactDRTest IKPQOn True PQSupportOn ps + it "IKUsePQ, dh join" $ runAgentClientContactDRTest IKUsePQ True PQSupportOff ps + it "IKUsePQ, pq join" $ runAgentClientContactDRTest IKUsePQ True PQSupportOn ps + describe "classic join, ratchet keys ignored" $ do + it "IKUsePQ, dh join" $ runAgentClientContactDRTest IKUsePQ False PQSupportOff ps + it "IKUsePQ, pq join" $ runAgentClientContactDRTest IKUsePQ False PQSupportOn ps + runAgentClientContactTestPQ3 :: HasCallStack => Bool -> (AgentClient, InitialKeys) -> (AgentClient, PQSupport) -> (AgentClient, PQSupport) -> AgentMsgId -> IO () runAgentClientContactTestPQ3 viaProxy (alice, aPQ) (bob, bPQ) (tom, tPQ) baseId = runRight_ $ do (_, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive 1 True True SCMContact Nothing Nothing aPQ SMSubscribe @@ -1005,7 +1050,7 @@ runAgentClientContactTestPQ3 viaProxy (alice, aPQ) (bob, bPQ) (tom, tPQ) baseId msgId = subtract baseId . fst connectViaContact b pq qInfo = do aId <- A.prepareConnectionToJoin b 1 True qInfo pq - sqSecuredJoin <- A.joinConnection b NRMInteractive 1 aId True qInfo "bob's connInfo" pq SMSubscribe + sqSecuredJoin <- A.joinConnection b NRMInteractive 1 aId True qInfo "bob's connInfo" Nothing pq SMSubscribe liftIO $ sqSecuredJoin `shouldBe` False -- joining via contact address connection ("", _, A.REQ invId pqSup' _ "bob's connInfo") <- get alice liftIO $ pqSup' `shouldBe` PQSupportOn @@ -1051,7 +1096,7 @@ testRejectContactRequest = withAgentClients2 $ \alice bob -> runRight_ $ do (_addrConnId, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive 1 True True SCMContact Nothing Nothing IKPQOn SMSubscribe aliceId <- A.prepareConnectionToJoin bob 1 True qInfo PQSupportOn - sqSecured <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" PQSupportOn SMSubscribe + sqSecured <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" Nothing PQSupportOn SMSubscribe liftIO $ sqSecured `shouldBe` False -- joining via contact address connection ("", _, A.REQ invId PQSupportOn _ "bob's connInfo") <- get alice rejectContact alice invId @@ -1064,7 +1109,7 @@ testUpdateConnectionUserId = newUserId <- createUser alice False [noAuthSrvCfg testSMPServer] [noAuthSrvCfg testXFTPServer] _ <- changeConnectionUser alice 1 connId newUserId aliceId <- A.prepareConnectionToJoin bob 1 True qInfo PQSupportOn - sqSecured' <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" PQSupportOn SMSubscribe + sqSecured' <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" Nothing PQSupportOn SMSubscribe liftIO $ sqSecured' `shouldBe` True ("", _, A.CONF confId pqSup' _ "bob's connInfo") <- get alice liftIO $ pqSup' `shouldBe` PQSupportOn @@ -1224,13 +1269,13 @@ testInvitationErrors ps restart = do ("", "", DOWN _ [_]) <- nGet a aId <- runRight $ A.prepareConnectionToJoin b 1 True cReq PQSupportOn -- fails to secure the queue on testPort - BROKER srv (NETWORK _) <- runLeft $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" PQSupportOn SMSubscribe + BROKER srv (NETWORK _) <- runLeft $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" Nothing PQSupportOn SMSubscribe (testPort `isSuffixOf` srv) `shouldBe` True withServer1 ps $ do ("", "", UP _ [_]) <- nGet a let loopSecure = do -- secures the queue on testPort, but fails to create reply queue on testPort2 - BROKER srv2 (NETWORK _) <- runLeft $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" PQSupportOn SMSubscribe + BROKER srv2 (NETWORK _) <- runLeft $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" Nothing PQSupportOn SMSubscribe unless (testPort2 `isSuffixOf` srv2) $ putStrLn "retrying secure" >> threadDelay 200000 >> loopSecure loopSecure ("", "", DOWN _ [_]) <- nGet a @@ -1238,7 +1283,7 @@ testInvitationErrors ps restart = do threadDelay 200000 let loopCreate = do -- creates the reply queue on testPort2, but fails to send it to testPort - BROKER srv' (NETWORK _) <- runLeft $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" PQSupportOn SMSubscribe + BROKER srv' (NETWORK _) <- runLeft $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" Nothing PQSupportOn SMSubscribe unless (testPort `isSuffixOf` srv') $ putStrLn "retrying create" >> threadDelay 200000 >> loopCreate loopCreate restartAgentB restart b [aId] @@ -1247,7 +1292,7 @@ testInvitationErrors ps restart = do ("", "", UP _ [_]) <- nGet a threadDelay 200000 let loopConfirm n = - runExceptT (A.joinConnection b' NRMInteractive 1 aId True cReq "bob's connInfo" PQSupportOn SMSubscribe) >>= \case + runExceptT (A.joinConnection b' NRMInteractive 1 aId True cReq "bob's connInfo" Nothing PQSupportOn SMSubscribe) >>= \case Right True -> pure n Right r -> error $ "unexpected result " <> show r Left _ -> putStrLn "retrying confirm" >> threadDelay 200000 >> loopConfirm (n + 1) @@ -1294,12 +1339,12 @@ testContactErrors ps restart = do ("", "", DOWN _ [_]) <- nGet a aId <- runRight $ A.prepareConnectionToJoin b 1 True cReq PQSupportOn -- fails to create queue on testPort2 - BROKER srv2 (NETWORK _) <- runLeft $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" PQSupportOn SMSubscribe + BROKER srv2 (NETWORK _) <- runLeft $ A.joinConnection b NRMInteractive 1 aId True cReq "bob's connInfo" Nothing PQSupportOn SMSubscribe (testPort2 `isSuffixOf` srv2) `shouldBe` True b' <- restartAgentB restart b [aId] let loopCreate2 = do -- creates the reply queue on testPort2, but fails to send invitation to testPort - BROKER srv' (NETWORK _) <- runLeft $ A.joinConnection b' NRMInteractive 1 aId True cReq "bob's connInfo" PQSupportOn SMSubscribe + BROKER srv' (NETWORK _) <- runLeft $ A.joinConnection b' NRMInteractive 1 aId True cReq "bob's connInfo" Nothing PQSupportOn SMSubscribe unless (testPort `isSuffixOf` srv') $ putStrLn "retrying create 2" >> threadDelay 200000 >> loopCreate2 b'' <- withServer2 ps $ do loopCreate2 @@ -1309,7 +1354,7 @@ testContactErrors ps restart = do ("", "", UP _ [_]) <- nGet a let loopSend = do -- sends the invitation to testPort - runExceptT (A.joinConnection b'' NRMInteractive 1 aId True cReq "bob's connInfo" PQSupportOn SMSubscribe) >>= \case + runExceptT (A.joinConnection b'' NRMInteractive 1 aId True cReq "bob's connInfo" Nothing PQSupportOn SMSubscribe) >>= \case Right False -> pure () Right r -> error $ "unexpected result " <> show r Left _ -> putStrLn "retrying send" >> threadDelay 200000 >> loopSend @@ -1398,7 +1443,7 @@ testInvitationShortLink viaProxy a b = testJoinConn_ :: Bool -> Bool -> AgentClient -> ConnId -> AgentClient -> ConnectionRequestUri c -> ExceptT AgentErrorType IO () testJoinConn_ viaProxy sndSecure a bId b connReq = do aId <- A.prepareConnectionToJoin b 1 True connReq PQSupportOn - sndSecure' <- A.joinConnection b NRMInteractive 1 aId True connReq "bob's connInfo" PQSupportOn SMSubscribe + sndSecure' <- A.joinConnection b NRMInteractive 1 aId True connReq "bob's connInfo" Nothing PQSupportOn SMSubscribe liftIO $ sndSecure' `shouldBe` sndSecure ("", _, CONF confId _ "bob's connInfo") <- get a allowConnection a bId confId "alice's connInfo" @@ -1445,7 +1490,7 @@ testContactShortLink :: HasCallStack => Bool -> AgentClient -> AgentClient -> IO testContactShortLink viaProxy a b = withAgent 3 agentCfg initAgentServers testDB3 $ \c -> do let userData = UserLinkData "some user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} newLinkData = UserContactLinkData userCtData (contactId, CCLink connReq0 (Just shortLink)) <- runRight $ A.createConnection a NRMInteractive 1 True True SCMContact (Just newLinkData) Nothing CR.IKPQOn SMSubscribe Right connReq <- pure $ smpDecode (smpEncode connReq0) @@ -1476,7 +1521,7 @@ testContactShortLink viaProxy a b = exchangeGreetingsViaProxy viaProxy a bId b aId -- update user data let updatedData = UserLinkData "updated user data" - updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData} + updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData, ratchetKeys = Nothing} userLinkData' = UserContactLinkData updatedCtData shortLink' <- runRight $ setConnShortLink a contactId SCMContact userLinkData' Nothing shortLink' `shouldBe` shortLink @@ -1497,7 +1542,7 @@ testAddContactShortLink viaProxy a b = (contactId, CCLink connReq0 Nothing) <- runRight $ A.createConnection a NRMInteractive 1 True True SCMContact Nothing Nothing CR.IKPQOn SMSubscribe Right connReq <- pure $ smpDecode (smpEncode connReq0) -- let userData = UserLinkData "some user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} newLinkData = UserContactLinkData userCtData shortLink <- runRight $ setConnShortLink a contactId SCMContact newLinkData Nothing (FixedLinkData {linkConnReq = connReq'}, ContactLinkData _ userCtData') <- runRight $ getConnShortLink b 1 shortLink @@ -1527,7 +1572,7 @@ testAddContactShortLink viaProxy a b = exchangeGreetingsViaProxy viaProxy a bId b aId -- update user data let updatedData = UserLinkData "updated user data" - updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData} + updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData, ratchetKeys = Nothing} userLinkData' = UserContactLinkData updatedCtData shortLink' <- runRight $ setConnShortLink a contactId SCMContact userLinkData' Nothing shortLink' `shouldBe` shortLink @@ -1551,13 +1596,13 @@ testInvitationShortLinkRestart ps = withAgentClients2 $ \a b -> do testContactShortLinkRestart :: HasCallStack => (ASrvTransport, AStoreType) -> IO () testContactShortLinkRestart ps = withAgentClients2 $ \a b -> do let userData = UserLinkData "some user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} newLinkData = UserContactLinkData userCtData (contactId, CCLink connReq0 (Just shortLink)) <- withSmpServer ps $ runRight $ A.createConnection a NRMInteractive 1 True True SCMContact (Just newLinkData) Nothing CR.IKPQOn SMOnlyCreate Right connReq <- pure $ smpDecode (smpEncode connReq0) let updatedData = UserLinkData "updated user data" - updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData} + updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData, ratchetKeys = Nothing} updatedLinkData = UserContactLinkData updatedCtData withSmpServer ps $ do (fd', ContactLinkData _ userCtData') <- runRight $ getConnShortLink b 1 shortLink @@ -1575,14 +1620,14 @@ testContactShortLinkRestart ps = withAgentClients2 $ \a b -> do testAddContactShortLinkRestart :: HasCallStack => (ASrvTransport, AStoreType) -> IO () testAddContactShortLinkRestart ps = withAgentClients2 $ \a b -> do let userData = UserLinkData "some user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} newLinkData = UserContactLinkData userCtData ((contactId, CCLink connReq0 Nothing), shortLink) <- withSmpServer ps $ runRight $ do r@(contactId, _) <- A.createConnection a NRMInteractive 1 True True SCMContact Nothing Nothing CR.IKPQOn SMOnlyCreate (r,) <$> setConnShortLink a contactId SCMContact newLinkData Nothing Right connReq <- pure $ smpDecode (smpEncode connReq0) let updatedData = UserLinkData "updated user data" - updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData} + updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData, ratchetKeys = Nothing} updatedLinkData = UserContactLinkData updatedCtData withSmpServer ps $ do (fd', ContactLinkData _ userCtData') <- runRight $ getConnShortLink b 1 shortLink @@ -1629,7 +1674,7 @@ testOldContactQueueShortLink ps@(_, msType) = withAgentClients2 $ \a b -> do withSmpServer ps $ do let userData = UserLinkData "some user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} userLinkData = UserContactLinkData userCtData shortLink <- runRight $ setConnShortLink a contactId SCMContact userLinkData Nothing (FixedLinkData {linkConnReq = connReq'}, ContactLinkData _ userCtData') <- runRight $ getConnShortLink b 1 shortLink @@ -1638,7 +1683,7 @@ testOldContactQueueShortLink ps@(_, msType) = withAgentClients2 $ \a b -> do userCtData' `shouldBe` userCtData -- update user data let updatedData = UserLinkData "updated user data" - updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData} + updatedCtData = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedData, ratchetKeys = Nothing} userLinkData' = UserContactLinkData updatedCtData shortLink' <- runRight $ setConnShortLink a contactId SCMContact userLinkData' Nothing shortLink' `shouldBe` shortLink @@ -1656,7 +1701,7 @@ replaceSubstringInFile filePath oldText newText = do testPrepareCreateConnectionLink :: HasCallStack => (ASrvTransport, AStoreType) -> IO () testPrepareCreateConnectionLink ps = withSmpServer ps $ withAgentClients2 $ \a b -> do let userData = UserLinkData "test user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} userLinkData = UserContactLinkData userCtData g <- C.newRandom rootKey <- atomically $ C.generateKeyPair g @@ -1665,7 +1710,7 @@ testPrepareCreateConnectionLink ps = withSmpServer ps $ withAgentClients2 $ \a b (ccLink@(CCLink connReq (Just shortLink)), preparedParams) <- A.prepareConnectionLink a 1 rootKey linkEntId True Nothing Nothing liftIO $ strDecode (strEncode shortLink) `shouldBe` Right shortLink - _ <- A.createConnectionForLink a NRMInteractive 1 True ccLink preparedParams userLinkData CR.IKPQOn SMSubscribe + _ <- A.createConnectionForLink a NRMInteractive 1 True ccLink preparedParams userLinkData CR.IKPQOn Nothing SMSubscribe (FixedLinkData {linkConnReq = connReq', linkEntityId}, ContactLinkData _ userCtData') <- getConnShortLink b 1 shortLink liftIO $ Just linkEntId `shouldBe` linkEntityId Right connReqDecoded <- pure $ smpDecode (smpEncode connReq) @@ -2409,7 +2454,7 @@ makeConnectionForUsers_ :: HasCallStack => PQSupport -> SndQueueSecured -> Agent makeConnectionForUsers_ pqSupport sqSecured alice aliceUserId bob bobUserId = do (bobId, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive aliceUserId True True SCMInvitation Nothing Nothing (IKLinkPQ pqSupport) SMSubscribe aliceId <- A.prepareConnectionToJoin bob bobUserId True qInfo pqSupport - sqSecured' <- A.joinConnection bob NRMInteractive bobUserId aliceId True qInfo "bob's connInfo" pqSupport SMSubscribe + sqSecured' <- A.joinConnection bob NRMInteractive bobUserId aliceId True qInfo "bob's connInfo" Nothing pqSupport SMSubscribe liftIO $ sqSecured' `shouldBe` sqSecured ("", _, A.CONF confId pqSup' _ "bob's connInfo") <- get alice liftIO $ pqSup' `shouldBe` pqSupport @@ -2740,7 +2785,7 @@ testSetConnShortLinkAsync :: (ASrvTransport, AStoreType) -> IO () testSetConnShortLinkAsync ps = withAgentClients2 $ \alice bob -> withSmpServerStoreLogOn ps testPort $ \_ -> runRight_ $ do let userData = UserLinkData "test user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} newLinkData = UserContactLinkData userCtData (cId, CCLink qInfo (Just shortLink)) <- A.createConnection alice NRMInteractive 1 True True SCMContact (Just newLinkData) Nothing IKPQOn SMSubscribe -- verify initial link data @@ -2748,7 +2793,7 @@ testSetConnShortLinkAsync ps = withAgentClients2 $ \alice bob -> liftIO $ userCtData' `shouldBe` userCtData -- update link data async let updatedData = UserLinkData "updated user data" - updatedCtData = UserContactData {direct = False, owners = [], relays = [], userData = updatedData} + updatedCtData = UserContactData {direct = False, owners = [], relays = [], userData = updatedData, ratchetKeys = Nothing} setConnShortLinkAsync alice "1" cId (UserContactLinkData updatedCtData) Nothing ("1", cId', LINK shortLink' (UserContactLinkData updatedCtData')) <- get alice liftIO $ cId' `shouldBe` cId @@ -2772,7 +2817,7 @@ testGetConnShortLinkAsync :: (ASrvTransport, AStoreType) -> IO () testGetConnShortLinkAsync ps = withAgentClients2 $ \alice bob -> withSmpServerStoreLogOn ps testPort $ \_ -> runRight_ $ do let userData = UserLinkData "test user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} newLinkData = UserContactLinkData userCtData (_, CCLink qInfo (Just shortLink)) <- A.createConnection alice NRMInteractive 1 True True SCMContact (Just newLinkData) Nothing IKPQOn SMSubscribe -- get link data async - creates new connection for bob @@ -3702,8 +3747,8 @@ testDeliveryReceiptsVersion ps = do subscribeConnection a' bId subscribeConnection b' aId exchangeGreetingsMsgId_ PQEncOff 4 a' bId b' aId - checkVersion a' bId 7 - checkVersion b' aId 7 + checkVersion a' bId 8 + checkVersion b' aId 8 (6, PQEncOff) <- A.sendMessage a' bId PQEncOn SMP.noMsgFlags "hello" get a' ##> ("", bId, SENT 6) get b' =##> \case ("", c, Msg' 6 PQEncOff "hello") -> c == aId; _ -> False diff --git a/tests/AgentTests/ShortLinkTests.hs b/tests/AgentTests/ShortLinkTests.hs index edffaa3d9..9ca7d2d14 100644 --- a/tests/AgentTests/ShortLinkTests.hs +++ b/tests/AgentTests/ShortLinkTests.hs @@ -80,7 +80,7 @@ testContactShortLink = do g <- C.newRandom sigKeys <- atomically $ C.generateKeyPair @'C.Ed25519 g let userData = UserLinkData "some user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} userLinkData = UserContactLinkData userCtData (linkKey, linkData) = SL.encodeSignLinkData sigKeys supportedSMPAgentVRange contactConnRequest Nothing userLinkData (_linkId, k) = SL.contactShortLinkKdf linkKey @@ -96,14 +96,14 @@ testUpdateContactShortLink = do g <- C.newRandom sigKeys <- atomically $ C.generateKeyPair @'C.Ed25519 g let userData = UserLinkData "some user data" - userCtData = UserContactData {direct = True, owners = [], relays = [], userData} + userCtData = UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} userLinkData = UserContactLinkData userCtData (linkKey, linkData) = SL.encodeSignLinkData sigKeys supportedSMPAgentVRange contactConnRequest Nothing userLinkData (_linkId, k) = SL.contactShortLinkKdf linkKey Right (fd, _ud) <- runExceptT $ SL.encryptLinkData g k linkData -- encrypt updated user data let updatedUserData = UserLinkData "updated user data" - userCtData' = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedUserData} + userCtData' = UserContactData {direct = False, owners = [], relays = [relayLink1, relayLink2], userData = updatedUserData, ratchetKeys = Nothing} userLinkData' = UserContactLinkData userCtData' signed = SL.encodeSignUserData SCMContact (snd sigKeys) supportedSMPAgentVRange userLinkData' Right ud' <- runExceptT $ SL.encryptUserData g k signed @@ -118,7 +118,7 @@ testContactShortLinkBadDataHash = do g <- C.newRandom sigKeys <- atomically $ C.generateKeyPair @'C.Ed25519 g let userData = UserLinkData "some user data" - userLinkData = UserContactLinkData UserContactData {direct = True, owners = [], relays = [], userData} + userLinkData = UserContactLinkData UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} (_linkKey, linkData) = SL.encodeSignLinkData sigKeys supportedSMPAgentVRange contactConnRequest Nothing userLinkData -- different key linkKey <- LinkKey <$> atomically (C.randomBytes 32 g) @@ -134,13 +134,13 @@ testContactShortLinkBadSignature = do g <- C.newRandom sigKeys <- atomically $ C.generateKeyPair @'C.Ed25519 g let userData = UserLinkData "some user data" - userLinkData = UserContactLinkData UserContactData {direct = True, owners = [], relays = [], userData} + userLinkData = UserContactLinkData UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} (linkKey, linkData) = SL.encodeSignLinkData sigKeys supportedSMPAgentVRange contactConnRequest Nothing userLinkData (_linkId, k) = SL.contactShortLinkKdf linkKey Right (fd, _ud) <- runExceptT $ SL.encryptLinkData g k linkData -- encrypt updated user data let updatedUserData = UserLinkData "updated user data" - userLinkData' = UserContactLinkData UserContactData {direct = True, owners = [], relays = [], userData = updatedUserData} + userLinkData' = UserContactLinkData UserContactData {direct = True, owners = [], relays = [], userData = updatedUserData, ratchetKeys = Nothing} -- another signature key (_, pk) <- atomically $ C.generateKeyPair @'C.Ed25519 g let signed = SL.encodeSignUserData SCMContact pk supportedSMPAgentVRange userLinkData' @@ -156,7 +156,7 @@ testContactShortLinkOwner = do (pk, lnk) <- encryptLink g -- encrypt updated user data (ownerPK, owner) <- authNewOwner g pk - let ud = UserContactData {direct = True, owners = [owner], relays = [], userData = UserLinkData "updated user data"} + let ud = UserContactData {direct = True, owners = [owner], relays = [], userData = UserLinkData "updated user data", ratchetKeys = Nothing} testEncDec g pk lnk ud testEncDec g ownerPK lnk ud (_, wrongKey) <- atomically $ C.generateKeyPair @'C.Ed25519 g @@ -166,7 +166,7 @@ encryptLink :: TVar ChaChaDRG -> IO (C.PrivateKeyEd25519, (EncFixedDataBytes, Li encryptLink g = do sigKeys@(_, pk) <- atomically $ C.generateKeyPair @'C.Ed25519 g let userData = UserLinkData "some user data" - userLinkData = UserContactLinkData UserContactData {direct = True, owners = [], relays = [], userData} + userLinkData = UserContactLinkData UserContactData {direct = True, owners = [], relays = [], userData, ratchetKeys = Nothing} (linkKey, linkData) = SL.encodeSignLinkData sigKeys supportedSMPAgentVRange contactConnRequest Nothing userLinkData (_linkId, k) = SL.contactShortLinkKdf linkKey Right (fd, _ud) <- runExceptT $ SL.encryptLinkData g k linkData @@ -199,7 +199,7 @@ testContactShortLinkManyOwners = do (ownerPK4, owner4) <- authNewOwner g ownerPK1 (ownerPK5, owner5) <- authNewOwner g ownerPK3 let owners = [owner1, owner2, owner3, owner4, owner5] - ud = UserContactData {direct = True, owners, relays = [], userData = UserLinkData "updated user data"} + ud = UserContactData {direct = True, owners, relays = [], userData = UserLinkData "updated user data", ratchetKeys = Nothing} testEncDec g pk lnk ud testEncDec g ownerPK1 lnk ud testEncDec g ownerPK2 lnk ud @@ -216,7 +216,7 @@ testContactShortLinkInvalidOwners = do (pk, lnk) <- encryptLink g -- encrypt updated user data (ownerPK, owner) <- authNewOwner g pk - let mkCtData owners = UserContactData {direct = True, owners, relays = [], userData = UserLinkData "updated user data"} + let mkCtData owners = UserContactData {direct = True, owners, relays = [], userData = UserLinkData "updated user data", ratchetKeys = Nothing} -- decryption fails: owner uses root key let ud = mkCtData [owner {ownerKey = C.publicKey pk}] err = A_LINK $ "owner key for ID " <> ownerIdStr owner <> " matches root key" diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 88525eac0..1a928a836 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -234,7 +234,7 @@ agentDeliverMessageViaProxy aTestCfg@(aSrvs, _, aViaProxy) bTestCfg@(bSrvs, _, b withAgent 2 aCfg (servers bTestCfg) testDB2 $ \bob -> runRight_ $ do (bobId, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive 1 True True SCMInvitation Nothing Nothing CR.IKPQOn SMSubscribe aliceId <- A.prepareConnectionToJoin bob 1 True qInfo PQSupportOn - sqSecured <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" PQSupportOn SMSubscribe + sqSecured <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" Nothing PQSupportOn SMSubscribe liftIO $ sqSecured `shouldBe` True ("", _, A.CONF confId pqSup' _ "bob's connInfo") <- get alice liftIO $ pqSup' `shouldBe` PQSupportOn @@ -290,7 +290,7 @@ agentDeliverMessagesViaProxyConc agentServers msgs = prePair alice bob = do (bobId, CCLink qInfo Nothing) <- runExceptT' $ A.createConnection alice NRMInteractive 1 True True SCMInvitation Nothing Nothing CR.IKPQOn SMSubscribe aliceId <- runExceptT' $ A.prepareConnectionToJoin bob 1 True qInfo PQSupportOn - sqSecured <- runExceptT' $ A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" PQSupportOn SMSubscribe + sqSecured <- runExceptT' $ A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" Nothing PQSupportOn SMSubscribe liftIO $ sqSecured `shouldBe` True confId <- get alice >>= \case @@ -341,7 +341,7 @@ agentViaProxyVersionError = withAgent 2 agentCfg (servers [SMPServer testHost2 testPort2 testKeyHash]) testDB2 $ \bob -> runExceptT $ do (_bobId, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive 1 True True SCMInvitation Nothing Nothing CR.IKPQOn SMSubscribe aliceId <- A.prepareConnectionToJoin bob 1 True qInfo PQSupportOn - A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" PQSupportOn SMSubscribe + A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" Nothing PQSupportOn SMSubscribe pure () where servers srvs = (initAgentServersProxy_ SPMUnknown SPFProhibit) {smp = userServers srvs} @@ -361,7 +361,7 @@ agentViaProxyRetryOffline = do (aliceId, bobId) <- withServer2 $ \_ -> runRight $ do (bobId, CCLink qInfo Nothing) <- A.createConnection alice NRMInteractive 1 True True SCMInvitation Nothing Nothing CR.IKPQOn SMSubscribe aliceId <- A.prepareConnectionToJoin bob 1 True qInfo PQSupportOn - sqSecured <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" PQSupportOn SMSubscribe + sqSecured <- A.joinConnection bob NRMInteractive 1 aliceId True qInfo "bob's connInfo" Nothing PQSupportOn SMSubscribe liftIO $ sqSecured `shouldBe` True ("", _, A.CONF confId pqSup' _ "bob's connInfo") <- get alice liftIO $ pqSup' `shouldBe` PQSupportOn