From 0393b069beecb6895e66dd7023fa74e303f05811 Mon Sep 17 00:00:00 2001 From: Marat Alekperov Date: Mon, 16 Nov 2026 02:31:03 +0300 Subject: [PATCH 1/2] Add UTS specs for encryption (RSE1, RSE2, RSL5) - rest/unit/encoding/crypto.md: Crypto::getDefaultParams (RSE1a-e: the defaults, keyLength from the key, base64 and base64url keys, invalid and inconsistent key lengths) and Crypto::generateRandomKey (RSE2a-b). - realtime/unit/channels/channel_encryption.md: the RSL5c tests over ably-common's crypto-data-128.json and crypto-data-256.json. Publishing encrypts to the fixtures over JSON and MessagePack (RTL6a), subscribing and history decrypt them (RTL7d, RSL6a), a channel without a cipher delivers the payload still encrypted and logs an error (RSL6b), and a CipherParamOptions cipher is resolved with getDefaultParams (TB2b2). Encrypting reproduces the fixtures through a set_fixed_iv test hook. - completion-status.md and the README's file counts are updated. Co-Authored-By: Claude Opus 5.5 --- uts/README.md | 6 +- uts/docs/completion-status.md | 14 +- .../unit/channels/channel_encryption.md | 514 ++++++++++++++++++ uts/rest/unit/encoding/crypto.md | 245 +++++++++ 4 files changed, 769 insertions(+), 10 deletions(-) create mode 100644 uts/realtime/unit/channels/channel_encryption.md create mode 100644 uts/rest/unit/encoding/crypto.md diff --git a/uts/README.md b/uts/README.md index 8cc4d9b9d..19bd85ccb 100644 --- a/uts/README.md +++ b/uts/README.md @@ -43,13 +43,13 @@ uts/ | Category | Count | Description | |----------|-------|-------------| -| REST unit | 40 | Mocked HTTP client tests | +| REST unit | 41 | Mocked HTTP client tests | | REST integration | 11 | Ably sandbox tests | -| Realtime unit | 54 | Mocked WebSocket tests | +| Realtime unit | 55 | Mocked WebSocket tests | | Realtime integration (direct) | 13 | Direct sandbox tests | | Realtime integration (proxy) | 7 | Fault injection via Go proxy | | Helper specs | 4 | Mock infrastructure definitions | -| **Total** | **129** | | +| **Total** | **131** | | ## Three Test Tiers diff --git a/uts/docs/completion-status.md b/uts/docs/completion-status.md index 8ce03db1f..428539fd7 100644 --- a/uts/docs/completion-status.md +++ b/uts/docs/completion-status.md @@ -91,7 +91,7 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | RSL2 | History function (RSL2a–RSL2b3) | Yes — `rest/unit/channel/history.md`, `rest/integration/history.md` | | RSL3 | Presence attribute | Yes — `rest/unit/presence/rest_presence.md` (with RSP1a) | | RSL4 | Message encoding (RSL4a–RSL4d4) | Yes — `rest/unit/encoding/message_encoding.md`, `realtime/integration/channels/channel_publish_test.md` | -| RSL5 | Message encryption (RSL5a–RSL5c) | | +| RSL5 | Message encryption (RSL5a–RSL5c) | Yes — `realtime/unit/channels/channel_encryption.md` (through `RealtimeChannel`, RTL6a and RTL7d, with the ably-common crypto fixtures) | | RSL6 | Message decoding (RSL6a–RSL6b) | Yes — `rest/unit/encoding/message_encoding.md`, `realtime/integration/channels/channel_publish_test.md` covers RSL6, RSL6a2 | | RSL7 | SetOptions function | Yes — `rest/unit/channel/rest_channel_attributes.md` | | RSL8 | Status function (RSL8a) | Yes — `rest/unit/channel/rest_channel_attributes.md` | @@ -123,8 +123,8 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | Spec item | Description | UTS test spec | |-----------|-------------|---------------| -| RSE1 | Crypto::getDefaultParams (RSE1a–RSE1e) | | -| RSE2 | Crypto::generateRandomKey (RSE2a–RSE2b) | | +| RSE1 | Crypto::getDefaultParams (RSE1a–RSE1e) | Yes — `rest/unit/encoding/crypto.md` | +| RSE2 | Crypto::generateRandomKey (RSE2a–RSE2b) | Yes — `rest/unit/encoding/crypto.md` | ### RestAnnotations @@ -360,8 +360,8 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | AO1–AO2 | AuthOptions | Yes — `rest/unit/types/options_types.md` | | TB1–TB4 | ChannelOptions | Yes — `realtime/unit/channels/channel_options.md` | | DO1–DO2 | DeriveOptions | Yes — `realtime/unit/channels/channel_options.md` | -| TZ1–TZ2 | CipherParams | | -| CO1–CO2 | CipherParamOptions | | +| TZ1–TZ2 | CipherParams | Yes — `rest/unit/encoding/crypto.md` | +| CO1–CO2 | CipherParamOptions | Yes — `rest/unit/encoding/crypto.md`, `realtime/unit/channels/channel_encryption.md` (TB2b2) | | WPO1–WPO2 | WrapperSDKProxyOptions | | ### Push Notification Types @@ -436,7 +436,7 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | **REST channels** (RSN) | 4 | 4 | Full | | **REST channel** (RSL) | 13 | 13 | Full | | **REST presence** (RSP) | 5 | 4 | Mostly | -| **REST encryption** (RSE) | 2 | 0 | None | +| **REST encryption** (RSE) | 2 | 2 | Full | | **REST annotations** (RSAN) | 3 | 3 | Full | | **Realtime client** (RTC) | 14 | 14 | Full | | **Connection** (RTN) | 23 | 19 | Partial | @@ -450,7 +450,7 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | **Push notifications** (RSH) | 8 | 1 | Partial | | **Plugins** (PC/PT/VD) | 3 | 2 | Partial | | **Data types** | 30 | 12 | Partial | -| **Option types** | 8 | 5 | Partial | +| **Option types** | 8 | 7 | Mostly | | **Push types** | 3 | 0 | None | | **Introspection** (CR) | 1 | 0 | None | | **Defaults** (DF) | 1 | 0 | None | diff --git a/uts/realtime/unit/channels/channel_encryption.md b/uts/realtime/unit/channels/channel_encryption.md new file mode 100644 index 000000000..7c942d8cd --- /dev/null +++ b/uts/realtime/unit/channels/channel_encryption.md @@ -0,0 +1,514 @@ +# RealtimeChannel Encryption Tests + +Spec points: `RSL5`, `RSL5a`, `RSL5b`, `RSL5c`, `RTL6a`, `RTL7d`, `RSL6a`, `RSL6b`, `TB2b`, `TB2b1`, `TB2b2` + +## Test Type +Unit test with mocked WebSocket (and, for history, a mocked HTTP client) + +## Mock WebSocket Infrastructure + +See `uts/realtime/unit/helpers/mock_websocket.md` for the full Mock WebSocket Infrastructure specification, and +`uts/rest/unit/helpers/mock_http.md` for the HTTP mock. + +## Fixtures + +RSL5c requires these tests to use the ably-common fixtures +[`test-resources/crypto-data-128.json`](https://github.com/ably/ably-common/blob/main/test-resources/crypto-data-128.json) and +[`test-resources/crypto-data-256.json`](https://github.com/ably/ably-common/blob/main/test-resources/crypto-data-256.json). +`load_fixtures(name)` reads one, with these fields: + +| Field | Meaning | +|-------|---------| +| `algorithm`, `mode`, `keylength` | `aes`, `cbc`, and 128 or 256 | +| `key` | the key, base64 | +| `iv` | the initialization vector every item was encrypted with, base64 | +| `items[]` | the messages | +| `items[].encoded` | a message as the publisher passes it: `name`, `data`, and an `encoding` of `base64` (binary data) or `json` (a JSON object or array), or none (a string) | +| `items[].encrypted` | the same message on the wire over the JSON protocol: `name`, base64 ciphertext `data`, and `encoding` (e.g. `utf-8/cipher+aes-128-cbc/base64`) | +| `items[].msgpack` | the same message on the wire over MessagePack, base64 of its msgpack encoding: binary ciphertext `data` and `encoding` without the final `/base64` (e.g. `utf-8/cipher+aes-128-cbc`) | + +Test harness helpers: + +- **`fixture_data(fixture_message)`** — the `data` a publisher passes for an `items[].encoded` message: the string + itself with no `encoding`, `base64_decode(data)` for `base64`, and `parse_json(data)` for `json`. +- **`fixture_cipher_params(fixture)`** — `Crypto.getDefaultParams(CipherParamOptions(key: fixture.key, algorithm: + fixture.algorithm, mode: fixture.mode))`, with `set_fixed_iv(params, base64_decode(fixture.iv))` applied. +- **`set_fixed_iv(cipher_params, iv)`** — the test hook that makes an encryption deterministic. The features spec + has the IV come from a secure random source for every message, and TZ2 lets `CipherParams` carry "anything necessary + to implement the supported algorithms", so how a test fixes the IV is SDK-specific (e.g. an internal `iv` attribute). + Encrypting the fixture items with the fixture's IV must reproduce the fixture's ciphertext exactly. + +Every test runs over both fixtures, `crypto-data-128.json` and `crypto-data-256.json`, which covers RSL5b +(AES-128 and AES-256 CBC). + +--- + +## RSL5c, RTL6a - Published messages are encrypted to the fixture data (JSON) + +**Test ID**: `realtime/unit/RSL5c/publish-encrypts-fixtures-json-0` + +| Spec | Requirement | +|------|-------------| +| RSL5a | With a `cipher` channel option, message payloads are encrypted when sent to Ably | +| RSL5b | AES 256 and 128 CBC encryption must be supported | +| RSL5c | Tests must exist that encrypt and decrypt the ably-common fixture data for AES 128 and AES 256 | +| RTL6a | Messages are encoded in the same way as the `RestChannel#publish` method | + +Tests that publishing each fixture item on a channel with the fixture's cipher sends the fixture's `encrypted` data +and encoding over the JSON protocol. + +### Setup +```pseudo +fixture_files = ["crypto-data-128.json", "crypto-data-256.json"] +``` + +### Test Steps and Assertions +```pseudo +FOR EACH fixture_file IN fixture_files: + fixture = load_fixtures(fixture_file) + channel_name = "test-RSL5c-json-${random_id()}" + captured_messages = [] + + mock_ws = MockWebSocket( + onConnectionAttempt: (conn) => conn.respond_with_success(CONNECTED_MESSAGE), + onMessageFromClient: (msg) => { + IF msg.action == ATTACH: + mock_ws.send_to_client(ProtocolMessage(action: ATTACHED, channel: channel_name)) + ELSE IF msg.action == MESSAGE: + captured_messages.append(msg.messages[0]) + mock_ws.send_to_client(ProtocolMessage(action: ACK, msgSerial: msg.msgSerial, count: 1)) + } + ) + install_mock(mock_ws) + + client = Realtime(options: ClientOptions( + key: "appId.keyId:keySecret", + autoConnect: false, + useBinaryProtocol: false + )) + channel = client.channels.get(channel_name, RealtimeChannelOptions( + cipher: fixture_cipher_params(fixture), + attachOnSubscribe: false + )) + + client.connect() + AWAIT_STATE client.connection.state == ConnectionState.connected + AWAIT channel.attach() + + FOR EACH item IN fixture.items: + AWAIT channel.publish(name: item.encoded.name, data: fixture_data(item.encoded)) + + ASSERT length(captured_messages) == length(fixture.items) + FOR i IN 0..length(fixture.items) - 1: + item = fixture.items[i] + ASSERT captured_messages[i].name == item.encrypted.name + ASSERT captured_messages[i].data == item.encrypted.data + ASSERT captured_messages[i].encoding == item.encrypted.encoding + + CLOSE_CLIENT(client) +``` + +--- + +## RSL5c, RTL6a - Published messages are encrypted to the fixture data (MessagePack) + +**Test ID**: `realtime/unit/RSL5c/publish-encrypts-fixtures-msgpack-1` + +| Spec | Requirement | +|------|-------------| +| RSL5a | With a `cipher` channel option, message payloads are encrypted when sent to Ably | +| RSL5c | Tests must exist that encrypt and decrypt the ably-common fixture data for AES 128 and AES 256 | +| RSL4c | Over MessagePack, binary data is sent as is | + +Tests that over MessagePack the ciphertext is sent as binary, with no final `base64` step in the encoding, matching +each item's `msgpack` form. + +### Setup +```pseudo +fixture_files = ["crypto-data-128.json", "crypto-data-256.json"] +``` + +### Test Steps and Assertions +```pseudo +FOR EACH fixture_file IN fixture_files: + fixture = load_fixtures(fixture_file) + channel_name = "test-RSL5c-msgpack-${random_id()}" + captured_messages = [] + + mock_ws = MockWebSocket( + onConnectionAttempt: (conn) => conn.respond_with_success(CONNECTED_MESSAGE), + onMessageFromClient: (msg) => { + IF msg.action == ATTACH: + mock_ws.send_to_client(ProtocolMessage(action: ATTACHED, channel: channel_name)) + ELSE IF msg.action == MESSAGE: + mock_ws.send_to_client(ProtocolMessage(action: ACK, msgSerial: msg.msgSerial, count: 1)) + }, + onBinaryDataFrame: (bytes) => { + decoded = MSGPACK_DECODE(bytes) + IF decoded["action"] == MESSAGE_ACTION_INT: + captured_messages.append(decoded["messages"][0]) + } + ) + install_mock(mock_ws) + + client = Realtime(options: ClientOptions( + key: "appId.keyId:keySecret", + autoConnect: false, + useBinaryProtocol: true + )) + channel = client.channels.get(channel_name, RealtimeChannelOptions( + cipher: fixture_cipher_params(fixture), + attachOnSubscribe: false + )) + + client.connect() + AWAIT_STATE client.connection.state == ConnectionState.connected + AWAIT channel.attach() + + FOR EACH item IN fixture.items: + AWAIT channel.publish(name: item.encoded.name, data: fixture_data(item.encoded)) + + ASSERT length(captured_messages) == length(fixture.items) + FOR i IN 0..length(fixture.items) - 1: + expected = MSGPACK_DECODE(base64_decode(fixture.items[i].msgpack)) + ASSERT captured_messages[i]["name"] == expected["name"] + ASSERT captured_messages[i]["data"] IS Binary + ASSERT captured_messages[i]["data"] == expected["data"] + ASSERT captured_messages[i]["encoding"] == expected["encoding"] + + CLOSE_CLIENT(client) +``` + +--- + +## RSL5c, RTL7d - Received messages are decrypted from the fixture data (JSON) + +**Test ID**: `realtime/unit/RTL7d/subscribe-decrypts-fixtures-json-0` + +| Spec | Requirement | +|------|-------------| +| RSL5a | With a `cipher` channel option, message payloads are decrypted when received on the channel | +| RSL5c | Tests must exist that encrypt and decrypt the ably-common fixture data for AES 128 and AES 256 | +| RTL7d | Messages delivered are automatically decoded based on the `encoding` attribute; tests should exist to publish and subscribe to encoded messages using the RSL5c fixture data | + +Tests that each fixture item's `encrypted` message, received over the JSON protocol, is delivered to a subscriber +with the publisher's original `data` and no remaining `encoding`. + +### Setup +```pseudo +fixture_files = ["crypto-data-128.json", "crypto-data-256.json"] +``` + +### Test Steps and Assertions +```pseudo +FOR EACH fixture_file IN fixture_files: + fixture = load_fixtures(fixture_file) + channel_name = "test-RTL7d-json-${random_id()}" + received_messages = [] + + mock_ws = MockWebSocket( + onConnectionAttempt: (conn) => conn.respond_with_success(CONNECTED_MESSAGE), + onMessageFromClient: (msg) => { + IF msg.action == ATTACH: + mock_ws.send_to_client(ProtocolMessage(action: ATTACHED, channel: channel_name)) + } + ) + install_mock(mock_ws) + + client = Realtime(options: ClientOptions( + key: "appId.keyId:keySecret", + autoConnect: false, + useBinaryProtocol: false + )) + channel = client.channels.get(channel_name, RealtimeChannelOptions( + cipher: fixture_cipher_params(fixture), + attachOnSubscribe: false + )) + channel.subscribe((message) => received_messages.append(message)) + + client.connect() + AWAIT_STATE client.connection.state == ConnectionState.connected + AWAIT channel.attach() + + FOR EACH item IN fixture.items: + mock_ws.send_to_client(ProtocolMessage( + action: MESSAGE, + channel: channel_name, + messages: [Message.fromJson(item.encrypted)] + )) + + poll_until(() => length(received_messages) == length(fixture.items), timeout: 5 seconds) + + FOR i IN 0..length(fixture.items) - 1: + item = fixture.items[i] + ASSERT received_messages[i].name == item.encoded.name + ASSERT received_messages[i].data == fixture_data(item.encoded) + ASSERT received_messages[i].encoding == null + + CLOSE_CLIENT(client) +``` + +--- + +## RSL5c, RTL7d - Received messages are decrypted from the fixture data (MessagePack) + +**Test ID**: `realtime/unit/RTL7d/subscribe-decrypts-fixtures-msgpack-1` + +| Spec | Requirement | +|------|-------------| +| RSL5a | With a `cipher` channel option, message payloads are decrypted when received on the channel | +| RSL5c | Tests must exist that encrypt and decrypt the ably-common fixture data for AES 128 and AES 256 | +| RTL7d | Messages delivered are automatically decoded based on the `encoding` attribute | + +Tests that each fixture item's `msgpack` message, with binary ciphertext, received over MessagePack is delivered with +the publisher's original `data`. + +### Setup +```pseudo +fixture_files = ["crypto-data-128.json", "crypto-data-256.json"] +``` + +### Test Steps and Assertions +```pseudo +FOR EACH fixture_file IN fixture_files: + fixture = load_fixtures(fixture_file) + channel_name = "test-RTL7d-msgpack-${random_id()}" + received_messages = [] + + mock_ws = MockWebSocket( + onConnectionAttempt: (conn) => conn.respond_with_success(CONNECTED_MESSAGE), + onMessageFromClient: (msg) => { + IF msg.action == ATTACH: + mock_ws.send_to_client(ProtocolMessage(action: ATTACHED, channel: channel_name)) + } + ) + install_mock(mock_ws) + + client = Realtime(options: ClientOptions( + key: "appId.keyId:keySecret", + autoConnect: false, + useBinaryProtocol: true + )) + channel = client.channels.get(channel_name, RealtimeChannelOptions( + cipher: fixture_cipher_params(fixture), + attachOnSubscribe: false + )) + channel.subscribe((message) => received_messages.append(message)) + + client.connect() + AWAIT_STATE client.connection.state == ConnectionState.connected + AWAIT channel.attach() + + FOR EACH item IN fixture.items: + # The wire message as MessagePack carries it: binary ciphertext, encoding without the final base64 + wire_message = MSGPACK_DECODE(base64_decode(item.msgpack)) + mock_ws.send_to_client(ProtocolMessage( + action: MESSAGE, + channel: channel_name, + messages: [Message.fromJson(wire_message)] + )) + + poll_until(() => length(received_messages) == length(fixture.items), timeout: 5 seconds) + + FOR i IN 0..length(fixture.items) - 1: + item = fixture.items[i] + ASSERT received_messages[i].name == item.encoded.name + ASSERT received_messages[i].data == fixture_data(item.encoded) + ASSERT received_messages[i].encoding == null + + CLOSE_CLIENT(client) +``` + +--- + +## RSL6a - History messages are decrypted from the fixture data + +**Test ID**: `realtime/unit/RSL6a/history-decrypts-fixtures-0` + +| Spec | Requirement | +|------|-------------| +| RSL6a | All messages received will be decoded automatically based on the `encoding` field, applying the decryption rules of RSL5 | +| RSL5a | With a `cipher` channel option, message payloads are decrypted when received on the channel | +| RTL10 | `RealtimeChannel#history` returns messages from the REST history endpoint | + +Tests that a history page of fixture `encrypted` messages is returned decrypted. + +### Setup +```pseudo +fixture_files = ["crypto-data-128.json", "crypto-data-256.json"] +``` + +### Test Steps and Assertions +```pseudo +FOR EACH fixture_file IN fixture_files: + fixture = load_fixtures(fixture_file) + channel_name = "test-RSL6a-history-${random_id()}" + + mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + req.respond_with(200, fixture.items.map(item => item.encrypted), headers: {"Content-Type": "application/json"}) + } + ) + install_mock(mock_http) + + client = Realtime(options: ClientOptions( + key: "appId.keyId:keySecret", + autoConnect: false, + useBinaryProtocol: false + )) + channel = client.channels.get(channel_name, RealtimeChannelOptions(cipher: fixture_cipher_params(fixture))) + + result = AWAIT channel.history() + + ASSERT length(result.items) == length(fixture.items) + FOR i IN 0..length(fixture.items) - 1: + item = fixture.items[i] + ASSERT result.items[i].name == item.encoded.name + ASSERT result.items[i].data == fixture_data(item.encoded) + ASSERT result.items[i].encoding == null + + CLOSE_CLIENT(client) +``` + +--- + +## RSL6b - An encrypted message is delivered still encrypted without a cipher + +**Test ID**: `realtime/unit/RSL6b/no-cipher-delivers-encrypted-0` + +**Spec requirement:** If, for example, incompatible encryption details are provided or invalid Base64 is detected in the message payload, an error message will be sent to the logger, but the message will still be delivered with last successful decoding and the `encoding` field. For example, if a message had a decoding of "utf-8/cipher+aes-128-cbc/base64", and the payload was successfully Base64 decoded but the payload could not be decrypted because the `CipherParam` details were not configured, the message would be delivered with the binary payload and an `encoding` of "utf-8/cipher+aes-128-cbc". + +Tests that a channel with no `cipher` delivers an encrypted message with its base64 decoded and the rest of its +encoding kept, and logs an error. + +### Setup +```pseudo +fixture = load_fixtures("crypto-data-256.json") +item = fixture.items[0] # a string: encoding "utf-8/cipher+aes-256-cbc/base64" +channel_name = "test-RSL6b-${random_id()}" +received_messages = [] +captured_log_messages = [] + +log_handler = FUNCTION(level, message): + captured_log_messages.append({level: level, message: message}) + +mock_ws = MockWebSocket( + onConnectionAttempt: (conn) => conn.respond_with_success(CONNECTED_MESSAGE), + onMessageFromClient: (msg) => { + IF msg.action == ATTACH: + mock_ws.send_to_client(ProtocolMessage(action: ATTACHED, channel: channel_name)) + } +) +install_mock(mock_ws) + +client = Realtime(options: ClientOptions( + key: "appId.keyId:keySecret", + autoConnect: false, + useBinaryProtocol: false, + logHandler: log_handler, + logLevel: LOG_ERROR +)) +channel = client.channels.get(channel_name, RealtimeChannelOptions(attachOnSubscribe: false)) # no cipher +channel.subscribe((message) => received_messages.append(message)) +``` + +### Test Steps +```pseudo +client.connect() +AWAIT_STATE client.connection.state == ConnectionState.connected +AWAIT channel.attach() + +mock_ws.send_to_client(ProtocolMessage( + action: MESSAGE, + channel: channel_name, + messages: [Message.fromJson(item.encrypted)] +)) + +poll_until(() => length(received_messages) == 1, timeout: 5 seconds) +``` + +### Assertions +```pseudo +ASSERT received_messages[0].name == item.encrypted.name +ASSERT received_messages[0].data IS Binary +ASSERT received_messages[0].data == base64_decode(item.encrypted.data) +ASSERT received_messages[0].encoding == "utf-8/cipher+aes-256-cbc" + +ASSERT captured_log_messages.any(m => m.level == LOG_ERROR) == true +CLOSE_CLIENT(client) +``` + +--- + +## TB2b2 - A CipherParamOptions cipher option is resolved with getDefaultParams + +**Test ID**: `realtime/unit/TB2b2/cipher-param-options-0` + +| Spec | Requirement | +|------|-------------| +| TB2b | `cipher` is either a `CipherParams` instance or a `CipherParamOptions` instance | +| TB2b2 | For a `CipherParamOptions` instance, the client library should call `getDefaultParams`, passing it the options hash, to obtain a `CipherParams` instance | + +Tests that a channel whose `cipher` option is a `CipherParamOptions` holding only a base64 key encrypts what it +publishes with AES at that key's length, and decrypts it again when the server delivers it back. + +The IV here is random (no test hook can reach the `CipherParams` the SDK derives), so the ciphertext is checked +by its shape and by the round trip rather than against the fixture. + +### Setup +```pseudo +fixture = load_fixtures("crypto-data-256.json") +channel_name = "test-TB2b2-${random_id()}" +published_messages = [] +received_messages = [] + +mock_ws = MockWebSocket( + onConnectionAttempt: (conn) => conn.respond_with_success(CONNECTED_MESSAGE), + onMessageFromClient: (msg) => { + IF msg.action == ATTACH: + mock_ws.send_to_client(ProtocolMessage(action: ATTACHED, channel: channel_name)) + ELSE IF msg.action == MESSAGE: + published_messages.append(msg.messages[0]) + mock_ws.send_to_client(ProtocolMessage(action: ACK, msgSerial: msg.msgSerial, count: 1)) + # Deliver the published message back to the channel, as Ably would + mock_ws.send_to_client(ProtocolMessage(action: MESSAGE, channel: channel_name, messages: msg.messages)) + } +) +install_mock(mock_ws) + +client = Realtime(options: ClientOptions( + key: "appId.keyId:keySecret", + autoConnect: false, + useBinaryProtocol: false +)) +channel = client.channels.get(channel_name, RealtimeChannelOptions( + cipher: CipherParamOptions(key: fixture.key), # base64 string; algorithm, mode and keyLength from the defaults + attachOnSubscribe: false +)) +channel.subscribe((message) => received_messages.append(message)) +``` + +### Test Steps +```pseudo +client.connect() +AWAIT_STATE client.connection.state == ConnectionState.connected +AWAIT channel.attach() + +AWAIT channel.publish(name: "example", data: "The quick brown fox jumped over the lazy dog") +poll_until(() => length(received_messages) == 1, timeout: 5 seconds) +``` + +### Assertions +```pseudo +# Encrypted on the wire with AES-256-CBC: a 16-byte IV followed by whole 16-byte blocks +ASSERT published_messages[0].encoding == "utf-8/cipher+aes-256-cbc/base64" +ciphertext = base64_decode(published_messages[0].data) +ASSERT length(ciphertext) > 16 +ASSERT length(ciphertext) % 16 == 0 + +# Decrypted again on delivery +ASSERT received_messages[0].data == "The quick brown fox jumped over the lazy dog" +ASSERT received_messages[0].encoding == null +CLOSE_CLIENT(client) +``` diff --git a/uts/rest/unit/encoding/crypto.md b/uts/rest/unit/encoding/crypto.md new file mode 100644 index 000000000..f3ea6660a --- /dev/null +++ b/uts/rest/unit/encoding/crypto.md @@ -0,0 +1,245 @@ +# Crypto Tests + +Spec points: `RSE1`, `RSE1a`, `RSE1b`, `RSE1c`, `RSE1d`, `RSE1e`, `RSE2`, `RSE2a`, `RSE2b`, `TZ2a`, `TZ2b`, `TZ2c`, `TZ2d`, `CO2` + +## Test Type +Unit test — no network or mock transport is involved. `Crypto` here is the SDK's `Crypto` utility (RSE): whatever +the SDK exposes `Crypto::getDefaultParams` and `Crypto::generateRandomKey` on. + +## Notes + +- **Algorithm and mode names.** TZ2a and TZ2c give the defaults as `AES` and `CBC`. SDKs differ in the case they + report them in (`AES` / `aes`), and the `encoding` string uses lower case (`cipher+aes-256-cbc`), so these tests + compare the names case-insensitively with `lowercase(...)`. +- **`base64_decode(s)`** decodes a standard (RFC 4648 §4) base64 string to bytes; **`bytes_of_length(n)`** is any + `n`-byte binary value. + +--- + +## RSE1a, RSE1b, RSE1d, TZ2 - getDefaultParams fills in the defaults + +**Test ID**: `rest/unit/RSE1a/default-params-0` + +| Spec | Requirement | +|------|-------------| +| RSE1a | Returns a complete `CipherParams` instance, using the default values for any field not supplied | +| RSE1b | Takes a `CipherParamOptions` instance | +| RSE1d | Calculates a `keyLength` from the key (its size in bits) | +| TZ2a | `algorithm` defaults to `AES` | +| TZ2c | `mode` defaults to `CBC` | + +Tests that `getDefaultParams` given only a key returns AES-CBC parameters with the key and its length. + +### Setup +```pseudo +key = bytes_of_length(32) +``` + +### Test Steps +```pseudo +params = Crypto.getDefaultParams(CipherParamOptions(key: key)) +``` + +### Assertions +```pseudo +ASSERT lowercase(params.algorithm) == "aes" +ASSERT lowercase(params.mode) == "cbc" +ASSERT params.keyLength == 256 +ASSERT params.key == key +``` + +--- + +## RSE1d - keyLength is calculated from a 128-bit key + +**Test ID**: `rest/unit/RSE1d/key-length-from-key-0` + +**Spec requirement:** Calculates a `keyLength` from the key (its size in bits). + +Tests that a 16-byte key gives a `keyLength` of 128. + +### Setup +```pseudo +key = bytes_of_length(16) +``` + +### Test Steps +```pseudo +params = Crypto.getDefaultParams(CipherParamOptions(key: key)) +``` + +### Assertions +```pseudo +ASSERT params.keyLength == 128 +ASSERT params.key == key +``` + +--- + +## RSE1c - A base64-encoded string key is decoded + +**Test ID**: `rest/unit/RSE1c/base64-string-key-0` + +**Spec requirement:** The `key` must be either a binary or a base64-encoded string. If the key is a string, the function should base64-decode it into a binary. + +Tests that a key given as a base64 string is decoded, and its length calculated from the decoded bytes. + +### Setup +```pseudo +key_string = "o9qXZoPGDNla50VnRwH7cGqIrpyagTxGsRgimKJbY40=" # 32 bytes, ably-common crypto-data-256.json +``` + +### Test Steps +```pseudo +params = Crypto.getDefaultParams(CipherParamOptions(key: key_string)) +``` + +### Assertions +```pseudo +ASSERT params.key == base64_decode(key_string) +ASSERT params.keyLength == 256 +``` + +--- + +## RSE1c - A base64url string key is decoded leniently + +**Test ID**: `rest/unit/RSE1c/base64url-string-key-1` + +**Spec requirement:** Since the conversion to base64 is not under Ably control, this should be done leniently --- in particular, it should work with base64url (RFC 4648 s.5, which uses `-` and `_` instead of `+` and `/`) as well as base64 (RFC 4648 s.4). + +Tests that the same key gives the same `CipherParams` whether it is base64- or base64url-encoded. The key's bytes +are chosen so that its base64 form contains `+` and `/`. + +### Setup +```pseudo +base64_key = "+/+/+/+/+/+/+/+/+/+/+w==" # 16 bytes: fb ff bf fb ff bf … fb +base64url_key = "-_-_-_-_-_-_-_-_-_-_-w==" # the same bytes, base64url +``` + +### Test Steps +```pseudo +params_from_base64 = Crypto.getDefaultParams(CipherParamOptions(key: base64_key)) +params_from_base64url = Crypto.getDefaultParams(CipherParamOptions(key: base64url_key)) +``` + +### Assertions +```pseudo +ASSERT params_from_base64url.key == base64_decode(base64_key) +ASSERT params_from_base64url.key == params_from_base64.key +ASSERT params_from_base64url.keyLength == 128 +``` + +--- + +## RSE1e - An invalid key length is rejected + +**Test ID**: `rest/unit/RSE1e/invalid-key-length-0` + +**Spec requirement:** Checks that the provided options are valid and self-consistent as best it can, raises an exception if not. At a minimum, this should include checking the calculated `keyLength` is a valid key length for the encryption algorithm (for example, 128 or 256 for `AES`). + +Tests that a 20-byte (160-bit) key, which AES does not support, is rejected. + +### Setup +```pseudo +key = bytes_of_length(20) +``` + +### Test Steps +```pseudo +Crypto.getDefaultParams(CipherParamOptions(key: key)) FAILS WITH error +``` + +### Assertions +```pseudo +ASSERT error IS NOT null +``` + +--- + +## RSE1e - A keyLength inconsistent with the key is rejected + +**Test ID**: `rest/unit/RSE1e/inconsistent-key-length-1` + +**Spec requirement:** Checks that the provided options are valid and self-consistent as best it can, raises an exception if not. + +Tests that a `keyLength` that does not match the key's size (CO2c) is rejected. + +### Setup +```pseudo +key = bytes_of_length(32) # 256 bits +``` + +### Test Steps +```pseudo +Crypto.getDefaultParams(CipherParamOptions(key: key, keyLength: 128)) FAILS WITH error +``` + +### Assertions +```pseudo +ASSERT error IS NOT null +``` + +--- + +## RSE2a - generateRandomKey defaults to 256 bits + +**Test ID**: `rest/unit/RSE2a/default-key-length-0` + +**Spec requirement:** Takes an optional `keyLength` parameter, which is the length in bits of the key to be generated. If unspecified, this is equal to the default `keyLength` of the default algorithm: for `AES`, 256 bits. + +Tests that a key generated without a `keyLength` is 32 bytes long. + +### Test Steps +```pseudo +key = AWAIT Crypto.generateRandomKey() +``` + +### Assertions +```pseudo +ASSERT length(key) == 32 +``` + +--- + +## RSE2a - generateRandomKey with an explicit keyLength + +**Test ID**: `rest/unit/RSE2a/explicit-key-length-1` + +**Spec requirement:** Takes an optional `keyLength` parameter, which is the length in bits of the key to be generated. + +Tests that a 128-bit key is 16 bytes long, and is accepted by `getDefaultParams` as a 128-bit key. + +### Test Steps +```pseudo +key = AWAIT Crypto.generateRandomKey(keyLength: 128) +params = Crypto.getDefaultParams(CipherParamOptions(key: key)) +``` + +### Assertions +```pseudo +ASSERT length(key) == 16 +ASSERT params.keyLength == 128 +``` + +--- + +## RSE2b - generateRandomKey returns random binary keys + +**Test ID**: `rest/unit/RSE2b/random-binary-key-0` + +**Spec requirement:** Returns (or calls back with, if the language cryptographic randomness primitives are blocking or async) the key as a binary (e.g. a byte array, depending on the language). + +Tests that the key is binary, and that two generated keys differ. + +### Test Steps +```pseudo +key1 = AWAIT Crypto.generateRandomKey() +key2 = AWAIT Crypto.generateRandomKey() +``` + +### Assertions +```pseudo +ASSERT key1 IS Binary +ASSERT key1 != key2 +``` From dd18d605fd495e2e7606f3712a5ba6063e0b96c4 Mon Sep 17 00:00:00 2001 From: Marat Alekperov Date: Mon, 16 Nov 2026 02:31:03 +0300 Subject: [PATCH 2/2] TB3: compare the cipher algorithm case-insensitively TZ2a gives the default algorithm as `AES`, but realtime/unit/TB3/with-cipher-key-0 asserted "aes". SDKs report it in either case, as crypto.md's tests allow. Co-Authored-By: Claude Opus 5.5 --- uts/realtime/unit/channels/channel_options.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/uts/realtime/unit/channels/channel_options.md b/uts/realtime/unit/channels/channel_options.md index bb7d1bbb6..360faec39 100644 --- a/uts/realtime/unit/channels/channel_options.md +++ b/uts/realtime/unit/channels/channel_options.md @@ -102,7 +102,8 @@ options = RealtimeChannelOptions.withCipherKey(key) ### Assertions ```pseudo ASSERT options.cipherParams IS NOT null -ASSERT options.cipherParams.algorithm == "aes" +# TZ2a gives the default as `AES`; SDKs report it as `AES` or `aes`, so compare case-insensitively +ASSERT lowercase(options.cipherParams.algorithm) == "aes" ASSERT options.cipherParams.keyLength == 256 ```