diff --git a/changelog.d/6706-server-seal.changed.md b/changelog.d/6706-server-seal.changed.md new file mode 100644 index 0000000000..f8a986b115 --- /dev/null +++ b/changelog.d/6706-server-seal.changed.md @@ -0,0 +1,12 @@ +- **The PostgreSQL and SQL Server at-open seal of legacy plaintext sends its cells to a batching + cipher in batches, as the SQLite seal already does.** Under `vault_transit`, a surface of 200 + short legacy values was 200 Transit encrypt requests on these backends and is now 2, counted + against a fake Transit in `tests/test_server_seal_transit_batch.py`. A batch of more than one + value holds at most 128 values and 512 KiB of base64. A larger value is sent alone. The Transit + cipher can still send values one at a time in some cases; `TransitCipher.encrypt_many` states + when. A chunk cut after it starts sending every value alone holds one value, so that value's row + is written before the next request. + All three stores now write each batch's rows before encrypting the next. An in-process cipher, + such as AES-GCM, keeps each store's shape from before: SQLite writes a page per call, and the + server stores write each value before encrypting the next. The seal's transaction, + marker and rollback are unchanged. (vault `BACKLOG #6706`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 0ad1c862bd..f49934b553 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -5218,7 +5218,7 @@ reading this page already applies to a file the scan never opened. | AI broker (`[ai].endpoint`) | one POST per assist request; bounded at the API route by the `ai:assist` RBAC gate, the fail-closed `[ai].allowed_endpoints` SSRF allow-list and the 60 s per-request timeout. **There is NO per-actor pacing on `POST /ai/chat`** — it depends on plain `require(Permission.AI_ASSIST)`, not `require_paced`/`require_step_up`, so a holder of `ai:assist` can loop assist POSTs unthrottled | the LLM's own 429/503 surfaces as an `AiBrokerError` → HTTP `502` to the caller | the assist call fails; nothing is queued or retried | | DR backup destination (`[backup].destination`, ADR 0049) | **one writer** — leader-gated under `[cluster].enabled`, so exactly one node writes the shared destination; once per `schedule_at` pass plus any on-demand run. No engine-side cap: the OS/SMB redirector queues | a slow or full destination stretches the run; nothing is dropped and the next scheduled pass still fires | a failed or verify-failed run is logged + audited and is **never** counted as a good backup when pruning to `retention_keep` | | Vault Transit — store DEK unwrap (`MEFOR_STORE_VAULT_ADDR`, `[store].key_provider = vault`, ADR 0019) | one HTTPS request per DEK unwrap (startup / rotation), not per message | a failure is fail-closed — the store does not open | operator fixes Vault and restarts | -| Vault Transit — bulk at-rest cipher (`MEFOR_STORE_TRANSIT_KEY`, `[store].cipher_provider = vault_transit`, ADR 0138) | **one synchronous HTTPS round trip per encrypted cell** on store writes and reads, except where the store batches: the cipher-cell walk (`restore-verify --full`, `cipher-audit`) and the SQLite store's at-open `_seal_surface` sweep send up to `BATCH_MAX_ITEMS` cells per request (`store/crypto.py`, vault BACKLOG #6706). `_enc`/`_dec` are sync. At least the SQLite, Postgres and SQL Server message writes and queue claims hand their cell calls to the row-seal Transit pool through `row_seal.cipher_call`, which hands a call over only for a cipher that sets `blocks_on_io`, as `TransitCipher` does (BACKLOG #3929). `get_message` opens its cells off the event loop through `asyncio.to_thread`. On each of the three stores, at least content search, attachment chunk sealing and the TOTP secret reads run their cell calls off it through `asyncio.to_thread`. On the audit chain (stated here once; other documents link here), at least: one `generate_hmac` per audit row appended; one `verify_signed_data` per audit row a chain walk checks, and one of the genesis row at every open that reaches `settle_audit_ranges` holding the genesis row's key (and one more where the host key provider's store-id pin check runs); one `verify_signed_data` per one-row check, such as the Transit-bound attestation's audit row each time that attestation is read and the newest keyed audit row an AD session revocation check reads, both run off the event loop through `to_thread`; per failed `verify_signed_data`, one more `generate_hmac` (the version probe) when hvac raises the failure as `InvalidRequest`, then, unless that probe read it as a refused version or `is_vault_unavailable` reads it as an outage, one `generate_hmac` and one `verify_signed_data` over fixed input and, when those succeed, one more `verify_signed_data` of the row, and when that fails too, the fixed-input pair once more, and when both failures are an HTTP 408 or 504 the chain walk then ends with a `CipherError` while every other check reads the row as not verifying (`TransitCipher._recheck_refused_row`, `_audit_row_mac`, BACKLOG #8222); one `generate_hmac`, in place of the `verify_signed_data`, per row whose stored MAC is malformed; and one `generate_hmac` per range row whose outgoing key is held, for its handover tag, on every walk, and at every open that reaches `settle_audit_ranges` (a chain with a genesis row at seq 1, opened by a handle that holds a keying secret) unless the genesis row failed its check, in order, stopping at the first range row that fails a check (`settle_audit_ranges`). The append's `generate_hmac`, the chain walk, and at open the genesis-row verify and the range rows' handover-tag checks run on that pool through `cipher_call` (BACKLOG #3929). `rotate-key`'s handover tag goes through `cipher_call` too, but the roll reaches it only under an in-heap key, so it runs inline: a handle holding the Transit MAC has the Transit key active, the roll never closes the active key's range, and `rotate-key` refuses `vault_transit` (BACKLOG #2109). The row seals (ADR 0217) make Transit `generate_hmac` and `verify_signed_data` calls of their own, on the same pool of `TRANSIT_SEAL_WORKERS` (8) threads (`store/row_seal.py`), so a seal check can wait behind cell and audit calls. A call still on the event loop blocks the loop while it runs, and each `to_thread` call holds a thread of asyncio's default executor | Vault's own rate limit or a slow Transit **stalls the event loop across the whole engine** for each call still made on it. The `to_thread` calls can fill asyncio's default executor, which other off-loop work in the engine shares, and a call past the pool's 8, a row-seal check or a cell or audit call, waits for a free thread with no deadline. A failed cell call raises `CipherError` (a batch decrypt returns it for that cell instead), and a row-seal failure raises the row sealer's own errors (`TransitSealUnavailableError`, `TransitSealUnverifiableError`). An audit-chain call's failure raises `CipherError` too, except where `TransitCipher.verify_audit_hmac` logs it and reads the row as a break: at least the cost-only `generate_hmac` beside a malformed stored MAC, and a row `_recheck_refused_row` reads as refused; and except where a handover-tag `generate_hmac` answered with a non-empty string that is no well-formed MAC (`AuditMacMalformedError`) is logged and read as a tag that does not match in the walk (`_handover_tag_ok`), a break at that range row; the open still refuses on it (unruled, on the owner's queue; listed below), and where the open's check reaches such a row no walk runs to read it. On a stage's cell call the stage errors/dead-letters that row; at least a TOTP judgement reads it as unknown, and a content search or a TOTP secret read raises it to its caller. At open, at least these refuse the open: a `CipherError` from a cell decrypt the open makes, such as the SQLite store's state and reference cache loads; one from the genesis append's `generate_hmac` on a fresh store; one from a range row's handover-tag `generate_hmac`, `AuditMacMalformedError` included; and one the genesis row's check raises other than `AuditKeyVersionRefusedError`; for a both-asks 408 or 504 on the genesis check, that is when the fixed-input verify after the second ask also fails, and when it verifies the open logs a genesis break and opens instead (as before this change, engine PR 2903 at `686c5f7443`; unruled). A refused version, a genesis row `verify_audit_hmac` reads as a break with no raise, and a genesis verify that timed out on both asks (`AuditVerifyTimedOutError`, which `_audit_row_mac` reads there as not verifying), are logged by `settle_audit_ranges` as a break, and the store opens | the store stays open and the row is retried by the normal stage re-claim; after a refused open, the operator fixes Vault and restarts | +| Vault Transit — bulk at-rest cipher (`MEFOR_STORE_TRANSIT_KEY`, `[store].cipher_provider = vault_transit`, ADR 0138) | **one synchronous HTTPS round trip per encrypted cell** on store writes and reads, except where the store batches: the cipher-cell walk (`restore-verify --full`, `cipher-audit`) and the at-open `_seal_surface` sweep of the SQLite, Postgres and SQL Server stores send up to `BATCH_MAX_ITEMS` cells per request, while the cipher still batches (`store/crypto.py`, vault BACKLOG #6706). `_enc`/`_dec` are sync. At least the SQLite, Postgres and SQL Server message writes and queue claims hand their cell calls to the row-seal Transit pool through `row_seal.cipher_call`, which hands a call over only for a cipher that sets `blocks_on_io`, as `TransitCipher` does (BACKLOG #3929). `get_message` opens its cells off the event loop through `asyncio.to_thread`. On each of the three stores, at least content search, attachment chunk sealing and the TOTP secret reads run their cell calls off it through `asyncio.to_thread`. On the audit chain (stated here once; other documents link here), at least: one `generate_hmac` per audit row appended; one `verify_signed_data` per audit row a chain walk checks, and one of the genesis row at every open that reaches `settle_audit_ranges` holding the genesis row's key (and one more where the host key provider's store-id pin check runs); one `verify_signed_data` per one-row check, such as the Transit-bound attestation's audit row each time that attestation is read and the newest keyed audit row an AD session revocation check reads, both run off the event loop through `to_thread`; per failed `verify_signed_data`, one more `generate_hmac` (the version probe) when hvac raises the failure as `InvalidRequest`, then, unless that probe read it as a refused version or `is_vault_unavailable` reads it as an outage, one `generate_hmac` and one `verify_signed_data` over fixed input and, when those succeed, one more `verify_signed_data` of the row, and when that fails too, the fixed-input pair once more, and when both failures are an HTTP 408 or 504 the chain walk then ends with a `CipherError` while every other check reads the row as not verifying (`TransitCipher._recheck_refused_row`, `_audit_row_mac`, BACKLOG #8222); one `generate_hmac`, in place of the `verify_signed_data`, per row whose stored MAC is malformed; and one `generate_hmac` per range row whose outgoing key is held, for its handover tag, on every walk, and at every open that reaches `settle_audit_ranges` (a chain with a genesis row at seq 1, opened by a handle that holds a keying secret) unless the genesis row failed its check, in order, stopping at the first range row that fails a check (`settle_audit_ranges`). The append's `generate_hmac`, the chain walk, and at open the genesis-row verify and the range rows' handover-tag checks run on that pool through `cipher_call` (BACKLOG #3929). `rotate-key`'s handover tag goes through `cipher_call` too, but the roll reaches it only under an in-heap key, so it runs inline: a handle holding the Transit MAC has the Transit key active, the roll never closes the active key's range, and `rotate-key` refuses `vault_transit` (BACKLOG #2109). The row seals (ADR 0217) make Transit `generate_hmac` and `verify_signed_data` calls of their own, on the same pool of `TRANSIT_SEAL_WORKERS` (8) threads (`store/row_seal.py`), so a seal check can wait behind cell and audit calls. A call still on the event loop blocks the loop while it runs, and each `to_thread` call holds a thread of asyncio's default executor | Vault's own rate limit or a slow Transit **stalls the event loop across the whole engine** for each call still made on it. The `to_thread` calls can fill asyncio's default executor, which other off-loop work in the engine shares, and a call past the pool's 8, a row-seal check or a cell or audit call, waits for a free thread with no deadline. A failed cell call raises `CipherError` (a batch decrypt returns it for that cell instead), and a row-seal failure raises the row sealer's own errors (`TransitSealUnavailableError`, `TransitSealUnverifiableError`). An audit-chain call's failure raises `CipherError` too, except where `TransitCipher.verify_audit_hmac` logs it and reads the row as a break: at least the cost-only `generate_hmac` beside a malformed stored MAC, and a row `_recheck_refused_row` reads as refused; and except where a handover-tag `generate_hmac` answered with a non-empty string that is no well-formed MAC (`AuditMacMalformedError`) is logged and read as a tag that does not match in the walk (`_handover_tag_ok`), a break at that range row; the open still refuses on it (unruled, on the owner's queue; listed below), and where the open's check reaches such a row no walk runs to read it. On a stage's cell call the stage errors/dead-letters that row; at least a TOTP judgement reads it as unknown, and a content search or a TOTP secret read raises it to its caller. At open, at least these refuse the open: a `CipherError` from a cell decrypt the open makes, such as the SQLite store's state and reference cache loads; one from the genesis append's `generate_hmac` on a fresh store; one from a range row's handover-tag `generate_hmac`, `AuditMacMalformedError` included; and one the genesis row's check raises other than `AuditKeyVersionRefusedError`; for a both-asks 408 or 504 on the genesis check, that is when the fixed-input verify after the second ask also fails, and when it verifies the open logs a genesis break and opens instead (as before this change, engine PR 2903 at `686c5f7443`; unruled). A refused version, a genesis row `verify_audit_hmac` reads as a break with no raise, and a genesis verify that timed out on both asks (`AuditVerifyTimedOutError`, which `_audit_row_mac` reads there as not verifying), are logged by `settle_audit_ranges` as a break, and the store opens | the store stays open and the row is retried by the normal stage re-claim; after a refused open, the operator fixes Vault and restarts | | Vault KV v2 (`MEFOR_SECRETS_VAULT_ADDR`) | one HTTPS request per secret resolution at config load / connector construction | fail-closed — the connection refuses to build | operator fixes Vault and reloads | | Alerts — SMTP sink (`[alerts].email_smtp_host`) | one connection per send, from the notifier's **single** background drain task and bounded 1000-item queue, which the webhook sink shares; the webhook row says how the two sends of one event run | over-cap events are **dropped with a warning** rather than growing the queue | a send failure is swallowed + logged; the alert is not retried | | Alerts — per-user security-event email (`[auth].notify_security_events`) | one connection per notification, serialized on a **second, independent** drain task with its **own** bounded 1000-item queue — so the SMTP relay sees up to **two** concurrent sessions from this engine, not one | at cap the event is **dropped with a warning**; the audited `GET /me/security-events` feed still records it when it is the user's own event, but not an administrator's change to their account (`auth/notifications.py` states the rule) | the send failure is swallowed + logged, never propagated onto the login or admin path; recovery is the pull feed, for the events it carries | diff --git a/messagefoundry/store/crypto_transit.py b/messagefoundry/store/crypto_transit.py index 33cac4443a..a7e7acca84 100644 --- a/messagefoundry/store/crypto_transit.py +++ b/messagefoundry/store/crypto_transit.py @@ -777,6 +777,14 @@ def _send_alone_from_now(self, op: str, why: str) -> None: ) self._batch_alone = True + @property + def batches_now(self) -> bool: + """Whether :meth:`encrypt_many` and :meth:`decrypt_many` still send batches: False once + this cipher sends every value alone (BACKLOG #6706). At least a batch Transit answers with + HTTP 400, and a failure the classifier could not read, are sent value by value without + turning batching off, so this stays True then.""" + return not self._batch_alone + def decrypt_many(self, items: Sequence[CipherItem]) -> list[str | CipherError]: """Each ``(stored, aad)`` of ``items`` opened, in order, in as few Transit ``decrypt`` requests as the batch bounds allow (BACKLOG #6706). Each result is the plaintext or a diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 1bfddad0f1..6e5ec2262c 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -217,6 +217,7 @@ cipher_call, classify_unrotated, row_sealer_for_cipher, + seal_chunks, ) from messagefoundry.store.schema_verify import IndexShape from messagefoundry.store.sealed_cache import ( @@ -3975,21 +3976,21 @@ async def _seal_surface( ) if not rows: break - for r in rows: - await conn.execute( - f"UPDATE {table} SET {column}=$1 WHERE {where_keys}", - ( - await self._aencrypt( - r["v"], - aad=( - aad_of(r) - if aad_of is not None - else cell_aad(table, column, *(r[c] for c in aad_cols)) - ), - ) - ), - *(r[c] for c in keys), - ) + async for chunk, sealed_values in seal_chunks( + self._cipher, + table, + column, + rows, + aad_cols=aad_cols, + aad_of=aad_of, + local_whole_page=False, + ): + for value, r in zip(sealed_values, chunk, strict=True): + await conn.execute( + f"UPDATE {table} SET {column}=$1 WHERE {where_keys}", + value, + *(r[c] for c in keys), + ) sealed += len(rows) # Top the reserve back up for whatever follows; the burst itself was reserved above. await self._charge_bound_batch() diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 18832fb2bf..70b891b69e 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -46,20 +46,27 @@ import hmac import logging import time -from collections.abc import Callable, Iterable +from collections.abc import AsyncIterator, Callable, Iterable, Sequence from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass -from typing import Final, Protocol +from typing import Any, Final, Protocol from messagefoundry.controlchars import scrub_control_chars from messagefoundry.store.crypto import ( _KEY_ID_LEN, + BATCH_MAX_CHARS, + BATCH_MAX_ITEMS, NO_STORE_ID, + BatchCipher, Cipher, CipherError, CipherUnavailableError, + b64_chars, + batch_chars, + cell_aad, cipher_blocks_on_io, derive_row_seal_key, + encrypt_many, row_seal_key_id, ) from messagefoundry.store.crypto import ( @@ -579,6 +586,78 @@ async def cipher_call[**P, T]( return call(*args, **kwargs) +def _batch_cost(plaintext: str, aad: bytes | None) -> int: + """What ``TransitCipher.encrypt_many`` counts a value as against :data:`BATCH_MAX_CHARS`.""" + return b64_chars(len(plaintext.encode("utf-8"))) + batch_chars("", aad) + + +async def seal_chunks( + cipher: Cipher, + table: str, + column: str, + rows: Sequence[Any], + *, + aad_cols: tuple[str, ...], + aad_of: Callable[[Any], bytes] | None = None, + local_whole_page: bool, +) -> AsyncIterator[tuple[Sequence[Any], list[str]]]: + """Yield ``(chunk, sealed)``: each chunk of ``rows`` with every row's ``v`` encrypted under its + cell AAD, in row order. "Seal" here is the at-rest cell encryption (``mfenc:``), not this + module's row seal. The three stores' at-open ``_seal_surface`` share it (BACKLOG #6706). Each + writes a chunk's rows before the next chunk is encrypted. + + The AAD is ``aad_of(row)`` when given (the queue payload's routing tag, BACKLOG #2593), else + :func:`cell_aad` over ``aad_cols``. The cut is chosen per chunk, from one read of the cipher: + + - A :class:`BatchCipher` whose ``batches_now`` is True (False when it has none) is cut at + :data:`BATCH_MAX_ITEMS` values and :data:`BATCH_MAX_CHARS` of base64, the cost + ``TransitCipher.encrypt_many`` cuts its requests by, so a chunk Transit accepts as a batch + is one request. A value over the character bound is a chunk of its own. A chunk Transit + refuses (at least an HTTP 400, a 413, or a reply without its ``reference`` echo) is sent + value by value inside the one call, up to one request per value more, while the seal's + transaction waits. A cancelled seal can then leave up to :data:`BATCH_MAX_ITEMS` values + running on in the Transit pool. + A cipher that stops batching between the cut and the call can still send that chunk's + values alone inside the one call. + - An in-process cipher, such as AES-GCM, keeps the store's shape from before batching: with + ``local_whole_page`` (SQLite) the whole page is one chunk, else one value per chunk. + - Any other cipher, a Transit cipher sending values alone included, gets one value per chunk, + so each call is followed by its write. + + Only the first case is sized here. The cipher itself may still measure a value: + ``TransitCipher.encrypt_many`` sizes every value, alone or not. + + Each chunk is one :func:`cipher_call` of :func:`encrypt_many`, and a failure raises, as that + does.""" + items = [ + ( + r["v"], + aad_of(r) if aad_of is not None else cell_aad(table, column, *(r[c] for c in aad_cols)), + ) + for r in rows + ] + start = 0 + while start < len(items): + # Read once per chunk; a cipher that does not say it batches is not cut as a batch. + batching = isinstance(cipher, BatchCipher) and getattr(cipher, "batches_now", False) is True + if batching: + end, size = start + 1, _batch_cost(*items[start]) + while end < len(items) and end - start < BATCH_MAX_ITEMS: + cost = _batch_cost(*items[end]) + if size + cost > BATCH_MAX_CHARS: + break + size += cost + end += 1 + elif local_whole_page and not cipher_blocks_on_io(cipher): + end = len(items) + else: + end = start + 1 + if start: + await asyncio.sleep(0) # an in-process cipher runs inline; let the loop serve between + yield rows[start:end], await cipher_call(cipher, encrypt_many, cipher, items[start:end]) + start = end + + #: The start check's fixed 32-byte input: a digest of its own label, so it is no row's seal input #: (a row's digest is over a length-prefixed label, store id and encoding). _START_PROBE_DIGEST: Final = hashlib.sha256(b"mefor/row-seal/transit/start-probe/v1").digest() diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 0e590a8091..edd5abb177 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -209,6 +209,7 @@ cipher_call, classify_unrotated, row_sealer_for_cipher, + seal_chunks, ) from messagefoundry.store.schema_verify import IndexShape from messagefoundry.store.sealed_cache import ( @@ -4795,23 +4796,20 @@ async def _seal_surface( rows = [dict(zip(names, r)) for r in await cur.fetchall()] # noqa: B905 if not rows: break - for r in rows: - await cur.execute( - f"UPDATE {table} SET [{column}]=? WHERE {where_keys}", - ( - ( - await self._aencrypt( - r["v"], - aad=( - aad_of(r) - if aad_of is not None - else cell_aad(table, column, *(r[c] for c in aad_cols)) - ), - ) - ), - *(r[c] for c in keys), - ), - ) + async for chunk, sealed_values in seal_chunks( + self._cipher, + table, + column, + rows, + aad_cols=aad_cols, + aad_of=aad_of, + local_whole_page=False, + ): + for value, r in zip(sealed_values, chunk, strict=True): + await cur.execute( + f"UPDATE {table} SET [{column}]=? WHERE {where_keys}", + (value, *(r[c] for c in keys)), + ) sealed += len(rows) await self._commit(conn) except BaseException: diff --git a/messagefoundry/store/store.py b/messagefoundry/store/store.py index 38dc19eb79..8e579176a4 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -155,7 +155,6 @@ cipher_info, cipher_meta_key, decrypt_json_cell, - encrypt_many, report_sealed_surface, reseal_rotation_fingerprints, rotation_fingerprint_cipher, @@ -227,6 +226,7 @@ revoke_seal_refusals, row_sealer_for_cipher, seal_bytes, + seal_chunks, seal_row_ref, transit_seal_refusals, ) @@ -13136,30 +13136,24 @@ async def _seal_surface( rows = list(await cur.fetchall()) if not rows: break - # One batch per page, so a Transit cipher seals it in few requests (BACKLOG #6706). - sealed_values = await cipher_call( + async for chunk, sealed_values in seal_chunks( self._cipher, - encrypt_many, - self._cipher, - [ - ( - r["v"], - aad_of(r) - if aad_of is not None - else cell_aad(table, column, *(r[c] for c in aad_cols)), - ) - for r in rows - ], - ) - await self._update_every_row( - f"UPDATE {table} SET {column}=? WHERE {where_keys}", - [ - (value, *(r[c] for c in keys)) - for value, r in zip(sealed_values, rows, strict=True) - ], - f"{table}.{column}", - exact=True, - ) + table, + column, + rows, + aad_cols=aad_cols, + aad_of=aad_of, + local_whole_page=True, + ): + await self._update_every_row( + f"UPDATE {table} SET {column}=? WHERE {where_keys}", + [ + (value, *(r[c] for c in keys)) + for value, r in zip(sealed_values, chunk, strict=True) + ], + f"{table}.{column}", + exact=True, + ) sealed += len(rows) await self._commit() except BaseException as exc: diff --git a/tests/test_asvs_gcm_invocation_bound.py b/tests/test_asvs_gcm_invocation_bound.py index 7d0904ce1e..1c1c0a95f9 100644 --- a/tests/test_asvs_gcm_invocation_bound.py +++ b/tests/test_asvs_gcm_invocation_bound.py @@ -400,6 +400,7 @@ async def test_a_rotation_burst_is_charged_PER_BATCH_not_only_at_close( "_enc", "_aenc", "_aencrypt", + "seal_chunks", # the at-open seal's page (BACKLOG #6706) } ) @@ -432,6 +433,10 @@ def test_the_encrypt_reader_sees_each_call_shape_and_skips_prose() -> None: "x = await self._aenc(v, aad=a)", "x = self._reencrypt_value(v)", "x = reseal_unless_tag_failure(c, v)", + "async for chunk, vs in seal_chunks(\n" + " self._cipher, t, c, rows, aad_cols=a, local_whole_page=True\n" + " ):\n" + " pass", ) for line in seen: assert _names_an_encrypt(f"def f(self):\n {line}\n"), line diff --git a/tests/test_server_seal_transit_batch.py b/tests/test_server_seal_transit_batch.py new file mode 100644 index 0000000000..275bf49882 --- /dev/null +++ b/tests/test_server_seal_transit_batch.py @@ -0,0 +1,464 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The PostgreSQL and SQL Server at-open seal encrypts many cells per Transit request (vault BACKLOG +#6706). + +All three stores' seals now encrypt each page in chunks through ``row_seal.seal_chunks``. The two +server ``_seal_surface`` sweeps sealed each cell with its own ``cipher.encrypt``, so under +``vault_transit`` a surface of N legacy values cost N Transit requests. These tests drive the real +``_seal_surface`` of each server store against an in-memory stand-in for its connection, so no +server is needed, and count requests against the batch-answering fake Transit. Synthetic data only. +""" + +from __future__ import annotations + +import os +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any + +import pytest + +pytest.importorskip("requests", reason="Transit batch tests need the [vault] extra") +pytest.importorskip("hvac", reason="Transit batch tests need the [vault] extra") + +from hvac.exceptions import InvalidRequest, UnexpectedError # type: ignore[import-untyped] + +from messagefoundry.store import row_seal +from messagefoundry.store.crypto import BATCH_MAX_ITEMS, AesGcmCipher, cell_aad +from messagefoundry.store.postgres import PostgresStore +from messagefoundry.store.row_seal import seal_chunks +from messagefoundry.store.sqlserver import SqlServerStore +from messagefoundry.store.store import MessageStore +from tests.test_transit_batch import _BatchTransit, _cipher, _write_messages + +_ROWS = 200 +_LIKE = "mfenc:%" + + +def _legacy_rows() -> list[dict[str, Any]]: + """``state`` rows holding legacy plaintext, keyed by (namespace, key).""" + return [ + {"namespace": "ns", "key": f"k{i}", "value": f"synthetic value {i}"} for i in range(_ROWS) + ] + + +def _pending(rows: list[dict[str, Any]], limit: int) -> list[dict[str, Any]]: + return [ + {"namespace": r["namespace"], "key": r["key"], "v": r["value"]} + for r in rows + if r["value"] and not r["value"].startswith("mfenc:") + ][:limit] + + +def _limit(sql: str, word: str) -> int: + """The row limit a page SELECT names after ``word`` (``LIMIT 500`` or ``TOP (500)``).""" + tail = sql.split(word, 1)[1].strip().lstrip("(") + return int(tail.split(")")[0].split()[0]) + + +def _tag(row: Any) -> bytes: + """A row-built AAD, standing in for the queue payload's routing tag.""" + return f"tag/{row['namespace']}/{row['key']}".encode() + + +def _assert_sealed( + rows: list[dict[str, Any]], transit: _BatchTransit, aad_of: Callable[[Any], bytes] | None +) -> None: + opener = _cipher(transit) + for i, r in enumerate(rows): + assert r["value"].startswith("mfenc:") + aad = aad_of(r) if aad_of else cell_aad("state", "value", r["namespace"], r["key"]) + assert opener.decrypt(r["value"], aad=aad) == f"synthetic value {i}" + + +#: (page size, row-built AAD, Transit requests). One request per cell before the batch path: 200. +#: One page of 500 holds all 200 rows, cut 128 + 72 into two batches; four pages of 50 are one +#: batch each. +_CASES = [(500, None, 2), (50, _tag, 4)] + + +class _PgConn: + """The asyncpg connection calls the PostgreSQL seal makes, over a list of rows.""" + + def __init__(self, rows: list[dict[str, Any]]) -> None: + self.rows = rows + + @asynccontextmanager + async def transaction(self) -> AsyncIterator[None]: + yield + + async def fetchval(self, sql: str, *params: Any) -> Any: + assert "keyed_surface" in sql + return 1 # this open wrote the marker + + async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]: + return _pending(self.rows, _limit(sql, "LIMIT")) + + async def execute(self, sql: str, value: str, namespace: str, key: str) -> None: + assert sql.startswith("UPDATE state SET value=$1") + for r in self.rows: + if (r["namespace"], r["key"]) == (namespace, key): + r["value"] = value + + +def _pg_store(conn: _PgConn, transit: _BatchTransit) -> PostgresStore: + store = object.__new__(PostgresStore) + store._cipher = _cipher(transit) + + async def surface_keyed(table: str, column: str) -> bool: + return False + + async def fetchval(sql: str, *params: Any) -> int: + return len(_pending(conn.rows, _ROWS)) + + async def holds_ciphertext(table: str, column: str, like: str) -> bool: + return False + + async def noop(*args: Any, **kwargs: Any) -> None: + return None + + @asynccontextmanager + async def timed_acquire(*, record: bool = True) -> AsyncIterator[_PgConn]: + yield conn + + store._surface_keyed = surface_keyed # type: ignore[method-assign] + store._fetchval = fetchval # type: ignore[method-assign] + store._surface_holds_ciphertext = holds_ciphertext # type: ignore[method-assign] + store._charge_bound_batch = noop # type: ignore[method-assign] + store._timed_acquire = timed_acquire # type: ignore[method-assign] + return store + + +@pytest.mark.parametrize(("batch", "aad_of", "requests"), _CASES) +async def test_the_postgres_seal_seals_many_cells_per_transit_request( + batch: int, aad_of: Callable[[Any], bytes] | None, requests: int +) -> None: + transit = _BatchTransit() + conn = _PgConn(_legacy_rows()) + store = _pg_store(conn, transit) + sealed = await store._seal_surface( + "state", "value", _LIKE, aad_cols=("namespace", "key"), aad_of=aad_of, batch=batch + ) + assert sealed == _ROWS + assert transit.encrypt_requests == requests + _assert_sealed(conn.rows, transit, aad_of) + + +class _MssqlCursor: + """The aioodbc cursor calls the SQL Server seal makes, over a list of rows.""" + + def __init__(self, rows: list[dict[str, Any]]) -> None: + self.rows = rows + self.description: list[tuple[str]] = [] + self._result: list[tuple[Any, ...]] = [] + + async def execute(self, sql: str, params: tuple[Any, ...] = ()) -> None: + if sql.startswith("SELECT TOP"): + self.description = [("namespace",), ("key",), ("v",)] + self._result = [ + (r["namespace"], r["key"], r["v"]) for r in _pending(self.rows, _limit(sql, "TOP")) + ] + return + assert sql.startswith("UPDATE state SET [value]=?") + value, namespace, key = params + for r in self.rows: + if (r["namespace"], r["key"]) == (namespace, key): + r["value"] = value + + async def fetchall(self) -> list[tuple[Any, ...]]: + return self._result + + +class _MssqlConn: + async def rollback(self) -> None: + raise AssertionError("the seal rolled back") + + +def _mssql_store(cur: _MssqlCursor, transit: _BatchTransit) -> SqlServerStore: + store = object.__new__(SqlServerStore) + store._cipher = _cipher(transit) + conn = _MssqlConn() + + async def surface_keyed(table: str, column: str) -> bool: + return False + + async def count_unmarked(count_sql: str, *params: str) -> int: + return len(_pending(cur.rows, _ROWS)) + + async def holds_ciphertext(table: str, column: str, like: str) -> bool: + return False + + async def claim(conn: Any, cur: Any, table: str, column: str) -> bool: + return True + + async def noop(*args: Any, **kwargs: Any) -> None: + return None + + @asynccontextmanager + async def acquire() -> AsyncIterator[_MssqlConn]: + yield conn + + @asynccontextmanager + async def cursor(conn: Any) -> AsyncIterator[_MssqlCursor]: + yield cur + + store._surface_keyed = surface_keyed # type: ignore[method-assign] + store._count_unmarked = count_unmarked # type: ignore[method-assign] + store._surface_holds_ciphertext = holds_ciphertext # type: ignore[method-assign] + store._claim_keyed_surface = claim # type: ignore[method-assign] + store._commit = noop # type: ignore[method-assign] + store._charge_bound_batch = noop # type: ignore[method-assign] + store._acquire = acquire # type: ignore[method-assign] + store._cursor = cursor # type: ignore[method-assign] + return store + + +@pytest.mark.parametrize(("batch", "aad_of", "requests"), _CASES) +async def test_the_sqlserver_seal_seals_many_cells_per_transit_request( + batch: int, aad_of: Callable[[Any], bytes] | None, requests: int +) -> None: + transit = _BatchTransit() + cur = _MssqlCursor(_legacy_rows()) + store = _mssql_store(cur, transit) + sealed = await store._seal_surface( + "state", "value", _LIKE, aad_cols=("namespace", "key"), aad_of=aad_of, batch=batch + ) + assert sealed == _ROWS + assert transit.encrypt_requests == requests + _assert_sealed(cur.rows, transit, aad_of) + + +class _CountingBatchCipher: + """A batch cipher recording how many values each ``encrypt_many`` call carries.""" + + batches_now = True + + def __init__(self) -> None: + self.calls: list[int] = [] + + def encrypt(self, plaintext: str, *, aad: bytes | None = None) -> str: + raise AssertionError("the page went value by value") + + def decrypt(self, stored: str, *, aad: bytes | None = None) -> str: + raise AssertionError("unused") + + def decrypt_many(self, items: Any) -> list[Any]: + raise AssertionError("unused") + + def encrypt_many(self, items: Any) -> list[str]: + self.calls.append(len(items)) + return [f"mfenc:{plaintext}" for plaintext, _aad in items] + + +async def _chunks( + cipher: Any, rows: list[dict[str, Any]], *, whole_page: bool = False +) -> list[tuple[int, list[str]]]: + return [ + (len(chunk), sealed) + async for chunk, sealed in seal_chunks( + cipher, + "state", + "value", + rows, + aad_cols=("namespace", "key"), + local_whole_page=whole_page, + ) + ] + + +async def test_a_page_is_one_cipher_call_per_batch_bound() -> None: + """One cipher call carries at most ``BATCH_MAX_ITEMS`` values: a page of 200 is two calls, 128 + then 72. This checks call sizes only; it neither reaches the Transit pool nor cancels a seal.""" + cipher = _CountingBatchCipher() + rows = _pending(_legacy_rows(), _ROWS) + chunks = await _chunks(cipher, rows) + assert cipher.calls == [BATCH_MAX_ITEMS, _ROWS - BATCH_MAX_ITEMS] + assert [n for n, _ in chunks] == cipher.calls + assert [v for _, sealed in chunks for v in sealed] == [f"mfenc:{r['v']}" for r in rows] + + +async def test_chunks_cost_no_more_transit_requests_than_one_call_over_the_page() -> None: + """Chunks cut by item count alone split the cipher's own character-bound runs twice: 500 + values of about 3 KB were 4 requests in one call and 7 when cut at 128 items.""" + rows = [{"namespace": "ns", "key": f"k{i}", "v": f"{i:04d}" + "x" * 3046} for i in range(500)] + whole = _BatchTransit() + _cipher(whole).encrypt_many( + [(r["v"], cell_aad("state", "value", r["namespace"], r["key"])) for r in rows] + ) + chunked = _BatchTransit() + chunks = await _chunks(_cipher(chunked), rows) + assert sum(n for n, _ in chunks) == len(rows) + assert chunked.encrypt_requests == whole.encrypt_requests == len(chunks) + + +class _SingleValueCipher: + """A cipher with no batch path whose calls wait on I/O, logging each encrypt into a log the + writes share.""" + + blocks_on_io = True + + def __init__(self, log: list[str]) -> None: + self.log = log + + def encrypt(self, plaintext: str, *, aad: bytes | None = None) -> str: + self.log.append("encrypt") + return f"mfenc:{plaintext}" + + def decrypt(self, stored: str, *, aad: bytes | None = None) -> str: + raise AssertionError("unused") + + +class _LoggedPgConn(_PgConn): + def __init__(self, rows: list[dict[str, Any]], log: list[str]) -> None: + super().__init__(rows) + self.log = log + + async def execute(self, sql: str, value: str, namespace: str, key: str) -> None: + self.log.append("write") + await super().execute(sql, value, namespace, key) + + +class _LoggedMssqlCursor(_MssqlCursor): + def __init__(self, rows: list[dict[str, Any]], log: list[str]) -> None: + super().__init__(rows) + self.log = log + + async def execute(self, sql: str, params: tuple[Any, ...] = ()) -> None: + if sql.startswith("UPDATE"): + self.log.append("write") + await super().execute(sql, params) + + +@pytest.mark.parametrize("backend", ["postgres", "sqlserver"]) +async def test_a_single_value_cipher_writes_each_value_before_the_next_call(backend: str) -> None: + """A cipher with no batch path whose calls wait on I/O gets one value per chunk, so on the + server stores each encrypt is followed by its write. An in-process cipher is not covered by + this, and the real Transit cipher sending alone is covered only at the chunk level.""" + log: list[str] = [] + store: PostgresStore | SqlServerStore + if backend == "postgres": + conn = _LoggedPgConn(_legacy_rows(), log) + store = _pg_store(conn, _BatchTransit()) + else: + cur = _LoggedMssqlCursor(_legacy_rows(), log) + store = _mssql_store(cur, _BatchTransit()) + store._cipher = _SingleValueCipher(log) # type: ignore[assignment] + sealed = await store._seal_surface("state", "value", _LIKE, aad_cols=("namespace", "key")) + assert sealed == _ROWS + assert log == ["encrypt", "write"] * _ROWS + + +async def test_an_aes_gcm_page_makes_no_sizing_copy(monkeypatch: pytest.MonkeyPatch) -> None: + """Under AES-GCM the page is cut whole and none of the three ``row_seal`` sizing helpers is + called. This watches those three names only, not an encode added anywhere else.""" + sized: list[object] = [] + + def counted(*args: Any) -> int: + sized.append(args) + return 0 + + for name in ("b64_chars", "batch_chars", "_batch_cost"): + monkeypatch.setattr(row_seal, name, counted) + cipher = AesGcmCipher(bytearray(os.urandom(32)), write_v2=True) + rows = _pending(_legacy_rows(), _ROWS) + chunks = await _chunks(cipher, rows, whole_page=True) + assert sized == [] + assert [n for n, _ in chunks] == [_ROWS] + # Control: a batch cipher's page is sized through the same patched names. + await _chunks(_cipher(_BatchTransit()), rows) + assert len(sized) >= _ROWS + + +def _refusing(transit: _BatchTransit, error: Exception) -> None: + """Make ``transit`` answer every batch encrypt with ``error`` and serve single values.""" + real = transit.encrypt_data + + def answer(**kw: Any) -> dict[str, Any]: + if kw.get("batch_input") is not None: + transit.encrypt_requests += 1 + raise error + return real(**kw) + + transit.encrypt_data = answer # type: ignore[method-assign] + + +async def test_a_transit_cipher_sending_alone_gets_one_value_per_chunk() -> None: + """Once Transit refuses a batch other than with a 400, the cipher sends values alone, and + every later chunk is one value, so each request is followed by its write.""" + transit = _BatchTransit() + _refusing(transit, UnexpectedError("413 Request Entity Too Large")) + cipher = _cipher(transit) + assert cipher.batches_now + chunks = await _chunks(cipher, _pending(_legacy_rows(), _ROWS)) + assert not cipher.batches_now + assert [n for n, _ in chunks] == [BATCH_MAX_ITEMS] + [1] * (_ROWS - BATCH_MAX_ITEMS) + + +async def test_a_vault_400_leaves_batching_on_and_chunks_batched() -> None: + """Vault's 400 to a batch is sent value by value, but batching stays on, so later chunks are + still cut as batches.""" + transit = _BatchTransit() + _refusing(transit, InvalidRequest("synthetic batch 400")) + cipher = _cipher(transit) + chunks = await _chunks(cipher, _pending(_legacy_rows(), _ROWS)) + assert cipher.batches_now + assert [n for n, _ in chunks] == [BATCH_MAX_ITEMS, _ROWS - BATCH_MAX_ITEMS] + assert transit.encrypt_requests == 2 + _ROWS + + +class _LoggedAesGcm(AesGcmCipher): + log: list[str] + + def encrypt(self, plaintext: str, *, aad: bytes | None = None) -> str: + self.log.append("encrypt") + return super().encrypt(plaintext, aad=aad) + + +@pytest.mark.parametrize("backend", ["postgres", "sqlserver"]) +async def test_a_server_seal_under_aes_gcm_writes_after_each_encrypt( + backend: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """An in-process cipher keeps the server stores' shape from before batching: one value per + chunk, its write awaited before the next encrypt. It checks that order, not memory held.""" + + async def no_reservation(*args: Any) -> None: + return None # the bound's persisted total needs a real database; this test has none + + monkeypatch.setattr(f"messagefoundry.store.{backend}.reserve_invocations_ahead", no_reservation) + log: list[str] = [] + store: PostgresStore | SqlServerStore + if backend == "postgres": + conn = _LoggedPgConn(_legacy_rows(), log) + store = _pg_store(conn, _BatchTransit()) + else: + cur = _LoggedMssqlCursor(_legacy_rows(), log) + store = _mssql_store(cur, _BatchTransit()) + cipher = _LoggedAesGcm(bytearray(os.urandom(32)), write_v2=True) + cipher.log = log + store._cipher = cipher + sealed = await store._seal_surface("state", "value", _LIKE, aad_cols=("namespace", "key")) + assert sealed == _ROWS + assert log == ["encrypt", "write"] * _ROWS + + +async def test_the_sqlite_seal_writes_a_whole_page_per_update_under_aes_gcm( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """An in-process cipher keeps SQLite's shape from before batching: the whole page of up to + 500 rows in one ``_update_every_row`` call.""" + db = tmp_path / "store.db" + await _write_messages(db, _ROWS) # keyless: legacy plaintext the keyed open seals + sizes: list[int] = [] + real = MessageStore._update_every_row + + async def counted(self: MessageStore, sql: str, params: Any, *args: Any, **kw: Any) -> None: + sizes.append(len(params)) + await real(self, sql, params, *args, **kw) + + monkeypatch.setattr(MessageStore, "_update_every_row", counted) + store = await MessageStore.open(db, cipher=AesGcmCipher(bytearray(os.urandom(32)))) + await store.close() + assert sizes + assert max(sizes) == _ROWS # 200 messages: one page per surface