From 55c624862c5b2462ab148f8b05118d9a2c8f2ca0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 22:16:31 -0600 Subject: [PATCH 01/10] Batch the PostgreSQL and SQL Server at-open seal through encrypt_many Each page of legacy plaintext the server _seal_surface sweeps reads is now sealed with one encrypt_many call through cipher_call, as the SQLite seal already is, so under vault_transit a page of 200 cells is 2 Transit requests instead of 200. Transaction, marker claim and rollback are unchanged. The new call-count tests drive each store's real _seal_surface against an in-memory connection and a batch-answering fake Transit; both fail at origin/main 7ef8ee3ea1 with 200 == 2. BACKLOG #6706 --- changelog.d/6706-server-seal.changed.md | 5 + messagefoundry/store/postgres.py | 29 ++-- messagefoundry/store/sqlserver.py | 33 ++-- tests/test_server_seal_transit_batch.py | 202 ++++++++++++++++++++++++ 4 files changed, 244 insertions(+), 25 deletions(-) create mode 100644 changelog.d/6706-server-seal.changed.md create mode 100644 tests/test_server_seal_transit_batch.py diff --git a/changelog.d/6706-server-seal.changed.md b/changelog.d/6706-server-seal.changed.md new file mode 100644 index 0000000000..821253078a --- /dev/null +++ b/changelog.d/6706-server-seal.changed.md @@ -0,0 +1,5 @@ +- **The PostgreSQL and SQL Server at-open seal of legacy plaintext sends each page of cells to the + cipher as one batch, as the SQLite seal already does.** Under `vault_transit` a surface of 200 + legacy values was 200 Transit encrypt requests on these backends; it is now 2 (batches of up to + 128 items), counted against a fake Transit in `tests/test_server_seal_transit_batch.py`. The + seal's transaction, marker and rollback are unchanged. (vault `BACKLOG #6706`) diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index ed35f300b5..602c602ee1 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -155,6 +155,7 @@ cipher_info, cipher_meta_key, decrypt_json_cell, + encrypt_many, report_sealed_surface, reseal_rotation_fingerprints, rotation_fingerprint_cipher, @@ -3968,19 +3969,25 @@ async def _seal_surface( ) if not rows: break - for r in rows: + # One batch per page, so a Transit cipher seals it in few requests (BACKLOG #6706). + sealed_values = await cipher_call( + 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 + ], + ) + for value, r in zip(sealed_values, rows, strict=True): 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)) - ), - ) - ), + value, *(r[c] for c in keys), ) sealed += len(rows) diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index df2716391f..b6a869960b 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -144,6 +144,7 @@ cipher_info, cipher_meta_key, decrypt_json_cell, + encrypt_many, report_sealed_surface, reseal_rotation_fingerprints, rotation_fingerprint_cipher, @@ -4789,22 +4790,26 @@ 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: + # One batch per page, so a Transit cipher seals it in few requests (BACKLOG + # #6706). + sealed_values = await cipher_call( + 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 + ], + ) + for value, r in zip(sealed_values, rows, strict=True): 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), - ), + (value, *(r[c] for c in keys)), ) sealed += len(rows) await self._commit(conn) diff --git a/tests/test_server_seal_transit_batch.py b/tests/test_server_seal_transit_batch.py new file mode 100644 index 0000000000..fb7f424eeb --- /dev/null +++ b/tests/test_server_seal_transit_batch.py @@ -0,0 +1,202 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The PostgreSQL and SQL Server at-open seal opens many cells per Transit request (vault BACKLOG +#6706). + +The SQLite seal already sends each page through ``encrypt_many`` (``test_transit_batch.py``). 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 + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +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 messagefoundry.store.crypto import cell_aad +from messagefoundry.store.postgres import PostgresStore +from messagefoundry.store.sqlserver import SqlServerStore +from tests.test_transit_batch import _BatchTransit, _cipher + +_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 _assert_sealed(rows: list[dict[str, Any]], transit: _BatchTransit) -> None: + opener = _cipher(transit) + for i, r in enumerate(rows): + assert r["value"].startswith("mfenc:") + aad = cell_aad("state", "value", r["namespace"], r["key"]) + assert opener.decrypt(r["value"], aad=aad) == f"synthetic value {i}" + + +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 + + +async def test_the_postgres_seal_seals_many_cells_per_transit_request() -> None: + transit = _BatchTransit() + conn = _PgConn(_legacy_rows()) + store = _pg_store(conn, transit) + sealed = await store._seal_surface("state", "value", _LIKE, aad_cols=("namespace", "key")) + assert sealed == _ROWS + # One request per cell before the batch path: 200. One page of 200 is two batches of 128. + assert transit.encrypt_requests == 2 + _assert_sealed(conn.rows, transit) + + +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 + + +async def test_the_sqlserver_seal_seals_many_cells_per_transit_request() -> None: + transit = _BatchTransit() + cur = _MssqlCursor(_legacy_rows()) + store = _mssql_store(cur, transit) + sealed = await store._seal_surface("state", "value", _LIKE, aad_cols=("namespace", "key")) + assert sealed == _ROWS + # One request per cell before the batch path: 200. One page of 200 is two batches of 128. + assert transit.encrypt_requests == 2 + _assert_sealed(cur.rows, transit) From aa3e1f138244ec3cbc9b8c5173bdd73f9c8cb66c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 22:59:42 -0600 Subject: [PATCH 02/10] One seal_page helper for the three at-open seals, one pool call per 128 cells Review round-98a5153e67 repairs. row_seal.seal_page builds each row's cell AAD (aad_of or cell_aad) and seals the page through cipher_call(encrypt_many) at most BATCH_MAX_ITEMS rows per call, yielding to the loop between calls; the SQLite, PostgreSQL and SQL Server _seal_surface all use it. A cancelled seal now leaves at most one 128-value pool job running on, and other Transit pool callers wait behind at most that many. Tests add a row-built AAD over several pages on both server stores, and the per-call bound. CONNECTIONS.md's Transit cost row names the server seals; the changelog states when the cipher stops batching. Proposed PR title: Server at-open seal batches Transit encrypts through one seal_page helper (BACKLOG #6706) Proposed ledger banner: PARTIAL -- the PostgreSQL and SQL Server _seal_surface sweeps batch their Transit encrypts (200 short legacy values: 200 requests before, 2 now; tests/test_server_seal_transit_batch.py fails on main). Left: message list and detail reads, Transit rewrap, added items 1 to 10 and 12 to 16, the score. Item 11 (seal's blocking Transit calls on the event loop) was already met by BACKLOG #3929. BACKLOG #6706 --- changelog.d/6706-server-seal.changed.md | 13 ++-- docs/CONNECTIONS.md | 2 +- messagefoundry/store/postgres.py | 18 +----- messagefoundry/store/row_seal.py | 42 +++++++++++- messagefoundry/store/sqlserver.py | 19 +----- messagefoundry/store/store.py | 18 +----- tests/test_asvs_gcm_invocation_bound.py | 2 + tests/test_server_seal_transit_batch.py | 85 +++++++++++++++++++++---- 8 files changed, 131 insertions(+), 68 deletions(-) diff --git a/changelog.d/6706-server-seal.changed.md b/changelog.d/6706-server-seal.changed.md index 821253078a..41ff661b75 100644 --- a/changelog.d/6706-server-seal.changed.md +++ b/changelog.d/6706-server-seal.changed.md @@ -1,5 +1,8 @@ -- **The PostgreSQL and SQL Server at-open seal of legacy plaintext sends each page of cells to the - cipher as one batch, as the SQLite seal already does.** Under `vault_transit` a surface of 200 - legacy values was 200 Transit encrypt requests on these backends; it is now 2 (batches of up to - 128 items), counted against a fake Transit in `tests/test_server_seal_transit_batch.py`. The - seal's transaction, marker and rollback are unchanged. (vault `BACKLOG #6706`) +- **The PostgreSQL and SQL Server at-open seal of legacy plaintext sends its cells to the cipher in + batches of up to 128, 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`. Larger values split into + more requests. A batch Transit answers with HTTP 400 is resent value by value, and once Transit + has refused a batch any other way, or answered one without its `reference` echo, the cipher + sends every value alone for the life of the process. The seal's transaction, marker and + rollback are unchanged. (vault `BACKLOG #6706`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 87cdc34b78..ca97867dcb 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -5194,7 +5194,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 store open; 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 once the genesis row authenticated, 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 run on that pool through `cipher_call`; at least the handover-tag calls still run **on the event loop**. 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 store open; 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 once the genesis row authenticated, 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 run on that pool through `cipher_call`; at least the handover-tag calls still run **on the event loop**. 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/postgres.py b/messagefoundry/store/postgres.py index 602c602ee1..64b9fe7f11 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -155,7 +155,6 @@ cipher_info, cipher_meta_key, decrypt_json_cell, - encrypt_many, report_sealed_surface, reseal_rotation_fingerprints, rotation_fingerprint_cipher, @@ -218,6 +217,7 @@ cipher_call, classify_unrotated, row_sealer_for_cipher, + seal_page, ) from messagefoundry.store.schema_verify import IndexShape from messagefoundry.store.sealed_cache import ( @@ -3969,20 +3969,8 @@ async def _seal_surface( ) if not rows: break - # One batch per page, so a Transit cipher seals it in few requests (BACKLOG #6706). - sealed_values = await cipher_call( - 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 - ], + sealed_values = await seal_page( + self._cipher, table, column, rows, aad_cols=aad_cols, aad_of=aad_of ) for value, r in zip(sealed_values, rows, strict=True): await conn.execute( diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 18832fb2bf..230138fb37 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -46,20 +46,23 @@ import hmac import logging import time -from collections.abc import Callable, Iterable +from collections.abc import 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_ITEMS, NO_STORE_ID, Cipher, CipherError, CipherUnavailableError, + cell_aad, cipher_blocks_on_io, derive_row_seal_key, + encrypt_many, row_seal_key_id, ) from messagefoundry.store.crypto import ( @@ -579,6 +582,41 @@ async def cipher_call[**P, T]( return call(*args, **kwargs) +async def seal_page( + cipher: Cipher, + table: str, + column: str, + rows: Sequence[Any], + *, + aad_cols: tuple[str, ...], + aad_of: Callable[[Any], bytes] | None = None, +) -> list[str]: + """Each row's ``v`` sealed under its cell AAD, in row order: the at-open seal's page (BACKLOG + #6706), shared by the three stores' ``_seal_surface``. + + The AAD is ``aad_of(row)`` when given (the queue payload's routing tag, BACKLOG #2593), else + :func:`cell_aad` over ``aad_cols``. Each :data:`BATCH_MAX_ITEMS` rows are one :func:`cipher_call` + of :func:`encrypt_many`, so a Transit cipher seals them in few requests while one pool job holds + at most that many values: a cancelled seal leaves at most one such call running on, and other + pool callers wait behind at most one. Any failure raises, as :func:`encrypt_many` does.""" + sealed: list[str] = [] + for start in range(0, len(rows), BATCH_MAX_ITEMS): + if start: + await asyncio.sleep(0) # an in-process cipher runs inline; let the loop serve between + chunk = rows[start : start + BATCH_MAX_ITEMS] + 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 chunk + ] + sealed.extend(await cipher_call(cipher, encrypt_many, cipher, items)) + return sealed + + #: 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 b6a869960b..f7917d5f90 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -144,7 +144,6 @@ cipher_info, cipher_meta_key, decrypt_json_cell, - encrypt_many, report_sealed_surface, reseal_rotation_fingerprints, rotation_fingerprint_cipher, @@ -210,6 +209,7 @@ cipher_call, classify_unrotated, row_sealer_for_cipher, + seal_page, ) from messagefoundry.store.schema_verify import IndexShape from messagefoundry.store.sealed_cache import ( @@ -4790,21 +4790,8 @@ async def _seal_surface( rows = [dict(zip(names, r)) for r in await cur.fetchall()] # noqa: B905 if not rows: break - # One batch per page, so a Transit cipher seals it in few requests (BACKLOG - # #6706). - sealed_values = await cipher_call( - 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 - ], + sealed_values = await seal_page( + self._cipher, table, column, rows, aad_cols=aad_cols, aad_of=aad_of ) for value, r in zip(sealed_values, rows, strict=True): await cur.execute( diff --git a/messagefoundry/store/store.py b/messagefoundry/store/store.py index 22363c937f..79b5074112 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_page, seal_row_ref, transit_seal_refusals, ) @@ -13011,20 +13011,8 @@ 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( - 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 - ], + sealed_values = await seal_page( + self._cipher, table, column, rows, aad_cols=aad_cols, aad_of=aad_of ) await self._update_every_row( f"UPDATE {table} SET {column}=? WHERE {where_keys}", diff --git a/tests/test_asvs_gcm_invocation_bound.py b/tests/test_asvs_gcm_invocation_bound.py index 7d0904ce1e..8fdf95da7f 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_page", # the at-open seal's page (BACKLOG #6706) } ) @@ -432,6 +433,7 @@ 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)", + "x = await seal_page(self._cipher, t, c, rows, aad_cols=a)", ) 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 index fb7f424eeb..626043bf07 100644 --- a/tests/test_server_seal_transit_batch.py +++ b/tests/test_server_seal_transit_batch.py @@ -12,7 +12,7 @@ from __future__ import annotations -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager from typing import Any @@ -21,8 +21,9 @@ pytest.importorskip("requests", reason="Transit batch tests need the [vault] extra") pytest.importorskip("hvac", reason="Transit batch tests need the [vault] extra") -from messagefoundry.store.crypto import cell_aad +from messagefoundry.store.crypto import BATCH_MAX_ITEMS, cell_aad from messagefoundry.store.postgres import PostgresStore +from messagefoundry.store.row_seal import seal_page from messagefoundry.store.sqlserver import SqlServerStore from tests.test_transit_batch import _BatchTransit, _cipher @@ -51,14 +52,26 @@ def _limit(sql: str, word: str) -> int: return int(tail.split(")")[0].split()[0]) -def _assert_sealed(rows: list[dict[str, Any]], transit: _BatchTransit) -> None: +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 = cell_aad("state", "value", r["namespace"], r["key"]) + 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. +#: A page of 200 is two batches of 128; 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.""" @@ -111,15 +124,19 @@ async def timed_acquire(*, record: bool = True) -> AsyncIterator[_PgConn]: return store -async def test_the_postgres_seal_seals_many_cells_per_transit_request() -> None: +@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")) + sealed = await store._seal_surface( + "state", "value", _LIKE, aad_cols=("namespace", "key"), aad_of=aad_of, batch=batch + ) assert sealed == _ROWS - # One request per cell before the batch path: 200. One page of 200 is two batches of 128. - assert transit.encrypt_requests == 2 - _assert_sealed(conn.rows, transit) + assert transit.encrypt_requests == requests + _assert_sealed(conn.rows, transit, aad_of) class _MssqlCursor: @@ -191,12 +208,52 @@ async def cursor(conn: Any) -> AsyncIterator[_MssqlCursor]: return store -async def test_the_sqlserver_seal_seals_many_cells_per_transit_request() -> None: +@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")) + sealed = await store._seal_surface( + "state", "value", _LIKE, aad_cols=("namespace", "key"), aad_of=aad_of, batch=batch + ) assert sealed == _ROWS - # One request per cell before the batch path: 200. One page of 200 is two batches of 128. - assert transit.encrypt_requests == 2 - _assert_sealed(cur.rows, transit) + 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.""" + + 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 test_a_page_is_one_cipher_call_per_batch_bound() -> None: + """One call carries at most ``BATCH_MAX_ITEMS`` values, so a cancelled seal leaves at most that + many running on in the Transit pool, and other pool callers wait behind at most that many.""" + cipher = _CountingBatchCipher() + rows = _pending(_legacy_rows(), _ROWS) + sealed = await seal_page( + cipher, # type: ignore[arg-type] + "state", + "value", + rows, + aad_cols=("namespace", "key"), + ) + assert cipher.calls == [BATCH_MAX_ITEMS, _ROWS - BATCH_MAX_ITEMS] + assert sealed == [f"mfenc:{r['v']}" for r in rows] From 898c41d82767107a6460a9c69d85609483152bab Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 23:33:52 -0600 Subject: [PATCH 03/10] At-open seal chunks follow the cipher's own batch cut, written chunk by chunk Review round-2763fa8efe repairs. seal_page cut a page by item count alone, so TransitCipher.encrypt_many split each chunk again by characters: 500 values of about 3 KB took 7 requests where one call took 4. row_seal.seal_chunks now cuts at BATCH_MAX_ITEMS and BATCH_MAX_CHARS with encrypt_many's own cost, so a batching cipher sends one request per chunk, and yields each chunk so the three stores write its rows before sealing the next: the transaction is never idle for a whole page's Transit work, and an attachment chunk page holds one sealed value at a time again. The changelog no longer enumerates when the cipher stops batching. Proposed PR title: Server at-open seal batches Transit encrypts (BACKLOG #6706) Proposed ledger banner: PARTIAL -- the PostgreSQL and SQL Server _seal_surface sweeps batch their Transit encrypts (200 short legacy values: 200 requests before, 2 now; tests/test_server_seal_transit_batch.py fails on main). Left: message list and detail reads, Transit rewrap, added items 1 to 10 and 12 to 16, the score. Item 11 (the seal's blocking Transit calls on the event loop) was already met by engine PR 3156 (BACKLOG #3929). BACKLOG #6706 --- changelog.d/6706-server-seal.changed.md | 15 +++--- messagefoundry/store/postgres.py | 18 +++---- messagefoundry/store/row_seal.py | 62 +++++++++++++++---------- messagefoundry/store/sqlserver.py | 16 +++---- messagefoundry/store/store.py | 24 +++++----- tests/test_asvs_gcm_invocation_bound.py | 4 +- tests/test_server_seal_transit_batch.py | 40 +++++++++++----- 7 files changed, 106 insertions(+), 73 deletions(-) diff --git a/changelog.d/6706-server-seal.changed.md b/changelog.d/6706-server-seal.changed.md index 41ff661b75..c0ea726298 100644 --- a/changelog.d/6706-server-seal.changed.md +++ b/changelog.d/6706-server-seal.changed.md @@ -1,8 +1,9 @@ - **The PostgreSQL and SQL Server at-open seal of legacy plaintext sends its cells to the cipher in - batches of up to 128, 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`. Larger values split into - more requests. A batch Transit answers with HTTP 400 is resent value by value, and once Transit - has refused a batch any other way, or answered one without its `reference` echo, the cipher - sends every value alone for the life of the process. The seal's transaction, marker and - rollback are unchanged. (vault `BACKLOG #6706`) + 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 holds at most 128 values and + 512 KiB of base64, so larger values take more requests. The cipher can still seal values one at a + time, at least for a batch Transit answers with HTTP 400 and, for the rest of that cipher's life, + after Transit refuses a batch in some other ways; `TransitCipher.encrypt_many` states when. All + three stores now write each batch's rows before sealing the next. The seal's transaction, marker + and rollback are unchanged. (vault `BACKLOG #6706`) diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 64b9fe7f11..329bdeb2a3 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -217,7 +217,7 @@ cipher_call, classify_unrotated, row_sealer_for_cipher, - seal_page, + seal_chunks, ) from messagefoundry.store.schema_verify import IndexShape from messagefoundry.store.sealed_cache import ( @@ -3969,15 +3969,15 @@ async def _seal_surface( ) if not rows: break - sealed_values = await seal_page( + async for chunk, sealed_values in seal_chunks( self._cipher, table, column, rows, aad_cols=aad_cols, aad_of=aad_of - ) - for value, r in zip(sealed_values, rows, strict=True): - await conn.execute( - f"UPDATE {table} SET {column}=$1 WHERE {where_keys}", - value, - *(r[c] for c in keys), - ) + ): + 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 230138fb37..bd96fe950b 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -46,7 +46,7 @@ import hmac import logging import time -from collections.abc import Callable, Iterable, Sequence +from collections.abc import AsyncIterator, Callable, Iterable, Sequence from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from typing import Any, Final, Protocol @@ -54,11 +54,14 @@ from messagefoundry.controlchars import scrub_control_chars from messagefoundry.store.crypto import ( _KEY_ID_LEN, + BATCH_MAX_CHARS, BATCH_MAX_ITEMS, NO_STORE_ID, Cipher, CipherError, CipherUnavailableError, + b64_chars, + batch_chars, cell_aad, cipher_blocks_on_io, derive_row_seal_key, @@ -582,7 +585,7 @@ async def cipher_call[**P, T]( return call(*args, **kwargs) -async def seal_page( +async def seal_chunks( cipher: Cipher, table: str, column: str, @@ -590,31 +593,42 @@ async def seal_page( *, aad_cols: tuple[str, ...], aad_of: Callable[[Any], bytes] | None = None, -) -> list[str]: - """Each row's ``v`` sealed under its cell AAD, in row order: the at-open seal's page (BACKLOG - #6706), shared by the three stores' ``_seal_surface``. +) -> AsyncIterator[tuple[Sequence[Any], list[str]]]: + """Yield ``(chunk, sealed)``: each chunk of ``rows`` with every row's ``v`` sealed under its + cell AAD, in row order. The at-open seal's page (BACKLOG #6706), shared by the three stores' + ``_seal_surface``, which write each chunk before the next is sealed. The AAD is ``aad_of(row)`` when given (the queue payload's routing tag, BACKLOG #2593), else - :func:`cell_aad` over ``aad_cols``. Each :data:`BATCH_MAX_ITEMS` rows are one :func:`cipher_call` - of :func:`encrypt_many`, so a Transit cipher seals them in few requests while one pool job holds - at most that many values: a cancelled seal leaves at most one such call running on, and other - pool callers wait behind at most one. Any failure raises, as :func:`encrypt_many` does.""" - sealed: list[str] = [] - for start in range(0, len(rows), BATCH_MAX_ITEMS): - if start: + :func:`cell_aad` over ``aad_cols``. A chunk 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 batching Transit cipher seals one chunk in one request, and a value over the character + bound is a chunk of its own. Each chunk is one :func:`cipher_call` of :func:`encrypt_many`: + while the cipher batches, a cancelled seal leaves at most one request's values running on in + the Transit pool. Once it sends values alone, one chunk is up to :data:`BATCH_MAX_ITEMS` + requests. Any failure raises, as :func:`encrypt_many` 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 + ] + first = True + start = 0 + while start < len(items): + end, size = start, 0 + while end < len(items) and end - start < BATCH_MAX_ITEMS: + plaintext, aad = items[end] + cost = b64_chars(len(plaintext.encode("utf-8"))) + batch_chars("", aad) + if end > start and size + cost > BATCH_MAX_CHARS: + break + size += cost + end += 1 + if not first: await asyncio.sleep(0) # an in-process cipher runs inline; let the loop serve between - chunk = rows[start : start + BATCH_MAX_ITEMS] - 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 chunk - ] - sealed.extend(await cipher_call(cipher, encrypt_many, cipher, items)) - return sealed + first = False + 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 diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index f7917d5f90..cdd0fc390d 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -209,7 +209,7 @@ cipher_call, classify_unrotated, row_sealer_for_cipher, - seal_page, + seal_chunks, ) from messagefoundry.store.schema_verify import IndexShape from messagefoundry.store.sealed_cache import ( @@ -4790,14 +4790,14 @@ async def _seal_surface( rows = [dict(zip(names, r)) for r in await cur.fetchall()] # noqa: B905 if not rows: break - sealed_values = await seal_page( + async for chunk, sealed_values in seal_chunks( self._cipher, table, column, rows, aad_cols=aad_cols, aad_of=aad_of - ) - for value, r in zip(sealed_values, rows, strict=True): - await cur.execute( - 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): + 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 79b5074112..d2d8b5d149 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -226,7 +226,7 @@ revoke_seal_refusals, row_sealer_for_cipher, seal_bytes, - seal_page, + seal_chunks, seal_row_ref, transit_seal_refusals, ) @@ -13011,18 +13011,18 @@ async def _seal_surface( rows = list(await cur.fetchall()) if not rows: break - sealed_values = await seal_page( + async for chunk, sealed_values in seal_chunks( self._cipher, table, column, rows, aad_cols=aad_cols, aad_of=aad_of - ) - 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, - ) + ): + 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 8fdf95da7f..b27b1e5311 100644 --- a/tests/test_asvs_gcm_invocation_bound.py +++ b/tests/test_asvs_gcm_invocation_bound.py @@ -400,7 +400,7 @@ async def test_a_rotation_burst_is_charged_PER_BATCH_not_only_at_close( "_enc", "_aenc", "_aencrypt", - "seal_page", # the at-open seal's page (BACKLOG #6706) + "seal_chunks", # the at-open seal's page (BACKLOG #6706) } ) @@ -433,7 +433,7 @@ 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)", - "x = await seal_page(self._cipher, t, c, rows, aad_cols=a)", + "async for chunk, vs in seal_chunks(self._cipher, t, c, rows, aad_cols=a):\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 index 626043bf07..bc6151c573 100644 --- a/tests/test_server_seal_transit_batch.py +++ b/tests/test_server_seal_transit_batch.py @@ -23,7 +23,7 @@ from messagefoundry.store.crypto import BATCH_MAX_ITEMS, cell_aad from messagefoundry.store.postgres import PostgresStore -from messagefoundry.store.row_seal import seal_page +from messagefoundry.store.row_seal import seal_chunks from messagefoundry.store.sqlserver import SqlServerStore from tests.test_transit_batch import _BatchTransit, _cipher @@ -243,17 +243,35 @@ def encrypt_many(self, items: Any) -> list[str]: return [f"mfenc:{plaintext}" for plaintext, _aad in items] +async def _chunks(cipher: Any, rows: list[dict[str, Any]]) -> list[tuple[int, list[str]]]: + return [ + (len(chunk), sealed) + async for chunk, sealed in seal_chunks( + cipher, "state", "value", rows, aad_cols=("namespace", "key") + ) + ] + + async def test_a_page_is_one_cipher_call_per_batch_bound() -> None: - """One call carries at most ``BATCH_MAX_ITEMS`` values, so a cancelled seal leaves at most that - many running on in the Transit pool, and other pool callers wait behind at most that many.""" + """One call carries at most ``BATCH_MAX_ITEMS`` values, so while the cipher batches a cancelled + seal leaves at most one request's values running on in the Transit pool.""" cipher = _CountingBatchCipher() rows = _pending(_legacy_rows(), _ROWS) - sealed = await seal_page( - cipher, # type: ignore[arg-type] - "state", - "value", - rows, - aad_cols=("namespace", "key"), - ) + chunks = await _chunks(cipher, rows) assert cipher.calls == [BATCH_MAX_ITEMS, _ROWS - BATCH_MAX_ITEMS] - assert sealed == [f"mfenc:{r['v']}" for r in rows] + 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) From e8c8fc34285a5035cf6a0d964ea370c34da8948e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 23:58:06 -0600 Subject: [PATCH 04/10] A cipher with no batch path seals one value per chunk, and is never sized Manager decisions of 2026-11-23 on round-7ae00633bf. seal_chunks gives a cipher that is not a BatchCipher one value per chunk, so each encrypt is followed by its write, as on main, and the seal's transaction is not idle across many calls. Only a BatchCipher is cut by size, so no unwiped UTF-8 copy of an AES-GCM or single-value plaintext is made to measure it; each value's cost is now computed once. Tests: a single-value fake logs encrypt and write in strict alternation on both server stores, and an AES-GCM page calls no sizing function; all three fail at 898c41d8276. Text: the test module docstring, the changelog's 512 KiB bound (a batch of more than one value) and its long sentence, and the seal_chunks docstring says "seal" there is cell encryption. Proposed PR title: Server at-open seal batches Transit encrypts (BACKLOG #6706) Proposed ledger banner: PARTIAL -- the PostgreSQL and SQL Server _seal_surface sweeps batch their Transit encrypts (200 short legacy values: 200 requests before, 2 now; tests/test_server_seal_transit_batch.py fails on main). Left: message list and detail reads, Transit rewrap, added items 1 to 9 and 12 to 16, item 10's list and detail half, the score. Item 11 was already met by engine PR 3156 (BACKLOG #3929). BACKLOG #6706 --- changelog.d/6706-server-seal.changed.md | 16 ++--- messagefoundry/store/row_seal.py | 51 +++++++++------- tests/test_server_seal_transit_batch.py | 77 ++++++++++++++++++++++++- 3 files changed, 113 insertions(+), 31 deletions(-) diff --git a/changelog.d/6706-server-seal.changed.md b/changelog.d/6706-server-seal.changed.md index c0ea726298..11be548f96 100644 --- a/changelog.d/6706-server-seal.changed.md +++ b/changelog.d/6706-server-seal.changed.md @@ -1,9 +1,9 @@ -- **The PostgreSQL and SQL Server at-open seal of legacy plaintext sends its cells to the 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 holds at most 128 values and - 512 KiB of base64, so larger values take more requests. The cipher can still seal values one at a - time, at least for a batch Transit answers with HTTP 400 and, for the rest of that cipher's life, - after Transit refuses a batch in some other ways; `TransitCipher.encrypt_many` states when. All - three stores now write each batch's rows before sealing the next. The seal's transaction, marker +- **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 cipher with no batch path, such as AES-GCM, still encrypts one value per call. All three + stores now write each batch's rows before encrypting the next. The seal's transaction, marker and rollback are unchanged. (vault `BACKLOG #6706`) diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index bd96fe950b..659368e265 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -57,6 +57,7 @@ BATCH_MAX_CHARS, BATCH_MAX_ITEMS, NO_STORE_ID, + BatchCipher, Cipher, CipherError, CipherUnavailableError, @@ -585,6 +586,11 @@ 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, @@ -594,18 +600,21 @@ async def seal_chunks( aad_cols: tuple[str, ...], aad_of: Callable[[Any], bytes] | None = None, ) -> AsyncIterator[tuple[Sequence[Any], list[str]]]: - """Yield ``(chunk, sealed)``: each chunk of ``rows`` with every row's ``v`` sealed under its - cell AAD, in row order. The at-open seal's page (BACKLOG #6706), shared by the three stores' - ``_seal_surface``, which write each chunk before the next is sealed. + """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``. A chunk 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 batching Transit cipher seals one chunk in one request, and a value over the character - bound is a chunk of its own. Each chunk is one :func:`cipher_call` of :func:`encrypt_many`: - while the cipher batches, a cancelled seal leaves at most one request's values running on in - the Transit pool. Once it sends values alone, one chunk is up to :data:`BATCH_MAX_ITEMS` - requests. Any failure raises, as :func:`encrypt_many` does.""" + :func:`cell_aad` over ``aad_cols``. For a :class:`BatchCipher`, a chunk is cut at + :data:`BATCH_MAX_ITEMS` values and :data:`BATCH_MAX_CHARS` of base64. That is the cost + ``TransitCipher.encrypt_many`` cuts its requests by, so while it batches one chunk is one + request. A cancelled seal then leaves at most that request's values running on in the Transit + pool. A value over the character bound is a chunk of its own. Once a Transit cipher sends values + alone, one chunk can still be up to :data:`BATCH_MAX_ITEMS` requests. Any other cipher gets one + value per chunk, so each call is followed by its write and no sizing copy of the plaintext is + made. Each chunk is one :func:`cipher_call` of :func:`encrypt_many`, and a failure raises, as + that does.""" items = [ ( r["v"], @@ -613,20 +622,20 @@ async def seal_chunks( ) for r in rows ] - first = True + batching = isinstance(cipher, BatchCipher) start = 0 while start < len(items): - end, size = start, 0 - while end < len(items) and end - start < BATCH_MAX_ITEMS: - plaintext, aad = items[end] - cost = b64_chars(len(plaintext.encode("utf-8"))) + batch_chars("", aad) - if end > start and size + cost > BATCH_MAX_CHARS: - break - size += cost - end += 1 - if not first: + end = start + 1 + if batching: + size = _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 + if start: await asyncio.sleep(0) # an in-process cipher runs inline; let the loop serve between - first = False yield rows[start:end], await cipher_call(cipher, encrypt_many, cipher, items[start:end]) start = end diff --git a/tests/test_server_seal_transit_batch.py b/tests/test_server_seal_transit_batch.py index bc6151c573..08a21f4437 100644 --- a/tests/test_server_seal_transit_batch.py +++ b/tests/test_server_seal_transit_batch.py @@ -3,7 +3,7 @@ """The PostgreSQL and SQL Server at-open seal opens many cells per Transit request (vault BACKLOG #6706). -The SQLite seal already sends each page through ``encrypt_many`` (``test_transit_batch.py``). The two +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 @@ -12,6 +12,7 @@ from __future__ import annotations +import os from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager from typing import Any @@ -21,7 +22,8 @@ pytest.importorskip("requests", reason="Transit batch tests need the [vault] extra") pytest.importorskip("hvac", reason="Transit batch tests need the [vault] extra") -from messagefoundry.store.crypto import BATCH_MAX_ITEMS, cell_aad +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 @@ -275,3 +277,74 @@ async def test_chunks_cost_no_more_transit_requests_than_one_call_over_the_page( 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, logging each encrypt into a log the writes share.""" + + 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 that sends values one at a time gets one value per chunk, so the seal's + transaction is never idle for more than one call, as before batching.""" + 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: + """Only a batch cipher is cut by size, so no unwiped UTF-8 copy of an AES-GCM plaintext is + made to measure it.""" + 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, raising=False) + cipher = AesGcmCipher(bytearray(os.urandom(32)), write_v2=True) + rows = _pending(_legacy_rows(), _ROWS) + chunks = await _chunks(cipher, rows) + assert sized == [] + assert sum(n for n, _ in chunks) == _ROWS From a8fad2288fa349ec0c95c23dc11a60814b33f44d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 00:12:09 -0600 Subject: [PATCH 05/10] Correct the at-open seal prose round-075f5c3cfb found false Text only. seal_chunks no longer says a chunk is one request while the cipher batches: a chunk Transit refuses takes up to one request per value more. The ordering test's docstring no longer claims the transaction is never idle for more than one call, which a Transit cipher sending values alone does not meet. The module docstring says encrypts, not opens. The changelog says the SQLite seal under a cipher with no batch path now writes one row per UPDATE call. Correction to e8c8fc34285's message: "as on main" holds for the server stores only, since SQLite wrote a page per call on main, and a value at a size cut is still costed twice. Proposed PR title: Server at-open seal batches Transit encrypts (BACKLOG #6706) BACKLOG #6706 --- changelog.d/6706-server-seal.changed.md | 4 +++- messagefoundry/store/row_seal.py | 9 +++++---- tests/test_server_seal_transit_batch.py | 6 +++--- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/changelog.d/6706-server-seal.changed.md b/changelog.d/6706-server-seal.changed.md index 11be548f96..f55ce5d5e1 100644 --- a/changelog.d/6706-server-seal.changed.md +++ b/changelog.d/6706-server-seal.changed.md @@ -5,5 +5,7 @@ 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 cipher with no batch path, such as AES-GCM, still encrypts one value per call. All three - stores now write each batch's rows before encrypting the next. The seal's transaction, marker + stores now write each batch's rows before encrypting the next. Under such a cipher the SQLite + seal now writes one row per UPDATE call where it wrote a page per call, so its first keyed open + is slower. The seal's transaction, marker and rollback are unchanged. (vault `BACKLOG #6706`) diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 659368e265..56e9300a9c 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -608,10 +608,11 @@ async def seal_chunks( The AAD is ``aad_of(row)`` when given (the queue payload's routing tag, BACKLOG #2593), else :func:`cell_aad` over ``aad_cols``. For a :class:`BatchCipher`, a chunk is cut at :data:`BATCH_MAX_ITEMS` values and :data:`BATCH_MAX_CHARS` of base64. That is the cost - ``TransitCipher.encrypt_many`` cuts its requests by, so while it batches one chunk is one - request. A cancelled seal then leaves at most that request's values running on in the Transit - pool. A value over the character bound is a chunk of its own. Once a Transit cipher sends values - alone, one chunk can still be up to :data:`BATCH_MAX_ITEMS` requests. Any other cipher gets one + ``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, + or any chunk once the cipher sends values alone, can take up to one request per value more, so + a cancelled seal can leave up to :data:`BATCH_MAX_ITEMS` values running on in the Transit pool, + and the seal's transaction waits across those requests. Any other cipher gets one value per chunk, so each call is followed by its write and no sizing copy of the plaintext is made. Each chunk is one :func:`cipher_call` of :func:`encrypt_many`, and a failure raises, as that does.""" diff --git a/tests/test_server_seal_transit_batch.py b/tests/test_server_seal_transit_batch.py index 08a21f4437..8a3dbbd127 100644 --- a/tests/test_server_seal_transit_batch.py +++ b/tests/test_server_seal_transit_batch.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""The PostgreSQL and SQL Server at-open seal opens many cells per Transit request (vault BACKLOG +"""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 @@ -316,8 +316,8 @@ async def execute(self, sql: str, params: tuple[Any, ...] = ()) -> None: @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 that sends values one at a time gets one value per chunk, so the seal's - transaction is never idle for more than one call, as before batching.""" + """A cipher with no batch path gets one value per chunk, so on the server stores each encrypt + is followed by its write. A Transit cipher sending values alone is not covered by this.""" log: list[str] = [] store: PostgresStore | SqlServerStore if backend == "postgres": From 229ec73cc520cec03d402ee3146d6e7474d89c43 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 00:22:23 -0600 Subject: [PATCH 06/10] Seal chunks by what the cipher does now: batch, one value alone, or a page Manager decisions of 2026-11-24 on round-075f5c3cfb. seal_chunks picks the cut per chunk. A BatchCipher that still batches is cut by encrypt_many's cost. A cipher whose calls wait on I/O and that sends values alone gets one value per chunk, so each request is followed by its write. Any other cipher, in-process AES-GCM included, is cut at BATCH_MAX_ITEMS with no sizing, so SQLite writes a page per _update_every_row call again. TransitCipher.batches_now says whether it still batches; a Vault 400 leaves it True. Tests: a Transit cipher sending alone gets one value per chunk; a Vault 400 keeps batched chunks; SQLite under AES-GCM writes 128 rows per call; the no-sizing test checks the patched names exist and has a batch-cipher control. All four fail at a8fad2288fa. Proposed PR title: Server at-open seal batches Transit encrypts (BACKLOG #6706) BACKLOG #6706 --- changelog.d/6706-server-seal.changed.md | 8 +-- messagefoundry/store/crypto_transit.py | 7 +++ messagefoundry/store/row_seal.py | 36 +++++++----- tests/test_server_seal_transit_batch.py | 76 +++++++++++++++++++++++-- 4 files changed, 104 insertions(+), 23 deletions(-) diff --git a/changelog.d/6706-server-seal.changed.md b/changelog.d/6706-server-seal.changed.md index f55ce5d5e1..56b3c04264 100644 --- a/changelog.d/6706-server-seal.changed.md +++ b/changelog.d/6706-server-seal.changed.md @@ -4,8 +4,6 @@ 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 cipher with no batch path, such as AES-GCM, still encrypts one value per call. All three - stores now write each batch's rows before encrypting the next. Under such a cipher the SQLite - seal now writes one row per UPDATE call where it wrote a page per call, so its first keyed open - is slower. The seal's transaction, marker - and rollback are unchanged. (vault `BACKLOG #6706`) + when. Once it sends every value alone, the seal writes each value's row before the next request. + All three stores now write each batch's rows before encrypting the next. The seal's transaction, + marker and rollback are unchanged. (vault `BACKLOG #6706`) diff --git a/messagefoundry/store/crypto_transit.py b/messagefoundry/store/crypto_transit.py index 33cac4443a..7de31957db 100644 --- a/messagefoundry/store/crypto_transit.py +++ b/messagefoundry/store/crypto_transit.py @@ -777,6 +777,13 @@ 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). A batch Transit answers with HTTP 400 + is 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/row_seal.py b/messagefoundry/store/row_seal.py index 56e9300a9c..8bf5b251a6 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -606,16 +606,22 @@ async def seal_chunks( 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``. For a :class:`BatchCipher`, a chunk is cut at - :data:`BATCH_MAX_ITEMS` values and :data:`BATCH_MAX_CHARS` of base64. That is 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, - or any chunk once the cipher sends values alone, can take up to one request per value more, so - a cancelled seal can leave up to :data:`BATCH_MAX_ITEMS` values running on in the Transit pool, - and the seal's transaction waits across those requests. Any other cipher gets one - value per chunk, so each call is followed by its write and no sizing copy of the plaintext is - made. Each chunk is one :func:`cipher_call` of :func:`encrypt_many`, and a failure raises, as - that does.""" + :func:`cell_aad` over ``aad_cols``. The cut is chosen per chunk: + + - A :class:`BatchCipher` that still batches (its ``batches_now``, True 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 + answers with HTTP 400 is sent value by value, up to one request per value more, while the + seal's transaction waits. + - A cipher whose calls wait on I/O and that sends values alone gets one value per chunk, so + each request is followed by its write. + - Any other cipher, such as in-process AES-GCM, is cut at :data:`BATCH_MAX_ITEMS` values, so a + store writes a page of rows per call. Neither of the last two is sized, so no sizing copy of + its plaintext is made. + + Each chunk is one :func:`cipher_call` of :func:`encrypt_many`, and a failure raises, as that + does.""" items = [ ( r["v"], @@ -623,18 +629,20 @@ async def seal_chunks( ) for r in rows ] - batching = isinstance(cipher, BatchCipher) start = 0 while start < len(items): - end = start + 1 - if batching: - size = _batch_cost(*items[start]) + if isinstance(cipher, BatchCipher) and getattr(cipher, "batches_now", True): + 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 cipher_blocks_on_io(cipher): + end = start + 1 + else: + end = min(start + BATCH_MAX_ITEMS, len(items)) 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]) diff --git a/tests/test_server_seal_transit_batch.py b/tests/test_server_seal_transit_batch.py index 8a3dbbd127..3ce5b8b79c 100644 --- a/tests/test_server_seal_transit_batch.py +++ b/tests/test_server_seal_transit_batch.py @@ -15,6 +15,7 @@ import os from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager +from pathlib import Path from typing import Any import pytest @@ -22,12 +23,15 @@ 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 tests.test_transit_batch import _BatchTransit, _cipher +from messagefoundry.store.store import MessageStore +from tests.test_transit_batch import _BatchTransit, _cipher, _write_messages _ROWS = 200 _LIKE = "mfenc:%" @@ -280,7 +284,10 @@ async def test_chunks_cost_no_more_transit_requests_than_one_call_over_the_page( class _SingleValueCipher: - """A cipher with no batch path, logging each encrypt into a log the writes share.""" + """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 @@ -342,9 +349,70 @@ def counted(*args: Any) -> int: return 0 for name in ("b64_chars", "batch_chars", "_batch_cost"): - monkeypatch.setattr(row_seal, name, counted, raising=False) + 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) assert sized == [] - assert sum(n for n, _ in chunks) == _ROWS + assert [n for n, _ in chunks] == [BATCH_MAX_ITEMS, _ROWS - BATCH_MAX_ITEMS] + # 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 + + +async def test_the_sqlite_seal_writes_a_page_of_rows_per_update_under_aes_gcm( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """An in-process cipher is cut by count, so the SQLite seal writes up to ``BATCH_MAX_ITEMS`` + rows per ``_update_every_row`` call, not one.""" + 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) == BATCH_MAX_ITEMS From c1f0dcb99adfa69dccdea91f83e65126ddac7070 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 00:36:07 -0600 Subject: [PATCH 07/10] Correct the seal_chunks prose round-b693abc6f5 found false Text only. The seal_chunks docstring says any refused chunk, not only a 400, is sent value by value with the cancel residual, that the alone cut can go stale, that SQLite writes up to 128 rows per call rather than a page, and that TransitCipher.encrypt_many still sizes every value. batches_now says "at least". The ordering test's docstring and the SQLite test's name no longer claim more than they test. Correction to 229ec73cc52's message: SQLite writes up to 128 rows per call, not a 500-row page as on main. Proposed PR title: Server at-open seal batches Transit encrypts (BACKLOG #6706) BACKLOG #6706 --- changelog.d/6706-server-seal.changed.md | 3 ++- messagefoundry/store/crypto_transit.py | 5 +++-- messagefoundry/store/row_seal.py | 17 +++++++++++------ tests/test_server_seal_transit_batch.py | 7 ++++--- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/changelog.d/6706-server-seal.changed.md b/changelog.d/6706-server-seal.changed.md index 56b3c04264..669d5dabbe 100644 --- a/changelog.d/6706-server-seal.changed.md +++ b/changelog.d/6706-server-seal.changed.md @@ -4,6 +4,7 @@ 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. Once it sends every value alone, the seal writes each value's row before the next request. + 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. The seal's transaction, marker and rollback are unchanged. (vault `BACKLOG #6706`) diff --git a/messagefoundry/store/crypto_transit.py b/messagefoundry/store/crypto_transit.py index 7de31957db..a7e7acca84 100644 --- a/messagefoundry/store/crypto_transit.py +++ b/messagefoundry/store/crypto_transit.py @@ -780,8 +780,9 @@ def _send_alone_from_now(self, op: str, why: str) -> None: @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). A batch Transit answers with HTTP 400 - is sent value by value without turning batching off, so this stays True then.""" + 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]: diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 8bf5b251a6..ee75a36107 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -612,13 +612,18 @@ async def seal_chunks( 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 - answers with HTTP 400 is sent value by value, up to one request per value more, while the - seal's transaction waits. + 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 whose calls wait on I/O and that sends values alone gets one value per chunk, so - each request is followed by its write. - - Any other cipher, such as in-process AES-GCM, is cut at :data:`BATCH_MAX_ITEMS` values, so a - store writes a page of rows per call. Neither of the last two is sized, so no sizing copy of - its plaintext is made. + each call is followed by the chunk's write, unless the cipher stops batching between the cut + and the call. + - Any other cipher, such as in-process AES-GCM, is cut at :data:`BATCH_MAX_ITEMS` values, so + the SQLite store writes up to that many rows per ``_update_every_row`` call. + + 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.""" diff --git a/tests/test_server_seal_transit_batch.py b/tests/test_server_seal_transit_batch.py index 3ce5b8b79c..a9502be2b8 100644 --- a/tests/test_server_seal_transit_batch.py +++ b/tests/test_server_seal_transit_batch.py @@ -323,8 +323,9 @@ async def execute(self, sql: str, params: tuple[Any, ...] = ()) -> None: @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 gets one value per chunk, so on the server stores each encrypt - is followed by its write. A Transit cipher sending values alone is not covered by this.""" + """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": @@ -397,7 +398,7 @@ async def test_a_vault_400_leaves_batching_on_and_chunks_batched() -> None: assert transit.encrypt_requests == 2 + _ROWS -async def test_the_sqlite_seal_writes_a_page_of_rows_per_update_under_aes_gcm( +async def test_the_sqlite_seal_writes_many_rows_per_update_under_aes_gcm( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """An in-process cipher is cut by count, so the SQLite seal writes up to ``BATCH_MAX_ITEMS`` From 8e1983d8ddf0d7859134832ca2a3c57bef439641 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 00:48:51 -0600 Subject: [PATCH 08/10] In-process ciphers keep each store's seal shape from main Manager decision of 2026-11-24 on round-b693abc6f5. Only a cipher whose batches_now reads True is cut as a batch; one without it is not. An in-process cipher, AES-GCM included, takes seal_chunks' local_whole_page: SQLite passes True and seals and writes the whole page per call, and PostgreSQL and SQL Server pass False and write each value before the next encrypt, so an attachment_chunk page holds one sealed value at a time. batches_now is read once per chunk. Parity tests: the SQLite seal under AES-GCM writes 200 rows per call, and each server seal under AES-GCM alternates encrypt and write; all three fail at c1f0dcb99ad. Proposed PR title: Server at-open seal batches Transit encrypts (BACKLOG #6706) BACKLOG #6706 --- changelog.d/6706-server-seal.changed.md | 4 +- messagefoundry/store/postgres.py | 8 +++- messagefoundry/store/row_seal.py | 27 ++++++----- messagefoundry/store/sqlserver.py | 8 +++- messagefoundry/store/store.py | 8 +++- tests/test_server_seal_transit_batch.py | 60 +++++++++++++++++++++---- 6 files changed, 91 insertions(+), 24 deletions(-) diff --git a/changelog.d/6706-server-seal.changed.md b/changelog.d/6706-server-seal.changed.md index 669d5dabbe..f8a986b115 100644 --- a/changelog.d/6706-server-seal.changed.md +++ b/changelog.d/6706-server-seal.changed.md @@ -6,5 +6,7 @@ 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. The seal's transaction, + 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/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 329bdeb2a3..6c9ce153ea 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -3970,7 +3970,13 @@ async def _seal_surface( if not rows: break async for chunk, sealed_values in seal_chunks( - self._cipher, table, column, rows, aad_cols=aad_cols, aad_of=aad_of + 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( diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index ee75a36107..393bb66e94 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -599,6 +599,7 @@ async def seal_chunks( *, 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 @@ -606,21 +607,21 @@ async def seal_chunks( 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: + :func:`cell_aad` over ``aad_cols``. The cut is chosen per chunk, from one read of the cipher: - - A :class:`BatchCipher` that still batches (its ``batches_now``, True when it has none) is - cut at :data:`BATCH_MAX_ITEMS` values and :data:`BATCH_MAX_CHARS` of base64, the cost + - 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 whose calls wait on I/O and that sends values alone gets one value per chunk, so - each call is followed by the chunk's write, unless the cipher stops batching between the cut - and the call. - - Any other cipher, such as in-process AES-GCM, is cut at :data:`BATCH_MAX_ITEMS` values, so - the SQLite store writes up to that many rows per ``_update_every_row`` call. + 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. @@ -636,7 +637,9 @@ async def seal_chunks( ] start = 0 while start < len(items): - if isinstance(cipher, BatchCipher) and getattr(cipher, "batches_now", True): + # 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]) @@ -644,10 +647,10 @@ async def seal_chunks( break size += cost end += 1 - elif cipher_blocks_on_io(cipher): - end = start + 1 + elif local_whole_page and not cipher_blocks_on_io(cipher): + end = len(items) else: - end = min(start + BATCH_MAX_ITEMS, len(items)) + 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]) diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index cdd0fc390d..a6addf2c35 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -4791,7 +4791,13 @@ async def _seal_surface( if not rows: break async for chunk, sealed_values in seal_chunks( - self._cipher, table, column, rows, aad_cols=aad_cols, aad_of=aad_of + 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( diff --git a/messagefoundry/store/store.py b/messagefoundry/store/store.py index d2d8b5d149..1deaa6535c 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -13012,7 +13012,13 @@ async def _seal_surface( if not rows: break async for chunk, sealed_values in seal_chunks( - self._cipher, table, column, rows, aad_cols=aad_cols, aad_of=aad_of + self._cipher, + 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}", diff --git a/tests/test_server_seal_transit_batch.py b/tests/test_server_seal_transit_batch.py index a9502be2b8..1e73f8f58c 100644 --- a/tests/test_server_seal_transit_batch.py +++ b/tests/test_server_seal_transit_batch.py @@ -232,6 +232,8 @@ async def test_the_sqlserver_seal_seals_many_cells_per_transit_request( 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] = [] @@ -249,11 +251,18 @@ def encrypt_many(self, items: Any) -> list[str]: return [f"mfenc:{plaintext}" for plaintext, _aad in items] -async def _chunks(cipher: Any, rows: list[dict[str, Any]]) -> list[tuple[int, list[str]]]: +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") + cipher, + "state", + "value", + rows, + aad_cols=("namespace", "key"), + local_whole_page=whole_page, ) ] @@ -353,9 +362,9 @@ def counted(*args: Any) -> int: 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) + chunks = await _chunks(cipher, rows, whole_page=True) assert sized == [] - assert [n for n, _ in chunks] == [BATCH_MAX_ITEMS, _ROWS - BATCH_MAX_ITEMS] + 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 @@ -398,11 +407,46 @@ async def test_a_vault_400_leaves_batching_on_and_chunks_batched() -> None: assert transit.encrypt_requests == 2 + _ROWS -async def test_the_sqlite_seal_writes_many_rows_per_update_under_aes_gcm( +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, so one sealed value is held at a time.""" + + 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 is cut by count, so the SQLite seal writes up to ``BATCH_MAX_ITEMS`` - rows per ``_update_every_row`` call, not one.""" + """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] = [] @@ -416,4 +460,4 @@ async def counted(self: MessageStore, sql: str, params: Any, *args: Any, **kw: A store = await MessageStore.open(db, cipher=AesGcmCipher(bytearray(os.urandom(32)))) await store.close() assert sizes - assert max(sizes) == BATCH_MAX_ITEMS + assert max(sizes) == _ROWS # 200 messages: one page per surface From 9c08204ee5e23abbb9f03a059c4bb23f1b70113e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 01:06:34 -0600 Subject: [PATCH 09/10] Correct the prose round-8620f80d15 found false or unwrapped Text only. The AES-GCM ordering test's docstring no longer claims a memory bound it does not check. The seal_chunks docstring bullet is wrapped to the module's width. The encrypt reader's example call names local_whole_page, as a real call must. Correction to 8e1983d8ddf's message: under AES-GCM a server seal holds at most two sealed values at a time (the one being written and the next), not one. Proposed PR title: Server at-open seal batches Transit encrypts (BACKLOG #6706) BACKLOG #6706 --- messagefoundry/store/row_seal.py | 3 ++- tests/test_asvs_gcm_invocation_bound.py | 5 ++++- tests/test_server_seal_transit_batch.py | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/messagefoundry/store/row_seal.py b/messagefoundry/store/row_seal.py index 393bb66e94..70b891b69e 100644 --- a/messagefoundry/store/row_seal.py +++ b/messagefoundry/store/row_seal.py @@ -609,7 +609,8 @@ async def seal_chunks( 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 + - 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 diff --git a/tests/test_asvs_gcm_invocation_bound.py b/tests/test_asvs_gcm_invocation_bound.py index b27b1e5311..1c1c0a95f9 100644 --- a/tests/test_asvs_gcm_invocation_bound.py +++ b/tests/test_asvs_gcm_invocation_bound.py @@ -433,7 +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(self._cipher, t, c, rows, aad_cols=a):\n pass", + "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 index 1e73f8f58c..8d36864c78 100644 --- a/tests/test_server_seal_transit_batch.py +++ b/tests/test_server_seal_transit_batch.py @@ -420,7 +420,7 @@ 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, so one sealed value is held at a time.""" + 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 From 3ac0399d02544d4496359ad935e6161202a891fe Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 12:18:11 -0600 Subject: [PATCH 10/10] Correct three test comments that overstate what the seal-batch tests check Delta review round-3d66014289 (hold item 2 on PR 3233) found them: the _CASES comment said a page of 200 is two batches of 128 (it is 128 + 72); the batch-bound test's docstring tied it to a cancel in the Transit pool it never reaches; the AES-GCM sizing test's docstring claimed no UTF-8 copy is made, though it watches three names only. Text only. BACKLOG #6706 --- tests/test_server_seal_transit_batch.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/test_server_seal_transit_batch.py b/tests/test_server_seal_transit_batch.py index 8d36864c78..275bf49882 100644 --- a/tests/test_server_seal_transit_batch.py +++ b/tests/test_server_seal_transit_batch.py @@ -74,7 +74,8 @@ def _assert_sealed( #: (page size, row-built AAD, Transit requests). One request per cell before the batch path: 200. -#: A page of 200 is two batches of 128; four pages of 50 are one batch each. +#: 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)] @@ -268,8 +269,8 @@ async def _chunks( async def test_a_page_is_one_cipher_call_per_batch_bound() -> None: - """One call carries at most ``BATCH_MAX_ITEMS`` values, so while the cipher batches a cancelled - seal leaves at most one request's values running on in the Transit pool.""" + """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) @@ -350,8 +351,8 @@ async def test_a_single_value_cipher_writes_each_value_before_the_next_call(back async def test_an_aes_gcm_page_makes_no_sizing_copy(monkeypatch: pytest.MonkeyPatch) -> None: - """Only a batch cipher is cut by size, so no unwiped UTF-8 copy of an AES-GCM plaintext is - made to measure it.""" + """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: