Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions changelog.d/6706-server-seal.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
- **The PostgreSQL and SQL Server at-open seal of legacy plaintext sends its cells to a batching
cipher in batches, as the SQLite seal already does.** Under `vault_transit`, a surface of 200
short legacy values was 200 Transit encrypt requests on these backends and is now 2, counted
against a fake Transit in `tests/test_server_seal_transit_batch.py`. A batch of more than one
value holds at most 128 values and 512 KiB of base64. A larger value is sent alone. The Transit
cipher can still send values one at a time in some cases; `TransitCipher.encrypt_many` states
when. A chunk cut after it starts sending every value alone holds one value, so that value's row
is written before the next request.
All three stores now write each batch's rows before encrypting the next. An in-process cipher,
such as AES-GCM, keeps each store's shape from before: SQLite writes a page per call, and the
server stores write each value before encrypting the next. The seal's transaction,
marker and rollback are unchanged. (vault `BACKLOG #6706`)
2 changes: 1 addition & 1 deletion docs/CONNECTIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5218,7 +5218,7 @@ reading this page already applies to a file the scan never opened.
| AI broker (`[ai].endpoint`) | one POST per assist request; bounded at the API route by the `ai:assist` RBAC gate, the fail-closed `[ai].allowed_endpoints` SSRF allow-list and the 60 s per-request timeout. **There is NO per-actor pacing on `POST /ai/chat`** — it depends on plain `require(Permission.AI_ASSIST)`, not `require_paced`/`require_step_up`, so a holder of `ai:assist` can loop assist POSTs unthrottled | the LLM's own 429/503 surfaces as an `AiBrokerError` → HTTP `502` to the caller | the assist call fails; nothing is queued or retried |
| DR backup destination (`[backup].destination`, ADR 0049) | **one writer** — leader-gated under `[cluster].enabled`, so exactly one node writes the shared destination; once per `schedule_at` pass plus any on-demand run. No engine-side cap: the OS/SMB redirector queues | a slow or full destination stretches the run; nothing is dropped and the next scheduled pass still fires | a failed or verify-failed run is logged + audited and is **never** counted as a good backup when pruning to `retention_keep` |
| Vault Transit — store DEK unwrap (`MEFOR_STORE_VAULT_ADDR`, `[store].key_provider = vault`, ADR 0019) | one HTTPS request per DEK unwrap (startup / rotation), not per message | a failure is fail-closed — the store does not open | operator fixes Vault and restarts |
| Vault Transit — bulk at-rest cipher (`MEFOR_STORE_TRANSIT_KEY`, `[store].cipher_provider = vault_transit`, ADR 0138) | **one synchronous HTTPS round trip per encrypted cell** on store writes and reads, except where the store batches: the cipher-cell walk (`restore-verify --full`, `cipher-audit`) and the SQLite store's at-open `_seal_surface` sweep send up to `BATCH_MAX_ITEMS` cells per request (`store/crypto.py`, vault BACKLOG #6706). `_enc`/`_dec` are sync. At least the SQLite, Postgres and SQL Server message writes and queue claims hand their cell calls to the row-seal Transit pool through `row_seal.cipher_call`, which hands a call over only for a cipher that sets `blocks_on_io`, as `TransitCipher` does (BACKLOG #3929). `get_message` opens its cells off the event loop through `asyncio.to_thread`. On each of the three stores, at least content search, attachment chunk sealing and the TOTP secret reads run their cell calls off it through `asyncio.to_thread`. On the audit chain (stated here once; other documents link here), at least: one `generate_hmac` per audit row appended; one `verify_signed_data` per audit row a chain walk checks, and one of the genesis row at every open that reaches `settle_audit_ranges` holding the genesis row's key (and one more where the host key provider's store-id pin check runs); one `verify_signed_data` per one-row check, such as the Transit-bound attestation's audit row each time that attestation is read and the newest keyed audit row an AD session revocation check reads, both run off the event loop through `to_thread`; per failed `verify_signed_data`, one more `generate_hmac` (the version probe) when hvac raises the failure as `InvalidRequest`, then, unless that probe read it as a refused version or `is_vault_unavailable` reads it as an outage, one `generate_hmac` and one `verify_signed_data` over fixed input and, when those succeed, one more `verify_signed_data` of the row, and when that fails too, the fixed-input pair once more, and when both failures are an HTTP 408 or 504 the chain walk then ends with a `CipherError` while every other check reads the row as not verifying (`TransitCipher._recheck_refused_row`, `_audit_row_mac`, BACKLOG #8222); one `generate_hmac`, in place of the `verify_signed_data`, per row whose stored MAC is malformed; and one `generate_hmac` per range row whose outgoing key is held, for its handover tag, on every walk, and at every open that reaches `settle_audit_ranges` (a chain with a genesis row at seq 1, opened by a handle that holds a keying secret) unless the genesis row failed its check, in order, stopping at the first range row that fails a check (`settle_audit_ranges`). The append's `generate_hmac`, the chain walk, and at open the genesis-row verify and the range rows' handover-tag checks run on that pool through `cipher_call` (BACKLOG #3929). `rotate-key`'s handover tag goes through `cipher_call` too, but the roll reaches it only under an in-heap key, so it runs inline: a handle holding the Transit MAC has the Transit key active, the roll never closes the active key's range, and `rotate-key` refuses `vault_transit` (BACKLOG #2109). The row seals (ADR 0217) make Transit `generate_hmac` and `verify_signed_data` calls of their own, on the same pool of `TRANSIT_SEAL_WORKERS` (8) threads (`store/row_seal.py`), so a seal check can wait behind cell and audit calls. A call still on the event loop blocks the loop while it runs, and each `to_thread` call holds a thread of asyncio's default executor | Vault's own rate limit or a slow Transit **stalls the event loop across the whole engine** for each call still made on it. The `to_thread` calls can fill asyncio's default executor, which other off-loop work in the engine shares, and a call past the pool's 8, a row-seal check or a cell or audit call, waits for a free thread with no deadline. A failed cell call raises `CipherError` (a batch decrypt returns it for that cell instead), and a row-seal failure raises the row sealer's own errors (`TransitSealUnavailableError`, `TransitSealUnverifiableError`). An audit-chain call's failure raises `CipherError` too, except where `TransitCipher.verify_audit_hmac` logs it and reads the row as a break: at least the cost-only `generate_hmac` beside a malformed stored MAC, and a row `_recheck_refused_row` reads as refused; and except where a handover-tag `generate_hmac` answered with a non-empty string that is no well-formed MAC (`AuditMacMalformedError`) is logged and read as a tag that does not match in the walk (`_handover_tag_ok`), a break at that range row; the open still refuses on it (unruled, on the owner's queue; listed below), and where the open's check reaches such a row no walk runs to read it. On a stage's cell call the stage errors/dead-letters that row; at least a TOTP judgement reads it as unknown, and a content search or a TOTP secret read raises it to its caller. At open, at least these refuse the open: a `CipherError` from a cell decrypt the open makes, such as the SQLite store's state and reference cache loads; one from the genesis append's `generate_hmac` on a fresh store; one from a range row's handover-tag `generate_hmac`, `AuditMacMalformedError` included; and one the genesis row's check raises other than `AuditKeyVersionRefusedError`; for a both-asks 408 or 504 on the genesis check, that is when the fixed-input verify after the second ask also fails, and when it verifies the open logs a genesis break and opens instead (as before this change, engine PR 2903 at `686c5f7443`; unruled). A refused version, a genesis row `verify_audit_hmac` reads as a break with no raise, and a genesis verify that timed out on both asks (`AuditVerifyTimedOutError`, which `_audit_row_mac` reads there as not verifying), are logged by `settle_audit_ranges` as a break, and the store opens | the store stays open and the row is retried by the normal stage re-claim; after a refused open, the operator fixes Vault and restarts |
| Vault Transit — bulk at-rest cipher (`MEFOR_STORE_TRANSIT_KEY`, `[store].cipher_provider = vault_transit`, ADR 0138) | **one synchronous HTTPS round trip per encrypted cell** on store writes and reads, except where the store batches: the cipher-cell walk (`restore-verify --full`, `cipher-audit`) and the at-open `_seal_surface` sweep of the SQLite, Postgres and SQL Server stores send up to `BATCH_MAX_ITEMS` cells per request, while the cipher still batches (`store/crypto.py`, vault BACKLOG #6706). `_enc`/`_dec` are sync. At least the SQLite, Postgres and SQL Server message writes and queue claims hand their cell calls to the row-seal Transit pool through `row_seal.cipher_call`, which hands a call over only for a cipher that sets `blocks_on_io`, as `TransitCipher` does (BACKLOG #3929). `get_message` opens its cells off the event loop through `asyncio.to_thread`. On each of the three stores, at least content search, attachment chunk sealing and the TOTP secret reads run their cell calls off it through `asyncio.to_thread`. On the audit chain (stated here once; other documents link here), at least: one `generate_hmac` per audit row appended; one `verify_signed_data` per audit row a chain walk checks, and one of the genesis row at every open that reaches `settle_audit_ranges` holding the genesis row's key (and one more where the host key provider's store-id pin check runs); one `verify_signed_data` per one-row check, such as the Transit-bound attestation's audit row each time that attestation is read and the newest keyed audit row an AD session revocation check reads, both run off the event loop through `to_thread`; per failed `verify_signed_data`, one more `generate_hmac` (the version probe) when hvac raises the failure as `InvalidRequest`, then, unless that probe read it as a refused version or `is_vault_unavailable` reads it as an outage, one `generate_hmac` and one `verify_signed_data` over fixed input and, when those succeed, one more `verify_signed_data` of the row, and when that fails too, the fixed-input pair once more, and when both failures are an HTTP 408 or 504 the chain walk then ends with a `CipherError` while every other check reads the row as not verifying (`TransitCipher._recheck_refused_row`, `_audit_row_mac`, BACKLOG #8222); one `generate_hmac`, in place of the `verify_signed_data`, per row whose stored MAC is malformed; and one `generate_hmac` per range row whose outgoing key is held, for its handover tag, on every walk, and at every open that reaches `settle_audit_ranges` (a chain with a genesis row at seq 1, opened by a handle that holds a keying secret) unless the genesis row failed its check, in order, stopping at the first range row that fails a check (`settle_audit_ranges`). The append's `generate_hmac`, the chain walk, and at open the genesis-row verify and the range rows' handover-tag checks run on that pool through `cipher_call` (BACKLOG #3929). `rotate-key`'s handover tag goes through `cipher_call` too, but the roll reaches it only under an in-heap key, so it runs inline: a handle holding the Transit MAC has the Transit key active, the roll never closes the active key's range, and `rotate-key` refuses `vault_transit` (BACKLOG #2109). The row seals (ADR 0217) make Transit `generate_hmac` and `verify_signed_data` calls of their own, on the same pool of `TRANSIT_SEAL_WORKERS` (8) threads (`store/row_seal.py`), so a seal check can wait behind cell and audit calls. A call still on the event loop blocks the loop while it runs, and each `to_thread` call holds a thread of asyncio's default executor | Vault's own rate limit or a slow Transit **stalls the event loop across the whole engine** for each call still made on it. The `to_thread` calls can fill asyncio's default executor, which other off-loop work in the engine shares, and a call past the pool's 8, a row-seal check or a cell or audit call, waits for a free thread with no deadline. A failed cell call raises `CipherError` (a batch decrypt returns it for that cell instead), and a row-seal failure raises the row sealer's own errors (`TransitSealUnavailableError`, `TransitSealUnverifiableError`). An audit-chain call's failure raises `CipherError` too, except where `TransitCipher.verify_audit_hmac` logs it and reads the row as a break: at least the cost-only `generate_hmac` beside a malformed stored MAC, and a row `_recheck_refused_row` reads as refused; and except where a handover-tag `generate_hmac` answered with a non-empty string that is no well-formed MAC (`AuditMacMalformedError`) is logged and read as a tag that does not match in the walk (`_handover_tag_ok`), a break at that range row; the open still refuses on it (unruled, on the owner's queue; listed below), and where the open's check reaches such a row no walk runs to read it. On a stage's cell call the stage errors/dead-letters that row; at least a TOTP judgement reads it as unknown, and a content search or a TOTP secret read raises it to its caller. At open, at least these refuse the open: a `CipherError` from a cell decrypt the open makes, such as the SQLite store's state and reference cache loads; one from the genesis append's `generate_hmac` on a fresh store; one from a range row's handover-tag `generate_hmac`, `AuditMacMalformedError` included; and one the genesis row's check raises other than `AuditKeyVersionRefusedError`; for a both-asks 408 or 504 on the genesis check, that is when the fixed-input verify after the second ask also fails, and when it verifies the open logs a genesis break and opens instead (as before this change, engine PR 2903 at `686c5f7443`; unruled). A refused version, a genesis row `verify_audit_hmac` reads as a break with no raise, and a genesis verify that timed out on both asks (`AuditVerifyTimedOutError`, which `_audit_row_mac` reads there as not verifying), are logged by `settle_audit_ranges` as a break, and the store opens | the store stays open and the row is retried by the normal stage re-claim; after a refused open, the operator fixes Vault and restarts |
| Vault KV v2 (`MEFOR_SECRETS_VAULT_ADDR`) | one HTTPS request per secret resolution at config load / connector construction | fail-closed — the connection refuses to build | operator fixes Vault and reloads |
| Alerts — SMTP sink (`[alerts].email_smtp_host`) | one connection per send, from the notifier's **single** background drain task and bounded 1000-item queue, which the webhook sink shares; the webhook row says how the two sends of one event run | over-cap events are **dropped with a warning** rather than growing the queue | a send failure is swallowed + logged; the alert is not retried |
| Alerts — per-user security-event email (`[auth].notify_security_events`) | one connection per notification, serialized on a **second, independent** drain task with its **own** bounded 1000-item queue — so the SMTP relay sees up to **two** concurrent sessions from this engine, not one | at cap the event is **dropped with a warning**; the audited `GET /me/security-events` feed still records it when it is the user's own event, but not an administrator's change to their account (`auth/notifications.py` states the rule) | the send failure is swallowed + logged, never propagated onto the login or admin path; recovery is the pull feed, for the events it carries |
Expand Down
8 changes: 8 additions & 0 deletions messagefoundry/store/crypto_transit.py
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,14 @@ def _send_alone_from_now(self, op: str, why: str) -> None:
)
self._batch_alone = True

@property
def batches_now(self) -> bool:
"""Whether :meth:`encrypt_many` and :meth:`decrypt_many` still send batches: False once
this cipher sends every value alone (BACKLOG #6706). At least a batch Transit answers with
HTTP 400, and a failure the classifier could not read, are sent value by value without
turning batching off, so this stays True then."""
return not self._batch_alone

def decrypt_many(self, items: Sequence[CipherItem]) -> list[str | CipherError]:
"""Each ``(stored, aad)`` of ``items`` opened, in order, in as few Transit ``decrypt``
requests as the batch bounds allow (BACKLOG #6706). Each result is the plaintext or a
Expand Down
31 changes: 16 additions & 15 deletions messagefoundry/store/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@
cipher_call,
classify_unrotated,
row_sealer_for_cipher,
seal_chunks,
)
from messagefoundry.store.schema_verify import IndexShape
from messagefoundry.store.sealed_cache import (
Expand Down Expand Up @@ -3891,7 +3892,7 @@
if total:
log.info("encrypted %d existing value(s) at rest", total)

async def _seal_surface(

Check warning on line 3895 in messagefoundry/store/postgres.py

View workflow job for this annotation

GitHub Actions / complexity triage (advisory)

Complexity increased

`_seal_surface` complexity 12 -> 13 (mccabe threshold 10)
self,
table: str,
column: str,
Expand Down Expand Up @@ -3975,21 +3976,21 @@
)
if not rows:
break
for r in rows:
await conn.execute(
f"UPDATE {table} SET {column}=$1 WHERE {where_keys}",
(
await self._aencrypt(
r["v"],
aad=(
aad_of(r)
if aad_of is not None
else cell_aad(table, column, *(r[c] for c in aad_cols))
),
)
),
*(r[c] for c in keys),
)
async for chunk, sealed_values in seal_chunks(
self._cipher,
table,
column,
rows,
aad_cols=aad_cols,
aad_of=aad_of,
local_whole_page=False,
):
for value, r in zip(sealed_values, chunk, strict=True):
await conn.execute(
f"UPDATE {table} SET {column}=$1 WHERE {where_keys}",
value,
*(r[c] for c in keys),
)
sealed += len(rows)
# Top the reserve back up for whatever follows; the burst itself was reserved above.
await self._charge_bound_batch()
Expand Down
Loading
Loading