From 01b083e19703224bc80fd977cc6cad1d77cf65e9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:31:20 -0600 Subject: [PATCH 01/39] tests: pin that the HTTP listener decodes no Content-Encoding (BACKLOG #5660) A gzipped POST body is handled exactly as sent. A binary inbound commits the compressed bytes and answers 202; hl7v2, json, xml and text refuse them 422 with one ERROR row, single-byte text included, because a gzip header carries NUL bytes. The row as filed expected 202 for single-byte text; measured, it is 422. No behaviour change. Verified-by: tests --- tests/test_inbound_http_content_encoding.py | 116 ++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 tests/test_inbound_http_content_encoding.py diff --git a/tests/test_inbound_http_content_encoding.py b/tests/test_inbound_http_content_encoding.py new file mode 100644 index 0000000000..5600ec6e5c --- /dev/null +++ b/tests/test_inbound_http_content_encoding.py @@ -0,0 +1,116 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The inbound HTTP listener decodes no ``Content-Encoding`` (BACKLOG #5660). + +This is intended behaviour, and ``docs/CONNECTIONS.md`` states it in the HTTP listener section. A +partner that gzips its POST body gets that body handled exactly as sent: the listener neither reads +nor refuses the ``Content-Encoding`` header, so what happens next is decided by the inbound's +``content_type`` alone. Every text and structured type refuses the body at ingress with ``422`` and +one ``ERROR`` row: the compressed bytes are not UTF-8, and even under a single-byte charset that +maps every byte, the gzip header's NUL bytes are refused. A binary type commits the compressed bytes +as they are and answers ``202``. The row as filed expected a ``202`` for single-byte text too; the +measurement below says otherwise. These tests pin each outcome, so a change to any of them is a +decision someone has to make and document, never a drift. Synthetic, PHI-free payloads only.""" + +from __future__ import annotations + +import gzip +from pathlib import Path + +import pytest + +from messagefoundry.config.models import ContentType +from messagefoundry.config.wiring import Http, build_inbound_connection +from messagefoundry.parsing import binary +from messagefoundry.store.store import MessageStatus, MessageStore +from tests.test_inbound_http_source import _http, _start_source + +_GZIP = {"Content-Encoding": "gzip"} + + +@pytest.fixture +async def store(tmp_path: Path): + s = await MessageStore.open(tmp_path / "http-encoding.db") + yield s + await s.close() + + +def _gzipped(text: str) -> bytes: + # mtime=0 so the bytes are the same on every run. + return gzip.compress(text.encode("utf-8"), mtime=0) + + +async def _statuses(store: MessageStore) -> list[str]: + cur = await store._db.execute("SELECT status FROM messages") + return [row["status"] for row in await cur.fetchall()] + + +@pytest.mark.parametrize( + ("content_type", "plain"), + [ + pytest.param( + ContentType.HL7V2, "MSH|^~\\&|S|F|R|RF|20260101||ADT^A01|MSG1|P|2.5.1\r", id="hl7v2" + ), + pytest.param(ContentType.JSON, '{"kind": "order"}', id="json"), + pytest.param(ContentType.XML, "", id="xml"), + pytest.param(ContentType.TEXT, "synthetic text body", id="text-utf8"), + ], +) +async def test_a_gzipped_body_is_refused_422_where_its_bytes_do_not_decode( + store: MessageStore, content_type: ContentType, plain: str +) -> None: + """The compressed bytes are not valid UTF-8, so the receipt handler refuses them as a body the + engine cannot decode: a permanent refusal, ``422``, recorded as one ``ERROR`` row. Nothing + inflates the body first.""" + ic = build_inbound_connection("IB_HTTP", Http(port=0), router="r", content_type=content_type) + src = await _start_source(store, ic) + try: + resp = await _http(src.sockport, body=_gzipped(plain), extra_headers=_GZIP) + finally: + await src.stop() + assert resp.status == 422 + assert resp.json()["error"] == "message was not accepted" + assert await _statuses(store) == [MessageStatus.ERROR.value] + + +async def test_a_gzipped_body_on_a_binary_inbound_is_committed_compressed( + store: MessageStore, +) -> None: + """A binary inbound carries its body as base64 of the bytes received (ADR 0028), so the + committed message is the gzip stream itself, answered ``202``. A Handler that wants the plain + payload inflates it.""" + compressed = _gzipped("synthetic binary payload") + ic = build_inbound_connection( + "IB_HTTP", Http(port=0), router="r", content_type=ContentType.BINARY + ) + src = await _start_source(store, ic) + try: + resp = await _http(src.sockport, body=compressed, extra_headers=_GZIP) + finally: + await src.stop() + assert resp.status == 202 + msg = await store.get_message(resp.json()["message_id"]) + assert msg is not None + assert msg["status"] == MessageStatus.RECEIVED.value + assert binary.decode(msg["raw"]) == compressed + + +async def test_a_gzipped_body_on_a_single_byte_text_inbound_is_refused_for_its_nul_bytes( + store: MessageStore, +) -> None: + """Latin-1 maps every byte to a character, so the compressed bytes do decode. They are still + refused ``422``: a gzip header with no flags set carries NUL bytes, and the engine refuses a NUL + in a text body. A single-byte charset therefore does not let a compressed body through either.""" + compressed = _gzipped("synthetic text body") + assert b"\x00" in compressed # the premise: the stream itself holds a NUL + ic = build_inbound_connection( + "IB_HTTP", Http(port=0), router="r", content_type=ContentType.TEXT + ) + ic.spec.settings["encoding"] = "latin-1" # as the codec tests set it, past the factory + src = await _start_source(store, ic) + try: + resp = await _http(src.sockport, body=compressed, extra_headers=_GZIP) + finally: + await src.stop() + assert resp.status == 422 + assert await _statuses(store) == [MessageStatus.ERROR.value] From 64e6535576c1aa5f6104ae4f5eaac14c8129acb8 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:32:29 -0600 Subject: [PATCH 02/39] docs: record that the HTTP listener decodes no Content-Encoding (BACKLOG #5660) The HTTP listener section of docs/CONNECTIONS.md now states that a compressed body is read as sent, and what each content_type does with it: a binary inbound commits it and answers 202, at least hl7v2, json, xml and text refuse it 422 with one ERROR row. Intended behaviour, per the row's verdict of record. Proposed PR title: HTTP listener: record and pin that no Content-Encoding is decoded (BACKLOG #5660) Proposed vault banner: CLOSED -- docs gap closed: docs/CONNECTIONS.md HTTP listener section records the per-content-type outcome of a gzipped body; tests/test_inbound_http_content_encoding.py pins it. Measured: single-byte text answers 422, not 202 as filed (gzip header NUL bytes). Verified-by: none --- docs/CONNECTIONS.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index c6e2f540d7..5b7a23760c 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -1002,6 +1002,15 @@ refusals come before the TLS handshake, so the socket is closed with no answer i `503`: a TLS client cannot read a plaintext one (BACKLOG #2479). `GET`/`HEAD` are static, non-PHI health probes and write **no** ingress row; any other method is `405`. A probe is held to the same head rules as any request, so an HTTP/1.1 probe must send one `Host` header. Methods are case-sensitive (RFC 9110), so a lowercase `get` or `post` is not a probe or an intake request. +**No `Content-Encoding` is decoded, by design** (BACKLOG #5660). The listener reads the body as +sent and neither inflates nor refuses a `Content-Encoding` such as `gzip`, so a compressed body +reaches the engine compressed and the inbound's `content_type` decides what follows. A `binary` +inbound commits the compressed bytes and answers `202`; a Handler that wants the payload inflates +it. At least `hl7v2`, `json`, `xml` and `text` refuse it at ingress with `422` and one `ERROR` row: +the bytes are not UTF-8, and even under a single-byte `encoding` the NUL bytes in a gzip header +are refused. A partner that compresses its POST bodies has to stop, or send to a `binary` inbound. +`tests/test_inbound_http_content_encoding.py` pins each of these outcomes. + **Synchronous captured-downstream reply (`reply_from`, ADR 0154 increment B).** Naming `reply_from` makes the HTTP turn **block** until the named outbound's reply has been captured **and committed to the store**, then returns that reply as the response body — a proxy API rather than a receipt. The **committed row is From c19c9360af66232f3878ffa59ee55bc3abf44e27 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:44:40 -0600 Subject: [PATCH 03/39] tests: pin the Content-Encoding refusal reasons and a plain control (BACKLOG #5660) Review round 1 repair. Each 422 arm now asserts its refusal reason (decode error, or the NUL guard under latin-1) and first sends the same body plain to the same inbound for a 202, so the refusal is the compression's. Adds fhir and a dicom arm (422, no magic), sets latin-1 through Http(encoding=...), and says "at least" in the module docstring. Verified-by: tests --- tests/test_inbound_http_content_encoding.py | 124 ++++++++++++-------- 1 file changed, 73 insertions(+), 51 deletions(-) diff --git a/tests/test_inbound_http_content_encoding.py b/tests/test_inbound_http_content_encoding.py index 5600ec6e5c..e55c666ed5 100644 --- a/tests/test_inbound_http_content_encoding.py +++ b/tests/test_inbound_http_content_encoding.py @@ -3,31 +3,42 @@ """The inbound HTTP listener decodes no ``Content-Encoding`` (BACKLOG #5660). This is intended behaviour, and ``docs/CONNECTIONS.md`` states it in the HTTP listener section. A -partner that gzips its POST body gets that body handled exactly as sent: the listener neither reads -nor refuses the ``Content-Encoding`` header, so what happens next is decided by the inbound's -``content_type`` alone. Every text and structured type refuses the body at ingress with ``422`` and -one ``ERROR`` row: the compressed bytes are not UTF-8, and even under a single-byte charset that -maps every byte, the gzip header's NUL bytes are refused. A binary type commits the compressed bytes -as they are and answers ``202``. The row as filed expected a ``202`` for single-byte text too; the -measurement below says otherwise. These tests pin each outcome, so a change to any of them is a -decision someone has to make and document, never a drift. Synthetic, PHI-free payloads only.""" +partner that compresses its POST body gets that body handled exactly as sent: the listener neither +reads nor refuses the ``Content-Encoding`` header, so what happens next is decided by the inbound's +``content_type`` and ``encoding``. These tests pin at least these outcomes for a gzipped body: + +- ``hl7v2``, ``json``, ``xml``, ``text`` and ``fhir`` under UTF-8 refuse it ``422`` as a decode + error, with one ``ERROR`` row; +- ``text`` under a single-byte ``encoding`` decodes it, then refuses it ``422`` for the NUL bytes + in the gzip header. A coding with no NUL byte would be committed there as its bytes; +- ``binary`` commits the compressed bytes and answers ``202``; ``dicom`` refuses them ``422``, + since they carry no DICOM magic. + +The row as filed expected a ``202`` for single-byte text; the measurement below says otherwise for +gzip. A change to any of these is a decision someone has to make and document, never a drift. +Synthetic, PHI-free payloads only.""" from __future__ import annotations import gzip from pathlib import Path +from typing import Any import pytest from messagefoundry.config.models import ContentType from messagefoundry.config.wiring import Http, build_inbound_connection from messagefoundry.parsing import binary +from messagefoundry.pipeline.ingress_guards import NUL_REJECTED_REASON from messagefoundry.store.store import MessageStatus, MessageStore -from tests.test_inbound_http_source import _http, _start_source +from tests.test_inbound_http_source import _http, _Response, _start_source _GZIP = {"Content-Encoding": "gzip"} +_HL7 = "MSH|^~\\&|S|F|R|RF|20260101||ADT^A01|MSG1|P|2.5.1\rPID|1||100||DOE^JANE\r" +# Not imported from test_inbound_http_source: a fixture imported by name and then taken as a +# parameter reads to ruff as a redefinition (F811). @pytest.fixture async def store(tmp_path: Path): s = await MessageStore.open(tmp_path / "http-encoding.db") @@ -40,54 +51,74 @@ def _gzipped(text: str) -> bytes: return gzip.compress(text.encode("utf-8"), mtime=0) -async def _statuses(store: MessageStore) -> list[str]: - cur = await store._db.execute("SELECT status FROM messages") - return [row["status"] for row in await cur.fetchall()] +async def _rows(store: MessageStore) -> list[Any]: + cur = await store._db.execute("SELECT status, error FROM messages") + return list(await cur.fetchall()) + + +async def _post( + store: MessageStore, http: Http, content_type: ContentType, body: bytes, **headers: str +) -> _Response: + ic = build_inbound_connection("IB_HTTP", http, router="r", content_type=content_type) + src = await _start_source(store, ic) + try: + return await _http(src.sockport, body=body, extra_headers=headers or None) + finally: + await src.stop() @pytest.mark.parametrize( ("content_type", "plain"), [ - pytest.param( - ContentType.HL7V2, "MSH|^~\\&|S|F|R|RF|20260101||ADT^A01|MSG1|P|2.5.1\r", id="hl7v2" - ), + pytest.param(ContentType.HL7V2, _HL7, id="hl7v2"), pytest.param(ContentType.JSON, '{"kind": "order"}', id="json"), pytest.param(ContentType.XML, "", id="xml"), pytest.param(ContentType.TEXT, "synthetic text body", id="text-utf8"), + pytest.param(ContentType.FHIR, '{"resourceType": "Patient"}', id="fhir"), ], ) -async def test_a_gzipped_body_is_refused_422_where_its_bytes_do_not_decode( +async def test_a_gzipped_body_is_refused_422_as_a_decode_error( store: MessageStore, content_type: ContentType, plain: str ) -> None: """The compressed bytes are not valid UTF-8, so the receipt handler refuses them as a body the engine cannot decode: a permanent refusal, ``422``, recorded as one ``ERROR`` row. Nothing - inflates the body first.""" - ic = build_inbound_connection("IB_HTTP", Http(port=0), router="r", content_type=content_type) - src = await _start_source(store, ic) - try: - resp = await _http(src.sockport, body=_gzipped(plain), extra_headers=_GZIP) - finally: - await src.stop() + inflates the body first. The same body sent plain is accepted, so the refusal is the + compression's and not the inbound's.""" + plain_resp = await _post(store, Http(port=0), content_type, plain.encode("utf-8")) + assert plain_resp.status == 202 + resp = await _post(store, Http(port=0), content_type, _gzipped(plain), **_GZIP) assert resp.status == 422 assert resp.json()["error"] == "message was not accepted" - assert await _statuses(store) == [MessageStatus.ERROR.value] + rows = await _rows(store) + assert [r["status"] for r in rows] == [MessageStatus.RECEIVED.value, MessageStatus.ERROR.value] + assert str(rows[1]["error"]).startswith("[refusal kind: permanent] decode error (utf-8)") + + +async def test_a_gzipped_body_on_a_single_byte_text_inbound_is_refused_for_its_nul_bytes( + store: MessageStore, +) -> None: + """Latin-1 maps every byte to a character, so the compressed bytes do decode. They are still + refused ``422``, because a gzip header with no flags set carries NUL bytes and the engine + refuses a NUL in a text body. That is a property of gzip, not a rule about compression: a coding + whose bytes hold no NUL would be committed under this charset as its bytes.""" + compressed = _gzipped("synthetic text body") + assert b"\x00" in compressed # the premise: the stream itself holds a NUL + resp = await _post( + store, Http(port=0, encoding="latin-1"), ContentType.TEXT, compressed, **_GZIP + ) + assert resp.status == 422 + rows = await _rows(store) + assert [r["status"] for r in rows] == [MessageStatus.ERROR.value] + assert str(rows[0]["error"]).startswith(f"[refusal kind: permanent] {NUL_REJECTED_REASON}") async def test_a_gzipped_body_on_a_binary_inbound_is_committed_compressed( store: MessageStore, ) -> None: - """A binary inbound carries its body as base64 of the bytes received (ADR 0028), so the - committed message is the gzip stream itself, answered ``202``. A Handler that wants the plain - payload inflates it.""" + """A ``binary`` inbound carries its body as base64 of the bytes received (ADR 0028), so the + committed message is the gzip stream itself, answered ``202``.""" compressed = _gzipped("synthetic binary payload") - ic = build_inbound_connection( - "IB_HTTP", Http(port=0), router="r", content_type=ContentType.BINARY - ) - src = await _start_source(store, ic) - try: - resp = await _http(src.sockport, body=compressed, extra_headers=_GZIP) - finally: - await src.stop() + resp = await _post(store, Http(port=0), ContentType.BINARY, compressed, **_GZIP) assert resp.status == 202 msg = await store.get_message(resp.json()["message_id"]) assert msg is not None @@ -95,22 +126,13 @@ async def test_a_gzipped_body_on_a_binary_inbound_is_committed_compressed( assert binary.decode(msg["raw"]) == compressed -async def test_a_gzipped_body_on_a_single_byte_text_inbound_is_refused_for_its_nul_bytes( +async def test_a_gzipped_body_on_a_dicom_inbound_is_refused_for_its_missing_magic( store: MessageStore, ) -> None: - """Latin-1 maps every byte to a character, so the compressed bytes do decode. They are still - refused ``422``: a gzip header with no flags set carries NUL bytes, and the engine refuses a NUL - in a text body. A single-byte charset therefore does not let a compressed body through either.""" - compressed = _gzipped("synthetic text body") - assert b"\x00" in compressed # the premise: the stream itself holds a NUL - ic = build_inbound_connection( - "IB_HTTP", Http(port=0), router="r", content_type=ContentType.TEXT - ) - ic.spec.settings["encoding"] = "latin-1" # as the codec tests set it, past the factory - src = await _start_source(store, ic) - try: - resp = await _http(src.sockport, body=compressed, extra_headers=_GZIP) - finally: - await src.stop() + """``dicom`` is a binary type too, but it checks the body's magic bytes, which a gzip stream + does not carry: refused ``422`` as a declared-type mismatch.""" + resp = await _post(store, Http(port=0), ContentType.DICOM, _gzipped("synthetic"), **_GZIP) assert resp.status == 422 - assert await _statuses(store) == [MessageStatus.ERROR.value] + rows = await _rows(store) + assert [r["status"] for r in rows] == [MessageStatus.ERROR.value] + assert "does not match its declared content type" in str(rows[0]["error"]) From acd5e20808a6ce9aaa94cf7ffecd708d6c28af75 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:45:31 -0600 Subject: [PATCH 04/39] docs: correct the Content-Encoding paragraph after review (BACKLOG #5660) Review round 1 repair. The refusals come from decoding and the NUL guard, not from a rule about compression: a NUL-free deflate body on a single-byte text inbound is committed as its bytes. Says so, names encoding beside content_type, adds fhir and dicom, drops the bare 202 that a reply_from inbound does not give, and points a Handler at the bounded gzip_decompress. Proposed PR title: HTTP listener: record and pin that no Content-Encoding is decoded (BACKLOG #5660) Proposed vault banner: CLOSED -- docs gap closed: docs/CONNECTIONS.md HTTP listener section records that no Content-Encoding is decoded and what each content_type does with a gzipped body; tests/test_inbound_http_content_encoding.py pins it. Measured: single-byte text answers 422 for gzip (header NUL bytes), not 202 as filed; a NUL-free deflate body there is committed as its bytes. Verified-by: none --- docs/CONNECTIONS.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 5b7a23760c..317aa88406 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -1004,12 +1004,18 @@ refusals come before the TLS handshake, so the socket is closed with no answer i **No `Content-Encoding` is decoded, by design** (BACKLOG #5660). The listener reads the body as sent and neither inflates nor refuses a `Content-Encoding` such as `gzip`, so a compressed body -reaches the engine compressed and the inbound's `content_type` decides what follows. A `binary` -inbound commits the compressed bytes and answers `202`; a Handler that wants the payload inflates -it. At least `hl7v2`, `json`, `xml` and `text` refuse it at ingress with `422` and one `ERROR` row: -the bytes are not UTF-8, and even under a single-byte `encoding` the NUL bytes in a gzip header -are refused. A partner that compresses its POST bodies has to stop, or send to a `binary` inbound. -`tests/test_inbound_http_content_encoding.py` pins each of these outcomes. +reaches the engine compressed, and the inbound's `content_type` and `encoding` decide what follows, +as for any other body. For a gzipped body, at least: under UTF-8, `hl7v2`, `json`, `xml`, `text` +and `fhir` refuse it at ingress with `422` and one `ERROR` row, as a body that does not decode; +`text` under a single-byte `encoding` decodes it and then refuses it `422` for the NUL bytes a gzip +header carries; `dicom` refuses it `422`, since it carries no DICOM magic; and `binary` commits the +compressed bytes as an accepted body. **The refusals are not a rule about compression.** A coding +whose bytes hold no NUL, such as many short `deflate` streams, is committed as its bytes on a `text` +inbound under a single-byte `encoding`, and routed as if it were the payload. So a partner that +compresses its POST bodies should stop, or send to a `binary` inbound whose Handler inflates them +with the bounded `gzip_decompress` (`parsing/compression.py`, ADR 0123), never a bare +`gzip.decompress`, which sets no bound on what a partner-sized body inflates to. +`tests/test_inbound_http_content_encoding.py` pins the gzip outcomes above. **Synchronous captured-downstream reply (`reply_from`, ADR 0154 increment B).** Naming `reply_from` makes the HTTP turn **block** until the named outbound's reply has been captured **and committed to the store**, From ca7aad2484e885c589e37644c03a55d9417f6636 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:57:39 -0600 Subject: [PATCH 05/39] tests: pin the NUL-free deflate case and the not-queued half (BACKLOG #5660) Review round 2 repair. Adds the deflate body a latin-1 text inbound commits as its bytes, so the docs' claim that the refusals are no rule about compression is measured. Every refusal now checks the answer names the ERROR row and that nothing refused reached the queue. Rows read in rowid order; one listener takes both the plain control and the gzipped body. Verified-by: tests --- tests/test_inbound_http_content_encoding.py | 137 +++++++++++++------- 1 file changed, 92 insertions(+), 45 deletions(-) diff --git a/tests/test_inbound_http_content_encoding.py b/tests/test_inbound_http_content_encoding.py index e55c666ed5..e1b569d70b 100644 --- a/tests/test_inbound_http_content_encoding.py +++ b/tests/test_inbound_http_content_encoding.py @@ -5,29 +5,31 @@ This is intended behaviour, and ``docs/CONNECTIONS.md`` states it in the HTTP listener section. A partner that compresses its POST body gets that body handled exactly as sent: the listener neither reads nor refuses the ``Content-Encoding`` header, so what happens next is decided by the inbound's -``content_type`` and ``encoding``. These tests pin at least these outcomes for a gzipped body: +``content_type`` and ``encoding``. These tests pin at least these outcomes: -- ``hl7v2``, ``json``, ``xml``, ``text`` and ``fhir`` under UTF-8 refuse it ``422`` as a decode - error, with one ``ERROR`` row; -- ``text`` under a single-byte ``encoding`` decodes it, then refuses it ``422`` for the NUL bytes - in the gzip header. A coding with no NUL byte would be committed there as its bytes; -- ``binary`` commits the compressed bytes and answers ``202``; ``dicom`` refuses them ``422``, - since they carry no DICOM magic. +- ``hl7v2``, ``json``, ``xml``, ``text`` and ``fhir`` under UTF-8 refuse a gzipped body ``422`` + as a decode error, with one ``ERROR`` row; +- ``text`` under latin-1, which maps every byte, decodes a gzipped body and then refuses it ``422`` + for the NUL bytes in the gzip header; a ``deflate`` body that holds no NUL is committed there as + its bytes, answered ``202``. So the refusals are not a rule about compression; +- ``binary`` commits the compressed bytes and answers ``202``; ``dicom`` refuses them ``422``, as it + refuses any body without DICOM magic. -The row as filed expected a ``202`` for single-byte text; the measurement below says otherwise for -gzip. A change to any of these is a decision someone has to make and document, never a drift. -Synthetic, PHI-free payloads only.""" +The row as filed expected a ``202`` for single-byte text; for gzip the measurement says otherwise. +The bodies are compressed with the stdlib directly, as a partner would, rather than with the +engine's own helpers. Synthetic, PHI-free payloads only.""" from __future__ import annotations import gzip +import zlib from pathlib import Path from typing import Any import pytest from messagefoundry.config.models import ContentType -from messagefoundry.config.wiring import Http, build_inbound_connection +from messagefoundry.config.wiring import ConnectionSpec, Http, build_inbound_connection from messagefoundry.parsing import binary from messagefoundry.pipeline.ingress_guards import NUL_REJECTED_REASON from messagefoundry.store.store import MessageStatus, MessageStore @@ -52,21 +54,48 @@ def _gzipped(text: str) -> bytes: async def _rows(store: MessageStore) -> list[Any]: - cur = await store._db.execute("SELECT status, error FROM messages") + cur = await store._db.execute("SELECT id, status, error FROM messages ORDER BY rowid") return list(await cur.fetchall()) -async def _post( - store: MessageStore, http: Http, content_type: ContentType, body: bytes, **headers: str -) -> _Response: +async def _queued(store: MessageStore) -> int: + cur = await store._db.execute("SELECT COUNT(*) AS n FROM queue") + row = await cur.fetchone() + assert row is not None + return int(row["n"]) + + +async def _post_each( + store: MessageStore, + http: ConnectionSpec, + content_type: ContentType, + *bodies: tuple[bytes, dict[str, str] | None], +) -> list[_Response]: + """POST each body, with its headers, to one listener, in order.""" ic = build_inbound_connection("IB_HTTP", http, router="r", content_type=content_type) src = await _start_source(store, ic) try: - return await _http(src.sockport, body=body, extra_headers=headers or None) + return [ + await _http(src.sockport, body=body, extra_headers=headers) for body, headers in bodies + ] finally: await src.stop() +async def _assert_refused( + store: MessageStore, resp: _Response, reason: str, *, queued: int = 0 +) -> None: + """The answer is a permanent ``422`` naming the newest row, which is ``ERROR`` with ``reason``, + and the refused body did not reach the ingress stage: ``queued`` counts the bodies accepted + before it.""" + assert resp.status == 422 + row = (await _rows(store))[-1] + assert resp.json() == {"error": "message was not accepted", "refused_message_id": row["id"]} + assert row["status"] == MessageStatus.ERROR.value + assert str(row["error"]).startswith(f"[refusal kind: permanent] {reason}"), row["error"] + assert await _queued(store) == queued, "a refused body reached the ingress stage" + + @pytest.mark.parametrize( ("content_type", "plain"), [ @@ -81,35 +110,55 @@ async def test_a_gzipped_body_is_refused_422_as_a_decode_error( store: MessageStore, content_type: ContentType, plain: str ) -> None: """The compressed bytes are not valid UTF-8, so the receipt handler refuses them as a body the - engine cannot decode: a permanent refusal, ``422``, recorded as one ``ERROR`` row. Nothing - inflates the body first. The same body sent plain is accepted, so the refusal is the - compression's and not the inbound's.""" - plain_resp = await _post(store, Http(port=0), content_type, plain.encode("utf-8")) + engine cannot decode. Nothing inflates the body first. The same payload sent plain to the same + listener is accepted first, so the refusal is the compression's and not the inbound's.""" + plain_resp, gz_resp = await _post_each( + store, + Http(port=0), + content_type, + (plain.encode("utf-8"), None), + (_gzipped(plain), _GZIP), + ) assert plain_resp.status == 202 - resp = await _post(store, Http(port=0), content_type, _gzipped(plain), **_GZIP) - assert resp.status == 422 - assert resp.json()["error"] == "message was not accepted" rows = await _rows(store) assert [r["status"] for r in rows] == [MessageStatus.RECEIVED.value, MessageStatus.ERROR.value] - assert str(rows[1]["error"]).startswith("[refusal kind: permanent] decode error (utf-8)") + await _assert_refused(store, gz_resp, "decode error (utf-8)", queued=1) -async def test_a_gzipped_body_on_a_single_byte_text_inbound_is_refused_for_its_nul_bytes( +async def test_a_gzipped_body_under_latin_1_is_refused_for_its_nul_bytes( store: MessageStore, ) -> None: """Latin-1 maps every byte to a character, so the compressed bytes do decode. They are still - refused ``422``, because a gzip header with no flags set carries NUL bytes and the engine - refuses a NUL in a text body. That is a property of gzip, not a rule about compression: a coding - whose bytes hold no NUL would be committed under this charset as its bytes.""" + refused, because a gzip header with no flags set carries NUL bytes and the engine refuses a NUL + in a text body.""" compressed = _gzipped("synthetic text body") assert b"\x00" in compressed # the premise: the stream itself holds a NUL - resp = await _post( - store, Http(port=0, encoding="latin-1"), ContentType.TEXT, compressed, **_GZIP + [resp] = await _post_each( + store, Http(port=0, encoding="latin-1"), ContentType.TEXT, (compressed, _GZIP) ) - assert resp.status == 422 - rows = await _rows(store) - assert [r["status"] for r in rows] == [MessageStatus.ERROR.value] - assert str(rows[0]["error"]).startswith(f"[refusal kind: permanent] {NUL_REJECTED_REASON}") + await _assert_refused(store, resp, NUL_REJECTED_REASON) + + +async def test_a_nul_free_deflate_body_under_latin_1_is_committed_as_its_bytes( + store: MessageStore, +) -> None: + """The refusal above is a property of gzip's header, not a rule about compression: a zlib + stream that holds no NUL decodes under latin-1, passes every text check, and is committed as + the compressed bytes read as latin-1, answered ``202``. This is why the docs tell a partner to + stop compressing rather than rely on a refusal.""" + compressed = zlib.compress(b"synthetic " + b"f" * 34 + b" body 1995") + assert b"\x00" not in compressed # the premise: this stream holds no NUL + [resp] = await _post_each( + store, + Http(port=0, encoding="latin-1"), + ContentType.TEXT, + (compressed, {"Content-Encoding": "deflate"}), + ) + assert resp.status == 202 + msg = await store.get_message(resp.json()["message_id"]) + assert msg is not None + assert msg["status"] == MessageStatus.RECEIVED.value + assert msg["raw"].encode("latin-1") == compressed async def test_a_gzipped_body_on_a_binary_inbound_is_committed_compressed( @@ -118,7 +167,7 @@ async def test_a_gzipped_body_on_a_binary_inbound_is_committed_compressed( """A ``binary`` inbound carries its body as base64 of the bytes received (ADR 0028), so the committed message is the gzip stream itself, answered ``202``.""" compressed = _gzipped("synthetic binary payload") - resp = await _post(store, Http(port=0), ContentType.BINARY, compressed, **_GZIP) + [resp] = await _post_each(store, Http(port=0), ContentType.BINARY, (compressed, _GZIP)) assert resp.status == 202 msg = await store.get_message(resp.json()["message_id"]) assert msg is not None @@ -126,13 +175,11 @@ async def test_a_gzipped_body_on_a_binary_inbound_is_committed_compressed( assert binary.decode(msg["raw"]) == compressed -async def test_a_gzipped_body_on_a_dicom_inbound_is_refused_for_its_missing_magic( - store: MessageStore, -) -> None: - """``dicom`` is a binary type too, but it checks the body's magic bytes, which a gzip stream - does not carry: refused ``422`` as a declared-type mismatch.""" - resp = await _post(store, Http(port=0), ContentType.DICOM, _gzipped("synthetic"), **_GZIP) - assert resp.status == 422 - rows = await _rows(store) - assert [r["status"] for r in rows] == [MessageStatus.ERROR.value] - assert "does not match its declared content type" in str(rows[0]["error"]) +async def test_a_gzipped_body_on_a_dicom_inbound_is_not_committed(store: MessageStore) -> None: + """``dicom`` is a binary type too, but unlike ``binary`` it does not commit the gzip stream: it + refuses it as a declared-type mismatch, as it refuses any body without DICOM magic. This pins + only that the compressed bytes are not accepted there, not anything about compression.""" + [resp] = await _post_each( + store, Http(port=0), ContentType.DICOM, (_gzipped("synthetic"), _GZIP) + ) + await _assert_refused(store, resp, "ingress body does not match its declared content type") From 53c766f19e32076e554079ba80ff4915173382d3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:58:13 -0600 Subject: [PATCH 06/39] docs: narrow the Content-Encoding paragraph after review round 2 (BACKLOG #5660) Says latin-1 rather than any single-byte charset, since cp1252 and ascii refuse many gzip bodies as decode errors first. Drops "by design" for what the record holds: intended under BACKLOG #5660, no ADR. Stops offering a binary inbound as the workaround, because the inflated payload would meet no text or HL7 ingress check, and links the bounded decompressors instead of restating them. Proposed PR title: HTTP listener: record and pin that no Content-Encoding is decoded (BACKLOG #5660) Proposed vault banner: CLOSED -- docs gap closed: docs/CONNECTIONS.md HTTP listener section records that no Content-Encoding is decoded and what each content_type does with a compressed body; tests/test_inbound_http_content_encoding.py pins it. Measured: gzip on latin-1 text answers 422 (header NUL bytes), not 202 as filed; a NUL-free deflate body there answers 202 and is committed as its bytes. Verified-by: none --- docs/CONNECTIONS.md | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 317aa88406..7115f7063a 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -1002,20 +1002,21 @@ refusals come before the TLS handshake, so the socket is closed with no answer i `503`: a TLS client cannot read a plaintext one (BACKLOG #2479). `GET`/`HEAD` are static, non-PHI health probes and write **no** ingress row; any other method is `405`. A probe is held to the same head rules as any request, so an HTTP/1.1 probe must send one `Host` header. Methods are case-sensitive (RFC 9110), so a lowercase `get` or `post` is not a probe or an intake request. -**No `Content-Encoding` is decoded, by design** (BACKLOG #5660). The listener reads the body as -sent and neither inflates nor refuses a `Content-Encoding` such as `gzip`, so a compressed body -reaches the engine compressed, and the inbound's `content_type` and `encoding` decide what follows, -as for any other body. For a gzipped body, at least: under UTF-8, `hl7v2`, `json`, `xml`, `text` -and `fhir` refuse it at ingress with `422` and one `ERROR` row, as a body that does not decode; -`text` under a single-byte `encoding` decodes it and then refuses it `422` for the NUL bytes a gzip -header carries; `dicom` refuses it `422`, since it carries no DICOM magic; and `binary` commits the -compressed bytes as an accepted body. **The refusals are not a rule about compression.** A coding -whose bytes hold no NUL, such as many short `deflate` streams, is committed as its bytes on a `text` -inbound under a single-byte `encoding`, and routed as if it were the payload. So a partner that -compresses its POST bodies should stop, or send to a `binary` inbound whose Handler inflates them -with the bounded `gzip_decompress` (`parsing/compression.py`, ADR 0123), never a bare -`gzip.decompress`, which sets no bound on what a partner-sized body inflates to. -`tests/test_inbound_http_content_encoding.py` pins the gzip outcomes above. +**No `Content-Encoding` is decoded.** This is intended behaviour, recorded under BACKLOG #5660; no +ADR rules on it. The listener reads the body as sent and neither inflates nor refuses a +`Content-Encoding` such as `gzip`, so a compressed body reaches the engine compressed, and the +inbound's `content_type` and `encoding` decide what follows, as for any other body. For a gzipped +body, at least: under UTF-8, `hl7v2`, `json`, `xml`, `text` and `fhir` refuse it at ingress with +`422` and one `ERROR` row, as a body that does not decode; `text` under an `encoding` that maps +every byte, such as `latin-1`, decodes it and then refuses it `422` for the NUL bytes a gzip header +carries; `dicom` refuses it `422`, as it refuses any body without DICOM magic; and `binary` commits +the compressed bytes as an accepted body. **The refusals are not a rule about compression.** A +`deflate` body whose bytes hold no NUL is committed as its bytes on a `latin-1` `text` inbound, and +routed as if it were the payload. **A partner that compresses its POST bodies should stop.** A +`binary` inbound accepts them, but checks only their size, so a payload a Handler inflates there +has met none of the text or HL7 ingress checks, and the Handler cannot see `Content-Encoding`, only +the bytes. The bounded decompressors are listed under *Unpacking a payload* below. +`tests/test_inbound_http_content_encoding.py` pins each outcome above. **Synchronous captured-downstream reply (`reply_from`, ADR 0154 increment B).** Naming `reply_from` makes the HTTP turn **block** until the named outbound's reply has been captured **and committed to the store**, From 6530ca4f6f7c3be3368dc6d0fcb61a635cfd33bf Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:11:16 -0600 Subject: [PATCH 07/39] http_listener: answer Expect: 100-continue once authorised (BACKLOG #6476) A client that holds its body back for the interim answer, as .NET and SOAP stacks do by default, got neither 100 Continue nor a final status, and waited until its own timeout or the listener's 408. The listener now sends 100 Continue from _read_body's new before_read hook: after header-mode auth, after the max_body_bytes check, before the first body byte. So an unauthorised or over-size request still gets its 401 or 413 and never a 100, and its client never sends the body. HTTP/1.0, an empty body and any other expectation get no 100, as before; an Expect sent on two lines is read as one list. New tests/test_inbound_http_expect_continue.py: the three positive arms failed before the change (no interim answer within 2 s); the refusal arms pin that no 100 precedes a 401 or 413. Verified-by: tests --- messagefoundry/transports/http_listener.py | 69 +++++- tests/test_inbound_http_expect_continue.py | 231 +++++++++++++++++++++ 2 files changed, 296 insertions(+), 4 deletions(-) create mode 100644 tests/test_inbound_http_expect_continue.py diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index d0e0d62d99..1eb3db47f9 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -51,7 +51,7 @@ import socket import ssl import time -from collections.abc import Callable, Mapping +from collections.abc import Awaitable, Callable, Mapping from typing import TYPE_CHECKING, Any, ClassVar, assert_never, cast from messagefoundry.config.listener_proxies import ( @@ -188,7 +188,15 @@ class HttpRequest: metadata (ADR 0004 §4), never executed; the body is handed verbatim to the pipeline handler. """ - __slots__ = ("method", "target", "headers", "body", "repeated", "forwarded_header") + __slots__ = ( + "method", + "target", + "headers", + "body", + "repeated", + "forwarded_header", + "expects_continue", + ) def __init__( self, @@ -198,6 +206,7 @@ def __init__( body: bytes, repeated: frozenset[str], forwarded_header: str = "", + expects_continue: bool = False, ) -> None: self.method = method self.target = target @@ -212,6 +221,9 @@ def __init__( #: them. ``headers`` keeps only the last line, and the walk in #: ``HttpSource._forwarded_client`` must cross line boundaries (BACKLOG #5525). self.forwarded_header = forwarded_header + #: Whether the client holds its body back for a ``100 Continue`` (BACKLOG #6476): an + #: ``Expect`` naming ``100-continue`` on a version above HTTP/1.0. See :func:`_expects_continue`. + self.expects_continue = expects_continue def _status_line(status: int) -> str: @@ -268,6 +280,23 @@ def _status_line(status: int) -> str: #: refused, because those are the declared bytes this listener would never read. _BODY_METHODS = frozenset({"POST", "PUT", "PATCH"}) +#: The interim answer to ``Expect: 100-continue`` (RFC 9110 section 15.2.1, BACKLOG #6476). It is a +#: bare status line: a 1xx carries no content, and :func:`build_response` writes final answers only. +_CONTINUE = b"HTTP/1.1 100 Continue\r\n\r\n" + + +def _expects_continue(version: str, expect: str | None) -> bool: + """Whether a request's ``Expect`` header asks for ``100 Continue`` before its body. + + The expectation is matched case-insensitively among the field's comma-separated members (RFC + 9110 section 10.1.1). An HTTP/1.0 request never gets one, since a server MUST NOT send a 1xx to + an HTTP/1.0 client. Any other expectation is ignored, as it was before BACKLOG #6476, rather + than refused ``417``, which that section allows but does not require.""" + if expect is None or version == "HTTP/1.0": + return False + return any(m.strip(" \t").lower() == "100-continue" for m in expect.split(",")) + + #: The ``error`` text of every answer to a body the receipt handler refused AFTER recording it with #: status ERROR. ``RegistryRunner._handle_inbound_http`` holds the guards that do this. The receipt #: path and the sync-reply path both answer it, so a caller is never told a refused body was accepted @@ -504,6 +533,8 @@ async def _read_head( # repeat hidden behind an underscore spelling is still a repeat (BACKLOG #2051). folded_counts: dict[str, int] = {} forwarded_lines: list[str] = [] + # Every Expect line, since a field sent twice is one comma-separated list (RFC 9110 5.3). + expect_lines: list[str] = [] for line in lines[1:]: if not line: continue @@ -537,6 +568,8 @@ async def _read_head( headers[key] = value.strip(" \t") if key == _FORWARDED_FOR: forwarded_lines.append(headers[key]) + elif key == "expect": + expect_lines.append(headers[key]) # Reject AMBIGUOUS framing before any Content-Length is trusted — the HTTP request-smuggling # defense (RFC 7230 §3.3.3). A duplicate Content-Length / Transfer-Encoding, or the two present @@ -616,7 +649,15 @@ async def _read_head( raise HttpRequestError(400, "missing Host header", kind="framing_error") repeated = frozenset(name for name, count in folded_counts.items() if count > 1) - return HttpRequest(method, target, headers, b"", repeated, ",".join(forwarded_lines)) + return HttpRequest( + method, + target, + headers, + b"", + repeated, + ",".join(forwarded_lines), + expects_continue=_expects_continue(version, ",".join(expect_lines) or None), + ) async def _read_body( @@ -624,12 +665,18 @@ async def _read_body( head: HttpRequest, *, max_body_bytes: int | None, + before_read: Callable[[int], Awaitable[None]] | None = None, ) -> bytes: """Read the body belonging to an already-parsed ``head``, applying the body cap. Split out of :func:`_read_request` so authentication can run between the two halves (see :func:`_read_head`). + ``before_read`` is awaited with the declared length once that length has passed the cap, and + before the first body byte is read. It is the one point where a request is known to be + authorised and within its size, so the ``100 Continue`` answer is sent from it (BACKLOG #6476). + It is not called for a method that reads no body. + **This function no longer decides framing, and the ordering warning that used to live here is gone because the thing it warned about was done deliberately** (BACKLOG #1125, ASVS 4.2.1). It said the GET/HEAD short-circuit running before the chunked refusal was load-bearing, and that @@ -656,6 +703,8 @@ async def _read_body( if max_body_bytes is not None and content_length > max_body_bytes: # Refuse on the DECLARED size before reading a single body byte (don't buffer to find out). raise HttpRequestError(413, "body exceeds cap", kind="frame_oversize") + if before_read is not None: + await before_read(content_length) return await _read_exactly(reader, content_length) @@ -1933,7 +1982,19 @@ async def _read_authenticated() -> HttpRequest: """ head = await _read_head(reader, max_header_bytes=self.max_header_bytes) self._authorize_head(head, peer_host) - head.body = await _read_body(reader, head, max_body_bytes=self.max_body_bytes) + + async def _ready(length: int) -> None: + # BACKLOG #6476: a client holding its body back for the interim answer gets it + # only here, once authorised and within max_body_bytes, so a refused client never + # sends a body. Inside the receive_timeout budget, and its drain is bounded too, so + # a peer that stops reading cannot hold the slot (a TimeoutError answers 408). + if length and head.expects_continue: + writer.write(_CONTINUE) + await asyncio.wait_for(writer.drain(), _CLIENT_SHUTDOWN_GRACE) + + head.body = await _read_body( + reader, head, max_body_bytes=self.max_body_bytes, before_read=_ready + ) return head # ASVS 2.4.1 / 15.2.2. The wait happens BEFORE any request byte is read, so the excess is diff --git a/tests/test_inbound_http_expect_continue.py b/tests/test_inbound_http_expect_continue.py new file mode 100644 index 0000000000..d5998b0387 --- /dev/null +++ b/tests/test_inbound_http_expect_continue.py @@ -0,0 +1,231 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The inbound HTTP listener answers ``Expect: 100-continue`` (BACKLOG #6476). + +A client that sends the expectation, at least the .NET and SOAP stacks that do so by default, holds +its body back until the server answers ``100 Continue`` or a final status. Before this change the +listener answered neither: it waited for a body that would not come until the client's own wait ran +out, and with a client that waits longer than ``receive_timeout`` the request ended in a ``408``. + +The interim answer is sent only once the request is authorised and its declared size is within +``max_body_bytes``, immediately before the body is read. So an unauthorised or over-size request +still gets its refusal, and the client never sends a body the listener would only refuse. Both +arms are pinned here, as are the cases RFC 9110 section 10.1.1 tells a server to skip: an HTTP/1.0 +request and a request with no content. Synthetic, PHI-free payloads only.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +from messagefoundry.config.models import ConnectorType, Source +from messagefoundry.transports.http_listener import HttpSource +from messagefoundry.transports.receipt import IngressReceipt, receipt_handler + +_KEY = "synthetic-intake-key" +_CONTINUE = b"HTTP/1.1 100 Continue\r\n\r\n" +#: Long enough for a loopback answer, short enough that a listener that never answers the +#: expectation fails the test quickly rather than at the client's own timeout. +_INTERIM_WAIT = 2.0 + + +class _Started: + def __init__(self, source: HttpSource, bodies: list[bytes]) -> None: + self.source = source + self.bodies = bodies + + +async def _start(**settings: Any) -> _Started: + base: dict[str, Any] = {"host": "127.0.0.1", "port": 0} + base.update(settings) + source = HttpSource(Source(type=ConnectorType.HTTP, settings=base)) + bodies: list[bytes] = [] + + async def handler(raw: bytes) -> IngressReceipt: + bodies.append(raw) + return IngressReceipt.accepted("msg-1") + + await source.start(receipt_handler(handler)) + return _Started(source, bodies) + + +def _head( + body_length: int, + *, + expect: str | None = "100-continue", + version: str = "HTTP/1.1", + key: str | None = None, +) -> bytes: + lines = [f"POST /ingest {version}", "Host: localhost", f"Content-Length: {body_length}"] + if expect is not None: + lines.append(f"Expect: {expect}") + if key is not None: + lines.append(f"x-api-key: {key}") + return ("\r\n".join([*lines, "", ""])).encode("ascii") + + +async def _first_answer(reader: asyncio.StreamReader) -> bytes: + """The first response head the listener writes, or ``b""`` when it writes none in time.""" + try: + return await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), _INTERIM_WAIT) + except (TimeoutError, asyncio.IncompleteReadError, ConnectionResetError): + return b"" + + +async def _exchange( + port: int, head: bytes, body: bytes, *, wait_for_interim: bool = True +) -> tuple[bytes, bytes]: + """Send ``head``; if ``wait_for_interim``, wait for the listener's first answer before the body, + as a client honouring the expectation does. Returns that first answer and everything after.""" + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + writer.write(head) + await writer.drain() + first = b"" + if wait_for_interim: + first = await _first_answer(reader) + if first != _CONTINUE: + # A final answer: a client honouring the expectation never sends the body. + rest = await asyncio.wait_for(reader.read(-1), 5.0) + return first, rest + writer.write(body) + await writer.drain() + try: + rest = await asyncio.wait_for(reader.read(-1), 5.0) + except (ConnectionResetError, OSError): + rest = b"" + return first, rest + finally: + writer.close() + try: # noqa: SIM105 + await writer.wait_closed() + except OSError: + pass + + +def _status(head: bytes) -> int: + return int(head.split(b" ", 2)[1]) if head else 0 + + +async def test_an_authorised_request_is_answered_100_continue_before_its_body() -> None: + started = await _start(intake_auth="api_key", intake_api_key=_KEY) + try: + first, rest = await _exchange(started.source.sockport, _head(2, key=_KEY), b"{}") + finally: + await started.source.stop() + assert first == _CONTINUE + assert _status(rest) == 202 + assert started.bodies == [b"{}"] + + +async def test_an_unauthorised_request_gets_its_refusal_and_never_a_100_continue() -> None: + started = await _start(intake_auth="api_key", intake_api_key=_KEY) + try: + first, rest = await _exchange(started.source.sockport, _head(2, key="wrong"), b"{}") + finally: + await started.source.stop() + assert _status(first) == 401 + assert _CONTINUE not in first + rest + assert started.bodies == [] + + +async def test_a_request_with_no_credential_gets_its_refusal_and_never_a_100_continue() -> None: + started = await _start(intake_auth="bearer", intake_api_key=_KEY) + try: + first, rest = await _exchange(started.source.sockport, _head(2), b"{}") + finally: + await started.source.stop() + assert _status(first) == 401 + assert _CONTINUE not in first + rest + assert started.bodies == [] + + +async def test_an_over_size_request_gets_413_and_never_a_100_continue() -> None: + started = await _start(max_body_bytes=4) + try: + first, rest = await _exchange(started.source.sockport, _head(10), b"0123456789") + finally: + await started.source.stop() + assert _status(first) == 413 + assert _CONTINUE not in first + rest + assert started.bodies == [] + + +async def test_without_intake_auth_the_100_continue_follows_the_head() -> None: + started = await _start() + try: + first, rest = await _exchange(started.source.sockport, _head(2), b"{}") + finally: + await started.source.stop() + assert first == _CONTINUE + assert _status(rest) == 202 + + +async def test_the_expectation_token_is_case_insensitive() -> None: + started = await _start() + try: + first, rest = await _exchange( + started.source.sockport, _head(2, expect="100-Continue"), b"{}" + ) + finally: + await started.source.stop() + assert first == _CONTINUE + assert _status(rest) == 202 + + +async def test_the_expectation_is_found_in_a_list_or_a_second_expect_line() -> None: + """A field sent twice is one comma-separated list (RFC 9110 section 5.3), and the head parse + keeps only the last value of each header, so the expectation is read across every line.""" + started = await _start() + try: + port = started.source.sockport + listed = await _exchange(port, _head(2, expect="synthetic, 100-continue"), b"{}") + split = await _exchange(port, _head(2, expect="100-continue\r\nExpect: synthetic"), b"{}") + finally: + await started.source.stop() + for first, rest in (listed, split): + assert first == _CONTINUE + assert _status(rest) == 202 + + +async def test_no_100_continue_is_sent_without_the_expectation_or_for_http_1_0() -> None: + """RFC 9110 section 10.1.1: a server MUST NOT send ``100 Continue`` to an HTTP/1.0 client, and + there is nothing to send it for without the expectation. The body is read as before.""" + started = await _start() + try: + plain = await _exchange( + started.source.sockport, _head(2, expect=None), b"{}", wait_for_interim=False + ) + old = await _exchange( + started.source.sockport, _head(2, version="HTTP/1.0"), b"{}", wait_for_interim=False + ) + finally: + await started.source.stop() + for _, rest in (plain, old): + assert _status(rest) == 202 + assert _CONTINUE not in rest + + +async def test_no_100_continue_is_sent_for_an_empty_body() -> None: + """A request with no content has no body to hold back, so the final answer comes directly.""" + started = await _start() + try: + first, rest = await _exchange(started.source.sockport, _head(0), b"") + finally: + await started.source.stop() + assert _CONTINUE not in first + rest + assert _status(first) == 202 + + +async def test_an_unknown_expectation_is_ignored_as_before() -> None: + """Only ``100-continue`` is answered. Any other expectation is ignored, as it was before this + change, rather than refused ``417``: RFC 9110 lets a server do either.""" + started = await _start() + try: + first, rest = await _exchange( + started.source.sockport, _head(2, expect="synthetic"), b"{}", wait_for_interim=False + ) + finally: + await started.source.stop() + assert _status(rest) == 202 + assert _CONTINUE not in first + rest From 1b1ad6928c96c505a971e6baeced7da100c1e3f1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:11:58 -0600 Subject: [PATCH 08/39] docs: the HTTP listener answers Expect: 100-continue (BACKLOG #6476) The HTTP listener section of docs/CONNECTIONS.md says when the interim answer is sent, that a refused request never gets one, and which requests get none. Proposed PR title: HTTP listener: answer Expect: 100-continue only after authorisation (BACKLOG #6476) Proposed vault banner: CLOSED -- the HTTP listener sends 100 Continue after head authentication and the max_body_bytes check, before the body read; unauthorised and over-size requests get their refusal and no 100. Tests in tests/test_inbound_http_expect_continue.py; documented in docs/CONNECTIONS.md. Unknown expectations stay ignored, not 417. Verified-by: none --- docs/CONNECTIONS.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 7115f7063a..ba5d558ecd 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -1018,6 +1018,13 @@ has met none of the text or HL7 ingress checks, and the Handler cannot see `Cont the bytes. The bounded decompressors are listed under *Unpacking a payload* below. `tests/test_inbound_http_content_encoding.py` pins each outcome above. +**`Expect: 100-continue` is answered** (BACKLOG #6476). A client that holds its body back for the +interim answer, as .NET and SOAP stacks do by default, gets `100 Continue` once its request has +passed the checks made before the body is read: at least the head rules, intake authentication and +`max_body_bytes`. A request any of them refuses gets that refusal instead, never a `100`, so its +client never sends the body. An HTTP/1.0 request and a request with an empty body get no `100`, and +any other expectation is ignored rather than refused `417`. + **Synchronous captured-downstream reply (`reply_from`, ADR 0154 increment B).** Naming `reply_from` makes the HTTP turn **block** until the named outbound's reply has been captured **and committed to the store**, then returns that reply as the response body — a proxy API rather than a receipt. The **committed row is From 47b519ef9c672c7acdec71cabe8e8db29fd50664 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:24:37 -0600 Subject: [PATCH 09/39] http_listener: no 100 Continue once stop() began; a stalled one reads as peer_reset (BACKLOG #6476) Review round 1 repair. The interim answer is skipped once stop() has begun or the writer is closing, so a body that arrived with the head still reaches the BACKLOG #5715 shutdown handling rather than a drain error. A 100 Continue the peer never reads is a ConnectionError, logged as peer_reset like a stalled _respond, not the 408 for a slow request. The write goes through _respond. The hook takes no length and is not called for an empty body; Expect lines go to _expects_continue as a list. New arms: repeated credential header (400), spent budget (429), and stop() begun between head and body. Verified-by: tests --- messagefoundry/transports/http_listener.py | 64 ++++++++++------- tests/test_inbound_http_expect_continue.py | 84 +++++++++++++++++++--- 2 files changed, 113 insertions(+), 35 deletions(-) diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 1eb3db47f9..0eac0730b5 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -285,16 +285,21 @@ def _status_line(status: int) -> str: _CONTINUE = b"HTTP/1.1 100 Continue\r\n\r\n" -def _expects_continue(version: str, expect: str | None) -> bool: - """Whether a request's ``Expect`` header asks for ``100 Continue`` before its body. - - The expectation is matched case-insensitively among the field's comma-separated members (RFC - 9110 section 10.1.1). An HTTP/1.0 request never gets one, since a server MUST NOT send a 1xx to - an HTTP/1.0 client. Any other expectation is ignored, as it was before BACKLOG #6476, rather - than refused ``417``, which that section allows but does not require.""" - if expect is None or version == "HTTP/1.0": +def _expects_continue(version: str, expect_lines: list[str]) -> bool: + """Whether a request's ``Expect`` lines ask for ``100 Continue`` before its body. + + The expectation is matched case-insensitively among the comma-separated members of every + ``Expect`` line, since a field sent twice is one list (RFC 9110 sections 5.3 and 10.1.1). An + HTTP/1.0 request never gets one, since a server MUST NOT send a 1xx to an HTTP/1.0 client. Any + other expectation is ignored, as it was before BACKLOG #6476, rather than refused ``417``, + which that section allows but does not require.""" + if version == "HTTP/1.0": return False - return any(m.strip(" \t").lower() == "100-continue" for m in expect.split(",")) + return any( + member.strip(" \t").lower() == "100-continue" + for line in expect_lines + for member in line.split(",") + ) #: The ``error`` text of every answer to a body the receipt handler refused AFTER recording it with @@ -533,7 +538,7 @@ async def _read_head( # repeat hidden behind an underscore spelling is still a repeat (BACKLOG #2051). folded_counts: dict[str, int] = {} forwarded_lines: list[str] = [] - # Every Expect line, since a field sent twice is one comma-separated list (RFC 9110 5.3). + # Every Expect line: `headers` keeps only the last, and `_expects_continue` reads them all. expect_lines: list[str] = [] for line in lines[1:]: if not line: @@ -656,7 +661,7 @@ async def _read_head( b"", repeated, ",".join(forwarded_lines), - expects_continue=_expects_continue(version, ",".join(expect_lines) or None), + expects_continue=_expects_continue(version, expect_lines), ) @@ -665,17 +670,17 @@ async def _read_body( head: HttpRequest, *, max_body_bytes: int | None, - before_read: Callable[[int], Awaitable[None]] | None = None, + before_read: Callable[[], Awaitable[None]] | None = None, ) -> bytes: """Read the body belonging to an already-parsed ``head``, applying the body cap. Split out of :func:`_read_request` so authentication can run between the two halves (see :func:`_read_head`). - ``before_read`` is awaited with the declared length once that length has passed the cap, and - before the first body byte is read. It is the one point where a request is known to be - authorised and within its size, so the ``100 Continue`` answer is sent from it (BACKLOG #6476). - It is not called for a method that reads no body. + ``before_read`` is awaited once a non-empty declared length has passed the cap, before the + first body byte is read. ``HttpSource._serve_one`` sends ``100 Continue`` from it, having + authorised the head first (BACKLOG #6476). It is not called for an empty body or for a method + that reads none. **This function no longer decides framing, and the ordering warning that used to live here is gone because the thing it warned about was done deliberately** (BACKLOG #1125, ASVS 4.2.1). It @@ -703,8 +708,8 @@ async def _read_body( if max_body_bytes is not None and content_length > max_body_bytes: # Refuse on the DECLARED size before reading a single body byte (don't buffer to find out). raise HttpRequestError(413, "body exceeds cap", kind="frame_oversize") - if before_read is not None: - await before_read(content_length) + if before_read is not None and content_length: + await before_read() return await _read_exactly(reader, content_length) @@ -1983,14 +1988,21 @@ async def _read_authenticated() -> HttpRequest: head = await _read_head(reader, max_header_bytes=self.max_header_bytes) self._authorize_head(head, peer_host) - async def _ready(length: int) -> None: - # BACKLOG #6476: a client holding its body back for the interim answer gets it - # only here, once authorised and within max_body_bytes, so a refused client never - # sends a body. Inside the receive_timeout budget, and its drain is bounded too, so - # a peer that stops reading cannot hold the slot (a TimeoutError answers 408). - if length and head.expects_continue: - writer.write(_CONTINUE) - await asyncio.wait_for(writer.drain(), _CLIENT_SHUTDOWN_GRACE) + async def _ready() -> None: + # BACKLOG #6476: the interim answer is sent only here, after header-mode auth above + # and the max_body_bytes check in _read_body, so a refused client is never invited + # to send its body. Not once stop() has begun or the writer is closing: the body + # read then fails or finds a buffered body as it would without the expectation, so + # the #5715 handling below still sees it. + if not head.expects_continue or self._admission.stopping or writer.is_closing(): + return + try: + await self._respond(writer, _CONTINUE, budget=_CLIENT_SHUTDOWN_GRACE) + except TimeoutError: + # A peer that stops reading. Raised as a connection fault, not a timeout, so + # it reads as `peer_reset`, as a stalled `_respond` does, rather than as the + # 408 the receive_timeout arm below answers a slow request with. + raise ConnectionError("the peer did not read the 100 Continue") from None head.body = await _read_body( reader, head, max_body_bytes=self.max_body_bytes, before_read=_ready diff --git a/tests/test_inbound_http_expect_continue.py b/tests/test_inbound_http_expect_continue.py index d5998b0387..5713350935 100644 --- a/tests/test_inbound_http_expect_continue.py +++ b/tests/test_inbound_http_expect_continue.py @@ -2,16 +2,17 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """The inbound HTTP listener answers ``Expect: 100-continue`` (BACKLOG #6476). -A client that sends the expectation, at least the .NET and SOAP stacks that do so by default, holds -its body back until the server answers ``100 Continue`` or a final status. Before this change the -listener answered neither: it waited for a body that would not come until the client's own wait ran -out, and with a client that waits longer than ``receive_timeout`` the request ended in a ``408``. +A client that sends the expectation waits a short while for ``100 Continue`` or a final status +before it sends its body. Before this change the listener answered neither, so every such client +sat out its own wait first, and one that waits longer than ``receive_timeout`` got a ``408``. The interim answer is sent only once the request is authorised and its declared size is within ``max_body_bytes``, immediately before the body is read. So an unauthorised or over-size request -still gets its refusal, and the client never sends a body the listener would only refuse. Both -arms are pinned here, as are the cases RFC 9110 section 10.1.1 tells a server to skip: an HTTP/1.0 -request and a request with no content. Synthetic, PHI-free payloads only.""" +gets its refusal and never a ``100``, and its client is never invited to send the body. The refusal +arms pinned here are at least a wrong or missing credential, a repeated credential header, a spent +failed-attempt budget and an over-size declaration. No ``100`` is sent to an HTTP/1.0 client, which +RFC 9110 section 10.1.1 forbids, nor for a request with no content or once ``stop()`` has begun. +Synthetic, PHI-free payloads only.""" from __future__ import annotations @@ -55,12 +56,14 @@ def _head( expect: str | None = "100-continue", version: str = "HTTP/1.1", key: str | None = None, + extra: tuple[str, ...] = (), ) -> bytes: lines = [f"POST /ingest {version}", "Host: localhost", f"Content-Length: {body_length}"] if expect is not None: lines.append(f"Expect: {expect}") if key is not None: lines.append(f"x-api-key: {key}") + lines.extend(extra) return ("\r\n".join([*lines, "", ""])).encode("ascii") @@ -85,8 +88,11 @@ async def _exchange( if wait_for_interim: first = await _first_answer(reader) if first != _CONTINUE: - # A final answer: a client honouring the expectation never sends the body. - rest = await asyncio.wait_for(reader.read(-1), 5.0) + # A final answer, or none: a client honouring the expectation sends no body then. + try: + rest = await asyncio.wait_for(reader.read(-1), 5.0) + except (ConnectionResetError, OSError): + rest = b"" return first, rest writer.write(body) await writer.drain() @@ -140,6 +146,66 @@ async def test_a_request_with_no_credential_gets_its_refusal_and_never_a_100_con assert started.bodies == [] +async def test_a_repeated_credential_header_gets_400_and_never_a_100_continue() -> None: + started = await _start(intake_auth="api_key", intake_api_key=_KEY) + try: + first, rest = await _exchange( + started.source.sockport, _head(2, key=_KEY, extra=(f"x-api-key: {_KEY}",)), b"{}" + ) + finally: + await started.source.stop() + assert _status(first) == 400 + assert _CONTINUE not in first + rest + assert started.bodies == [] + + +async def test_a_spent_failed_attempt_budget_gets_429_and_never_a_100_continue() -> None: + """The budget is consulted before the credential, so even the right key is refused here.""" + + class _Spent: + def check(self, peer: str) -> bool: + return False + + def charge_failure(self, peer: str, *, charge_global: bool = True) -> None: + pass + + def note_success(self, peer: str) -> None: + pass + + started = await _start(intake_auth="api_key", intake_api_key=_KEY) + started.source.intake_rate_limiter = _Spent() # type: ignore[assignment] + try: + first, rest = await _exchange(started.source.sockport, _head(2, key=_KEY), b"{}") + finally: + await started.source.stop() + assert _status(first) == 429 + assert _CONTINUE not in first + rest + assert started.bodies == [] + + +async def test_no_100_continue_is_sent_once_stop_has_begun() -> None: + """A stop() that begins between the head and the body leaves the body read to the shutdown + handling it would get without the expectation (BACKLOG #5715), rather than writing an + invitation the listener is about to close on. Here the listener only reads as stopping, so the + body sent with the head is still read and answered.""" + started = await _start() + source = started.source + authorize = source._authorize_head + + def _authorize_then_stop(head: Any, peer_host: str | None) -> None: + authorize(head, peer_host) + source._admission.stopping = True + + source._authorize_head = _authorize_then_stop # type: ignore[method-assign] + try: + first, rest = await _exchange(source.sockport, _head(2), b"{}", wait_for_interim=False) + finally: + source._admission.stopping = False + await source.stop() + assert _CONTINUE not in first + rest + assert _status(rest) == 202 + + async def test_an_over_size_request_gets_413_and_never_a_100_continue() -> None: started = await _start(max_body_bytes=4) try: From 28d79ffde64bcbd14a5f2ea353268800cfad6491 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:25:32 -0600 Subject: [PATCH 10/39] docs: narrow the Expect: 100-continue paragraph after review (BACKLOG #6476) Review round 1 repair. Drops the claim that a refused client never sends its body: a client waits only a short while, and one that sends anyway may see a reset. Drops the .NET/SOAP default claim. Says a 100 is no promise to accept, and that no 100 is sent once the listener stops. Proposed PR title: HTTP listener: answer Expect: 100-continue only after authorisation (BACKLOG #6476) Proposed vault banner: CLOSED -- the HTTP listener sends 100 Continue after head authentication and the max_body_bytes check, before the body read; unauthorised, over-size, repeated-credential and rate-limited requests get their refusal and no 100. Tests in tests/test_inbound_http_expect_continue.py; documented in docs/CONNECTIONS.md. Not built: the row's 417 for an unknown expectation, which stays ignored (RFC 9110 makes 417 a MAY). Verified-by: none --- docs/CONNECTIONS.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index ba5d558ecd..6e495e6b66 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -1018,12 +1018,15 @@ has met none of the text or HL7 ingress checks, and the Handler cannot see `Cont the bytes. The bounded decompressors are listed under *Unpacking a payload* below. `tests/test_inbound_http_content_encoding.py` pins each outcome above. -**`Expect: 100-continue` is answered** (BACKLOG #6476). A client that holds its body back for the -interim answer, as .NET and SOAP stacks do by default, gets `100 Continue` once its request has -passed the checks made before the body is read: at least the head rules, intake authentication and -`max_body_bytes`. A request any of them refuses gets that refusal instead, never a `100`, so its -client never sends the body. An HTTP/1.0 request and a request with an empty body get no `100`, and -any other expectation is ignored rather than refused `417`. +**`Expect: 100-continue` is answered** (BACKLOG #6476). A client that sends the expectation waits a +short while for the interim answer before it sends its body. It gets `100 Continue` once its +request has passed the checks made before the body is read: at least the head rules, intake +authentication and `max_body_bytes`. A request any of them refuses gets that refusal instead, never +a `100`. A client that stops waiting and sends its body anyway may then see the connection reset +rather than read the refusal. A `100` is not a promise to accept: a body within `max_body_bytes` +can still be refused after it is read, at least over the engine's ingress ceiling. An HTTP/1.0 +request and a request with an empty body get no `100`, nor does one that arrives as the listener +stops, and any other expectation is ignored rather than refused `417`. **Synchronous captured-downstream reply (`reply_from`, ADR 0154 increment B).** Naming `reply_from` makes the HTTP turn **block** until the named outbound's reply has been captured **and committed to the store**, From 78964199a4d0626e8062e8a736f55dec56d0b030 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:39:06 -0600 Subject: [PATCH 11/39] http_listener: answer only a single Expect: 100-continue line (BACKLOG #6476) Review round 2 repair. An Expect sent on two lines, as a list, or with a quoted comma is no longer merged into a 100 Continue: a front end may read only one line, and would not anticipate the interim answer, the shape the duplicate Host and credential refusals exist to prevent. Such a request is read as before. The unreachable drain-timeout arm is gone (a 25-byte first write never waits on drain), and the hook is passed only when the request expects a 100. Tests: the closing-writer guard now has an arm that fails without it; the stop() arm closes the writer as stop() does; a GET probe with the expectation gets no 100. Verified-by: tests --- messagefoundry/transports/http_listener.py | 61 ++++++++------- tests/test_inbound_http_expect_continue.py | 87 ++++++++++++++++------ 2 files changed, 95 insertions(+), 53 deletions(-) diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 0eac0730b5..31a3641217 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -221,8 +221,8 @@ def __init__( #: them. ``headers`` keeps only the last line, and the walk in #: ``HttpSource._forwarded_client`` must cross line boundaries (BACKLOG #5525). self.forwarded_header = forwarded_header - #: Whether the client holds its body back for a ``100 Continue`` (BACKLOG #6476): an - #: ``Expect`` naming ``100-continue`` on a version above HTTP/1.0. See :func:`_expects_continue`. + #: Whether the client holds its body back for a ``100 Continue`` (BACKLOG #6476): a + #: single ``Expect: 100-continue`` on a version above HTTP/1.0. See :func:`_expects_continue`. self.expects_continue = expects_continue @@ -285,20 +285,23 @@ def _status_line(status: int) -> str: _CONTINUE = b"HTTP/1.1 100 Continue\r\n\r\n" -def _expects_continue(version: str, expect_lines: list[str]) -> bool: - """Whether a request's ``Expect`` lines ask for ``100 Continue`` before its body. - - The expectation is matched case-insensitively among the comma-separated members of every - ``Expect`` line, since a field sent twice is one list (RFC 9110 sections 5.3 and 10.1.1). An - HTTP/1.0 request never gets one, since a server MUST NOT send a 1xx to an HTTP/1.0 client. Any - other expectation is ignored, as it was before BACKLOG #6476, rather than refused ``417``, - which that section allows but does not require.""" - if version == "HTTP/1.0": - return False - return any( - member.strip(" \t").lower() == "100-continue" - for line in expect_lines - for member in line.split(",") +def _expects_continue(version: str, expect: str | None, lines: int) -> bool: + """Whether a request asks for ``100 Continue`` before its body: one ``Expect`` line, on a + version above HTTP/1.0, whose whole value is ``100-continue`` in any case (RFC 9110 section + 10.1.1). + + Anything else is not answered, and its body is read as before BACKLOG #6476: an HTTP/1.0 + request, since a server MUST NOT send a 1xx to an HTTP/1.0 client; any other expectation, + rather than a ``417``, which that section allows but does not require; and, deliberately, an + ``Expect`` sent on two lines or holding a list. A front end may read only the first line, or + not parse the list, and then not anticipate an interim answer this listener would send, which + is the shape the duplicate ``Host`` and credential refusals exist to prevent (BACKLOG #1972, + #2051). Ignoring such a request costs its client only the wait it has without this answer.""" + return ( + version != "HTTP/1.0" + and lines == 1 + and expect is not None + and expect.lower() == "100-continue" ) @@ -538,8 +541,6 @@ async def _read_head( # repeat hidden behind an underscore spelling is still a repeat (BACKLOG #2051). folded_counts: dict[str, int] = {} forwarded_lines: list[str] = [] - # Every Expect line: `headers` keeps only the last, and `_expects_continue` reads them all. - expect_lines: list[str] = [] for line in lines[1:]: if not line: continue @@ -573,8 +574,6 @@ async def _read_head( headers[key] = value.strip(" \t") if key == _FORWARDED_FOR: forwarded_lines.append(headers[key]) - elif key == "expect": - expect_lines.append(headers[key]) # Reject AMBIGUOUS framing before any Content-Length is trusted — the HTTP request-smuggling # defense (RFC 7230 §3.3.3). A duplicate Content-Length / Transfer-Encoding, or the two present @@ -661,7 +660,9 @@ async def _read_head( b"", repeated, ",".join(forwarded_lines), - expects_continue=_expects_continue(version, expect_lines), + expects_continue=_expects_continue( + version, headers.get("expect"), header_counts.get("expect", 0) + ), ) @@ -1993,19 +1994,17 @@ async def _ready() -> None: # and the max_body_bytes check in _read_body, so a refused client is never invited # to send its body. Not once stop() has begun or the writer is closing: the body # read then fails or finds a buffered body as it would without the expectation, so - # the #5715 handling below still sees it. - if not head.expects_continue or self._admission.stopping or writer.is_closing(): + # the #5715 handling below still sees it. A 25-byte first write does not wait on + # drain, so this adds no stall a peer could hold. + if self._admission.stopping or writer.is_closing(): return - try: - await self._respond(writer, _CONTINUE, budget=_CLIENT_SHUTDOWN_GRACE) - except TimeoutError: - # A peer that stops reading. Raised as a connection fault, not a timeout, so - # it reads as `peer_reset`, as a stalled `_respond` does, rather than as the - # 408 the receive_timeout arm below answers a slow request with. - raise ConnectionError("the peer did not read the 100 Continue") from None + await self._respond(writer, _CONTINUE, budget=_CLIENT_SHUTDOWN_GRACE) head.body = await _read_body( - reader, head, max_body_bytes=self.max_body_bytes, before_read=_ready + reader, + head, + max_body_bytes=self.max_body_bytes, + before_read=_ready if head.expects_continue else None, ) return head diff --git a/tests/test_inbound_http_expect_continue.py b/tests/test_inbound_http_expect_continue.py index 5713350935..dd43b23b1c 100644 --- a/tests/test_inbound_http_expect_continue.py +++ b/tests/test_inbound_http_expect_continue.py @@ -27,7 +27,8 @@ _CONTINUE = b"HTTP/1.1 100 Continue\r\n\r\n" #: Long enough for a loopback answer, short enough that a listener that never answers the #: expectation fails the test quickly rather than at the client's own timeout. -_INTERIM_WAIT = 2.0 +_INTERIM_WAIT = 5.0 +_PROBE = "\r\n".join(["GET / HTTP/1.1", "Host: localhost", "Expect: 100-continue", "", ""]).encode() class _Started: @@ -183,27 +184,50 @@ def note_success(self, peer: str) -> None: assert started.bodies == [] -async def test_no_100_continue_is_sent_once_stop_has_begun() -> None: - """A stop() that begins between the head and the body leaves the body read to the shutdown - handling it would get without the expectation (BACKLOG #5715), rather than writing an - invitation the listener is about to close on. Here the listener only reads as stopping, so the - body sent with the head is still read and answered.""" - started = await _start() - source = started.source +def _close_after_auth(source: HttpSource, *, stopping: bool) -> None: + """Make the listener close every client writer right after header-mode auth, as stop() does, + and optionally read as stopping, so the 100 Continue decision meets a closing writer.""" authorize = source._authorize_head - def _authorize_then_stop(head: Any, peer_host: str | None) -> None: + def _authorize_then_close(head: Any, peer_host: str | None) -> None: authorize(head, peer_host) - source._admission.stopping = True + if stopping: + source._admission.stopping = True + for writer in list(source._clients): + writer.close() + + source._authorize_head = _authorize_then_close # type: ignore[method-assign] + - source._authorize_head = _authorize_then_stop # type: ignore[method-assign] +async def test_no_100_continue_is_sent_once_stop_has_begun() -> None: + """stop() sets the listener stopping and closes a still-reading writer in one step. A request + caught between its head and its body then gets no 100 Continue and no answer; its body, sent + with the head, is not committed, as BACKLOG #5715 handles it without the expectation.""" + started = await _start() + _close_after_auth(started.source, stopping=True) try: - first, rest = await _exchange(source.sockport, _head(2), b"{}", wait_for_interim=False) + first, rest = await _exchange( + started.source.sockport, _head(2), b"{}", wait_for_interim=False + ) finally: - source._admission.stopping = False - await source.stop() + started.source._admission.stopping = False + await started.source.stop() assert _CONTINUE not in first + rest - assert _status(rest) == 202 + assert started.bodies == [] + + +async def test_a_closing_writer_gets_no_100_continue_and_its_buffered_body_is_still_read() -> None: + """A writer that is closing while the listener serves, as after a client's close right behind + a complete request, gets no 100 Continue: writing one there would fail and discard a body + already in the buffer. The body is read and handed on, as without the expectation (BACKLOG + #5715); only its answer is lost.""" + started = await _start() + _close_after_auth(started.source, stopping=False) + try: + await _exchange(started.source.sockport, _head(2), b"{}", wait_for_interim=False) + finally: + await started.source.stop() + assert started.bodies == [b"{}"] async def test_an_over_size_request_gets_413_and_never_a_100_continue() -> None: @@ -239,21 +263,40 @@ async def test_the_expectation_token_is_case_insensitive() -> None: assert _status(rest) == 202 -async def test_the_expectation_is_found_in_a_list_or_a_second_expect_line() -> None: - """A field sent twice is one comma-separated list (RFC 9110 section 5.3), and the head parse - keeps only the last value of each header, so the expectation is read across every line.""" +async def test_a_listed_or_repeated_expect_gets_no_100_continue() -> None: + """Only a single ``Expect`` line whose whole value is ``100-continue`` is answered. A front end + may read only one of two lines, or not parse a list, and so not anticipate an interim answer; + such a request is read as it was before this change, with no ``100``.""" started = await _start() try: port = started.source.sockport - listed = await _exchange(port, _head(2, expect="synthetic, 100-continue"), b"{}") - split = await _exchange(port, _head(2, expect="100-continue\r\nExpect: synthetic"), b"{}") + cases = [ + _head(2, expect="synthetic, 100-continue"), + _head(2, expect=None, extra=("Expect: 100-continue", "Expect: 100-continue")), + _head(2, expect='synthetic="a, 100-continue"'), + ] + answers = [await _exchange(port, head, b"{}", wait_for_interim=False) for head in cases] finally: await started.source.stop() - for first, rest in (listed, split): - assert first == _CONTINUE + for first, rest in answers: + assert _CONTINUE not in first + rest assert _status(rest) == 202 +async def test_a_health_probe_with_the_expectation_gets_no_100_continue() -> None: + started = await _start() + try: + reader, writer = await asyncio.open_connection("127.0.0.1", started.source.sockport) + writer.write(_PROBE) + await writer.drain() + answer = await asyncio.wait_for(reader.read(-1), 5.0) + writer.close() + finally: + await started.source.stop() + assert _status(answer) == 200 + assert _CONTINUE not in answer + + async def test_no_100_continue_is_sent_without_the_expectation_or_for_http_1_0() -> None: """RFC 9110 section 10.1.1: a server MUST NOT send ``100 Continue`` to an HTTP/1.0 client, and there is nothing to send it for without the expectation. The body is read as before.""" From c665c0753dbc250ad9207ca8a7a0e2664c4b1141 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:39:53 -0600 Subject: [PATCH 12/39] docs: say which Expect requests get no 100 Continue (BACKLOG #6476) Review round 2 repair. Only a single Expect: 100-continue line is answered; the list of requests that get none is now "at least", and names a closing connection and a stop() begun between head and body as the triggers. Proposed PR title: HTTP listener: answer Expect: 100-continue only after authorisation (BACKLOG #6476) Proposed vault banner: CLOSED -- the HTTP listener sends 100 Continue for a single Expect: 100-continue line, after head authentication and the max_body_bytes check and before the body read; unauthorised, over-size, repeated-credential and rate-limited requests get their refusal and no 100. Tests in tests/test_inbound_http_expect_continue.py; documented in docs/CONNECTIONS.md. Not built: the row's 417 for an unknown expectation, which stays ignored (RFC 9110 makes 417 a MAY). Verified-by: none --- docs/CONNECTIONS.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 6e495e6b66..56b82ad7f4 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -1024,9 +1024,12 @@ request has passed the checks made before the body is read: at least the head ru authentication and `max_body_bytes`. A request any of them refuses gets that refusal instead, never a `100`. A client that stops waiting and sends its body anyway may then see the connection reset rather than read the refusal. A `100` is not a promise to accept: a body within `max_body_bytes` -can still be refused after it is read, at least over the engine's ingress ceiling. An HTTP/1.0 -request and a request with an empty body get no `100`, nor does one that arrives as the listener -stops, and any other expectation is ignored rather than refused `417`. +can still be refused after it is read, at least over the engine's ingress ceiling. Only a single +`Expect` line whose whole value is `100-continue`, in any case, is answered. At least these get no +`100` and have their body read as before: an HTTP/1.0 request, a request with an empty body, a +request whose connection is closing or whose listener began to stop between its head and its body, +an `Expect` sent on two lines or as a list, since a front end may read only one of them, and any +other expectation, which is ignored rather than refused `417`. **Synchronous captured-downstream reply (`reply_from`, ADR 0154 increment B).** Naming `reply_from` makes the HTTP turn **block** until the named outbound's reply has been captured **and committed to the store**, From a8b3c76443800b15931f00b42f374832eda65ba6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:11:35 -0600 Subject: [PATCH 13/39] http_listener: the 100 Continue carries the baseline headers (BACKLOG #6476) Found by the unrepaired review round on c665c07: the bare status-line literal was a new site in tests/test_response_emitter_inventory.py's register (15 failures), and it made build_response's "every response carries the baseline" claim false. _CONTINUE is now built from _status_line(100) and _BASELINE_RESPONSE_HEADERS, as the harness sink's interim answer is, so no new emitter site exists and the claim holds; the docstring says how. Also cites RFC 9110 section 15.2 for the HTTP/1.0 1xx ban. Verified-by: tests --- messagefoundry/transports/http_listener.py | 27 +++++++++++++++------- tests/test_inbound_http_expect_continue.py | 19 +++++++++++---- 2 files changed, 34 insertions(+), 12 deletions(-) diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 31a3641217..aa8ff99bee 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -228,6 +228,7 @@ def __init__( def _status_line(status: int) -> str: reason = { + 100: "Continue", 200: "OK", 202: "Accepted", 204: "No Content", @@ -280,10 +281,6 @@ def _status_line(status: int) -> str: #: refused, because those are the declared bytes this listener would never read. _BODY_METHODS = frozenset({"POST", "PUT", "PATCH"}) -#: The interim answer to ``Expect: 100-continue`` (RFC 9110 section 15.2.1, BACKLOG #6476). It is a -#: bare status line: a 1xx carries no content, and :func:`build_response` writes final answers only. -_CONTINUE = b"HTTP/1.1 100 Continue\r\n\r\n" - def _expects_continue(version: str, expect: str | None, lines: int) -> bool: """Whether a request asks for ``100 Continue`` before its body: one ``Expect`` line, on a @@ -291,8 +288,8 @@ def _expects_continue(version: str, expect: str | None, lines: int) -> bool: 10.1.1). Anything else is not answered, and its body is read as before BACKLOG #6476: an HTTP/1.0 - request, since a server MUST NOT send a 1xx to an HTTP/1.0 client; any other expectation, - rather than a ``417``, which that section allows but does not require; and, deliberately, an + request, which a server MUST NOT send a 1xx to (section 15.2); any other expectation, + rather than a ``417``, which section 10.1.1 allows but does not require; and, deliberately, an ``Expect`` sent on two lines or holding a list. A front end may read only the first line, or not parse the list, and then not anticipate an interim answer this listener would send, which is the shape the duplicate ``Host`` and credential refusals exist to prevent (BACKLOG #1972, @@ -408,6 +405,19 @@ def _validated_header(name: str, value: str) -> str: ("Content-Security-Policy", "frame-ancestors 'none'; base-uri 'none'"), ) +#: The interim answer to ``Expect: 100-continue`` (RFC 9110 section 15.2.1, BACKLOG #6476). Built +#: here rather than by :func:`build_response`, which writes final answers with ``Content-Length`` +#: and ``Connection: close``; a 1xx carries neither. It still carries the baseline above, as the +#: harness sink's interim answer does, so every response this listener writes has it. +_CONTINUE = "\r\n".join( + [ + _status_line(100), + *(_validated_header(name, value) for name, value in _BASELINE_RESPONSE_HEADERS), + "", + "", + ] +).encode("ascii") + def build_response( status: int, @@ -424,8 +434,9 @@ def build_response( ``WWW-Authenticate`` on a ``401``, ``Retry-After`` on a ``429``. **Every response also carries :data:`_BASELINE_RESPONSE_HEADERS`** (ASVS 3.4.4 / 3.4.6). This - function is the chokepoint all twelve call sites feed, so the baseline is a property of the - serializer rather than a list of remembered call sites. It matters most on the ADR 0154 sync-reply + function is the chokepoint every final answer feeds, so the baseline is a property of the + serializer rather than a list of remembered call sites. The one other response, the interim + :data:`_CONTINUE`, is built beside the baseline from the same tuple. It matters most on the ADR 0154 sync-reply path below, which echoes a DOWNSTREAM PARTNER'S ``Content-Type`` verbatim beside partner-supplied bytes: without ``nosniff`` and a framing decision that response can serve a partner-derived ``text/html`` document over this listener's own TLS. ``extra_headers`` still wins on a name diff --git a/tests/test_inbound_http_expect_continue.py b/tests/test_inbound_http_expect_continue.py index dd43b23b1c..e38f5a4cf6 100644 --- a/tests/test_inbound_http_expect_continue.py +++ b/tests/test_inbound_http_expect_continue.py @@ -11,7 +11,7 @@ gets its refusal and never a ``100``, and its client is never invited to send the body. The refusal arms pinned here are at least a wrong or missing credential, a repeated credential header, a spent failed-attempt budget and an over-size declaration. No ``100`` is sent to an HTTP/1.0 client, which -RFC 9110 section 10.1.1 forbids, nor for a request with no content or once ``stop()`` has begun. +RFC 9110 section 15.2 forbids, nor for a request with no content or once ``stop()`` has begun. Synthetic, PHI-free payloads only.""" from __future__ import annotations @@ -20,11 +20,12 @@ from typing import Any from messagefoundry.config.models import ConnectorType, Source -from messagefoundry.transports.http_listener import HttpSource +from messagefoundry.transports.http_listener import _BASELINE_RESPONSE_HEADERS, HttpSource +from messagefoundry.transports.http_listener import _CONTINUE as _LISTENER_CONTINUE from messagefoundry.transports.receipt import IngressReceipt, receipt_handler _KEY = "synthetic-intake-key" -_CONTINUE = b"HTTP/1.1 100 Continue\r\n\r\n" +_CONTINUE = _LISTENER_CONTINUE #: Long enough for a loopback answer, short enough that a listener that never answers the #: expectation fails the test quickly rather than at the client's own timeout. _INTERIM_WAIT = 5.0 @@ -114,6 +115,16 @@ def _status(head: bytes) -> int: return int(head.split(b" ", 2)[1]) if head else 0 +def test_the_interim_answer_is_a_bare_100_with_the_baseline_headers() -> None: + """A 1xx carries no Content-Length and no Connection: close, but it does carry the same + browser-safety baseline as every final answer from this listener.""" + head, sep, rest = _CONTINUE.partition(b"\r\n\r\n") + assert sep and rest == b"" + lines = head.decode("ascii").split("\r\n") + assert lines[0] == "HTTP/1.1 100 Continue" + assert lines[1:] == [f"{name}: {value}" for name, value in _BASELINE_RESPONSE_HEADERS] + + async def test_an_authorised_request_is_answered_100_continue_before_its_body() -> None: started = await _start(intake_auth="api_key", intake_api_key=_KEY) try: @@ -298,7 +309,7 @@ async def test_a_health_probe_with_the_expectation_gets_no_100_continue() -> Non async def test_no_100_continue_is_sent_without_the_expectation_or_for_http_1_0() -> None: - """RFC 9110 section 10.1.1: a server MUST NOT send ``100 Continue`` to an HTTP/1.0 client, and + """RFC 9110 section 15.2: a server MUST NOT send ``100 Continue`` to an HTTP/1.0 client, and there is nothing to send it for without the expectation. The body is read as before.""" started = await _start() try: From 54097b0c833936cfa77ae5ac91f84fb11bf66747 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:19:14 -0600 Subject: [PATCH 14/39] http_listener: a listener-wide in-flight body budget (BACKLOG #6978) Adjudicated: the claim holds. max_body_bytes bounds one body and max_connections the connections, so the bodies one listener held at once were bounded only by their product, 4 GiB at the defaults. Measured on the base: three concurrent requests each declaring max_body_bytes were all read, none refused. New setting max_inflight_body_bytes, default 256 MiB, None/0 = off, also on the Http() factory. Each body takes its declared length from the budget after authentication and the max_body_bytes check, before a byte is read and before any 100 Continue; one that does not fit is refused 503 with Retry-After (an at_capacity event naming the setting), one larger than the whole budget 413. The share is given back once the body is handed to the engine, or when the request ends any other way. A max_body_bytes above the budget is refused at construction, naming both settings and withholding both values. tests/test_inbound_http_body_budget.py: the 503 arm failed on the base (the second request got no answer); also the 413 arm, the no-100 arm, release on a short body, off, the default and the construction refusal. Verified-by: tests --- messagefoundry/config/wiring.py | 7 + messagefoundry/transports/http_listener.py | 100 ++++++++-- tests/test_inbound_http_body_budget.py | 213 +++++++++++++++++++++ 3 files changed, 309 insertions(+), 11 deletions(-) create mode 100644 tests/test_inbound_http_body_budget.py diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index 2ffa0499be..d0100cd7a3 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -3657,6 +3657,8 @@ def Http( | None = 60.0, # bound the whole-request read (slow-loris guard), seconds max_body_bytes: int | None = 16 * 1024 * 1024, # cap one request body's bytes (OOM guard) max_header_bytes: int | None = 64 * 1024, # cap the request line + headers (header-flood guard) + # cap the body bytes ALL requests hold at once (BACKLOG #6978); at least max_body_bytes + max_inflight_body_bytes: int | None = 256 * 1024 * 1024, max_connections_per_host: int | None = None, # cap clients from ONE peer address; OFF by default max_handshakes_per_host: int @@ -3733,6 +3735,10 @@ def Http( **DoS guards** are HTTP twins of MLLP's: ``max_connections`` (flood), ``receive_timeout`` (slow-loris — bounds the whole-request read), ``max_body_bytes`` (the frame-cap twin — refused on the declared ``Content-Length`` before a byte is buffered), and ``max_header_bytes`` (header flood). + ``max_inflight_body_bytes`` (256 MiB) bounds the declared body bytes of every request being read + or handed to the engine at once, so the bodies in flight are not bounded only by + ``max_connections`` times ``max_body_bytes``; a body that does not fit is refused ``503`` with + ``Retry-After`` before a byte is read (BACKLOG #6978). ``max_connections_per_host`` caps concurrent sockets from one peer address and **ships off** here (vault BACKLOG #2606): behind a reverse proxy every partner arrives from one address, so a cap would become the listener's whole capacity. Set one only where the listener sees real client @@ -3830,6 +3836,7 @@ def Http( "receive_timeout": receive_timeout, "max_body_bytes": max_body_bytes, "max_header_bytes": max_header_bytes, + "max_inflight_body_bytes": max_inflight_body_bytes, "max_connections_per_host": max_connections_per_host, "max_handshakes_per_host": max_handshakes_per_host, "max_messages_per_second": max_messages_per_second, diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index aa8ff99bee..9e42e43f79 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -117,8 +117,10 @@ __all__ = [ "DEFAULT_BIND_HOST", "DEFAULT_MAX_BODY_BYTES", + "BODY_BUDGET_RETRY_AFTER_SECONDS", "DEFAULT_MAX_HANDSHAKES_PER_HOST", "DEFAULT_MAX_HEADER_BYTES", + "DEFAULT_MAX_INFLIGHT_BODY_BYTES", "HttpRequest", "HttpRequestError", "HttpSource", @@ -148,6 +150,15 @@ #: first and one stalling address could hold every slot. ``docs/DEPLOYMENT.md``, *Per-address #: listener caps behind the VIP*, holds the rationale and the L4 load-balancer counter-case. DEFAULT_MAX_HANDSHAKES_PER_HOST = 32 +#: The most declared body bytes the whole listener holds at once, across every request whose body is +#: being read or handed to the engine (BACKLOG #6978). ``max_body_bytes`` bounds one body and +#: ``max_connections`` the connections, so without this the bodies in flight were bounded only by +#: their product, 4 GiB at the defaults, from authenticated peers. 256 MiB is sixteen bodies at the +#: default ``max_body_bytes``: room for a burst of large ones, a sixteenth of that product. +DEFAULT_MAX_INFLIGHT_BODY_BYTES = 256 * 1024 * 1024 +#: The ``Retry-After`` seconds on the ``503`` refusing a body the in-flight budget has no room for. +#: The budget frees as soon as the bodies ahead of it are committed, so a short wait is enough. +BODY_BUDGET_RETRY_AFTER_SECONDS = 5 _HEADER_CAP_OFF_HINT = ( "this cap cannot be switched off; leave it unset or None for the 64 KiB default" ) @@ -682,17 +693,18 @@ async def _read_body( head: HttpRequest, *, max_body_bytes: int | None, - before_read: Callable[[], Awaitable[None]] | None = None, + before_read: Callable[[int], Awaitable[None]] | None = None, ) -> bytes: """Read the body belonging to an already-parsed ``head``, applying the body cap. Split out of :func:`_read_request` so authentication can run between the two halves (see :func:`_read_head`). - ``before_read`` is awaited once a non-empty declared length has passed the cap, before the - first body byte is read. ``HttpSource._serve_one`` sends ``100 Continue`` from it, having - authorised the head first (BACKLOG #6476). It is not called for an empty body or for a method - that reads none. + ``before_read`` is awaited with the declared length once a non-empty one has passed the cap, + before the first body byte is read. ``HttpSource._serve_one`` takes the length from the + listener's in-flight budget there (BACKLOG #6978), then sends ``100 Continue``, having + authorised the head first (BACKLOG #6476); either may refuse by raising. It is not called for + an empty body or for a method that reads none. **This function no longer decides framing, and the ordering warning that used to live here is gone because the thing it warned about was done deliberately** (BACKLOG #1125, ASVS 4.2.1). It @@ -721,7 +733,7 @@ async def _read_body( # Refuse on the DECLARED size before reading a single body byte (don't buffer to find out). raise HttpRequestError(413, "body exceeds cap", kind="frame_oversize") if before_read is not None and content_length: - await before_read() + await before_read(content_length) return await _read_exactly(reader, content_length) @@ -1062,6 +1074,28 @@ def __init__(self, config: Source) -> None: transport="HTTP source", ) self.max_header_bytes: int = _header_cap(s.get("max_header_bytes")) + # BACKLOG #6978: the listener-wide bound on body bytes in flight; None/0 switches it off. + self.max_inflight_body_bytes: int | None = positive_cap( + s.get("max_inflight_body_bytes", DEFAULT_MAX_INFLIGHT_BODY_BYTES), + int, + knob="max_inflight_body_bytes", + transport="HTTP source", + ) + if ( + self.max_inflight_body_bytes is not None + and self.max_body_bytes is not None + and self.max_body_bytes > self.max_inflight_body_bytes + ): + # A body max_body_bytes admits could then never fit even an idle listener's budget, + # and every such request would be told to retry a refusal that never clears. + raise ValueError( + "HTTP source max_body_bytes must not be above max_inflight_body_bytes " + "(values withheld)" + ) + #: Declared body bytes of the requests now holding a share of the budget, and each one's + #: share by its writer, so whichever path ends the request gives back exactly what it took. + self._inflight_body_bytes = 0 + self._body_shares: dict[asyncio.StreamWriter, int] = {} # Message-rate pacing (BACKLOG #1114), read through the shared helper so this connector # cannot drift from MLLP on what "unset" means. Absent -> OFF, unlike the caps above. The # port changed REACHABILITY, never the default -- a stock HTTP inbound still has no bound. @@ -1543,6 +1577,35 @@ async def _emit_event( except Exception as exc: # swallow + log; a capture bug can't drop an HTTP client logger.warning("HTTP connection-event emit failed: %s", safe_exc(exc)) + def _take_body_share(self, writer: asyncio.StreamWriter, length: int) -> None: + """Hold ``length`` declared body bytes of the in-flight budget for ``writer``, or refuse + the request before a body byte is read (BACKLOG #6978). + + Taken after authentication and the ``max_body_bytes`` check, so only a request that would + otherwise be read can hold a share. A body larger than the whole budget could never fit, + so it is ``413``, as a body over ``max_body_bytes`` is; one that does not fit what is left + now is ``503`` with ``Retry-After``, since the budget frees as earlier bodies commit. + Synchronous between the check and the add, so two requests on the loop cannot both take + the last room.""" + budget = self.max_inflight_body_bytes + if budget is None: + return + if length > budget: + raise HttpRequestError(413, "body exceeds cap", kind="frame_oversize") + if self._inflight_body_bytes + length > budget: + raise HttpRequestError( + 503, + "max_inflight_body_bytes", + kind="at_capacity", + headers={"Retry-After": str(BODY_BUDGET_RETRY_AFTER_SECONDS)}, + ) + self._inflight_body_bytes += length + self._body_shares[writer] = self._body_shares.get(writer, 0) + length + + def _give_body_share(self, writer: asyncio.StreamWriter) -> None: + """Give back whatever share ``writer``'s request holds; a no-op when it holds none.""" + self._inflight_body_bytes -= self._body_shares.pop(writer, 0) + # ---- intake authentication (ADR 0154 D6) --------------------------------------------------- # # Every refusal below is PRE-INGRESS: it happens before the pipeline handler runs, so nothing is @@ -1966,6 +2029,8 @@ async def _on_client( self._admission.release(peer_host, epoch) self._clients.discard(writer) self._answering.discard(writer) + # A request that ended before its body reached the engine gives its share back here. + self._give_body_share(writer) writer.close() try: # noqa: SIM105 # Bound the close (see stop()): an unbounded Proactor writer.wait_closed() would @@ -2000,13 +2065,19 @@ async def _read_authenticated() -> HttpRequest: head = await _read_head(reader, max_header_bytes=self.max_header_bytes) self._authorize_head(head, peer_host) - async def _ready() -> None: + async def _ready(length: int) -> None: + # BACKLOG #6978: hold this body's share of the listener's in-flight budget, or + # refuse it before a byte is read. Before the interim answer, so a client told to + # retry is never also invited to send. + self._take_body_share(writer, length) + if not head.expects_continue: + return # BACKLOG #6476: the interim answer is sent only here, after header-mode auth above # and the max_body_bytes check in _read_body, so a refused client is never invited # to send its body. Not once stop() has begun or the writer is closing: the body # read then fails or finds a buffered body as it would without the expectation, so - # the #5715 handling below still sees it. A 25-byte first write does not wait on - # drain, so this adds no stall a peer could hold. + # the #5715 handling below still sees it. A first write this short does not wait + # on drain, so this adds no stall a peer could hold. if self._admission.stopping or writer.is_closing(): return await self._respond(writer, _CONTINUE, budget=_CLIENT_SHUTDOWN_GRACE) @@ -2015,7 +2086,7 @@ async def _ready() -> None: reader, head, max_body_bytes=self.max_body_bytes, - before_read=_ready if head.expects_continue else None, + before_read=_ready, ) return head @@ -2107,7 +2178,14 @@ async def _ready() -> None: # persisted before the response is written — as a RECEIVED ingress row, or as an ERROR row when # the handler refuses it. try: - receipt = await self._handler(request.body) + try: + receipt = await self._handler(request.body) + finally: + # BACKLOG #6978: the body is the engine's now, committed or refused, so its share + # of the in-flight budget is free, and this turn stops holding the bytes. A + # reply_from turn may wait reply_timeout more, and holds nothing while it does. + request.body = b"" + self._give_body_share(writer) except Exception as exc: # BACKLOG #5680, the HTTP twin of the MLLP listener's #1619 arm: a fault inside the # inbound handler, such as a failed ingress commit, is an engine-side failure. Left to diff --git a/tests/test_inbound_http_body_budget.py b/tests/test_inbound_http_body_budget.py new file mode 100644 index 0000000000..a39325f2c4 --- /dev/null +++ b/tests/test_inbound_http_body_budget.py @@ -0,0 +1,213 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The HTTP listener's in-flight body budget (BACKLOG #6978). + +``max_body_bytes`` bounds one body and ``max_connections`` bounds the connections, so before this +budget the bodies one listener could hold at once were bounded only by their product: at the +defaults, 256 connections of 16 MiB each, 4 GiB of resident payload from authenticated peers. +``max_inflight_body_bytes`` bounds the declared bytes of every body being read or handed to the +engine at once. A request whose declared body does not fit in what is left is refused ``503`` with +``Retry-After`` before a body byte is read, rather than buffered. A body larger than the whole +budget can never fit, so it is refused ``413``. Synthetic, PHI-free payloads only.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest + +from messagefoundry.config.models import ConnectorType, Source +from messagefoundry.config.wiring import Http +from messagefoundry.transports import http_listener +from messagefoundry.transports.http_listener import HttpSource +from messagefoundry.transports.receipt import IngressReceipt, receipt_handler + +_CONTINUE = http_listener._CONTINUE + + +class _Started: + def __init__(self, source: HttpSource, bodies: list[bytes], events: list[tuple[Any, ...]]): + self.source = source + self.bodies = bodies + self.events = events + + +async def _start(**settings: Any) -> _Started: + base: dict[str, Any] = {"host": "127.0.0.1", "port": 0} + base.update(settings) + source = HttpSource(Source(type=ConnectorType.HTTP, settings=base)) + bodies: list[bytes] = [] + events: list[tuple[Any, ...]] = [] + + async def handler(raw: bytes) -> IngressReceipt: + bodies.append(raw) + return IngressReceipt.accepted(f"msg-{len(bodies)}") + + async def sink(kind: str, peer_host: str | None, reason: str | None) -> None: + events.append((kind, reason)) + + source.on_connection_event = sink + await source.start(receipt_handler(handler)) + return _Started(source, bodies, events) + + +def _head(length: int, *extra: str) -> bytes: + lines = ["POST /ingest HTTP/1.1", "Host: localhost", f"Content-Length: {length}", *extra] + return "\r\n".join([*lines, "", ""]).encode("ascii") + + +async def _answer(reader: asyncio.StreamReader) -> bytes: + try: + return await asyncio.wait_for(reader.read(-1), 5.0) + except (ConnectionResetError, OSError): + return b"" + + +def _status(answer: bytes) -> int: + return int(answer.split(b" ", 2)[1]) if answer else 0 + + +def _headers(answer: bytes) -> dict[str, str]: + head = answer.partition(b"\r\n\r\n")[0].decode("iso-8859-1").split("\r\n")[1:] + return {k.strip().lower(): v.strip() for k, _, v in (line.partition(":") for line in head)} + + +async def _until(predicate: Any) -> None: + for _ in range(200): + if predicate(): + return + await asyncio.sleep(0.01) + raise AssertionError("condition not reached") + + +async def _send_and_read(port: int, head: bytes, body: bytes) -> bytes: + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + writer.write(head + body) + await writer.drain() + return await _answer(reader) + finally: + writer.close() + try: # noqa: SIM105 + await writer.wait_closed() + except OSError: + pass + + +async def test_a_body_that_does_not_fit_the_budget_is_refused_503_not_buffered() -> None: + """One request holds 1000 of a 1500-byte budget while its body arrives. A second request + declaring 1000 more is refused at once with ``503`` and ``Retry-After``, before the listener + reads a byte of it. Once the first is answered its share is free again, and a third is read. + + Before the budget the second request was read like the first: the listener waited for its + body, so it got no answer here within the read timeout.""" + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1500) + port = started.source.sockport + first_reader, first_writer = await asyncio.open_connection("127.0.0.1", port) + try: + first_writer.write(_head(1000) + b"a" * 10) # holds its share while the rest is awaited + await first_writer.drain() + await _until(lambda: started.source._inflight_body_bytes == 1000) + second = await _send_and_read(port, _head(1000), b"") + assert _status(second) == 503 + assert _headers(second)["retry-after"] == str(http_listener.BODY_BUDGET_RETRY_AFTER_SECONDS) + assert ("at_capacity", "max_inflight_body_bytes") in started.events + first_writer.write(b"a" * 990) + await first_writer.drain() + first = await _answer(first_reader) + finally: + first_writer.close() + try: + assert _status(first) == 202 + assert started.source._inflight_body_bytes == 0 + third = await _send_and_read(port, _head(1000), b"b" * 1000) + assert _status(third) == 202 + finally: + await started.source.stop() + assert started.bodies == [b"a" * 1000, b"b" * 1000] + + +async def test_a_request_whose_body_never_arrives_gives_its_share_back() -> None: + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000) + port = started.source.sockport + try: + reader, writer = await asyncio.open_connection("127.0.0.1", port) + writer.write(_head(1000) + b"a" * 10) + await writer.drain() + writer.write_eof() # the body stops short: refused 400, and its share released + assert _status(await _answer(reader)) == 400 + writer.close() + await _until(lambda: started.source._inflight_body_bytes == 0) + assert _status(await _send_and_read(port, _head(1000), b"c" * 1000)) == 202 + finally: + await started.source.stop() + + +async def test_a_refused_request_that_expects_continue_gets_no_100() -> None: + """The budget is taken before the interim answer, so a client that waits for it is told to + retry instead of being invited to send a body the listener has no room for.""" + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000) + port = started.source.sockport + first_reader, first_writer = await asyncio.open_connection("127.0.0.1", port) + try: + first_writer.write(_head(1000) + b"a") + await first_writer.drain() + await _until(lambda: started.source._inflight_body_bytes == 1000) + second = await _send_and_read(port, _head(10, "Expect: 100-continue"), b"") + finally: + first_writer.close() + await started.source.stop() + assert _status(second) == 503 + assert _CONTINUE not in second + + +async def test_with_max_body_bytes_off_a_body_over_the_whole_budget_is_413() -> None: + """It could never fit, so asking the sender to retry would be false.""" + started = await _start(max_body_bytes=None, max_inflight_body_bytes=100) + try: + answer = await _send_and_read(started.source.sockport, _head(101), b"") + finally: + await started.source.stop() + assert _status(answer) == 413 + assert started.bodies == [] + + +async def test_the_budget_switched_off_bounds_nothing() -> None: + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=0) + port = started.source.sockport + first_reader, first_writer = await asyncio.open_connection("127.0.0.1", port) + try: + first_writer.write(_head(1000) + b"a") + await first_writer.drain() + await asyncio.sleep(0.1) + second = await _send_and_read(port, _head(1000), b"b" * 1000) + first_writer.write(b"a" * 999) + await first_writer.drain() + first = await _answer(first_reader) + finally: + first_writer.close() + await started.source.stop() + assert (_status(first), _status(second)) == (202, 202) + + +def test_the_default_budget_binds_below_what_the_connection_and_body_caps_allow() -> None: + source = HttpSource(Source(type=ConnectorType.HTTP, settings={"port": 0})) + assert source.max_inflight_body_bytes == http_listener.DEFAULT_MAX_INFLIGHT_BODY_BYTES + assert source.max_connections is not None and source.max_body_bytes is not None + assert source.max_body_bytes <= source.max_inflight_body_bytes + assert source.max_inflight_body_bytes < source.max_connections * source.max_body_bytes + + +def test_a_body_cap_above_the_budget_is_refused_at_construction() -> None: + """A body that passes ``max_body_bytes`` must be able to fit an empty budget, or it would be + refused every time; the refusal names both settings and withholds both values.""" + settings = {"port": 0, "max_body_bytes": 2001, "max_inflight_body_bytes": 2000} + with pytest.raises(ValueError, match="max_body_bytes.*max_inflight_body_bytes") as caught: + HttpSource(Source(type=ConnectorType.HTTP, settings=settings)) + assert "2000" not in str(caught.value) and "2001" not in str(caught.value) + + +def test_the_factory_carries_the_budget() -> None: + assert Http(port=0).settings["max_inflight_body_bytes"] == 256 * 1024 * 1024 + assert Http(port=0, max_inflight_body_bytes=None).settings["max_inflight_body_bytes"] is None From 877bfc5bf486af1c43c7f092b1341d6da3e14b14 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:23:43 -0600 Subject: [PATCH 15/39] docs: the HTTP listener's max_inflight_body_bytes (BACKLOG #6978) A settings-table row in the HTTP listener section of docs/CONNECTIONS.md: what the budget bounds, when a body takes and gives back its share, the 503 with Retry-After and the 413, the construction refusal, and how to switch it off. The pre-ingress refusal list names the 503. Proposed PR title: HTTP listener: bound the body bytes in flight across the listener (BACKLOG #6978) Proposed vault banner: CLOSED -- adjudicated real (three concurrent max-size bodies were all read on the base). New Http setting max_inflight_body_bytes, default 256 MiB: a body that does not fit is refused 503 with Retry-After before a byte is read, one over the whole budget 413; a max_body_bytes above it is refused at build. Tests in tests/test_inbound_http_body_budget.py; documented in docs/CONNECTIONS.md. Verified-by: none --- docs/CONNECTIONS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 56b82ad7f4..c1f14e6a0e 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -904,6 +904,7 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `max_connections_per_host` | **off** | cap on concurrent connections from **one peer address**, answered `503` with an `at_capacity` event whose reason reads `max_connections_per_host` (vault BACKLOG #2606); a `tls = true` listener closes the socket unanswered instead, on every event loop, as the pre-ingress refusals below say. **Ships off, unlike MLLP/TCP/X12**: this connector answers one request per connection, so behind a reverse proxy every partner arrives from one address and any cap would be the listener's whole capacity. Set one only where the listener sees real client addresses. | | `max_handshakes_per_host` | `32` | cap on sockets from **one peer address** that hold a connection slot while **still in their TLS handshake** (vault BACKLOG #4888). It bites only on a `tls = true` listener, where a socket holds a slot through its handshake on every event loop (BACKLOG #2479); there the socket is closed unanswered with an `at_capacity` event whose reason reads `max_handshakes_per_host`. A socket leaves the count when its handshake ends, so it caps how many requests one address can **start** at once, not how many it holds once their handshakes are done. **Ships on**; `None`/`0` = off. Why, what it does not bound, and the L4 load-balancer case: [DEPLOYMENT.md](DEPLOYMENT.md#per-address-listener-caps-behind-the-vip). | | `max_body_bytes` | `16 MiB` | the MLLP frame cap's HTTP twin — an over-declared `Content-Length` is refused `413` **before a body byte is read** (OOM guard). `None`/`0` = unlimited, and the connection logs a `WARNING` naming the setting each time it is built (BACKLOG #2749). | +| `max_inflight_body_bytes` | `256 MiB` | cap the declared body bytes of **every** request this listener is reading or handing to the engine at once (BACKLOG #6978). Without it the bodies in flight were bounded only by `max_connections` times `max_body_bytes`, 4 GiB at the defaults, from authenticated peers. Each body takes its declared `Content-Length` from the budget once it has passed intake authentication and `max_body_bytes`, before a body byte is read and before any `100 Continue`, and gives it back once the engine has the body. One that does not fit what is left is refused `503` with `Retry-After: 5` and an `at_capacity` event whose reason reads `max_inflight_body_bytes`; one larger than the whole budget, possible only with `max_body_bytes` off, is refused `413`. Nothing is recorded for either, so the sender re-sends. A sender that sends its body without waiting may see the connection reset rather than read the `503`, as with a `413`. A `max_body_bytes` above this budget is refused when the connection is built, which `serve` and `messagefoundry check` both do. `None`/`0` = off. | | `max_header_bytes` | `64 KiB` | cap the request line + headers (header-flood guard). This one cap can't be switched off: unset or `None` takes the 64 KiB default, and `0` (or `"0"`) is refused at load rather than silently becoming the default (BACKLOG #1872). | | `max_messages_per_second` | **off** | sustained message-rate ceiling for the **whole listener** (ASVS 2.4.1 / 15.2.2, BACKLOG #1114 — the MLLP pacer, ported). Over budget the connector **waits before reading the request**, so the partner is back-pressured and then served in full — **nothing is dropped, refused or answered differently**, and the wait sits outside `receive_timeout` so a paced partner is never handed a `408` for a delay the engine imposed. **Listener-wide, not per-connection**, unlike MLLP/TCP/X12: this connector answers one request per connection, so a per-connection bucket would be charged once and thrown away, bounding nothing. A `GET`/`HEAD` probe waits behind an outstanding debt but **charges nothing**, and neither does a request refused before its body reaches the engine. Only a body the engine reads and records spends budget, including one it then refuses with a `422`, so a peer that submits nothing cannot starve one that does. Unset = no bound, deliberately: a guessed rate throttles real traffic, so the number has to come from your own feed profile. | | `message_burst` | = the rate | tokens the bucket holds, i.e. how large a burst passes unpaced before the sustained rate applies. Only meaningful with `max_messages_per_second` set. Floor of 1 so the listener can always make progress. | @@ -995,7 +996,7 @@ d20261104T003342588-cbb49e (BACKLOG #5102), recorded as the ADR 0154 amendment o A **pre-ingress** refusal answers synchronously and emits an ADR 0021 `connection_event`: `403` (not in `source_ip_allowlist`), `408` (the request didn't fully arrive within `receive_timeout`), `413` (over `max_body_bytes` **or** -`max_header_bytes`), `400` (a malformed request line or header, or framing this listener will not guess at -- including at least any `Transfer-Encoding`, a duplicated or non-digit `Content-Length`, whitespace before a header colon, a folded header line, a bare CR or LF, a control character in a header value, an HTTP version other than 1.x, a missing `Host` on any version but HTTP/1.0, more than one `Host`, and a non-zero body declared on a method other than `POST`/`PUT`/`PATCH`), `411` (a `POST`/`PUT`/`PATCH` with no `Content-Length`; the body is never read to EOF), `503` (at +`max_header_bytes`), `400` (a malformed request line or header, or framing this listener will not guess at -- including at least any `Transfer-Encoding`, a duplicated or non-digit `Content-Length`, whitespace before a header colon, a folded header line, a bare CR or LF, a control character in a header value, an HTTP version other than 1.x, a missing `Host` on any version but HTTP/1.0, more than one `Host`, and a non-zero body declared on a method other than `POST`/`PUT`/`PATCH`), `411` (a `POST`/`PUT`/`PATCH` with no `Content-Length`; the body is never read to EOF), `503` with `Retry-After` (a declared body over what is left of `max_inflight_body_bytes`), `503` (at `max_connections` — the connection is accepted, then refused and closed at the application layer). On a `tls = true` listener, on every event loop, the `source_ip_allowlist` and connection-cap refusals come before the TLS handshake, so the socket is closed with no answer instead of a `403` or From 1a21e9cdbd880b65e90b68ade9a4b61b2d2b2671 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:41:00 -0600 Subject: [PATCH 16/39] http_listener: charge the body budget on bytes received (BACKLOG #6978) Review round 1 repair. Charging the declared Content-Length let sixteen sockets that declared 16 MiB and sent nothing hold the whole default budget and refuse every partner, a lockout sixteen times cheaper than max_connections. The body is now read in 64 KiB chunks, each charged as it arrives: a declared body that fits what received bodies hold is read, one that does not is refused 503 before a byte is read, and bytes that would take the listener over the budget are refused 503 mid-body. A budget refusal now reaches the refusal observers, as every listener-cap refusal does. The 413 names max_inflight_body_bytes. The max_body_bytes-off warning names the budget. The factory comment sits on the parameter's own line, so the IDE form reads it as help, not as a section heading. Tests: the mid-body arm, a declared-only body that holds no room, the observer arm, an off arm that asserts the setting reads as off, and the factory default tied to the listener's constant. Verified-by: tests --- messagefoundry/config/wiring.py | 7 +- messagefoundry/transports/http_listener.py | 112 +++++++--- tests/test_inbound_http_body_budget.py | 237 ++++++++++++++------- 3 files changed, 243 insertions(+), 113 deletions(-) diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index d0100cd7a3..98400d4927 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -3657,8 +3657,7 @@ def Http( | None = 60.0, # bound the whole-request read (slow-loris guard), seconds max_body_bytes: int | None = 16 * 1024 * 1024, # cap one request body's bytes (OOM guard) max_header_bytes: int | None = 64 * 1024, # cap the request line + headers (header-flood guard) - # cap the body bytes ALL requests hold at once (BACKLOG #6978); at least max_body_bytes - max_inflight_body_bytes: int | None = 256 * 1024 * 1024, + max_inflight_body_bytes: int | None = 256 * 1024 * 1024, # cap body bytes held by ALL requests max_connections_per_host: int | None = None, # cap clients from ONE peer address; OFF by default max_handshakes_per_host: int @@ -3735,10 +3734,10 @@ def Http( **DoS guards** are HTTP twins of MLLP's: ``max_connections`` (flood), ``receive_timeout`` (slow-loris — bounds the whole-request read), ``max_body_bytes`` (the frame-cap twin — refused on the declared ``Content-Length`` before a byte is buffered), and ``max_header_bytes`` (header flood). - ``max_inflight_body_bytes`` (256 MiB) bounds the declared body bytes of every request being read + ``max_inflight_body_bytes`` (256 MiB) bounds the body bytes of every request being read or handed to the engine at once, so the bodies in flight are not bounded only by ``max_connections`` times ``max_body_bytes``; a body that does not fit is refused ``503`` with - ``Retry-After`` before a byte is read (BACKLOG #6978). + ``Retry-After`` (BACKLOG #6978). ``max_connections_per_host`` caps concurrent sockets from one peer address and **ships off** here (vault BACKLOG #2606): behind a reverse proxy every partner arrives from one address, so a cap would become the listener's whole capacity. Set one only where the listener sees real client diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 9e42e43f79..7ad2ca5efa 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -77,7 +77,7 @@ from messagefoundry.proactor_accept import guard_accepts from messagefoundry.redaction import safe_exc from messagefoundry.tls_handshake_failures import HUNG_UP, HandshakeFailures, handshake_cause -from messagefoundry.transports.admission import ListenerAdmission +from messagefoundry.transports.admission import ListenerAdmission, notify_refusal from messagefoundry.transports.base import ( INTAKE_AUDIT_ACTIONS, InboundHandler, @@ -150,12 +150,15 @@ #: first and one stalling address could hold every slot. ``docs/DEPLOYMENT.md``, *Per-address #: listener caps behind the VIP*, holds the rationale and the L4 load-balancer counter-case. DEFAULT_MAX_HANDSHAKES_PER_HOST = 32 -#: The most declared body bytes the whole listener holds at once, across every request whose body is -#: being read or handed to the engine (BACKLOG #6978). ``max_body_bytes`` bounds one body and +#: The most body bytes the whole listener holds at once, across every request whose body is being +#: read or handed to the engine (BACKLOG #6978). ``max_body_bytes`` bounds one body and #: ``max_connections`` the connections, so without this the bodies in flight were bounded only by -#: their product, 4 GiB at the defaults, from authenticated peers. 256 MiB is sixteen bodies at the -#: default ``max_body_bytes``: room for a burst of large ones, a sixteenth of that product. +#: their product, 4 GiB at the defaults. 256 MiB is sixteen bodies at the default +#: ``max_body_bytes``: room for a burst of large ones, a sixteenth of that product. DEFAULT_MAX_INFLIGHT_BODY_BYTES = 256 * 1024 * 1024 +#: The most body bytes one read takes while the budget is charged, so a share grows with the bytes +#: actually received rather than with what a peer declared. +_BODY_CHUNK_BYTES = 64 * 1024 #: The ``Retry-After`` seconds on the ``503`` refusing a body the in-flight budget has no room for. #: The budget frees as soon as the bodies ahead of it are committed, so a short wait is enough. BODY_BUDGET_RETRY_AFTER_SECONDS = 5 @@ -694,6 +697,7 @@ async def _read_body( *, max_body_bytes: int | None, before_read: Callable[[int], Awaitable[None]] | None = None, + charge: Callable[[int], None] | None = None, ) -> bytes: """Read the body belonging to an already-parsed ``head``, applying the body cap. @@ -701,10 +705,11 @@ async def _read_body( :func:`_read_head`). ``before_read`` is awaited with the declared length once a non-empty one has passed the cap, - before the first body byte is read. ``HttpSource._serve_one`` takes the length from the - listener's in-flight budget there (BACKLOG #6978), then sends ``100 Continue``, having - authorised the head first (BACKLOG #6476); either may refuse by raising. It is not called for - an empty body or for a method that reads none. + before the first body byte is read. ``HttpSource._serve_one`` checks there that the length fits + the listener's in-flight budget (BACKLOG #6978), then sends ``100 Continue``, having authorised + the head first (BACKLOG #6476); either may refuse by raising. It is not called for an empty body + or for a method that reads none. ``charge``, when given, is called with the size of each chunk + as it is read, and may refuse by raising; see :func:`_read_exactly`. **This function no longer decides framing, and the ordering warning that used to live here is gone because the thing it warned about was done deliberately** (BACKLOG #1125, ASVS 4.2.1). It @@ -734,7 +739,7 @@ async def _read_body( raise HttpRequestError(413, "body exceeds cap", kind="frame_oversize") if before_read is not None and content_length: await before_read(content_length) - return await _read_exactly(reader, content_length) + return await _read_exactly(reader, content_length, charge=charge) async def _read_request( @@ -753,15 +758,33 @@ async def _read_request( return head -async def _read_exactly(reader: asyncio.StreamReader, n: int) -> bytes: +async def _read_exactly( + reader: asyncio.StreamReader, n: int, *, charge: Callable[[int], None] | None = None +) -> bytes: """Read exactly ``n`` declared Content-Length body bytes, or refuse. A peer that closes before sending all of it has broken its own declared framing — the same class of defect :func:`_read_head` already refuses via :class:`HttpRequestError`, just on the body side. Silently returning the short ``exc.partial`` bytes would let a truncated body flow - on to become an ingress row and a 202, understating what the sender actually declared.""" + on to become an ingress row and a 202, understating what the sender actually declared. + + With ``charge``, the body is read in chunks of at most :data:`_BODY_CHUNK_BYTES`, and each is + charged as it arrives, before it is kept (BACKLOG #6978). So a share of the in-flight budget + is bytes received, never bytes promised: a peer that declares a large body and sends none of + it holds nothing.""" if n == 0: return b"" + if charge is not None: + chunks: list[bytes] = [] + remaining = n + while remaining: + chunk = await reader.read(min(remaining, _BODY_CHUNK_BYTES)) + if not chunk: + raise HttpRequestError(400, "incomplete request body", kind="framing_error") + charge(len(chunk)) + chunks.append(chunk) + remaining -= len(chunk) + return b"".join(chunks) # Refused outside the handler: IncompleteReadError.partial holds the body read so far (#2085). with contextlib.suppress(asyncio.IncompleteReadError): return await reader.readexactly(n) @@ -1249,7 +1272,8 @@ def __init__(self, config: Source) -> None: # so a source it refuses has not logged it. The line names the setting, never its value. logger.warning( "HTTP source %s: max_body_bytes is off, so a request body of any declared size is " - "read whole; set a positive value to bound it", + "read whole, up to max_inflight_body_bytes where that is on; set a positive value " + "to bound it", self._log_name, ) @@ -1577,30 +1601,45 @@ async def _emit_event( except Exception as exc: # swallow + log; a capture bug can't drop an HTTP client logger.warning("HTTP connection-event emit failed: %s", safe_exc(exc)) - def _take_body_share(self, writer: asyncio.StreamWriter, length: int) -> None: - """Hold ``length`` declared body bytes of the in-flight budget for ``writer``, or refuse - the request before a body byte is read (BACKLOG #6978). + def _budget_refusal(self) -> HttpRequestError: + """The ``503`` for a body the in-flight budget has no room for (BACKLOG #6978), told to the + refusal observers as every listener-cap refusal is, so the security-signal layer sees it + even with connection events off.""" + notify_refusal(self._admission.name) + return HttpRequestError( + 503, + "max_inflight_body_bytes", + kind="at_capacity", + headers={"Retry-After": str(BODY_BUDGET_RETRY_AFTER_SECONDS)}, + ) + + def _check_body_room(self, length: int) -> None: + """Refuse a body the in-flight budget has no room for, before a byte of it is read. - Taken after authentication and the ``max_body_bytes`` check, so only a request that would - otherwise be read can hold a share. A body larger than the whole budget could never fit, - so it is ``413``, as a body over ``max_body_bytes`` is; one that does not fit what is left - now is ``503`` with ``Retry-After``, since the budget frees as earlier bodies commit. - Synchronous between the check and the add, so two requests on the loop cannot both take - the last room.""" + Run after authentication and the ``max_body_bytes`` check. It reserves nothing: the bytes + held are those bodies already received, so a peer that only declares a body holds no room. + A body larger than the whole budget could never fit, so it is ``413``, naming this + setting; one that does not fit what bodies now hold is ``503`` with ``Retry-After``, + since the budget frees as those bodies reach the engine.""" budget = self.max_inflight_body_bytes if budget is None: return if length > budget: - raise HttpRequestError(413, "body exceeds cap", kind="frame_oversize") - if self._inflight_body_bytes + length > budget: raise HttpRequestError( - 503, - "max_inflight_body_bytes", - kind="at_capacity", - headers={"Retry-After": str(BODY_BUDGET_RETRY_AFTER_SECONDS)}, + 413, "body exceeds max_inflight_body_bytes", kind="frame_oversize" ) - self._inflight_body_bytes += length - self._body_shares[writer] = self._body_shares.get(writer, 0) + length + if self._inflight_body_bytes + length > budget: + raise self._budget_refusal() + + def _charge_body(self, writer: asyncio.StreamWriter, size: int) -> None: + """Charge ``size`` received body bytes to ``writer``'s share, or refuse the request where + they would take the listener over its budget. Synchronous between the check and the add, so + two requests on the loop cannot both take the last room.""" + budget = self.max_inflight_body_bytes + if budget is not None and self._inflight_body_bytes + size > budget: + raise self._budget_refusal() + self._inflight_body_bytes += size + self._body_shares[writer] = self._body_shares.get(writer, 0) + size def _give_body_share(self, writer: asyncio.StreamWriter) -> None: """Give back whatever share ``writer``'s request holds; a no-op when it holds none.""" @@ -2066,10 +2105,10 @@ async def _read_authenticated() -> HttpRequest: self._authorize_head(head, peer_host) async def _ready(length: int) -> None: - # BACKLOG #6978: hold this body's share of the listener's in-flight budget, or - # refuse it before a byte is read. Before the interim answer, so a client told to - # retry is never also invited to send. - self._take_body_share(writer, length) + # BACKLOG #6978: refuse a body the listener's in-flight budget has no room for + # before a byte is read. Before the interim answer, so a client told to retry is + # never also invited to send. + self._check_body_room(length) if not head.expects_continue: return # BACKLOG #6476: the interim answer is sent only here, after header-mode auth above @@ -2087,6 +2126,11 @@ async def _ready(length: int) -> None: head, max_body_bytes=self.max_body_bytes, before_read=_ready, + charge=( + None + if self.max_inflight_body_bytes is None + else lambda size: self._charge_body(writer, size) + ), ) return head diff --git a/tests/test_inbound_http_body_budget.py b/tests/test_inbound_http_body_budget.py index a39325f2c4..ce1b108023 100644 --- a/tests/test_inbound_http_body_budget.py +++ b/tests/test_inbound_http_body_budget.py @@ -4,11 +4,13 @@ ``max_body_bytes`` bounds one body and ``max_connections`` bounds the connections, so before this budget the bodies one listener could hold at once were bounded only by their product: at the -defaults, 256 connections of 16 MiB each, 4 GiB of resident payload from authenticated peers. -``max_inflight_body_bytes`` bounds the declared bytes of every body being read or handed to the -engine at once. A request whose declared body does not fit in what is left is refused ``503`` with -``Retry-After`` before a body byte is read, rather than buffered. A body larger than the whole -budget can never fit, so it is refused ``413``. Synthetic, PHI-free payloads only.""" +defaults, 256 connections of 16 MiB each, 4 GiB of resident payload. ``max_inflight_body_bytes`` +bounds the body bytes of every request being read or handed to the engine at once. Each body is +charged as its bytes arrive, so a peer that only declares a body holds nothing. A request whose +declared body does not fit what bodies already hold is refused ``503`` with ``Retry-After`` before a +body byte is read; one whose arriving bytes would take the listener over the budget is refused the +same way mid-body. A body larger than the whole budget can never fit, so it is refused ``413``. +Synthetic, PHI-free payloads only.""" from __future__ import annotations @@ -19,11 +21,12 @@ from messagefoundry.config.models import ConnectorType, Source from messagefoundry.config.wiring import Http -from messagefoundry.transports import http_listener +from messagefoundry.transports import admission, http_listener from messagefoundry.transports.http_listener import HttpSource from messagefoundry.transports.receipt import IngressReceipt, receipt_handler _CONTINUE = http_listener._CONTINUE +_RETRY_AFTER = str(http_listener.BODY_BUDGET_RETRY_AFTER_SECONDS) class _Started: @@ -36,7 +39,7 @@ def __init__(self, source: HttpSource, bodies: list[bytes], events: list[tuple[A async def _start(**settings: Any) -> _Started: base: dict[str, Any] = {"host": "127.0.0.1", "port": 0} base.update(settings) - source = HttpSource(Source(type=ConnectorType.HTTP, settings=base)) + source = HttpSource(Source(type=ConnectorType.HTTP, name="IB_BUDGET", settings=base)) bodies: list[bytes] = [] events: list[tuple[Any, ...]] = [] @@ -74,121 +77,204 @@ def _headers(answer: bytes) -> dict[str, str]: async def _until(predicate: Any) -> None: - for _ in range(200): + for _ in range(300): if predicate(): return await asyncio.sleep(0.01) raise AssertionError("condition not reached") -async def _send_and_read(port: int, head: bytes, body: bytes) -> bytes: - reader, writer = await asyncio.open_connection("127.0.0.1", port) +class _Peer: + """One client connection kept open across several writes.""" + + def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + self.reader, self.writer = reader, writer + + @classmethod + async def open(cls, port: int, data: bytes) -> _Peer: + reader, writer = await asyncio.open_connection("127.0.0.1", port) + peer = cls(reader, writer) + await peer.send(data) + return peer + + async def send(self, data: bytes) -> None: + self.writer.write(data) + await self.writer.drain() + + async def answer(self) -> bytes: + return await _answer(self.reader) + + def close(self) -> None: + self.writer.close() + + +async def _send_and_read(port: int, data: bytes) -> bytes: + peer = await _Peer.open(port, data) try: - writer.write(head + body) - await writer.drain() - return await _answer(reader) + return await peer.answer() finally: - writer.close() - try: # noqa: SIM105 - await writer.wait_closed() - except OSError: - pass + peer.close() -async def test_a_body_that_does_not_fit_the_budget_is_refused_503_not_buffered() -> None: - """One request holds 1000 of a 1500-byte budget while its body arrives. A second request - declaring 1000 more is refused at once with ``503`` and ``Retry-After``, before the listener - reads a byte of it. Once the first is answered its share is free again, and a third is read. +async def test_a_body_that_does_not_fit_what_is_held_is_refused_503_before_it_is_read() -> None: + """One request holds 900 received bytes of a 1500-byte budget. A second request declaring + 1000 more is refused at once with ``503`` and ``Retry-After``, before the listener reads a + byte of it. Once the first is answered its share is free again, and a third is read. Before the budget the second request was read like the first: the listener waited for its body, so it got no answer here within the read timeout.""" started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1500) - port = started.source.sockport - first_reader, first_writer = await asyncio.open_connection("127.0.0.1", port) + source, port = started.source, started.source.sockport + peers: list[_Peer] = [] try: - first_writer.write(_head(1000) + b"a" * 10) # holds its share while the rest is awaited - await first_writer.drain() - await _until(lambda: started.source._inflight_body_bytes == 1000) - second = await _send_and_read(port, _head(1000), b"") + first = await _Peer.open(port, _head(1000) + b"a" * 900) + peers.append(first) + await _until(lambda: source._inflight_body_bytes == 900) + second = await _send_and_read(port, _head(1000)) assert _status(second) == 503 - assert _headers(second)["retry-after"] == str(http_listener.BODY_BUDGET_RETRY_AFTER_SECONDS) + assert _headers(second)["retry-after"] == _RETRY_AFTER assert ("at_capacity", "max_inflight_body_bytes") in started.events - first_writer.write(b"a" * 990) - await first_writer.drain() - first = await _answer(first_reader) + await first.send(b"a" * 100) + assert _status(await first.answer()) == 202 + assert source._inflight_body_bytes == 0 + assert _status(await _send_and_read(port, _head(1000) + b"b" * 1000)) == 202 finally: - first_writer.close() + for peer in peers: + peer.close() + await source.stop() + assert started.bodies == [b"a" * 1000, b"b" * 1000] + + +async def test_bytes_that_would_take_the_listener_over_the_budget_are_refused_mid_body() -> None: + """Two requests fit when declared, but their bodies together would not: the one whose bytes + arrive over the budget is refused ``503`` and its share given back, and the other completes.""" + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1500) + source, port = started.source, started.source.sockport + peers: list[_Peer] = [] try: - assert _status(first) == 202 - assert started.source._inflight_body_bytes == 0 - third = await _send_and_read(port, _head(1000), b"b" * 1000) - assert _status(third) == 202 + first = await _Peer.open(port, _head(1000) + b"a" * 500) + peers.append(first) + await _until(lambda: source._inflight_body_bytes == 500) + second = await _Peer.open(port, _head(1000) + b"b" * 900) + peers.append(second) + await _until(lambda: source._inflight_body_bytes == 1400) + await first.send(b"a" * 200) # 1600 would be over the budget + refused = await first.answer() + assert _status(refused) == 503 + assert _headers(refused)["retry-after"] == _RETRY_AFTER + await _until(lambda: source._inflight_body_bytes == 900) + await second.send(b"b" * 100) + assert _status(await second.answer()) == 202 finally: - await started.source.stop() - assert started.bodies == [b"a" * 1000, b"b" * 1000] + for peer in peers: + peer.close() + await source.stop() + assert started.bodies == [b"b" * 1000] -async def test_a_request_whose_body_never_arrives_gives_its_share_back() -> None: +async def test_a_declared_body_never_sent_holds_no_room() -> None: + """Bytes promised are not bytes held. Requests that declare the whole budget and send nothing + do not keep a request that does send its body out.""" started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000) - port = started.source.sockport + source, port = started.source, started.source.sockport + peers: list[_Peer] = [] try: - reader, writer = await asyncio.open_connection("127.0.0.1", port) - writer.write(_head(1000) + b"a" * 10) - await writer.drain() - writer.write_eof() # the body stops short: refused 400, and its share released - assert _status(await _answer(reader)) == 400 - writer.close() - await _until(lambda: started.source._inflight_body_bytes == 0) - assert _status(await _send_and_read(port, _head(1000), b"c" * 1000)) == 202 + for _ in range(3): + peers.append(await _Peer.open(port, _head(1000))) + await asyncio.sleep(0.1) + assert source._inflight_body_bytes == 0 + assert _status(await _send_and_read(port, _head(1000) + b"c" * 1000)) == 202 finally: - await started.source.stop() + for peer in peers: + peer.close() + await source.stop() + + +async def test_a_request_whose_body_stops_short_gives_its_share_back() -> None: + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000) + source, port = started.source, started.source.sockport + try: + peer = await _Peer.open(port, _head(1000) + b"a" * 10) + await _until(lambda: source._inflight_body_bytes == 10) + peer.writer.write_eof() # the body stops short: refused 400, and its share released + assert _status(await peer.answer()) == 400 + peer.close() + await _until(lambda: source._inflight_body_bytes == 0) + assert _status(await _send_and_read(port, _head(1000) + b"c" * 1000)) == 202 + finally: + await source.stop() async def test_a_refused_request_that_expects_continue_gets_no_100() -> None: - """The budget is taken before the interim answer, so a client that waits for it is told to + """The room is checked before the interim answer, so a client that waits for it is told to retry instead of being invited to send a body the listener has no room for.""" started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000) - port = started.source.sockport - first_reader, first_writer = await asyncio.open_connection("127.0.0.1", port) + source, port = started.source, started.source.sockport + peers: list[_Peer] = [] try: - first_writer.write(_head(1000) + b"a") - await first_writer.drain() - await _until(lambda: started.source._inflight_body_bytes == 1000) - second = await _send_and_read(port, _head(10, "Expect: 100-continue"), b"") + peers.append(await _Peer.open(port, _head(1000) + b"a" * 999)) + await _until(lambda: source._inflight_body_bytes == 999) + second = await _send_and_read(port, _head(10, "Expect: 100-continue")) finally: - first_writer.close() - await started.source.stop() + for peer in peers: + peer.close() + await source.stop() assert _status(second) == 503 assert _CONTINUE not in second +async def test_a_budget_refusal_reaches_the_refusal_observers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """As every listener-cap refusal does, so the security-signal layer sees it with connection + events off.""" + seen: list[str] = [] + monkeypatch.setattr(admission, "_REFUSAL_OBSERVERS", (seen.append,)) + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000) + source, port = started.source, started.source.sockport + peers: list[_Peer] = [] + try: + peers.append(await _Peer.open(port, _head(1000) + b"a" * 999)) + await _until(lambda: source._inflight_body_bytes == 999) + assert _status(await _send_and_read(port, _head(10))) == 503 + finally: + for peer in peers: + peer.close() + await source.stop() + assert seen == ["IB_BUDGET"] + + async def test_with_max_body_bytes_off_a_body_over_the_whole_budget_is_413() -> None: - """It could never fit, so asking the sender to retry would be false.""" + """It could never fit, so asking the sender to retry would be false. The reason names the + budget, since ``max_body_bytes`` is off.""" started = await _start(max_body_bytes=None, max_inflight_body_bytes=100) try: - answer = await _send_and_read(started.source.sockport, _head(101), b"") + answer = await _send_and_read(started.source.sockport, _head(101)) finally: await started.source.stop() assert _status(answer) == 413 + assert b"max_inflight_body_bytes" in answer assert started.bodies == [] async def test_the_budget_switched_off_bounds_nothing() -> None: started = await _start(max_body_bytes=1000, max_inflight_body_bytes=0) - port = started.source.sockport - first_reader, first_writer = await asyncio.open_connection("127.0.0.1", port) + source, port = started.source, started.source.sockport + assert source.max_inflight_body_bytes is None + peers: list[_Peer] = [] try: - first_writer.write(_head(1000) + b"a") - await first_writer.drain() + first = await _Peer.open(port, _head(1000) + b"a" * 999) + peers.append(first) await asyncio.sleep(0.1) - second = await _send_and_read(port, _head(1000), b"b" * 1000) - first_writer.write(b"a" * 999) - await first_writer.drain() - first = await _answer(first_reader) + second = await _send_and_read(port, _head(1000) + b"b" * 1000) + await first.send(b"a") + first_answer = await first.answer() finally: - first_writer.close() - await started.source.stop() - assert (_status(first), _status(second)) == (202, 202) + for peer in peers: + peer.close() + await source.stop() + assert (_status(first_answer), _status(second)) == (202, 202) + assert source._inflight_body_bytes == 0 def test_the_default_budget_binds_below_what_the_connection_and_body_caps_allow() -> None: @@ -200,7 +286,7 @@ def test_the_default_budget_binds_below_what_the_connection_and_body_caps_allow( def test_a_body_cap_above_the_budget_is_refused_at_construction() -> None: - """A body that passes ``max_body_bytes`` must be able to fit an empty budget, or it would be + """A body that passes ``max_body_bytes`` must be able to fit an idle budget, or it would be refused every time; the refusal names both settings and withholds both values.""" settings = {"port": 0, "max_body_bytes": 2001, "max_inflight_body_bytes": 2000} with pytest.raises(ValueError, match="max_body_bytes.*max_inflight_body_bytes") as caught: @@ -208,6 +294,7 @@ def test_a_body_cap_above_the_budget_is_refused_at_construction() -> None: assert "2000" not in str(caught.value) and "2001" not in str(caught.value) -def test_the_factory_carries_the_budget() -> None: - assert Http(port=0).settings["max_inflight_body_bytes"] == 256 * 1024 * 1024 +def test_the_factory_default_is_the_listener_default() -> None: + default = http_listener.DEFAULT_MAX_INFLIGHT_BODY_BYTES + assert Http(port=0).settings["max_inflight_body_bytes"] == default assert Http(port=0, max_inflight_body_bytes=None).settings["max_inflight_body_bytes"] is None From 680a87d1d3b05c4ef41fd48c60dd542e1a89a3bf Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:42:08 -0600 Subject: [PATCH 17/39] docs: max_inflight_body_bytes charges bytes received (BACKLOG #6978) Review round 1 repair, docs limb. The settings row says a body is charged as its bytes arrive, so a declared-only body holds nothing, and that a body can be refused 503 before or while it is read. Drops "from authenticated peers", false at the default intake_auth = none. The max_body_bytes row no longer says "unlimited" while the budget is on, and the pre-ingress 413 names the budget too. Proposed PR title: HTTP listener: bound the body bytes in flight across the listener (BACKLOG #6978) Proposed vault banner: CLOSED -- adjudicated real (three concurrent max-size bodies were all read on the base). New Http setting max_inflight_body_bytes, default 256 MiB, charged on body bytes as they arrive: a body that does not fit is refused 503 with Retry-After before or while it is read, one over the whole budget 413; a max_body_bytes above it is refused at build. Tests in tests/test_inbound_http_body_budget.py; documented in docs/CONNECTIONS.md. Verified-by: none --- docs/CONNECTIONS.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index c1f14e6a0e..2c164faa37 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -903,8 +903,8 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `receive_timeout` | `60.0` | bound the **whole-request** read — request line + headers + body (slowloris guard); over budget answers a synchronous `408`. `None`/`0` = no timeout. | | `max_connections_per_host` | **off** | cap on concurrent connections from **one peer address**, answered `503` with an `at_capacity` event whose reason reads `max_connections_per_host` (vault BACKLOG #2606); a `tls = true` listener closes the socket unanswered instead, on every event loop, as the pre-ingress refusals below say. **Ships off, unlike MLLP/TCP/X12**: this connector answers one request per connection, so behind a reverse proxy every partner arrives from one address and any cap would be the listener's whole capacity. Set one only where the listener sees real client addresses. | | `max_handshakes_per_host` | `32` | cap on sockets from **one peer address** that hold a connection slot while **still in their TLS handshake** (vault BACKLOG #4888). It bites only on a `tls = true` listener, where a socket holds a slot through its handshake on every event loop (BACKLOG #2479); there the socket is closed unanswered with an `at_capacity` event whose reason reads `max_handshakes_per_host`. A socket leaves the count when its handshake ends, so it caps how many requests one address can **start** at once, not how many it holds once their handshakes are done. **Ships on**; `None`/`0` = off. Why, what it does not bound, and the L4 load-balancer case: [DEPLOYMENT.md](DEPLOYMENT.md#per-address-listener-caps-behind-the-vip). | -| `max_body_bytes` | `16 MiB` | the MLLP frame cap's HTTP twin — an over-declared `Content-Length` is refused `413` **before a body byte is read** (OOM guard). `None`/`0` = unlimited, and the connection logs a `WARNING` naming the setting each time it is built (BACKLOG #2749). | -| `max_inflight_body_bytes` | `256 MiB` | cap the declared body bytes of **every** request this listener is reading or handing to the engine at once (BACKLOG #6978). Without it the bodies in flight were bounded only by `max_connections` times `max_body_bytes`, 4 GiB at the defaults, from authenticated peers. Each body takes its declared `Content-Length` from the budget once it has passed intake authentication and `max_body_bytes`, before a body byte is read and before any `100 Continue`, and gives it back once the engine has the body. One that does not fit what is left is refused `503` with `Retry-After: 5` and an `at_capacity` event whose reason reads `max_inflight_body_bytes`; one larger than the whole budget, possible only with `max_body_bytes` off, is refused `413`. Nothing is recorded for either, so the sender re-sends. A sender that sends its body without waiting may see the connection reset rather than read the `503`, as with a `413`. A `max_body_bytes` above this budget is refused when the connection is built, which `serve` and `messagefoundry check` both do. `None`/`0` = off. | +| `max_body_bytes` | `16 MiB` | the MLLP frame cap's HTTP twin — an over-declared `Content-Length` is refused `413` **before a body byte is read** (OOM guard). `None`/`0` = no per-body cap, and the connection logs a `WARNING` naming the setting each time it is built (BACKLOG #2749); `max_inflight_body_bytes` still bounds a body while it is on. | +| `max_inflight_body_bytes` | `256 MiB` | cap the body bytes **all** requests on this listener hold at once, while each body is read and until the engine has it (BACKLOG #6978). Without it the bodies in flight were bounded only by `max_connections` times `max_body_bytes`, 4 GiB at the defaults. A body is charged as its bytes arrive, so a peer that declares a body and sends none of it holds nothing. Once a request has passed intake authentication and `max_body_bytes`, and before any `100 Continue`, a declared body that does not fit what other bodies now hold is refused `503` with `Retry-After: 5`, before a byte of it is read; bytes that would take the listener over the cap as they arrive are refused the same way mid-body. Either writes an `at_capacity` event whose reason reads `max_inflight_body_bytes`. A declared body larger than the whole cap, possible only with `max_body_bytes` off, is refused `413` naming this setting. Nothing is recorded for any of these, so the sender re-sends. A sender that is still sending its body may see the connection reset rather than read the answer, as with a `413`. A `max_body_bytes` above this cap is refused when the connection is built, which `serve` and `messagefoundry check` both do. `None`/`0` = off. | | `max_header_bytes` | `64 KiB` | cap the request line + headers (header-flood guard). This one cap can't be switched off: unset or `None` takes the 64 KiB default, and `0` (or `"0"`) is refused at load rather than silently becoming the default (BACKLOG #1872). | | `max_messages_per_second` | **off** | sustained message-rate ceiling for the **whole listener** (ASVS 2.4.1 / 15.2.2, BACKLOG #1114 — the MLLP pacer, ported). Over budget the connector **waits before reading the request**, so the partner is back-pressured and then served in full — **nothing is dropped, refused or answered differently**, and the wait sits outside `receive_timeout` so a paced partner is never handed a `408` for a delay the engine imposed. **Listener-wide, not per-connection**, unlike MLLP/TCP/X12: this connector answers one request per connection, so a per-connection bucket would be charged once and thrown away, bounding nothing. A `GET`/`HEAD` probe waits behind an outstanding debt but **charges nothing**, and neither does a request refused before its body reaches the engine. Only a body the engine reads and records spends budget, including one it then refuses with a `422`, so a peer that submits nothing cannot starve one that does. Unset = no bound, deliberately: a guessed rate throttles real traffic, so the number has to come from your own feed profile. | | `message_burst` | = the rate | tokens the bucket holds, i.e. how large a burst passes unpaced before the sustained rate applies. Only meaningful with `max_messages_per_second` set. Floor of 1 so the listener can always make progress. | @@ -995,8 +995,8 @@ d20261104T003342588-cbb49e (BACKLOG #5102), recorded as the ADR 0154 amendment o `ERROR` row's error text opens with `[refusal kind: ]`, ahead of any refused-body allowance note. A **pre-ingress** refusal answers synchronously and emits an ADR 0021 `connection_event`: `403` (not in `source_ip_allowlist`), `408` (the -request didn't fully arrive within `receive_timeout`), `413` (over `max_body_bytes` **or** -`max_header_bytes`), `400` (a malformed request line or header, or framing this listener will not guess at -- including at least any `Transfer-Encoding`, a duplicated or non-digit `Content-Length`, whitespace before a header colon, a folded header line, a bare CR or LF, a control character in a header value, an HTTP version other than 1.x, a missing `Host` on any version but HTTP/1.0, more than one `Host`, and a non-zero body declared on a method other than `POST`/`PUT`/`PATCH`), `411` (a `POST`/`PUT`/`PATCH` with no `Content-Length`; the body is never read to EOF), `503` with `Retry-After` (a declared body over what is left of `max_inflight_body_bytes`), `503` (at +request didn't fully arrive within `receive_timeout`), `413` (over `max_body_bytes`, `max_header_bytes` +or the whole of `max_inflight_body_bytes`), `400` (a malformed request line or header, or framing this listener will not guess at -- including at least any `Transfer-Encoding`, a duplicated or non-digit `Content-Length`, whitespace before a header colon, a folded header line, a bare CR or LF, a control character in a header value, an HTTP version other than 1.x, a missing `Host` on any version but HTTP/1.0, more than one `Host`, and a non-zero body declared on a method other than `POST`/`PUT`/`PATCH`), `411` (a `POST`/`PUT`/`PATCH` with no `Content-Length`; the body is never read to EOF), `503` with `Retry-After` (a body that does not fit `max_inflight_body_bytes`, before or while it is read), `503` (at `max_connections` — the connection is accepted, then refused and closed at the application layer). On a `tls = true` listener, on every event loop, the `source_ip_allowlist` and connection-cap refusals come before the TLS handshake, so the socket is closed with no answer instead of a `403` or From b9af83d752e049702c9d4c2792a5e8e941bff72c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:59:12 -0600 Subject: [PATCH 18/39] http_listener: one body buffer, early share release, factory check (BACKLOG #6978) Review round 2 repair. Every body is now read in chunks into one growing bytearray, charged per chunk where the budget is on, so a peer sending tiny segments costs no per-segment object the charge misses, and the fuzz target reads through the same loop. A refused or timed-out read gives its share back before the event, audit and answer writes. A budget refusal is no longer told to the admission refusal observers, whose alert names the allowlist and connection caps as its cause. Switching the budget off logs a WARNING, as max_body_bytes does. The Http() factory refuses a literal max_body_bytes above a literal budget, so validate and the IDE agree with the listener, and both refusals name the budget as the setting to raise. Tests: share release on a 408 and on a handler fault, the warning, and the factory refusal; the observer arm now pins that observers are not told. Verified-by: tests --- messagefoundry/config/wiring.py | 13 ++++ messagefoundry/transports/http_listener.py | 55 +++++++++-------- tests/test_inbound_http_body_budget.py | 70 ++++++++++++++++++++-- 3 files changed, 106 insertions(+), 32 deletions(-) diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index 98400d4927..549bd5b3e8 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -3864,6 +3864,19 @@ def Http( } _validate_intake_auth(settings) _validate_sync_reply(settings) + # BACKLOG #6978: a body max_body_bytes admits must fit an idle in-flight budget. Checked here + # for two plain numbers, so `validate` and the IDE refuse what the listener would refuse at + # build; an env() value or another spelling is left to the listener's own check. + inflight = max_inflight_body_bytes + if ( + type(inflight) is int + and type(max_body_bytes) is int + and inflight > 0 + and max_body_bytes > inflight + ): + raise WiringError( + "Http max_inflight_body_bytes must be at least max_body_bytes (values withheld)" + ) # BACKLOG #5525, owner ruling 2026-11-10 ("Per-connection proxies"). Read by the listener's own # reader, so the factory and the listener cannot disagree on an entry; never [api].trusted_proxies. # The list refusal runs first, as its rule requires. A whole-setting env() is read through the diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 7ad2ca5efa..bf4058e9f2 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -43,7 +43,6 @@ from __future__ import annotations import asyncio -import contextlib import ipaddress import json import logging @@ -77,7 +76,7 @@ from messagefoundry.proactor_accept import guard_accepts from messagefoundry.redaction import safe_exc from messagefoundry.tls_handshake_failures import HUNG_UP, HandshakeFailures, handshake_cause -from messagefoundry.transports.admission import ListenerAdmission, notify_refusal +from messagefoundry.transports.admission import ListenerAdmission from messagefoundry.transports.base import ( INTAKE_AUDIT_ACTIONS, InboundHandler, @@ -768,27 +767,22 @@ class of defect :func:`_read_head` already refuses via :class:`HttpRequestError` body side. Silently returning the short ``exc.partial`` bytes would let a truncated body flow on to become an ingress row and a 202, understating what the sender actually declared. - With ``charge``, the body is read in chunks of at most :data:`_BODY_CHUNK_BYTES`, and each is - charged as it arrives, before it is kept (BACKLOG #6978). So a share of the in-flight budget - is bytes received, never bytes promised: a peer that declares a large body and sends none of - it holds nothing.""" + The body is read in chunks of at most :data:`_BODY_CHUNK_BYTES` into one growing buffer, and + ``charge``, when given, is called with each chunk's size as it arrives, before it is kept + (BACKLOG #6978). So a share of the in-flight budget is bytes received, never bytes promised: a + peer that declares a large body and sends none of it holds nothing. One buffer rather than a + list of chunks, so a peer sending tiny segments costs no per-segment object the charge misses.""" if n == 0: return b"" - if charge is not None: - chunks: list[bytes] = [] - remaining = n - while remaining: - chunk = await reader.read(min(remaining, _BODY_CHUNK_BYTES)) - if not chunk: - raise HttpRequestError(400, "incomplete request body", kind="framing_error") + body = bytearray() + while len(body) < n: + chunk = await reader.read(min(n - len(body), _BODY_CHUNK_BYTES)) + if not chunk: + raise HttpRequestError(400, "incomplete request body", kind="framing_error") + if charge is not None: charge(len(chunk)) - chunks.append(chunk) - remaining -= len(chunk) - return b"".join(chunks) - # Refused outside the handler: IncompleteReadError.partial holds the body read so far (#2085). - with contextlib.suppress(asyncio.IncompleteReadError): - return await reader.readexactly(n) - raise HttpRequestError(400, "incomplete request body", kind="framing_error") + body += chunk + return bytes(body) def _header_cap(value: Any) -> int: @@ -1112,10 +1106,10 @@ def __init__(self, config: Source) -> None: # A body max_body_bytes admits could then never fit even an idle listener's budget, # and every such request would be told to retry a refusal that never clears. raise ValueError( - "HTTP source max_body_bytes must not be above max_inflight_body_bytes " + "HTTP source max_inflight_body_bytes must be at least max_body_bytes " "(values withheld)" ) - #: Declared body bytes of the requests now holding a share of the budget, and each one's + #: Body bytes received by the requests now holding a share of the budget, and each one's #: share by its writer, so whichever path ends the request gives back exactly what it took. self._inflight_body_bytes = 0 self._body_shares: dict[asyncio.StreamWriter, int] = {} @@ -1266,6 +1260,14 @@ def __init__(self, config: Source) -> None: self._log_name, ranges, ) + if self.max_inflight_body_bytes is None: + # As for max_body_bytes below (BACKLOG #2749): allowed, documented, never silent. + logger.warning( + "HTTP source %s: max_inflight_body_bytes is off, so the request bodies held at once " + "are bounded only by max_connections and max_body_bytes; set a positive value to " + "bound them", + self._log_name, + ) if self.max_body_bytes is None: # Turning the body cap off is documented, so it is allowed, but never silent (BACKLOG # #2749, as FileSource does for its caps). Logged after every check in this constructor, @@ -1602,10 +1604,9 @@ async def _emit_event( logger.warning("HTTP connection-event emit failed: %s", safe_exc(exc)) def _budget_refusal(self) -> HttpRequestError: - """The ``503`` for a body the in-flight budget has no room for (BACKLOG #6978), told to the - refusal observers as every listener-cap refusal is, so the security-signal layer sees it - even with connection events off.""" - notify_refusal(self._admission.name) + """The ``503`` for a body the in-flight budget has no room for (BACKLOG #6978). Not told to + the admission refusal observers: the alert they feed names the allowlist and the connection + caps as its cause, which this refusal is not.""" return HttpRequestError( 503, "max_inflight_body_bytes", @@ -2164,6 +2165,7 @@ async def _ready(length: int) -> None: request = await _read_authenticated() except TimeoutError: # Slow-loris: the request didn't fully arrive within receive_timeout. Pre-ingress refuse. + self._give_body_share(writer) # before the event write, which may be slow (#6978) await self._emit_event("idle_timeout", peer_host=peer_host) await self._write_safely(writer, build_response(408, '{"error":"request timeout"}')) return True @@ -2174,6 +2176,7 @@ async def _ready(length: int) -> None: # for every other kind. Marked answering, as a request read in full is below, so a stop() # during the event or audit write leaves the refusal its writer. self._answering.add(writer) + self._give_body_share(writer) # the body was dropped; free its share before the writes reason = _with_forwarded(exc.reason, exc) await self._emit_event(exc.kind, peer_host=peer_host, reason=reason) await self._audit_intake_refusal(exc, peer_host) diff --git a/tests/test_inbound_http_body_budget.py b/tests/test_inbound_http_body_budget.py index ce1b108023..27a354c5d8 100644 --- a/tests/test_inbound_http_body_budget.py +++ b/tests/test_inbound_http_body_budget.py @@ -15,12 +15,13 @@ from __future__ import annotations import asyncio +import logging from typing import Any import pytest from messagefoundry.config.models import ConnectorType, Source -from messagefoundry.config.wiring import Http +from messagefoundry.config.wiring import Http, WiringError from messagefoundry.transports import admission, http_listener from messagefoundry.transports.http_listener import HttpSource from messagefoundry.transports.receipt import IngressReceipt, receipt_handler @@ -223,11 +224,11 @@ async def test_a_refused_request_that_expects_continue_gets_no_100() -> None: assert _CONTINUE not in second -async def test_a_budget_refusal_reaches_the_refusal_observers( +async def test_a_budget_refusal_is_not_told_to_the_refusal_observers( monkeypatch: pytest.MonkeyPatch, ) -> None: - """As every listener-cap refusal does, so the security-signal layer sees it with connection - events off.""" + """The alert those observers feed names the allowlist and the connection caps as its cause, + which a budget refusal is not; the ``at_capacity`` event names it instead.""" seen: list[str] = [] monkeypatch.setattr(admission, "_REFUSAL_OBSERVERS", (seen.append,)) started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000) @@ -241,7 +242,7 @@ async def test_a_budget_refusal_reaches_the_refusal_observers( for peer in peers: peer.close() await source.stop() - assert seen == ["IB_BUDGET"] + assert seen == [] async def test_with_max_body_bytes_off_a_body_over_the_whole_budget_is_413() -> None: @@ -289,7 +290,7 @@ def test_a_body_cap_above_the_budget_is_refused_at_construction() -> None: """A body that passes ``max_body_bytes`` must be able to fit an idle budget, or it would be refused every time; the refusal names both settings and withholds both values.""" settings = {"port": 0, "max_body_bytes": 2001, "max_inflight_body_bytes": 2000} - with pytest.raises(ValueError, match="max_body_bytes.*max_inflight_body_bytes") as caught: + with pytest.raises(ValueError, match="max_inflight_body_bytes.*max_body_bytes") as caught: HttpSource(Source(type=ConnectorType.HTTP, settings=settings)) assert "2000" not in str(caught.value) and "2001" not in str(caught.value) @@ -298,3 +299,60 @@ def test_the_factory_default_is_the_listener_default() -> None: default = http_listener.DEFAULT_MAX_INFLIGHT_BODY_BYTES assert Http(port=0).settings["max_inflight_body_bytes"] == default assert Http(port=0, max_inflight_body_bytes=None).settings["max_inflight_body_bytes"] is None + + +def test_the_factory_refuses_a_body_cap_above_the_budget() -> None: + """So ``validate`` and the IDE refuse what the listener would refuse when built.""" + with pytest.raises(WiringError, match="max_inflight_body_bytes.*max_body_bytes"): + Http(port=0, max_inflight_body_bytes=8 * 1024 * 1024) + Http(port=0, max_inflight_body_bytes=8 * 1024 * 1024, max_body_bytes=8 * 1024 * 1024) + Http(port=0, max_inflight_body_bytes=None) + + +def test_switching_the_budget_off_logs_a_warning(caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger="messagefoundry.transports.http_listener"): + HttpSource(Source(type=ConnectorType.HTTP, settings={"port": 0})) + assert not [r for r in caplog.records if "max_inflight_body_bytes is off" in r.message] + HttpSource( + Source(type=ConnectorType.HTTP, settings={"port": 0, "max_inflight_body_bytes": 0}) + ) + assert [r for r in caplog.records if "max_inflight_body_bytes is off" in r.message] + + +async def test_a_request_that_times_out_mid_body_gives_its_share_back() -> None: + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000, receive_timeout=0.3) + source, port = started.source, started.source.sockport + peer = await _Peer.open(port, _head(1000) + b"a" * 400) + try: + await _until(lambda: source._inflight_body_bytes == 400) + assert _status(await peer.answer()) == 408 + await _until(lambda: source._inflight_body_bytes == 0) + assert _status(await _send_and_read(port, _head(1000) + b"c" * 1000)) == 202 + finally: + peer.close() + await source.stop() + + +async def test_a_handler_fault_gives_the_share_back() -> None: + source = HttpSource( + Source( + type=ConnectorType.HTTP, + settings={ + "host": "127.0.0.1", + "port": 0, + "max_body_bytes": 1000, + "max_inflight_body_bytes": 1000, + }, + ) + ) + + async def handler(raw: bytes) -> IngressReceipt: + raise RuntimeError("synthetic handler fault") + + await source.start(receipt_handler(handler)) + try: + answer = await _send_and_read(source.sockport, _head(1000) + b"a" * 1000) + assert _status(answer) == 500 + assert source._inflight_body_bytes == 0 + finally: + await source.stop() From 12bbd909fdd86a9b281243b1541fc0d1feaa3847 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:00:18 -0600 Subject: [PATCH 19/39] docs: max_inflight_body_bytes refusals record no message row (BACKLOG #6978) Review round 2 repair, docs limb. "Nothing is recorded" contradicted the at_capacity event the same row names; no message row is what is meant. Says where a body cap above the budget is refused, and that switching the budget off logs a WARNING. Proposed PR title: HTTP listener: bound the body bytes in flight across the listener (BACKLOG #6978) Proposed vault banner: CLOSED -- adjudicated real (three concurrent max-size bodies were all read on the base). New Http setting max_inflight_body_bytes, default 256 MiB, charged on body bytes as they arrive: a body that does not fit is refused 503 with Retry-After before or while it is read, one over the whole budget 413; a max_body_bytes above it is refused by the factory or at build; off logs a WARNING. Tests in tests/test_inbound_http_body_budget.py; documented in docs/CONNECTIONS.md. Verified-by: none --- docs/CONNECTIONS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 2c164faa37..9c49d34038 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -904,7 +904,7 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `max_connections_per_host` | **off** | cap on concurrent connections from **one peer address**, answered `503` with an `at_capacity` event whose reason reads `max_connections_per_host` (vault BACKLOG #2606); a `tls = true` listener closes the socket unanswered instead, on every event loop, as the pre-ingress refusals below say. **Ships off, unlike MLLP/TCP/X12**: this connector answers one request per connection, so behind a reverse proxy every partner arrives from one address and any cap would be the listener's whole capacity. Set one only where the listener sees real client addresses. | | `max_handshakes_per_host` | `32` | cap on sockets from **one peer address** that hold a connection slot while **still in their TLS handshake** (vault BACKLOG #4888). It bites only on a `tls = true` listener, where a socket holds a slot through its handshake on every event loop (BACKLOG #2479); there the socket is closed unanswered with an `at_capacity` event whose reason reads `max_handshakes_per_host`. A socket leaves the count when its handshake ends, so it caps how many requests one address can **start** at once, not how many it holds once their handshakes are done. **Ships on**; `None`/`0` = off. Why, what it does not bound, and the L4 load-balancer case: [DEPLOYMENT.md](DEPLOYMENT.md#per-address-listener-caps-behind-the-vip). | | `max_body_bytes` | `16 MiB` | the MLLP frame cap's HTTP twin — an over-declared `Content-Length` is refused `413` **before a body byte is read** (OOM guard). `None`/`0` = no per-body cap, and the connection logs a `WARNING` naming the setting each time it is built (BACKLOG #2749); `max_inflight_body_bytes` still bounds a body while it is on. | -| `max_inflight_body_bytes` | `256 MiB` | cap the body bytes **all** requests on this listener hold at once, while each body is read and until the engine has it (BACKLOG #6978). Without it the bodies in flight were bounded only by `max_connections` times `max_body_bytes`, 4 GiB at the defaults. A body is charged as its bytes arrive, so a peer that declares a body and sends none of it holds nothing. Once a request has passed intake authentication and `max_body_bytes`, and before any `100 Continue`, a declared body that does not fit what other bodies now hold is refused `503` with `Retry-After: 5`, before a byte of it is read; bytes that would take the listener over the cap as they arrive are refused the same way mid-body. Either writes an `at_capacity` event whose reason reads `max_inflight_body_bytes`. A declared body larger than the whole cap, possible only with `max_body_bytes` off, is refused `413` naming this setting. Nothing is recorded for any of these, so the sender re-sends. A sender that is still sending its body may see the connection reset rather than read the answer, as with a `413`. A `max_body_bytes` above this cap is refused when the connection is built, which `serve` and `messagefoundry check` both do. `None`/`0` = off. | +| `max_inflight_body_bytes` | `256 MiB` | cap the body bytes **all** requests on this listener hold at once, while each body is read and until the engine has it (BACKLOG #6978). Without it the bodies in flight were bounded only by `max_connections` times `max_body_bytes`, 4 GiB at the defaults. A body is charged as its bytes arrive, so a peer that declares a body and sends none of it holds nothing. Once a request has passed intake authentication and `max_body_bytes`, and before any `100 Continue`, a declared body that does not fit what other bodies now hold is refused `503` with `Retry-After: 5`, before a byte of it is read; bytes that would take the listener over the cap as they arrive are refused the same way mid-body. Either writes an `at_capacity` event whose reason reads `max_inflight_body_bytes`. A declared body larger than the whole cap, possible only with `max_body_bytes` off, is refused `413` naming this setting. No message row is recorded for any of these, so the sender re-sends. A sender that is still sending its body may see the connection reset rather than read the answer, as with a `413`. A `max_body_bytes` above this cap is refused, by the `Http()` factory where both are plain numbers and otherwise when the connection is built, which `serve` and `messagefoundry check` both do. `None`/`0` = off, and the connection then logs a `WARNING` naming the setting each time it is built. | | `max_header_bytes` | `64 KiB` | cap the request line + headers (header-flood guard). This one cap can't be switched off: unset or `None` takes the 64 KiB default, and `0` (or `"0"`) is refused at load rather than silently becoming the default (BACKLOG #1872). | | `max_messages_per_second` | **off** | sustained message-rate ceiling for the **whole listener** (ASVS 2.4.1 / 15.2.2, BACKLOG #1114 — the MLLP pacer, ported). Over budget the connector **waits before reading the request**, so the partner is back-pressured and then served in full — **nothing is dropped, refused or answered differently**, and the wait sits outside `receive_timeout` so a paced partner is never handed a `408` for a delay the engine imposed. **Listener-wide, not per-connection**, unlike MLLP/TCP/X12: this connector answers one request per connection, so a per-connection bucket would be charged once and thrown away, bounding nothing. A `GET`/`HEAD` probe waits behind an outstanding debt but **charges nothing**, and neither does a request refused before its body reaches the engine. Only a body the engine reads and records spends budget, including one it then refuses with a `422`, so a peer that submits nothing cannot starve one that does. Unset = no bound, deliberately: a guessed rate throttles real traffic, so the number has to come from your own feed profile. | | `message_burst` | = the rate | tokens the bucket holds, i.e. how large a burst passes unpaced before the sustained rate applies. Only meaningful with `max_messages_per_second` set. Floor of 1 so the listener can always make progress. | From 3a6cb748c4e4b93c31cbaf018a804287f25028b7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:51:43 -0600 Subject: [PATCH 20/39] http_listener: a refused body read releases its bytes before the share (BACKLOG #6978) The request's share of max_inflight_body_bytes is given back as soon as _serve_one catches a refusal, a receive_timeout or a failed body read. The exception's traceback kept _read_exactly's frame alive through the refusal's event and audit writes, and that frame still held the partial body and its last chunk. So bytes the budget no longer counted stayed resident, up to about twice the budget at once. _read_exactly now clears its buffer and drops its last chunk on any exception, cancellation included, before it propagates. The early give-back stays where it is: moving it to a finally would hold the share through a reply_from wait. The comment at the HttpRequestError give-back no longer says the body was dropped; it says why the give-back is safe there. Three tests read _read_exactly's frame off the exception and fail before this change: a body that stops short, a mid-body budget refusal, and a cancellation by receive_timeout. Proposed PR title: HTTP listener in-flight body budget (BACKLOG #6978) Proposed vault banner: BUILT on b20054-6978b, a listener-wide max_inflight_body_bytes charged on bytes received, with a refused body read releasing its bytes before the share is given back. Awaiting PR. Verified-by: tests --- messagefoundry/transports/http_listener.py | 32 ++++++++--- tests/test_inbound_http_body_budget.py | 66 ++++++++++++++++++++++ 2 files changed, 89 insertions(+), 9 deletions(-) diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index bf4058e9f2..94d2295bf4 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -771,17 +771,29 @@ class of defect :func:`_read_head` already refuses via :class:`HttpRequestError` ``charge``, when given, is called with each chunk's size as it arrives, before it is kept (BACKLOG #6978). So a share of the in-flight budget is bytes received, never bytes promised: a peer that declares a large body and sends none of it holds nothing. One buffer rather than a - list of chunks, so a peer sending tiny segments costs no per-segment object the charge misses.""" + list of chunks, so a peer sending tiny segments costs no per-segment object the charge misses. + + On any exception, a refusal, a cancellation by ``receive_timeout`` or a failed read, the bytes + read so far are released before it propagates. The caller gives the request's share back as + soon as it catches the exception, and the exception's traceback keeps this frame alive through + the refusal's event and audit writes; a buffer still held there would be resident payload the + budget no longer counts.""" if n == 0: return b"" body = bytearray() - while len(body) < n: - chunk = await reader.read(min(n - len(body), _BODY_CHUNK_BYTES)) - if not chunk: - raise HttpRequestError(400, "incomplete request body", kind="framing_error") - if charge is not None: - charge(len(chunk)) - body += chunk + chunk = b"" + try: + while len(body) < n: + chunk = await reader.read(min(n - len(body), _BODY_CHUNK_BYTES)) + if not chunk: + raise HttpRequestError(400, "incomplete request body", kind="framing_error") + if charge is not None: + charge(len(chunk)) + body += chunk + except BaseException: + body.clear() + chunk = b"" + raise return bytes(body) @@ -2176,7 +2188,9 @@ async def _ready(length: int) -> None: # for every other kind. Marked answering, as a request read in full is below, so a stop() # during the event or audit write leaves the refusal its writer. self._answering.add(writer) - self._give_body_share(writer) # the body was dropped; free its share before the writes + # No body reached the engine, and _read_exactly released any bytes it had read, so the + # share is given back before the event and audit writes, which may be slow (#6978). + self._give_body_share(writer) reason = _with_forwarded(exc.reason, exc) await self._emit_event(exc.kind, peer_host=peer_host, reason=reason) await self._audit_intake_refusal(exc, peer_host) diff --git a/tests/test_inbound_http_body_budget.py b/tests/test_inbound_http_body_budget.py index 27a354c5d8..0402fd3020 100644 --- a/tests/test_inbound_http_body_budget.py +++ b/tests/test_inbound_http_body_budget.py @@ -16,6 +16,7 @@ import asyncio import logging +import traceback from typing import Any import pytest @@ -356,3 +357,68 @@ async def handler(raw: bytes) -> IngressReceipt: assert source._inflight_body_bytes == 0 finally: await source.stop() + + +def _read_exactly_locals(exc: BaseException) -> dict[str, Any]: + """The locals ``_read_exactly`` still holds through ``exc``'s traceback. + + A refusal gives the request's share back as soon as it is caught, while the exception, and with + it the frame that read the body, lives on through the refusal's event and audit writes. Whatever + that frame still holds is resident payload the budget no longer counts.""" + for frame, _ in traceback.walk_tb(exc.__traceback__): + if frame.f_code is http_listener._read_exactly.__code__: + return dict(frame.f_locals) + raise AssertionError("_read_exactly is not on the traceback") + + +def _resident(locals_: dict[str, Any]) -> int: + return sum(len(v) for v in locals_.values() if isinstance(v, (bytes, bytearray))) + + +async def test_a_body_that_stops_short_leaves_no_bytes_behind_its_refusal() -> None: + reader = asyncio.StreamReader() + reader.feed_data(b"a" * 300) + reader.feed_eof() + with pytest.raises(http_listener.HttpRequestError) as caught: + await http_listener._read_exactly(reader, 1000) + assert _resident(_read_exactly_locals(caught.value)) == 0 + + +async def test_a_mid_body_budget_refusal_leaves_no_bytes_behind_it() -> None: + reader = asyncio.StreamReader() + reader.feed_data(b"a" * 300) + charged: list[int] = [] + + def charge(size: int) -> None: + if charged: + raise http_listener.HttpRequestError(503, "max_inflight_body_bytes", kind="at_capacity") + charged.append(size) + + async def feed_more() -> None: + await asyncio.sleep(0.05) + reader.feed_data(b"b" * 300) + + feeder = asyncio.create_task(feed_more()) + with pytest.raises(http_listener.HttpRequestError) as caught: + await http_listener._read_exactly(reader, 1000, charge=charge) + await feeder + assert charged == [300] + assert _resident(_read_exactly_locals(caught.value)) == 0 + + +async def test_a_body_read_cancelled_by_the_receive_timeout_leaves_no_bytes_behind() -> None: + reader = asyncio.StreamReader() + reader.feed_data(b"a" * 300) + caught: list[BaseException] = [] + + async def read() -> bytes: + try: + return await http_listener._read_exactly(reader, 1000) + except asyncio.CancelledError as exc: + caught.append(exc) + raise + + with pytest.raises(TimeoutError): + await asyncio.wait_for(read(), 0.1) + assert len(caught) == 1 + assert _resident(_read_exactly_locals(caught[0])) == 0 From b00373f12c82e5190f25433aba59fe926095715d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:06:45 -0600 Subject: [PATCH 21/39] http_listener: every early exit frees the body before its writes (BACKLOG #6978) Repair round 1 after the code-review skill at xhigh. The handler-fault arm gave the share back in its finally, then awaited the handler_error event and the answer inside the except block, while the exception's traceback kept the handler's frames, and the body they were passed, alive. It now keeps only the reason and whether the fault is temporary, and does its writes after the except block has let go of the exception. A body read that failed with an OSError, or any other exception but a refusal or a receive_timeout, left _serve_one with its share still charged, and _on_client wrote its peer_reset event before its own give-back. A last except arm around the read now gives the share back and re-raises. _read_exactly lets go of its buffer in a finally rather than an except BaseException, with no pre-binding. Its docstring names the writes the refusal really holds, event and response, and says the stream's own buffer is outside the budget. New tests: a failed read leaves no bytes behind; a failed read gives its share back before its event; a handler fault holds no body, reached from the exception being handled, through its event. The last two fail on the previous head. Verified-by: tests --- messagefoundry/transports/http_listener.py | 35 +++++--- tests/test_inbound_http_body_budget.py | 93 ++++++++++++++++++++++ 2 files changed, 117 insertions(+), 11 deletions(-) diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 94d2295bf4..95a5b21808 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -773,15 +773,16 @@ class of defect :func:`_read_head` already refuses via :class:`HttpRequestError` peer that declares a large body and sends none of it holds nothing. One buffer rather than a list of chunks, so a peer sending tiny segments costs no per-segment object the charge misses. - On any exception, a refusal, a cancellation by ``receive_timeout`` or a failed read, the bytes - read so far are released before it propagates. The caller gives the request's share back as - soon as it catches the exception, and the exception's traceback keeps this frame alive through - the refusal's event and audit writes; a buffer still held there would be resident payload the - budget no longer counts.""" + However the read ends, a refusal, a cancellation by ``receive_timeout``, a failed read or the + return, this frame lets go of the bytes it read before it is left. ``HttpSource._serve_one`` + gives the request's share back as soon as the read raises, and the exception's traceback keeps + this frame alive through the refusal's event and response writes; a buffer still held there + would be resident payload the budget no longer counts. Bytes the stream has buffered but this + function has not yet read are outside the budget, bounded per connection by the stream's own + buffer limit.""" if n == 0: return b"" body = bytearray() - chunk = b"" try: while len(body) < n: chunk = await reader.read(min(n - len(body), _BODY_CHUNK_BYTES)) @@ -790,11 +791,11 @@ class of defect :func:`_read_head` already refuses via :class:`HttpRequestError` if charge is not None: charge(len(chunk)) body += chunk - except BaseException: + return bytes(body) + finally: + # The return value is built before this runs, so a completed read loses nothing. body.clear() chunk = b"" - raise - return bytes(body) def _header_cap(value: Any) -> int: @@ -2201,6 +2202,12 @@ async def _ready(length: int) -> None: ), ) return True + except BaseException: + # Any other way out of the read, at least a failed read (OSError) and a cancellation, + # goes on to `_on_client`, which writes its event before its own give-back. The bytes + # are already released by _read_exactly, so the share is given back here, first (#6978). + self._give_body_share(writer) + raise # A stop() that ran while the last bytes sat in the reader's buffer closed this writer as # still reading, so no answer could reach the peer: hand nothing on, and the sender resends # a body that was never recorded or answered, as it would after a close one read earlier. @@ -2238,6 +2245,7 @@ async def _ready(length: int) -> None: # (it becomes the message's ERROR/dead-letter + AlertSink). count-and-log holds: the body is # persisted before the response is written — as a RECEIVED ingress row, or as an ERROR row when # the handler refuses it. + fault: tuple[str, bool] | None = None try: try: receipt = await self._handler(request.body) @@ -2248,6 +2256,11 @@ async def _ready(length: int) -> None: request.body = b"" self._give_body_share(writer) except Exception as exc: + # Only what the answer needs is kept. The exception's traceback holds the handler's + # frames, and with them the body, so the writes below run after this block has let go + # of it: the share is already given back (BACKLOG #6978). + fault = (safe_exc(exc), isinstance(exc, OSError)) + if fault is not None: # BACKLOG #5680, the HTTP twin of the MLLP listener's #1619 arm: a fault inside the # inbound handler, such as a failed ingress commit, is an engine-side failure. Left to # `_on_client`, an OSError (TimeoutError included) read as `peer_reset` with no log line @@ -2257,9 +2270,9 @@ async def _ready(length: int) -> None: # allows. Charged to the pacer like any body read, so a sender that re-sends at once is # still paced. Returns True: the failure emitted its own kind, so the outer `closed` is # suppressed. + reason, temporary = fault if self._pacer is not None: self._pacer.charge(1, now=time.monotonic()) - reason = safe_exc(exc) logger.error( "HTTP source %s: a request failed in the inbound handler: %s (peer=%s)", self._log_name, @@ -2267,7 +2280,7 @@ async def _ready(length: int) -> None: peer_host or "unknown", ) await self._emit_event("handler_error", peer_host=peer_host, reason=reason) - if isinstance(exc, OSError): + if temporary: status, headers = _refusal_status(RefusalKind.TEMPORARY) answer = build_response( status, '{"error":"temporarily unavailable"}', extra_headers=headers diff --git a/tests/test_inbound_http_body_budget.py b/tests/test_inbound_http_body_budget.py index 0402fd3020..d93801dca4 100644 --- a/tests/test_inbound_http_body_budget.py +++ b/tests/test_inbound_http_body_budget.py @@ -16,6 +16,7 @@ import asyncio import logging +import sys import traceback from typing import Any @@ -422,3 +423,95 @@ async def read() -> bytes: await asyncio.wait_for(read(), 0.1) assert len(caught) == 1 assert _resident(_read_exactly_locals(caught[0])) == 0 + + +async def test_a_failed_body_read_leaves_no_bytes_behind() -> None: + reader = asyncio.StreamReader() + reader.feed_data(b"a" * 300) + + async def reset() -> None: + await asyncio.sleep(0.05) + reader.set_exception(ConnectionResetError("synthetic reset")) + + resetter = asyncio.create_task(reset()) + with pytest.raises(ConnectionResetError) as caught: + await http_listener._read_exactly(reader, 1000) + await resetter + assert _resident(_read_exactly_locals(caught.value)) == 0 + + +async def test_a_failed_body_read_gives_its_share_back_before_its_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A read that fails with an ``OSError`` leaves ``_serve_one`` for ``_on_client``, which writes + its ``peer_reset`` event before its own give-back; the share is given back first.""" + + async def failing_read(reader: asyncio.StreamReader, n: int, *, charge: Any = None) -> bytes: + charge(300) + raise ConnectionResetError("synthetic reset") + + monkeypatch.setattr(http_listener, "_read_exactly", failing_read) + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000) + source = started.source + held: list[int] = [] + sink = source.on_connection_event + + async def recording_sink(kind: str, peer_host: str | None, reason: str | None) -> None: + if kind == "peer_reset": + held.append(source._inflight_body_bytes) + assert sink is not None + await sink(kind, peer_host, reason) + + source.on_connection_event = recording_sink + try: + await _send_and_read(source.sockport, _head(1000) + b"a" * 1000) + await _until(lambda: bool(held)) + assert held == [0] + finally: + await source.stop() + + +def _resident_on_the_exception_being_handled() -> int: + """Payload bytes held by every frame on the exception now being handled, and on its causes.""" + total = 0 + exc: BaseException | None = sys.exc_info()[1] + seen: set[int] = set() + while exc is not None and id(exc) not in seen: + seen.add(id(exc)) + for frame, _ in traceback.walk_tb(exc.__traceback__): + total += _resident(dict(frame.f_locals)) + exc = exc.__cause__ or exc.__context__ + return total + + +async def test_a_handler_fault_holds_no_body_through_its_event() -> None: + """The handler-fault arm gives the share back before its event and answer writes, so nothing + reachable from the exception may still hold the body while they run.""" + source = HttpSource( + Source( + type=ConnectorType.HTTP, + settings={ + "host": "127.0.0.1", + "port": 0, + "max_body_bytes": 1000, + "max_inflight_body_bytes": 1000, + }, + ) + ) + seen: list[tuple[int, int]] = [] + + async def handler(raw: bytes) -> IngressReceipt: + raise RuntimeError("synthetic handler fault") + + async def sink(kind: str, peer_host: str | None, reason: str | None) -> None: + if kind == "handler_error": + seen.append((source._inflight_body_bytes, _resident_on_the_exception_being_handled())) + + source.on_connection_event = sink + await source.start(receipt_handler(handler)) + try: + answer = await _send_and_read(source.sockport, _head(1000) + b"a" * 1000) + assert _status(answer) == 500 + assert seen == [(0, 0)] + finally: + await source.stop() From 516b6ea38432e09b575405666134c1fa9b27958d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:07:30 -0600 Subject: [PATCH 22/39] docs: max_inflight_body_bytes does not charge the stream's own buffer (BACKLOG #6978) The HTTP listener row in docs/CONNECTIONS.md said a body is charged as its bytes arrive. Bytes a connection's stream has buffered but the listener has not yet read are not charged; the stream's own buffer limit bounds them per connection. The row now says so. Proposed PR title: HTTP listener in-flight body budget (BACKLOG #6978) Proposed vault banner: BUILT on b20054-6978b, a listener-wide max_inflight_body_bytes charged on bytes received, with every early exit from a request releasing its body before its event and answer writes. Awaiting PR. Verified-by: tests --- docs/CONNECTIONS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 9c49d34038..31f49f65ae 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -904,7 +904,7 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `max_connections_per_host` | **off** | cap on concurrent connections from **one peer address**, answered `503` with an `at_capacity` event whose reason reads `max_connections_per_host` (vault BACKLOG #2606); a `tls = true` listener closes the socket unanswered instead, on every event loop, as the pre-ingress refusals below say. **Ships off, unlike MLLP/TCP/X12**: this connector answers one request per connection, so behind a reverse proxy every partner arrives from one address and any cap would be the listener's whole capacity. Set one only where the listener sees real client addresses. | | `max_handshakes_per_host` | `32` | cap on sockets from **one peer address** that hold a connection slot while **still in their TLS handshake** (vault BACKLOG #4888). It bites only on a `tls = true` listener, where a socket holds a slot through its handshake on every event loop (BACKLOG #2479); there the socket is closed unanswered with an `at_capacity` event whose reason reads `max_handshakes_per_host`. A socket leaves the count when its handshake ends, so it caps how many requests one address can **start** at once, not how many it holds once their handshakes are done. **Ships on**; `None`/`0` = off. Why, what it does not bound, and the L4 load-balancer case: [DEPLOYMENT.md](DEPLOYMENT.md#per-address-listener-caps-behind-the-vip). | | `max_body_bytes` | `16 MiB` | the MLLP frame cap's HTTP twin — an over-declared `Content-Length` is refused `413` **before a body byte is read** (OOM guard). `None`/`0` = no per-body cap, and the connection logs a `WARNING` naming the setting each time it is built (BACKLOG #2749); `max_inflight_body_bytes` still bounds a body while it is on. | -| `max_inflight_body_bytes` | `256 MiB` | cap the body bytes **all** requests on this listener hold at once, while each body is read and until the engine has it (BACKLOG #6978). Without it the bodies in flight were bounded only by `max_connections` times `max_body_bytes`, 4 GiB at the defaults. A body is charged as its bytes arrive, so a peer that declares a body and sends none of it holds nothing. Once a request has passed intake authentication and `max_body_bytes`, and before any `100 Continue`, a declared body that does not fit what other bodies now hold is refused `503` with `Retry-After: 5`, before a byte of it is read; bytes that would take the listener over the cap as they arrive are refused the same way mid-body. Either writes an `at_capacity` event whose reason reads `max_inflight_body_bytes`. A declared body larger than the whole cap, possible only with `max_body_bytes` off, is refused `413` naming this setting. No message row is recorded for any of these, so the sender re-sends. A sender that is still sending its body may see the connection reset rather than read the answer, as with a `413`. A `max_body_bytes` above this cap is refused, by the `Http()` factory where both are plain numbers and otherwise when the connection is built, which `serve` and `messagefoundry check` both do. `None`/`0` = off, and the connection then logs a `WARNING` naming the setting each time it is built. | +| `max_inflight_body_bytes` | `256 MiB` | cap the body bytes **all** requests on this listener hold at once, while each body is read and until the engine has it (BACKLOG #6978). Without it the bodies in flight were bounded only by `max_connections` times `max_body_bytes`, 4 GiB at the defaults. A body is charged as its bytes arrive, so a peer that declares a body and sends none of it holds nothing. Bytes a connection's stream has buffered but the listener has not yet read are not charged; the stream's own buffer limit bounds them per connection. Once a request has passed intake authentication and `max_body_bytes`, and before any `100 Continue`, a declared body that does not fit what other bodies now hold is refused `503` with `Retry-After: 5`, before a byte of it is read; bytes that would take the listener over the cap as they arrive are refused the same way mid-body. Either writes an `at_capacity` event whose reason reads `max_inflight_body_bytes`. A declared body larger than the whole cap, possible only with `max_body_bytes` off, is refused `413` naming this setting. No message row is recorded for any of these, so the sender re-sends. A sender that is still sending its body may see the connection reset rather than read the answer, as with a `413`. A `max_body_bytes` above this cap is refused, by the `Http()` factory where both are plain numbers and otherwise when the connection is built, which `serve` and `messagefoundry check` both do. `None`/`0` = off, and the connection then logs a `WARNING` naming the setting each time it is built. | | `max_header_bytes` | `64 KiB` | cap the request line + headers (header-flood guard). This one cap can't be switched off: unset or `None` takes the 64 KiB default, and `0` (or `"0"`) is refused at load rather than silently becoming the default (BACKLOG #1872). | | `max_messages_per_second` | **off** | sustained message-rate ceiling for the **whole listener** (ASVS 2.4.1 / 15.2.2, BACKLOG #1114 — the MLLP pacer, ported). Over budget the connector **waits before reading the request**, so the partner is back-pressured and then served in full — **nothing is dropped, refused or answered differently**, and the wait sits outside `receive_timeout` so a paced partner is never handed a `408` for a delay the engine imposed. **Listener-wide, not per-connection**, unlike MLLP/TCP/X12: this connector answers one request per connection, so a per-connection bucket would be charged once and thrown away, bounding nothing. A `GET`/`HEAD` probe waits behind an outstanding debt but **charges nothing**, and neither does a request refused before its body reaches the engine. Only a body the engine reads and records spends budget, including one it then refuses with a `422`, so a peer that submits nothing cannot starve one that does. Unset = no bound, deliberately: a guessed rate throttles real traffic, so the number has to come from your own feed profile. | | `message_burst` | = the rate | tokens the bucket holds, i.e. how large a burst passes unpaced before the sustained rate applies. Only meaningful with `max_messages_per_second` set. Floor of 1 so the listener can always make progress. | From 777852e82aabd0442eff8d630707be09a438695f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:29:03 -0600 Subject: [PATCH 23/39] http_listener: clear the raising frames before an early give-back (BACKLOG #6978) Repair round 2 after the code-review skill at xhigh. Leaving the except block frees the handler's frames only when nothing cycles back to them. At least aiosqlite raises with the failed future, and so the error, a local of the frame that raised it, so a failed ingress commit kept the body resident until the cyclic collector ran, after its share was given back. The new _release_frames clears the locals of the finished frames on the exception and its cause and context chain, as the API client's _release_raising_frames does. The read now has one inner except BaseException that clears the frames and gives the share back, ahead of the 408, 4xx and _on_client arms, in place of a give-back per arm. The handler call clears its frames on any exception, a cancellation included, before its finally gives the share back. The _read_exactly docstring drops its closed list of exits and points at docs/CONNECTIONS.md for the uncharged stream buffer. Tests: a handler fault and a read refusal that each raise through a reference cycle, with the cyclic collector off, hold no body through their event; _release_frames frees a cycle through a cause chain. All three fail on the previous head. Verified-by: tests --- messagefoundry/transports/http_listener.py | 81 ++++++++++++------ tests/test_inbound_http_body_budget.py | 98 ++++++++++++++++++---- 2 files changed, 134 insertions(+), 45 deletions(-) diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 95a5b21808..f5da0d640a 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -50,6 +50,7 @@ import socket import ssl import time +import traceback from collections.abc import Awaitable, Callable, Mapping from typing import TYPE_CHECKING, Any, ClassVar, assert_never, cast @@ -773,13 +774,13 @@ class of defect :func:`_read_head` already refuses via :class:`HttpRequestError` peer that declares a large body and sends none of it holds nothing. One buffer rather than a list of chunks, so a peer sending tiny segments costs no per-segment object the charge misses. - However the read ends, a refusal, a cancellation by ``receive_timeout``, a failed read or the - return, this frame lets go of the bytes it read before it is left. ``HttpSource._serve_one`` - gives the request's share back as soon as the read raises, and the exception's traceback keeps - this frame alive through the refusal's event and response writes; a buffer still held there - would be resident payload the budget no longer counts. Bytes the stream has buffered but this - function has not yet read are outside the budget, bounded per connection by the stream's own - buffer limit.""" + However the read ends, this frame lets go of the bytes it read before it is left. + ``HttpSource._serve_one`` gives the request's share back as soon as the read raises, and the + exception's traceback can keep this frame alive through the writes that follow; a buffer still + held there would be resident payload the budget no longer counts. ``_serve_one`` also clears + the raising frames (:func:`_release_frames`); this is the half that does not rely on it. Bytes + the stream has buffered but this function has not yet read are not charged: docs/CONNECTIONS.md, + the ``max_inflight_body_bytes`` row, states how far they can reach.""" if n == 0: return b"" body = bytearray() @@ -798,6 +799,29 @@ class of defect :func:`_read_head` already refuses via :class:`HttpRequestError` chunk = b"" +def _release_frames(exc: BaseException) -> None: + """Clear the locals of the finished frames that raised ``exc`` and the errors it chains. + + BACKLOG #6978: a request's share of the in-flight budget is given back as soon as its read or + its handler raises, and the writes that follow can be slow. The raising frames may still hold + the body: as plain locals, which leaving the ``except`` block frees, or in a reference cycle, + which only the cyclic collector frees. At least aiosqlite makes one, keeping the failed future, + and so the error, as a local of the frame that raised it. Clearing the locals frees the body + either way. The walk follows ``__cause__`` and ``__context__``, skips a frame still executing, + and does not open exception groups. ``messagefoundry.apiclient.client._release_raising_frames`` + is the same walk for the client side, with a stop the listener does not need.""" + seen: set[int] = set() + pending: list[BaseException | None] = [exc] + while pending: + current = pending.pop() + if current is None or id(current) in seen: + continue + seen.add(id(current)) + if current.__traceback__ is not None: + traceback.clear_frames(current.__traceback__) + pending.extend((current.__cause__, current.__context__)) + + def _header_cap(value: Any) -> int: """Read ``max_header_bytes``, the one cap on this listener that cannot be switched off. @@ -2169,16 +2193,24 @@ async def _ready(length: int) -> None: return False # stopping while paused: nothing was read, so there is nothing to answer try: - # The whole head -> auth -> body sequence stays inside ONE receive_timeout budget; the - # refusal RESPONSE is written below, outside it, so a 401 write cannot be cut off by the - # slow-loris clock. - if self.receive_timeout: - request = await asyncio.wait_for(_read_authenticated(), self.receive_timeout) - else: - request = await _read_authenticated() + try: + # The whole head -> auth -> body sequence stays inside ONE receive_timeout budget; + # the refusal RESPONSE is written below, outside it, so a 401 write cannot be cut + # off by the slow-loris clock. + if self.receive_timeout: + request = await asyncio.wait_for(_read_authenticated(), self.receive_timeout) + else: + request = await _read_authenticated() + except BaseException as exc: + # BACKLOG #6978: however the read ends early, no body reached the engine, so its + # share is given back here, before any event, audit or answer write, the arms below + # and `_on_client`'s included. The frames that read it are cleared first, so nothing + # the exception reaches still holds bytes the budget no longer counts. + _release_frames(exc) + self._give_body_share(writer) + raise except TimeoutError: # Slow-loris: the request didn't fully arrive within receive_timeout. Pre-ingress refuse. - self._give_body_share(writer) # before the event write, which may be slow (#6978) await self._emit_event("idle_timeout", peer_host=peer_host) await self._write_safely(writer, build_response(408, '{"error":"request timeout"}')) return True @@ -2189,9 +2221,6 @@ async def _ready(length: int) -> None: # for every other kind. Marked answering, as a request read in full is below, so a stop() # during the event or audit write leaves the refusal its writer. self._answering.add(writer) - # No body reached the engine, and _read_exactly released any bytes it had read, so the - # share is given back before the event and audit writes, which may be slow (#6978). - self._give_body_share(writer) reason = _with_forwarded(exc.reason, exc) await self._emit_event(exc.kind, peer_host=peer_host, reason=reason) await self._audit_intake_refusal(exc, peer_host) @@ -2202,12 +2231,6 @@ async def _ready(length: int) -> None: ), ) return True - except BaseException: - # Any other way out of the read, at least a failed read (OSError) and a cancellation, - # goes on to `_on_client`, which writes its event before its own give-back. The bytes - # are already released by _read_exactly, so the share is given back here, first (#6978). - self._give_body_share(writer) - raise # A stop() that ran while the last bytes sat in the reader's buffer closed this writer as # still reading, so no answer could reach the peer: hand nothing on, and the sender resends # a body that was never recorded or answered, as it would after a close one read earlier. @@ -2249,6 +2272,11 @@ async def _ready(length: int) -> None: try: try: receipt = await self._handler(request.body) + except BaseException as exc: + # BACKLOG #6978: the handler's frames may still hold the body, a cancellation's + # included, through the writes that follow; clear them before the share is given. + _release_frames(exc) + raise finally: # BACKLOG #6978: the body is the engine's now, committed or refused, so its share # of the in-flight budget is free, and this turn stops holding the bytes. A @@ -2256,9 +2284,8 @@ async def _ready(length: int) -> None: request.body = b"" self._give_body_share(writer) except Exception as exc: - # Only what the answer needs is kept. The exception's traceback holds the handler's - # frames, and with them the body, so the writes below run after this block has let go - # of it: the share is already given back (BACKLOG #6978). + # Only what the answer needs is kept, and the writes below run after this block has + # let go of the exception (BACKLOG #6978). fault = (safe_exc(exc), isinstance(exc, OSError)) if fault is not None: # BACKLOG #5680, the HTTP twin of the MLLP listener's #1619 arm: a fault inside the diff --git a/tests/test_inbound_http_body_budget.py b/tests/test_inbound_http_body_budget.py index d93801dca4..db75e0abcb 100644 --- a/tests/test_inbound_http_body_budget.py +++ b/tests/test_inbound_http_body_budget.py @@ -15,9 +15,10 @@ from __future__ import annotations import asyncio +import gc import logging -import sys import traceback +import weakref from typing import Any import pytest @@ -471,22 +472,18 @@ async def recording_sink(kind: str, peer_host: str | None, reason: str | None) - await source.stop() -def _resident_on_the_exception_being_handled() -> int: - """Payload bytes held by every frame on the exception now being handled, and on its causes.""" - total = 0 - exc: BaseException | None = sys.exc_info()[1] - seen: set[int] = set() - while exc is not None and id(exc) not in seen: - seen.add(id(exc)) - for frame, _ in traceback.walk_tb(exc.__traceback__): - total += _resident(dict(frame.f_locals)) - exc = exc.__cause__ or exc.__context__ - return total +class _Holder: + """Something a handler frame holds beside the body, which a weak reference can watch.""" + + def __init__(self, body: bytes) -> None: + self.body = body async def test_a_handler_fault_holds_no_body_through_its_event() -> None: - """The handler-fault arm gives the share back before its event and answer writes, so nothing - reachable from the exception may still hold the body while they run.""" + """The handler-fault arm gives the share back before its event and answer writes, so the frames + that held the body must be freed before they run. The handler raises the way aiosqlite does, + with the error a local of the frame that raised it, a reference cycle that leaving the + ``except`` block cannot free; the cyclic collector is off so it cannot free it either.""" source = HttpSource( Source( type=ConnectorType.HTTP, @@ -498,20 +495,85 @@ async def test_a_handler_fault_holds_no_body_through_its_event() -> None: }, ) ) - seen: list[tuple[int, int]] = [] + watched: list[weakref.ref[_Holder]] = [] + seen: list[tuple[int, bool]] = [] async def handler(raw: bytes) -> IngressReceipt: - raise RuntimeError("synthetic handler fault") + holder = _Holder(raw) + watched.append(weakref.ref(holder)) + err = RuntimeError("synthetic handler fault") + raise err async def sink(kind: str, peer_host: str | None, reason: str | None) -> None: if kind == "handler_error": - seen.append((source._inflight_body_bytes, _resident_on_the_exception_being_handled())) + seen.append((source._inflight_body_bytes, watched[0]() is None)) source.on_connection_event = sink await source.start(receipt_handler(handler)) + gc.disable() try: answer = await _send_and_read(source.sockport, _head(1000) + b"a" * 1000) assert _status(answer) == 500 - assert seen == [(0, 0)] + assert seen == [(0, True)] + finally: + gc.enable() + await source.stop() + + +async def test_a_read_refusal_holds_no_body_through_its_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The read-refusal arms give the share back before their writes too, with the same cycle.""" + watched: list[weakref.ref[_Holder]] = [] + + async def refusing_read(reader: asyncio.StreamReader, n: int, *, charge: Any = None) -> bytes: + holder = _Holder(await reader.readexactly(300)) + charge(300) + watched.append(weakref.ref(holder)) + err = http_listener.HttpRequestError(400, "synthetic refusal", kind="framing_error") + raise err + + monkeypatch.setattr(http_listener, "_read_exactly", refusing_read) + started = await _start(max_body_bytes=1000, max_inflight_body_bytes=1000) + source = started.source + seen: list[tuple[int, bool]] = [] + + async def sink(kind: str, peer_host: str | None, reason: str | None) -> None: + if kind == "framing_error": + seen.append((source._inflight_body_bytes, watched[0]() is None)) + + source.on_connection_event = sink + gc.disable() + try: + answer = await _send_and_read(source.sockport, _head(1000) + b"a" * 1000) + assert _status(answer) == 400 + assert seen == [(0, True)] finally: + gc.enable() await source.stop() + + +def test_release_frames_frees_a_cycle_through_the_cause_chain() -> None: + watched: list[weakref.ref[_Holder]] = [] + + def inner() -> None: + holder = _Holder(b"a" * 300) + watched.append(weakref.ref(holder)) + err = OSError("synthetic") + raise err + + def outer() -> None: + try: + inner() + except OSError as exc: + raise RuntimeError("wrapped") from exc + + gc.disable() + try: + try: + outer() + except RuntimeError as exc: + http_listener._release_frames(exc) + assert watched[0]() is None + finally: + gc.enable() From 479c1e9aade962a97b388a2180e3260a62ba8d98 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:29:43 -0600 Subject: [PATCH 24/39] docs: state how far the uncharged stream buffer can reach (BACKLOG #6978) Repair round 2. The max_inflight_body_bytes row said the stream's own buffer limit bounds the uncharged bytes per connection, which reads as 64 KiB. asyncio pauses a stream only past twice its 64 KiB limit, and one transport read can add 256 KiB on the selector event loop, more under TLS. The row now says at least that much. Proposed PR title: HTTP listener in-flight body budget (BACKLOG #6978) Proposed vault banner: BUILT on b20054-6978b, a listener-wide max_inflight_body_bytes charged on bytes received; an early exit from a request clears the frames that held its body and gives its share back before its event and answer writes. Awaiting PR. Verified-by: tests --- docs/CONNECTIONS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 31f49f65ae..dfb409e903 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -904,7 +904,7 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `max_connections_per_host` | **off** | cap on concurrent connections from **one peer address**, answered `503` with an `at_capacity` event whose reason reads `max_connections_per_host` (vault BACKLOG #2606); a `tls = true` listener closes the socket unanswered instead, on every event loop, as the pre-ingress refusals below say. **Ships off, unlike MLLP/TCP/X12**: this connector answers one request per connection, so behind a reverse proxy every partner arrives from one address and any cap would be the listener's whole capacity. Set one only where the listener sees real client addresses. | | `max_handshakes_per_host` | `32` | cap on sockets from **one peer address** that hold a connection slot while **still in their TLS handshake** (vault BACKLOG #4888). It bites only on a `tls = true` listener, where a socket holds a slot through its handshake on every event loop (BACKLOG #2479); there the socket is closed unanswered with an `at_capacity` event whose reason reads `max_handshakes_per_host`. A socket leaves the count when its handshake ends, so it caps how many requests one address can **start** at once, not how many it holds once their handshakes are done. **Ships on**; `None`/`0` = off. Why, what it does not bound, and the L4 load-balancer case: [DEPLOYMENT.md](DEPLOYMENT.md#per-address-listener-caps-behind-the-vip). | | `max_body_bytes` | `16 MiB` | the MLLP frame cap's HTTP twin — an over-declared `Content-Length` is refused `413` **before a body byte is read** (OOM guard). `None`/`0` = no per-body cap, and the connection logs a `WARNING` naming the setting each time it is built (BACKLOG #2749); `max_inflight_body_bytes` still bounds a body while it is on. | -| `max_inflight_body_bytes` | `256 MiB` | cap the body bytes **all** requests on this listener hold at once, while each body is read and until the engine has it (BACKLOG #6978). Without it the bodies in flight were bounded only by `max_connections` times `max_body_bytes`, 4 GiB at the defaults. A body is charged as its bytes arrive, so a peer that declares a body and sends none of it holds nothing. Bytes a connection's stream has buffered but the listener has not yet read are not charged; the stream's own buffer limit bounds them per connection. Once a request has passed intake authentication and `max_body_bytes`, and before any `100 Continue`, a declared body that does not fit what other bodies now hold is refused `503` with `Retry-After: 5`, before a byte of it is read; bytes that would take the listener over the cap as they arrive are refused the same way mid-body. Either writes an `at_capacity` event whose reason reads `max_inflight_body_bytes`. A declared body larger than the whole cap, possible only with `max_body_bytes` off, is refused `413` naming this setting. No message row is recorded for any of these, so the sender re-sends. A sender that is still sending its body may see the connection reset rather than read the answer, as with a `413`. A `max_body_bytes` above this cap is refused, by the `Http()` factory where both are plain numbers and otherwise when the connection is built, which `serve` and `messagefoundry check` both do. `None`/`0` = off, and the connection then logs a `WARNING` naming the setting each time it is built. | +| `max_inflight_body_bytes` | `256 MiB` | cap the body bytes **all** requests on this listener hold at once, while each body is read and until the engine has it (BACKLOG #6978). Without it the bodies in flight were bounded only by `max_connections` times `max_body_bytes`, 4 GiB at the defaults. A body is charged as its bytes arrive, so a peer that declares a body and sends none of it holds nothing. Bytes a connection has received but the listener has not yet read are not charged, and per connection they can reach at least twice the stream's 64 KiB limit plus one transport read (256 KiB on the selector event loop), more under TLS. Once a request has passed intake authentication and `max_body_bytes`, and before any `100 Continue`, a declared body that does not fit what other bodies now hold is refused `503` with `Retry-After: 5`, before a byte of it is read; bytes that would take the listener over the cap as they arrive are refused the same way mid-body. Either writes an `at_capacity` event whose reason reads `max_inflight_body_bytes`. A declared body larger than the whole cap, possible only with `max_body_bytes` off, is refused `413` naming this setting. No message row is recorded for any of these, so the sender re-sends. A sender that is still sending its body may see the connection reset rather than read the answer, as with a `413`. A `max_body_bytes` above this cap is refused, by the `Http()` factory where both are plain numbers and otherwise when the connection is built, which `serve` and `messagefoundry check` both do. `None`/`0` = off, and the connection then logs a `WARNING` naming the setting each time it is built. | | `max_header_bytes` | `64 KiB` | cap the request line + headers (header-flood guard). This one cap can't be switched off: unset or `None` takes the 64 KiB default, and `0` (or `"0"`) is refused at load rather than silently becoming the default (BACKLOG #1872). | | `max_messages_per_second` | **off** | sustained message-rate ceiling for the **whole listener** (ASVS 2.4.1 / 15.2.2, BACKLOG #1114 — the MLLP pacer, ported). Over budget the connector **waits before reading the request**, so the partner is back-pressured and then served in full — **nothing is dropped, refused or answered differently**, and the wait sits outside `receive_timeout` so a paced partner is never handed a `408` for a delay the engine imposed. **Listener-wide, not per-connection**, unlike MLLP/TCP/X12: this connector answers one request per connection, so a per-connection bucket would be charged once and thrown away, bounding nothing. A `GET`/`HEAD` probe waits behind an outstanding debt but **charges nothing**, and neither does a request refused before its body reaches the engine. Only a body the engine reads and records spends budget, including one it then refuses with a `422`, so a peer that submits nothing cannot starve one that does. Unset = no bound, deliberately: a guessed rate throttles real traffic, so the number has to come from your own feed profile. | | `message_burst` | = the rate | tokens the bucket holds, i.e. how large a burst passes unpaced before the sustained rate applies. Only meaningful with `max_messages_per_second` set. Floor of 1 so the listener can always make progress. | From 6fd10ae6043a4f68dc432670633bd94dc8080862 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:20:43 -0600 Subject: [PATCH 25/39] http_listener: refuse intake_auth_health='allow' under mtls_subject (BACKLOG #6979) Adjudicated: the claim holds, as an exemption that exempts nothing. Under mtls_subject the TLS handshake requires the client certificate and _authorize_peer_cert checks its subject at accept, before a request byte is read, so a GET/HEAD probe without a listed certificate was refused whatever intake_auth_health said. Honouring "allow" would need an optional certificate at the handshake for every request, which would weaken client-certificate verification, so it is not done. The combination is now refused instead: by the Http() factory, so check, validate and the connections.toml desugar refuse it, and by HttpSource when built from a Source any other way. Both name the two settings. "allow" under api_key and bearer is unchanged. tests/test_inbound_http_mtls_health.py: the two refusal arms failed on the base; the header-mode arms and the accept-time check pass on both. Verified-by: tests --- messagefoundry/config/wiring.py | 13 ++- messagefoundry/transports/http_listener.py | 9 ++ tests/test_inbound_http_mtls_health.py | 99 ++++++++++++++++++++++ 3 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 tests/test_inbound_http_mtls_health.py diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index 549bd5b3e8..a5657a0fa3 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -4134,7 +4134,9 @@ def _validate_intake_auth(settings: Mapping[str, Any]) -> None: * a credential configured while ``intake_auth="none"`` — nothing would ever check it, and an operator reading that config would reasonably believe the listener was protected; * ``intake_client_subjects`` under ``api_key`` or ``bearer`` — the same reason: only - ``mtls_subject`` reads a client certificate (vault BACKLOG #2287). + ``mtls_subject`` reads a client certificate (vault BACKLOG #2287); + * ``intake_auth_health="allow"`` under ``mtls_subject`` — the certificate is checked before the + method is read, so the exemption would exempt nothing (BACKLOG #6979). The secret itself must be an ``env()`` reference with no default and no cast, mirroring ``File(credential_password=...)`` (ADR 0132): a fallback credential is a silent credential. @@ -4199,6 +4201,15 @@ def _validate_intake_auth(settings: Mapping[str, Any]) -> None: # mtls_subject. The check below reads tls by truthiness, so 0 would be refused as "needs tls=True". refuse_bool_literals({"tls": settings["tls"]}, "Http") + if settings["intake_auth_health"] == "allow": + # BACKLOG #6979: the certificate is required at the handshake and checked at accept, before + # the method is read, so no probe could be exempted; honouring it would mean an optional + # certificate at the handshake for every request, which is not done. + raise WiringError( + "Http intake_auth_health='allow' cannot apply under intake_auth='mtls_subject': the " + "client certificate is checked before the request method is read, so a GET/HEAD probe " + "still needs a listed certificate; remove intake_auth_health" + ) if not settings["tls"] or not settings["tls_ca_file"]: raise WiringError( "Http intake_auth='mtls_subject' needs tls=True and tls_ca_file — without a CA the " diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index f5da0d640a..8a44070566 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -1225,6 +1225,15 @@ def __init__(self, config: Source) -> None: s.get("intake_client_subjects") ) self.intake_auth_health: str = str(s.get("intake_auth_health") or "require") + if self.intake_auth == "mtls_subject" and self.intake_auth_health == "allow": + # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way. + # `_authorize_peer_cert` runs at accept, before the method is read, and the handshake + # requires the certificate first, so no probe could be exempted. + raise ValueError( + "HTTP source intake_auth_health='allow' cannot apply under " + "intake_auth='mtls_subject': the client certificate is checked before the request " + "method is read" + ) #: The reverse proxies whose ``X-Forwarded-For`` the failed-attempt budget may key on, under #: ``api_key`` and ``bearer`` only (BACKLOG #5525). Empty, the default, keys on the socket #: peer, read by :func:`_peer_budget_key`. At least the allowlist, the connection caps and diff --git a/tests/test_inbound_http_mtls_health.py b/tests/test_inbound_http_mtls_health.py new file mode 100644 index 0000000000..aa62020cd9 --- /dev/null +++ b/tests/test_inbound_http_mtls_health.py @@ -0,0 +1,99 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""``intake_auth_health = "allow"`` cannot mean anything under ``mtls_subject`` (BACKLOG #6979). + +Under ``mtls_subject`` the client certificate is required by the TLS handshake and its subject is +checked at accept by ``_authorize_peer_cert``, before a request byte is read, so before the listener +knows a request is a ``GET``/``HEAD`` probe. A probe with no listed certificate was refused like any +other request, and the ``"allow"`` an operator set to let a load balancer's probe through did nothing. +Making it work would mean asking for the certificate optionally at the handshake, which would weaken +client-certificate verification for every request; that is not done. The combination is refused +instead, by the ``Http()`` factory and by the listener when it is built, naming both settings.""" + +from __future__ import annotations + +from typing import Any, Literal + +import pytest + +from messagefoundry.config.models import ConnectorType, Source +from messagefoundry.config.wiring import Http, WiringError, env +from messagefoundry.transports.http_listener import HttpSource + +_SUBJECTS = {"CN=Partner CA": ["CN:partner.example"]} + + +def _mtls(**over: Any) -> dict[str, Any]: + settings: dict[str, Any] = { + "port": 8443, + "tls": True, + "tls_cert_file": "/tmp/server.pem", + "tls_key_file": "/tmp/server.key", + "tls_ca_file": "/tmp/ca.pem", + "intake_auth": "mtls_subject", + "intake_client_subjects": _SUBJECTS, + } + settings.update(over) + return settings + + +def test_the_factory_refuses_allow_under_mtls_subject() -> None: + with pytest.raises(WiringError, match="intake_auth_health.*mtls_subject"): + Http(**_mtls(intake_auth_health="allow")) + Http(**_mtls()) # "require", the default, still builds + Http(**_mtls(intake_auth_health="require")) + + +def test_the_listener_refuses_allow_under_mtls_subject_when_built() -> None: + """A ``Source`` built some way other than the factory is refused too, before any socket.""" + settings = { + "host": "127.0.0.1", + "port": 0, + "intake_auth": "mtls_subject", + "intake_client_subjects": _SUBJECTS, + "intake_auth_health": "allow", + } + with pytest.raises(ValueError, match="intake_auth_health.*mtls_subject"): + HttpSource(Source(type=ConnectorType.HTTP, settings=settings)) + + +@pytest.mark.parametrize("mode", ["api_key", "bearer"]) +def test_allow_still_builds_under_the_header_modes(mode: Literal["api_key", "bearer"]) -> None: + """There the credential is read from a header, after the method is known, so the exemption + is real (ADR 0154 D6).""" + Http( + port=8080, intake_auth=mode, intake_api_key=env("synthetic_key"), intake_auth_health="allow" + ) + HttpSource( + Source( + type=ConnectorType.HTTP, + settings={ + "port": 0, + "intake_auth": mode, + "intake_api_key": "synthetic-key", + "intake_auth_health": "allow", + }, + ) + ) + + +def test_the_certificate_check_runs_before_any_method_is_known() -> None: + """Why ``allow`` cannot be honoured there: the check takes no request at all, so it has no + method to exempt. A writer with no certificate is refused whatever request would follow.""" + source = HttpSource( + Source( + type=ConnectorType.HTTP, + settings={ + "port": 0, + "intake_auth": "mtls_subject", + "intake_client_subjects": _SUBJECTS, + }, + ) + ) + + class _NoCert: + def get_extra_info(self, name: str) -> None: + return None + + refusal = source._authorize_peer_cert(_NoCert(), "127.0.0.1") # type: ignore[arg-type] + assert refusal is not None and refusal.status == 401 From 10b946b6e75c7df65634b2f330e95ee71da6c302 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:21:31 -0600 Subject: [PATCH 26/39] docs: intake_auth_health='allow' is refused under mtls_subject (BACKLOG #6979) The intake_auth_health row of the HTTP listener settings table says the combination is refused at load and at build, and why it cannot be honoured. Proposed PR title: HTTP listener: refuse intake_auth_health='allow' under mtls_subject (BACKLOG #6979) Proposed vault banner: CLOSED -- adjudicated real: under mtls_subject the certificate is required at the handshake and checked at accept, before the method is read, so 'allow' exempted no probe. Not loosened: the combination is now refused by the Http() factory and by HttpSource at build, naming both settings. Tests in tests/test_inbound_http_mtls_health.py; documented in docs/CONNECTIONS.md. Verified-by: none --- docs/CONNECTIONS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index dfb409e903..bc81fc0841 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -919,7 +919,7 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `intake_api_key_next` | — | rotation slot, accepted **alongside** `intake_api_key` so a partner key rotates with no outage: set it, have the partner cut over, promote it, then clear it. Leaving it set keeps a retired credential live. | | `intake_api_key_header` | `"x-api-key"` | which header carries the `api_key` credential. A header **name**, not a secret. | | `intake_client_subjects` | — | `mtls_subject` allow-list, **keyed by the CA that issues each partner's certificate**: a table whose keys are issuing-CA DNs and whose values are lists of **qualified** subject names, `"CN:partner.example"` / `"SAN:DNS:partner.example"`. In TOML, `[inbound.settings.intake_client_subjects]` then `'CN=Acme Partner CA,O=Acme' = ["CN:partner.example"]`; in code, `intake_client_subjects={"CN=Acme Partner CA,O=Acme": ["CN:partner.example"]}`. A subject is admitted only when the CA under its key signed the leaf, found by signature and never by the leaf's issuer field alone, so a certificate with a listed subject is refused `403` when the loaded CA that signed it is not the one the subject is listed under (vault BACKLOG #2287). **Only a CA loaded from `tls_ca_file` counts**: a leaf signed by an intermediate the client sends is refused unless that intermediate is itself loaded in `tls_ca_file`. To admit one, load the intermediate beside the root that signed it (the listener does not accept a partial chain) and key its subjects by the intermediate's DN. Write the key as `cryptography`'s `Name.rfc4514_string()` renders the CA's subject, single-quoted in TOML; a key that does not round-trip to itself is refused naming the form to write, and the old flat list is refused at load. At start the listener warns about a key naming no loaded certificate the map can name, or naming two with one subject and different keys (as during a key rollover); no certificate is admitted under such a key until one of the two leaves `tls_ca_file`. The start can also warn about, or refuse, the `tls_ca_file` itself: which loaded certificates the map can name, and the start checks and warnings, are stated once, in the HTTP intake row of [SECURITY.md](SECURITY.md#table-b--data-plane-ingest-listeners). Only `mtls_subject` reads the table, so setting it under any other `intake_auth` is refused. Qualifying the namespace is what stops a spoofed commonName colliding with a pinned SAN; a bare `partner.example` is refused at the factory rather than silently matching nothing. [ADR 0154](adr/0154-synchronous-captured-downstream-reply-and-intake-authentication-for-the-inbound-http-listener-adr-0023-deferred-tail.md), amendment 2026-10-30, has the reasoning. | -| `intake_auth_health` | `"require"` | whether `GET`/`HEAD` health probes must authenticate too. **`"allow"` is a real exemption**: it hands anyone who can reach the socket an unauthenticated "is MessageFoundry up, and where" oracle. Set it only when a load-balancer check cannot carry the credential. It applies under `api_key` and `bearer` only: under `mtls_subject` the certificate is checked at accept, before the method is read, so a probe still needs a listed certificate. | +| `intake_auth_health` | `"require"` | whether `GET`/`HEAD` health probes must authenticate too. **`"allow"` is a real exemption**: it hands anyone who can reach the socket an unauthenticated "is MessageFoundry up, and where" oracle. Set it only when a load-balancer check cannot carry the credential. It applies under `api_key` and `bearer` only. Under `mtls_subject` the certificate is required at the TLS handshake and checked at accept, before the method is read, so a probe still needs a listed certificate, and `"allow"` there is refused when the configuration loads and when the connection is built, rather than accepted and ignored (BACKLOG #6979). | | `intake_auth_rate_limit` | `10` | **failed** intake-auth attempts per minute per peer, then `429` + `Retry-After`. A *successful* authentication never consumes budget, so this bounds guessing without capping throughput. `None`/`0` disables; text never does, except plain-digit text that spells zero, such as an `env()` that resolves to `"0"`. A negative value, a bool, a fraction, a zero that is not the integer `0` (such as `0.0`) or text other than plain ASCII digits, here or in `intake_auth_rate_limit_global`, is refused at load, at least `""`, whitespace, `"0.0"`, `" 0 "`, `"+5"` and `"1_000"`; without `trusted_proxies`, whose row is stricter, a whole number written in a code-first `Http(...)` as plain digit text or a float, such as `"10"` or `10.0`, loads as that count, and so does such an `env()` `default=` there (in `connections.toml` a value or `env()` `default=` must be an integer). An `env()` budget is checked on its `default=` at load, by the same rule, where a `default=` of `None` or `""` is refused, and on its resolved value by the same rule at least at start and by `messagefoundry check`, rather than run with a budget that refuses every request or is off when nobody wrote `None` or `0`. An `env()` budget that resolves to no value, such as a set but empty variable, is refused there too; one that resolves to `0` still disables it (BACKLOG #5677). | | `intake_auth_rate_limit_global` | `60` | **failed** attempts per minute across all peers. Consulted only for peers with no successful authentication in the window, so one attacker cannot `429` an authenticated partner whose key it does not share (an IPv6 peer keys on its `/64`; the `trusted_proxies` row says how keys are read). `None`/`0` disables. | | `trusted_proxies` | `[]` | the HTTP reverse proxies in front of this listener that append the client's address to `X-Forwarded-For`, as addresses or CIDR networks (BACKLOG #5525). **What the failed-attempt budget keys on.** With the list empty, the per-peer budget above keys on the **socket peer**. Behind a proxy every partner then shares the proxy's address, and ten failed requests from one client would `429` every partner behind it. When the socket peer is listed, the budget keys on the client address in `X-Forwarded-For` instead, read the way uvicorn reads it: the hops are read right to left, a listed hop is skipped, and the first unlisted one is the client. A port on an IPv4 hop or on a bracketed IPv6 hop (`[2001:db8::7]:443`) is ignored, and so is an IPv6 zone. A bare IPv6 hop that also reads as an address and a port, such as `2001:db8::1:1234`, is ambiguous: the request is checked against the budget of each reading and a failure is charged to each, and to the global budget once, so a client cannot leave its own budget by making its hop ambiguous, and the audit row and the event record the whole-address reading, or the other where that one is dropped as below. A bare IPv6 hop with one group too many to be an address, such as a full eight-group address followed by a port, is read as that address alone. One exception: a reading no client can hold, one in the unassigned part of `::/8` or one carrying an IPv4 address in `0.0.0.0/8`, multicast or the reserved class E block, is dropped where the other reading is one a client can hold and both share a `/64`. A real address is never such a reading, so the client's own reading is still charged; the drop stops the misreading of a NAT64 hop such as `64:ff9b::c000:221`, which is `64:ff9b::c000` and carries `0.0.192.0`, from keying one budget that unrelated NAT64 clients share. A misreading under NAT64's local-use prefix cannot be told from a client's address, and is still keyed. An IPv4-mapped hop keys the same budget as its IPv4 address. **An IPv6 client keys on its `/64`**, not its whole address: a host is usually handed a whole `/64` and may use any address in it, so keying on the address would let it mint a budget per address. A client delegated a shorter prefix, such as a `/56` or a `/48`, still holds one budget per `/64` it uses; the global budget bounds it across them. An address in a prefix that carries an IPv4 client, at least NAT64's `64:ff9b::/96` and `64:ff9b:1::/48`, Teredo's `2001::/32`, 6to4's `2002::/16` and the IPv4-compatible `::/96`, does not key on its `/64`, since one `/64` there may hold unrelated clients, or one IPv4 holder many `/64` networks: under `64:ff9b::/96`, Teredo and 6to4 it keys as the IPv4 client it carries, the budget that client holds over IPv4, and under `64:ff9b:1::/48` and `::/96` on the whole address. The socket peer is read the same way, mapped and zoned spellings included, and keys on its `/64` too, so a host keys the same budget whether or not a proxy is listed. **That `/64` key has a known availability cost**, on the socket peer under every `intake_auth`, `mtls_subject` included, and on a forwarded client: a network-specific NAT64 or SIIT prefix, such as `2001:db8:64::/96`, is not recognised as carrying an IPv4 client, so every client behind that gateway keys on its one `/64` and shares one budget, and so do link-local peers, which share `fe80::/64`. The audit row and the event record the full address. Hops left of the client are the client's own text and are never read, so the left-most value is never taken and a client rotating it cannot mint a fresh budget. A peer that is not listed has its `X-Forwarded-For` ignored. A listed peer keys on the socket peer when its header is missing, when the walk meets a hop that is not an address (such as `unknown`) before it meets an unlisted one, when every hop is listed, or when it has read 32 hops without meeting an unlisted one. An ambiguous hop counts as listed only when every reading left after that drop is listed and the whole-address reading is among them; otherwise it is the client and keyed as above. So a listed inner proxy whose address the proxy in front of it writes as an ambiguous bare IPv6 hop is not skipped where its other reading is one a client could hold, nor where the proxy writes it with a port and the whole-address reading is the one dropped, and every client behind it shares its budget; have that proxy write IPv6 hops bracketed. Skipping such a hop when only one reading is listed would let a client steer that reading onto a listed range and be skipped, and the walk would then key on the client's own text. The exemption from the global budget follows the same key, so behind a listed proxy each client is exempt only by a recent success under its own key, as a directly connected partner is. For IPv6 that key is the `/64`, so hosts that share a `/64` share one budget and one exemption, and one of them can spend the budget of the rest. A request a listed proxy keys on a partner's address that authenticated recently is therefore held to the per-peer budget alone, and spends that partner's budget. Setting the list with either budget off, or set to anything but an integer of at least 1 (a fraction such as `0.5`, a float such as `10.0` and an `env()` budget are all refused), is refused at load: with `intake_auth_rate_limit_global` off nothing bounds guessing across the clients behind the proxy, and with `intake_auth_rate_limit` off nothing bounds guessing keyed on a recently authenticated address. It applies under `intake_auth = "api_key"` or `"bearer"` only, and setting it under any other mode is refused at load. **It does not apply to `mtls_subject`**, which checks the certificate at accept, before any header is read; only the PROXY protocol could carry the client address there, and that is not built. At least `source_ip_allowlist`, `max_connections_per_host` and `max_handshakes_per_host` still see the socket peer. The audit row and the connection event of an intake refusal keep the socket peer as their peer, and add the client as `; forwarded_for=
` after the audit detail and the event reason. Each entry is read by the rules `[api].trusted_proxies` follows, so `'*'`, a zoned IPv6 entry, a CIDR with host bits set, and a name are refused, and so are entries that together span a whole address family, such as `0.0.0.0/0` or its two `/1` halves. **So are entries that together span more than a `/16` of IPv4 or a `/48` of IPv6**: 65,536 budget keys, counted as addresses for IPv4 and as `/64` networks for IPv6, the unit an IPv6 key is. Every host inside a listed range may write any `X-Forwarded-For` it likes, so the size of the list bounds the address space trusted that way, though one IPv6 `/64` may hold many hosts. A range in one of the IPv4-carrying prefixes above counts its addresses, or inside 6to4 its `/48` networks, one IPv4 holder each, not its `/64` networks. A near-whole range such as `2000::/3`, or `/1` to `/3` pieces that leave one gap, is the refused `'*'` in all but name. A `/16` is room for a balancer subnet or a cluster's pod range; list the proxies themselves where you can. At least a refusal of one entry names that entry by its index, and none quotes a value. A range that loads makes the listener log a `WARNING` counting the ranges each time it is built. Any non-empty list is also named in the `listener_trusted_proxies` entry of `GET /security/posture`, which the start's audit row and the `posture_loosened` alert read, and in the advisory `listener-trusted-proxies` line of `messagefoundry check`. The list may be a whole-setting `env()`. Its `default=` is read by these rules at load, as a literal is; a value from the environment is read once resolved, by the build `messagefoundry check` runs and at serve. A `MEFOR_VALUE_*` variable is always text and is refused with its own message: write the list in `environments/.toml`. The list is the connection's own: `[api].trusted_proxies` is not read. **List only a proxy that appends the client's address to `X-Forwarded-For`, or replaces the header with it.** **Never list an L4 or SNAT load balancer.** It writes no such header and passes on whatever the client sent, so with it listed every client chooses its own budget key by writing its own `X-Forwarded-For`, a partner's address included, and a client that writes none shares the balancer's address with every other client. A listed proxy that passes the header on unchanged lets every client behind it choose its budget key, including a partner's address, so a client could spend that partner's budget and lock it out. Every host inside a listed network is trusted as a proxy. | From 8aaad04e880a03af5237027ebd85feca3c1866f9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:34:19 -0600 Subject: [PATCH 27/39] http_listener: refuse allow under mtls_subject before the TLS build (BACKLOG #6979) Review round 1 repair. The listener's refusal now runs before the TLS context is built, so a certificate or anchor fault cannot report or log first, and it names the connection and the remedy. Its comment no longer rests on a handshake a Source built without TLS does not have. The Http() docstring and parameter help say the setting is refused under mtls_subject. The ordering test is renamed for what it pins: the check's inputs, not its call site. Verified-by: tests --- messagefoundry/config/wiring.py | 6 +++-- messagefoundry/transports/http_listener.py | 18 +++++++-------- tests/test_inbound_http_mtls_health.py | 27 +++++++++++----------- 3 files changed, 27 insertions(+), 24 deletions(-) diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index a5657a0fa3..0b0401fcf5 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -3692,7 +3692,7 @@ def Http( | None = None, # mtls_subject allow-list: issuing CA's DN -> QUALIFIED "CN:" / "SAN:DNS:" intake_auth_health: Literal[ "require", "allow" - ] = "require", # whether GET/HEAD probes need the credential too + ] = "require", # whether GET/HEAD probes need the credential too (refused under mtls_subject) intake_auth_rate_limit: int | None = INTAKE_AUTH_RATE_LIMIT_DEFAULT, # FAILED intake-auth attempts per minute per peer (0/None disables) intake_auth_rate_limit_global: int @@ -3787,7 +3787,9 @@ def Http( Health probes are **inside** the gate by default; ``intake_auth_health="allow"`` exempts ``GET``/ ``HEAD`` for a load-balancer check, at the cost of an unauthenticated "is MessageFoundry up, and - where" oracle on a PHI intake socket. + where" oracle on a PHI intake socket. Under ``api_key`` and ``bearer`` only: under + ``mtls_subject`` it is refused, since the certificate is checked before the method is read + (BACKLOG #6979). ``trusted_proxies`` (BACKLOG #5525) names the HTTP reverse proxies in front of the listener that append the client's address to ``X-Forwarded-For``, under ``api_key`` and ``bearer`` diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 8a44070566..969e63a8df 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -1106,6 +1106,15 @@ def __init__(self, config: Source) -> None: self.port: int = port_setting(s["port"], transport="HTTP source") #: How this source names itself in a log line. self._log_name: str = config.name or f"{self.host}:{self.port}" + if s.get("intake_auth") == "mtls_subject" and s.get("intake_auth_health") == "allow": + # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way, and + # before the TLS build below can log or refuse first. `_authorize_peer_cert` runs at + # accept, before the request method is read, so no probe could be exempted. + raise ValueError( + f"HTTP source {self._log_name}: intake_auth_health='allow' cannot apply under " + "intake_auth='mtls_subject', because the client certificate is checked before the " + "request method is read; remove intake_auth_health" + ) # Caps below: key absent → secure default; None/0 in any spelling (including the string "0" # an uncast env() yields) → disabled where allowed; a negative or NaN → refused at build # (BACKLOG #1872). @@ -1225,15 +1234,6 @@ def __init__(self, config: Source) -> None: s.get("intake_client_subjects") ) self.intake_auth_health: str = str(s.get("intake_auth_health") or "require") - if self.intake_auth == "mtls_subject" and self.intake_auth_health == "allow": - # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way. - # `_authorize_peer_cert` runs at accept, before the method is read, and the handshake - # requires the certificate first, so no probe could be exempted. - raise ValueError( - "HTTP source intake_auth_health='allow' cannot apply under " - "intake_auth='mtls_subject': the client certificate is checked before the request " - "method is read" - ) #: The reverse proxies whose ``X-Forwarded-For`` the failed-attempt budget may key on, under #: ``api_key`` and ``bearer`` only (BACKLOG #5525). Empty, the default, keys on the socket #: peer, read by :func:`_peer_budget_key`. At least the allowlist, the connection caps and diff --git a/tests/test_inbound_http_mtls_health.py b/tests/test_inbound_http_mtls_health.py index aa62020cd9..3af4327a51 100644 --- a/tests/test_inbound_http_mtls_health.py +++ b/tests/test_inbound_http_mtls_health.py @@ -45,16 +45,15 @@ def test_the_factory_refuses_allow_under_mtls_subject() -> None: def test_the_listener_refuses_allow_under_mtls_subject_when_built() -> None: - """A ``Source`` built some way other than the factory is refused too, before any socket.""" - settings = { - "host": "127.0.0.1", - "port": 0, - "intake_auth": "mtls_subject", - "intake_client_subjects": _SUBJECTS, - "intake_auth_health": "allow", - } - with pytest.raises(ValueError, match="intake_auth_health.*mtls_subject"): - HttpSource(Source(type=ConnectorType.HTTP, settings=settings)) + """A ``Source`` built some way other than the factory is refused too, before any socket and + before the TLS build, so a certificate path that does not exist is not what it reports. The + refusal names the connection and the remedy.""" + settings = {**_mtls(intake_auth_health="allow"), "host": "127.0.0.1", "port": 0} + settings["tls_cert_file"] = "/nonexistent/synthetic.pem" + with pytest.raises(ValueError, match="intake_auth_health.*mtls_subject") as caught: + HttpSource(Source(type=ConnectorType.HTTP, name="IB_MTLS", settings=settings)) + assert "IB_MTLS" in str(caught.value) + assert "remove intake_auth_health" in str(caught.value) @pytest.mark.parametrize("mode", ["api_key", "bearer"]) @@ -77,9 +76,11 @@ def test_allow_still_builds_under_the_header_modes(mode: Literal["api_key", "bea ) -def test_the_certificate_check_runs_before_any_method_is_known() -> None: - """Why ``allow`` cannot be honoured there: the check takes no request at all, so it has no - method to exempt. A writer with no certificate is refused whatever request would follow.""" +def test_the_certificate_check_takes_no_request_to_exempt() -> None: + """Why ``allow`` cannot be honoured there: ``_authorize_peer_cert`` takes the connection and + no request, so it has no method to exempt, and a connection with no certificate is refused. + This pins the check's inputs, not where ``_on_client`` calls it; that ordering is read from + the code, which calls it before ``_serve_one`` reads the head.""" source = HttpSource( Source( type=ConnectorType.HTTP, From f11f15325865f973af349c0fee417c8123b645b0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:37:26 -0600 Subject: [PATCH 28/39] docs: a probe certificate under mtls_subject may submit messages (BACKLOG #6979) Review round 1 repair, doc limb. The intake_auth_health row no longer says the combination was "accepted and ignored" as if that were the alternative still possible, and it states the cost an operator takes on instead: a certificate listed so a probe passes is admitted for every method. The doc-sweep test now pins that the row says the combination is refused. Proposed PR title: HTTP listener: refuse intake_auth_health='allow' under mtls_subject (BACKLOG #6979) Proposed vault banner: CLOSED -- adjudicated real: under mtls_subject the certificate is required at the handshake and checked at accept, before the method is read, so 'allow' exempted no probe. Not loosened: the combination is now refused by the Http() factory and by HttpSource at build, before the TLS build, naming both settings and the remedy. Tests in tests/test_inbound_http_mtls_health.py; documented in docs/CONNECTIONS.md. Verified-by: tests --- docs/CONNECTIONS.md | 2 +- tests/test_security_doc_rate_limits.py | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index bc81fc0841..d55d6341d7 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -919,7 +919,7 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `intake_api_key_next` | — | rotation slot, accepted **alongside** `intake_api_key` so a partner key rotates with no outage: set it, have the partner cut over, promote it, then clear it. Leaving it set keeps a retired credential live. | | `intake_api_key_header` | `"x-api-key"` | which header carries the `api_key` credential. A header **name**, not a secret. | | `intake_client_subjects` | — | `mtls_subject` allow-list, **keyed by the CA that issues each partner's certificate**: a table whose keys are issuing-CA DNs and whose values are lists of **qualified** subject names, `"CN:partner.example"` / `"SAN:DNS:partner.example"`. In TOML, `[inbound.settings.intake_client_subjects]` then `'CN=Acme Partner CA,O=Acme' = ["CN:partner.example"]`; in code, `intake_client_subjects={"CN=Acme Partner CA,O=Acme": ["CN:partner.example"]}`. A subject is admitted only when the CA under its key signed the leaf, found by signature and never by the leaf's issuer field alone, so a certificate with a listed subject is refused `403` when the loaded CA that signed it is not the one the subject is listed under (vault BACKLOG #2287). **Only a CA loaded from `tls_ca_file` counts**: a leaf signed by an intermediate the client sends is refused unless that intermediate is itself loaded in `tls_ca_file`. To admit one, load the intermediate beside the root that signed it (the listener does not accept a partial chain) and key its subjects by the intermediate's DN. Write the key as `cryptography`'s `Name.rfc4514_string()` renders the CA's subject, single-quoted in TOML; a key that does not round-trip to itself is refused naming the form to write, and the old flat list is refused at load. At start the listener warns about a key naming no loaded certificate the map can name, or naming two with one subject and different keys (as during a key rollover); no certificate is admitted under such a key until one of the two leaves `tls_ca_file`. The start can also warn about, or refuse, the `tls_ca_file` itself: which loaded certificates the map can name, and the start checks and warnings, are stated once, in the HTTP intake row of [SECURITY.md](SECURITY.md#table-b--data-plane-ingest-listeners). Only `mtls_subject` reads the table, so setting it under any other `intake_auth` is refused. Qualifying the namespace is what stops a spoofed commonName colliding with a pinned SAN; a bare `partner.example` is refused at the factory rather than silently matching nothing. [ADR 0154](adr/0154-synchronous-captured-downstream-reply-and-intake-authentication-for-the-inbound-http-listener-adr-0023-deferred-tail.md), amendment 2026-10-30, has the reasoning. | -| `intake_auth_health` | `"require"` | whether `GET`/`HEAD` health probes must authenticate too. **`"allow"` is a real exemption**: it hands anyone who can reach the socket an unauthenticated "is MessageFoundry up, and where" oracle. Set it only when a load-balancer check cannot carry the credential. It applies under `api_key` and `bearer` only. Under `mtls_subject` the certificate is required at the TLS handshake and checked at accept, before the method is read, so a probe still needs a listed certificate, and `"allow"` there is refused when the configuration loads and when the connection is built, rather than accepted and ignored (BACKLOG #6979). | +| `intake_auth_health` | `"require"` | whether `GET`/`HEAD` health probes must authenticate too. **`"allow"` is a real exemption**: it hands anyone who can reach the socket an unauthenticated "is MessageFoundry up, and where" oracle. Set it only when a load-balancer check cannot carry the credential. It applies under `api_key` and `bearer` only. Under `mtls_subject` the certificate is required at the TLS handshake and checked at accept, before the method is read, so `"allow"` there is refused when the configuration loads and when the connection is built (BACKLOG #6979). A probe then needs a listed certificate, and **a certificate listed for a probe may submit messages too**, since a listed subject is admitted for every method. | | `intake_auth_rate_limit` | `10` | **failed** intake-auth attempts per minute per peer, then `429` + `Retry-After`. A *successful* authentication never consumes budget, so this bounds guessing without capping throughput. `None`/`0` disables; text never does, except plain-digit text that spells zero, such as an `env()` that resolves to `"0"`. A negative value, a bool, a fraction, a zero that is not the integer `0` (such as `0.0`) or text other than plain ASCII digits, here or in `intake_auth_rate_limit_global`, is refused at load, at least `""`, whitespace, `"0.0"`, `" 0 "`, `"+5"` and `"1_000"`; without `trusted_proxies`, whose row is stricter, a whole number written in a code-first `Http(...)` as plain digit text or a float, such as `"10"` or `10.0`, loads as that count, and so does such an `env()` `default=` there (in `connections.toml` a value or `env()` `default=` must be an integer). An `env()` budget is checked on its `default=` at load, by the same rule, where a `default=` of `None` or `""` is refused, and on its resolved value by the same rule at least at start and by `messagefoundry check`, rather than run with a budget that refuses every request or is off when nobody wrote `None` or `0`. An `env()` budget that resolves to no value, such as a set but empty variable, is refused there too; one that resolves to `0` still disables it (BACKLOG #5677). | | `intake_auth_rate_limit_global` | `60` | **failed** attempts per minute across all peers. Consulted only for peers with no successful authentication in the window, so one attacker cannot `429` an authenticated partner whose key it does not share (an IPv6 peer keys on its `/64`; the `trusted_proxies` row says how keys are read). `None`/`0` disables. | | `trusted_proxies` | `[]` | the HTTP reverse proxies in front of this listener that append the client's address to `X-Forwarded-For`, as addresses or CIDR networks (BACKLOG #5525). **What the failed-attempt budget keys on.** With the list empty, the per-peer budget above keys on the **socket peer**. Behind a proxy every partner then shares the proxy's address, and ten failed requests from one client would `429` every partner behind it. When the socket peer is listed, the budget keys on the client address in `X-Forwarded-For` instead, read the way uvicorn reads it: the hops are read right to left, a listed hop is skipped, and the first unlisted one is the client. A port on an IPv4 hop or on a bracketed IPv6 hop (`[2001:db8::7]:443`) is ignored, and so is an IPv6 zone. A bare IPv6 hop that also reads as an address and a port, such as `2001:db8::1:1234`, is ambiguous: the request is checked against the budget of each reading and a failure is charged to each, and to the global budget once, so a client cannot leave its own budget by making its hop ambiguous, and the audit row and the event record the whole-address reading, or the other where that one is dropped as below. A bare IPv6 hop with one group too many to be an address, such as a full eight-group address followed by a port, is read as that address alone. One exception: a reading no client can hold, one in the unassigned part of `::/8` or one carrying an IPv4 address in `0.0.0.0/8`, multicast or the reserved class E block, is dropped where the other reading is one a client can hold and both share a `/64`. A real address is never such a reading, so the client's own reading is still charged; the drop stops the misreading of a NAT64 hop such as `64:ff9b::c000:221`, which is `64:ff9b::c000` and carries `0.0.192.0`, from keying one budget that unrelated NAT64 clients share. A misreading under NAT64's local-use prefix cannot be told from a client's address, and is still keyed. An IPv4-mapped hop keys the same budget as its IPv4 address. **An IPv6 client keys on its `/64`**, not its whole address: a host is usually handed a whole `/64` and may use any address in it, so keying on the address would let it mint a budget per address. A client delegated a shorter prefix, such as a `/56` or a `/48`, still holds one budget per `/64` it uses; the global budget bounds it across them. An address in a prefix that carries an IPv4 client, at least NAT64's `64:ff9b::/96` and `64:ff9b:1::/48`, Teredo's `2001::/32`, 6to4's `2002::/16` and the IPv4-compatible `::/96`, does not key on its `/64`, since one `/64` there may hold unrelated clients, or one IPv4 holder many `/64` networks: under `64:ff9b::/96`, Teredo and 6to4 it keys as the IPv4 client it carries, the budget that client holds over IPv4, and under `64:ff9b:1::/48` and `::/96` on the whole address. The socket peer is read the same way, mapped and zoned spellings included, and keys on its `/64` too, so a host keys the same budget whether or not a proxy is listed. **That `/64` key has a known availability cost**, on the socket peer under every `intake_auth`, `mtls_subject` included, and on a forwarded client: a network-specific NAT64 or SIIT prefix, such as `2001:db8:64::/96`, is not recognised as carrying an IPv4 client, so every client behind that gateway keys on its one `/64` and shares one budget, and so do link-local peers, which share `fe80::/64`. The audit row and the event record the full address. Hops left of the client are the client's own text and are never read, so the left-most value is never taken and a client rotating it cannot mint a fresh budget. A peer that is not listed has its `X-Forwarded-For` ignored. A listed peer keys on the socket peer when its header is missing, when the walk meets a hop that is not an address (such as `unknown`) before it meets an unlisted one, when every hop is listed, or when it has read 32 hops without meeting an unlisted one. An ambiguous hop counts as listed only when every reading left after that drop is listed and the whole-address reading is among them; otherwise it is the client and keyed as above. So a listed inner proxy whose address the proxy in front of it writes as an ambiguous bare IPv6 hop is not skipped where its other reading is one a client could hold, nor where the proxy writes it with a port and the whole-address reading is the one dropped, and every client behind it shares its budget; have that proxy write IPv6 hops bracketed. Skipping such a hop when only one reading is listed would let a client steer that reading onto a listed range and be skipped, and the walk would then key on the client's own text. The exemption from the global budget follows the same key, so behind a listed proxy each client is exempt only by a recent success under its own key, as a directly connected partner is. For IPv6 that key is the `/64`, so hosts that share a `/64` share one budget and one exemption, and one of them can spend the budget of the rest. A request a listed proxy keys on a partner's address that authenticated recently is therefore held to the per-peer budget alone, and spends that partner's budget. Setting the list with either budget off, or set to anything but an integer of at least 1 (a fraction such as `0.5`, a float such as `10.0` and an `env()` budget are all refused), is refused at load: with `intake_auth_rate_limit_global` off nothing bounds guessing across the clients behind the proxy, and with `intake_auth_rate_limit` off nothing bounds guessing keyed on a recently authenticated address. It applies under `intake_auth = "api_key"` or `"bearer"` only, and setting it under any other mode is refused at load. **It does not apply to `mtls_subject`**, which checks the certificate at accept, before any header is read; only the PROXY protocol could carry the client address there, and that is not built. At least `source_ip_allowlist`, `max_connections_per_host` and `max_handshakes_per_host` still see the socket peer. The audit row and the connection event of an intake refusal keep the socket peer as their peer, and add the client as `; forwarded_for=
` after the audit detail and the event reason. Each entry is read by the rules `[api].trusted_proxies` follows, so `'*'`, a zoned IPv6 entry, a CIDR with host bits set, and a name are refused, and so are entries that together span a whole address family, such as `0.0.0.0/0` or its two `/1` halves. **So are entries that together span more than a `/16` of IPv4 or a `/48` of IPv6**: 65,536 budget keys, counted as addresses for IPv4 and as `/64` networks for IPv6, the unit an IPv6 key is. Every host inside a listed range may write any `X-Forwarded-For` it likes, so the size of the list bounds the address space trusted that way, though one IPv6 `/64` may hold many hosts. A range in one of the IPv4-carrying prefixes above counts its addresses, or inside 6to4 its `/48` networks, one IPv4 holder each, not its `/64` networks. A near-whole range such as `2000::/3`, or `/1` to `/3` pieces that leave one gap, is the refused `'*'` in all but name. A `/16` is room for a balancer subnet or a cluster's pod range; list the proxies themselves where you can. At least a refusal of one entry names that entry by its index, and none quotes a value. A range that loads makes the listener log a `WARNING` counting the ranges each time it is built. Any non-empty list is also named in the `listener_trusted_proxies` entry of `GET /security/posture`, which the start's audit row and the `posture_loosened` alert read, and in the advisory `listener-trusted-proxies` line of `messagefoundry check`. The list may be a whole-setting `env()`. Its `default=` is read by these rules at load, as a literal is; a value from the environment is read once resolved, by the build `messagefoundry check` runs and at serve. A `MEFOR_VALUE_*` variable is always text and is refused with its own message: write the list in `environments/.toml`. The list is the connection's own: `[api].trusted_proxies` is not read. **List only a proxy that appends the client's address to `X-Forwarded-For`, or replaces the header with it.** **Never list an L4 or SNAT load balancer.** It writes no such header and passes on whatever the client sent, so with it listed every client chooses its own budget key by writing its own `X-Forwarded-For`, a partner's address included, and a client that writes none shares the balancer's address with every other client. A listed proxy that passes the header on unchanged lets every client behind it choose its budget key, including a partner's address, so a client could spend that partner's budget and lock it out. Every host inside a listed network is trusted as a proxy. | diff --git a/tests/test_security_doc_rate_limits.py b/tests/test_security_doc_rate_limits.py index 31a1fedf5d..09e2d39405 100644 --- a/tests/test_security_doc_rate_limits.py +++ b/tests/test_security_doc_rate_limits.py @@ -645,6 +645,11 @@ def _ninth_sweep_problems(config_text: str, connections_text: str) -> list[str]: "CONNECTIONS.md intake_auth_health does not say `allow` exempts nothing under " "mtls_subject, where the certificate is checked at accept" ) + if "is refused when the configuration loads and when the connection is built" not in health: + problems.append( + "CONNECTIONS.md intake_auth_health does not say `allow` is refused under mtls_subject " + "(BACKLOG #6979)" + ) return problems From 57e7332ffc74b3b1c5d036aec76f91b329cfddbe Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:50:50 -0600 Subject: [PATCH 29/39] wiring: refuse mtls_subject 'allow' after the TLS and subject checks (BACKLOG #6979) Review round 2 repair. The factory's intake_auth_health='allow' refusal now runs after the tls, tls_ca_file and subject checks, so a configuration missing those hears the more basic fault first, and the refusal's stated reason, a certificate checked at accept, is always true when it fires. The parameter help names the value refused, not the whole setting. The premise test now pins _authorize_peer_cert's parameters and that _on_client calls it before _serve_one, so the refusal's premise has a control. Verified-by: tests --- messagefoundry/config/wiring.py | 22 ++++++++++++---------- tests/test_inbound_http_mtls_health.py | 19 +++++++++++++++---- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index 0b0401fcf5..8eb6d63fba 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -3692,7 +3692,7 @@ def Http( | None = None, # mtls_subject allow-list: issuing CA's DN -> QUALIFIED "CN:" / "SAN:DNS:" intake_auth_health: Literal[ "require", "allow" - ] = "require", # whether GET/HEAD probes need the credential too (refused under mtls_subject) + ] = "require", # whether GET/HEAD probes need the credential too ('allow' refused under mtls_subject) intake_auth_rate_limit: int | None = INTAKE_AUTH_RATE_LIMIT_DEFAULT, # FAILED intake-auth attempts per minute per peer (0/None disables) intake_auth_rate_limit_global: int @@ -4203,15 +4203,6 @@ def _validate_intake_auth(settings: Mapping[str, Any]) -> None: # mtls_subject. The check below reads tls by truthiness, so 0 would be refused as "needs tls=True". refuse_bool_literals({"tls": settings["tls"]}, "Http") - if settings["intake_auth_health"] == "allow": - # BACKLOG #6979: the certificate is required at the handshake and checked at accept, before - # the method is read, so no probe could be exempted; honouring it would mean an optional - # certificate at the handshake for every request, which is not done. - raise WiringError( - "Http intake_auth_health='allow' cannot apply under intake_auth='mtls_subject': the " - "client certificate is checked before the request method is read, so a GET/HEAD probe " - "still needs a listed certificate; remove intake_auth_health" - ) if not settings["tls"] or not settings["tls_ca_file"]: raise WiringError( "Http intake_auth='mtls_subject' needs tls=True and tls_ca_file — without a CA the " @@ -4236,6 +4227,17 @@ def _validate_intake_auth(settings: Mapping[str, Any]) -> None: "with a pinned SAN; any other name matches nothing and would 403 every request from the " "partner it names" ) + # Last, so a configuration missing TLS or its subjects hears that first, and the reason + # given below, a certificate checked at accept, is then always true. + if settings["intake_auth_health"] == "allow": + # BACKLOG #6979: the certificate is required at the handshake and checked at accept, before + # the method is read, so no probe could be exempted; honouring it would mean an optional + # certificate at the handshake for every request, which is not done. + raise WiringError( + "Http intake_auth_health='allow' cannot apply under intake_auth='mtls_subject': the " + "client certificate is checked before the request method is read, so a GET/HEAD probe " + "still needs a listed certificate; remove intake_auth_health" + ) def _intake_subjects_by_issuer( diff --git a/tests/test_inbound_http_mtls_health.py b/tests/test_inbound_http_mtls_health.py index 3af4327a51..9589d555fa 100644 --- a/tests/test_inbound_http_mtls_health.py +++ b/tests/test_inbound_http_mtls_health.py @@ -12,6 +12,7 @@ from __future__ import annotations +import inspect from typing import Any, Literal import pytest @@ -40,6 +41,10 @@ def _mtls(**over: Any) -> dict[str, Any]: def test_the_factory_refuses_allow_under_mtls_subject() -> None: with pytest.raises(WiringError, match="intake_auth_health.*mtls_subject"): Http(**_mtls(intake_auth_health="allow")) + # A more basic fault is reported first, so the stated reason is never about a handshake the + # configuration does not have. + with pytest.raises(WiringError, match="needs tls=True and tls_ca_file"): + Http(**_mtls(intake_auth_health="allow", tls_ca_file=None)) Http(**_mtls()) # "require", the default, still builds Http(**_mtls(intake_auth_health="require")) @@ -77,10 +82,16 @@ def test_allow_still_builds_under_the_header_modes(mode: Literal["api_key", "bea def test_the_certificate_check_takes_no_request_to_exempt() -> None: - """Why ``allow`` cannot be honoured there: ``_authorize_peer_cert`` takes the connection and - no request, so it has no method to exempt, and a connection with no certificate is refused. - This pins the check's inputs, not where ``_on_client`` calls it; that ordering is read from - the code, which calls it before ``_serve_one`` reads the head.""" + """Why ``allow`` cannot be honoured there, pinned so the refusal's premise has a control: + ``_authorize_peer_cert`` takes the connection and the peer and no request, so it has no method + to exempt; ``_on_client`` calls it before ``_serve_one`` reads the head; and a connection with + no certificate is refused. If a change gives the check a request, or moves it after the head + is read, this fails and the refusal should be revisited rather than kept.""" + params = list(inspect.signature(HttpSource._authorize_peer_cert).parameters) + assert params == ["self", "writer", "peer_host"] + on_client = inspect.getsource(HttpSource._on_client) + assert "self._authorize_peer_cert(" in on_client and "self._serve_one(" in on_client + assert on_client.index("self._authorize_peer_cert(") < on_client.index("self._serve_one(") source = HttpSource( Source( type=ConnectorType.HTTP, From 20c91935279575015975d6c37e81ad46721aec80 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:51:43 -0600 Subject: [PATCH 30/39] docs: changelog fragment for the mtls_subject 'allow' refusal (BACKLOG #6979) Review round 2 repair, doc limb. Adds changelog.d/6979.security.md, since a configuration that loaded before now refuses, and names the remedy. The doc-sweep test's older failure message described wording the row no longer uses; it now says what the pinned phrase says. Proposed PR title: HTTP listener: refuse intake_auth_health='allow' under mtls_subject (BACKLOG #6979) Proposed vault banner: CLOSED -- adjudicated real: under mtls_subject the certificate is required at the handshake and checked at accept, before the method is read, so 'allow' exempted no probe. Not loosened: the combination is now refused by the Http() factory and by HttpSource at build, naming both settings and the remedy. Tests in tests/test_inbound_http_mtls_health.py; documented in docs/CONNECTIONS.md and changelog.d/6979.security.md. Verified-by: tests --- changelog.d/6979.security.md | 7 +++++++ tests/test_security_doc_rate_limits.py | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 changelog.d/6979.security.md diff --git a/changelog.d/6979.security.md b/changelog.d/6979.security.md new file mode 100644 index 0000000000..ce2c3abb92 --- /dev/null +++ b/changelog.d/6979.security.md @@ -0,0 +1,7 @@ +- **The HTTP listener refuses `intake_auth_health = "allow"` under `intake_auth = "mtls_subject"`.** + The client certificate is required at the TLS handshake and checked when the connection is + accepted, before the request method is read, so the setting exempted no probe. A probe still + needs a listed certificate, and that certificate may submit messages too. The combination is now + refused when the configuration loads and when the connection is built, naming both settings; + remove `intake_auth_health` to load. See the `intake_auth_health` row in + [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) diff --git a/tests/test_security_doc_rate_limits.py b/tests/test_security_doc_rate_limits.py index 09e2d39405..8c4d22c88b 100644 --- a/tests/test_security_doc_rate_limits.py +++ b/tests/test_security_doc_rate_limits.py @@ -642,8 +642,8 @@ def _ninth_sweep_problems(config_text: str, connections_text: str) -> list[str]: health = _row(connections_text, "intake_auth_health") if "It applies under `api_key` and `bearer` only" not in health: problems.append( - "CONNECTIONS.md intake_auth_health does not say `allow` exempts nothing under " - "mtls_subject, where the certificate is checked at accept" + "CONNECTIONS.md intake_auth_health does not say the exemption applies under " + "api_key and bearer only" ) if "is refused when the configuration loads and when the connection is built" not in health: problems.append( From 4d3851cf8fd60f24ccd398cb3f21ee1f06d8ecb7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:50:41 -0600 Subject: [PATCH 31/39] http_listener: refuse an intake_auth mode the listener does not know (BACKLOG #6979) HttpSource stored intake_auth unchecked, and every check that reads it treats a mode it does not know as no authentication: _authorize_head returns at once for anything but api_key and bearer, and the certificate check runs only under mtls_subject. A Source built other than through Http(), which refuses such a value, then served every peer unauthenticated on a typo such as "API_KEY" or "mtls". HttpSource.__init__ now refuses any intake_auth outside none, api_key, bearer and mtls_subject, beside the mtls_subject guard and before the TLS build, with the value withheld as the factory withholds it. Unset and empty still read as none, as before. Tests: seven unknown values are refused, and the error names none of them; every known mode, unset and empty included, still builds. The refusal tests fail before this change. Verified-by: tests --- messagefoundry/transports/http_listener.py | 11 +++++++++ tests/test_inbound_http_intake_auth.py | 28 ++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 969e63a8df..b7ded564f2 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -159,6 +159,9 @@ #: The most body bytes one read takes while the budget is charged, so a share grows with the bytes #: actually received rather than with what a peer declared. _BODY_CHUNK_BYTES = 64 * 1024 +#: The intake_auth modes this listener knows, the set the ``Http()`` factory accepts. Any other value +#: is refused when the source is built (BACKLOG #6979). +_INTAKE_AUTH_MODES = ("none", "api_key", "bearer", "mtls_subject") #: The ``Retry-After`` seconds on the ``503`` refusing a body the in-flight budget has no room for. #: The budget frees as soon as the bodies ahead of it are committed, so a short wait is enough. BODY_BUDGET_RETRY_AFTER_SECONDS = 5 @@ -1106,6 +1109,14 @@ def __init__(self, config: Source) -> None: self.port: int = port_setting(s["port"], transport="HTTP source") #: How this source names itself in a log line. self._log_name: str = config.name or f"{self.host}:{self.port}" + if (s.get("intake_auth") or "none") not in _INTAKE_AUTH_MODES: + # As the Http() factory refuses it, for a Source built any other way: every check below + # reads a mode it does not know as no authentication, so a typo would open the intake + # socket to every peer. The value is withheld, as the factory withholds it. + raise ValueError( + f"HTTP source {self._log_name}: intake_auth must be one of " + f"{'/'.join(_INTAKE_AUTH_MODES)} (value withheld)" + ) if s.get("intake_auth") == "mtls_subject" and s.get("intake_auth_health") == "allow": # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way, and # before the TLS build below can log or refuse first. `_authorize_peer_cert` runs at diff --git a/tests/test_inbound_http_intake_auth.py b/tests/test_inbound_http_intake_auth.py index f2bb6897bd..56a643fb6b 100644 --- a/tests/test_inbound_http_intake_auth.py +++ b/tests/test_inbound_http_intake_auth.py @@ -142,6 +142,34 @@ def test_credential_configured_without_a_mode_is_refused() -> None: Http(port=8080, intake_client_subjects={PARTNER_CA: ["CN:partner.example"]}) +@pytest.mark.parametrize( + "mode", ["API_KEY", "apikey", "api-key", "mtls", "basic", " bearer", "a-pasted-credential"] +) +def test_the_listener_refuses_an_intake_auth_mode_it_does_not_know(mode: str) -> None: + """A Source built other than through ``Http()`` skips the factory's mode check, and the listener + read any mode it did not know as no authentication at all: a typo opened the intake socket to + every peer. It refuses instead, as the factory does, with the value withheld.""" + with pytest.raises(ValueError, match="intake_auth must be one of") as refused: + HttpSource( + Source( + type=ConnectorType.HTTP, + name="IB_MODE", + settings={"host": "127.0.0.1", "port": 0, "intake_auth": mode}, + ) + ) + assert repr(mode) not in str(refused.value) + assert "a-pasted-credential" not in str(refused.value) + + +@pytest.mark.parametrize("mode", [None, "", "none", "api_key", "bearer"]) +def test_the_listener_builds_every_intake_auth_mode_it_knows(mode: str | None) -> None: + settings: dict[str, Any] = {"host": "127.0.0.1", "port": 0, "intake_auth": mode} + if mode in ("api_key", "bearer"): + settings["intake_api_key"] = KEY + source = HttpSource(Source(type=ConnectorType.HTTP, name="IB_MODE", settings=settings)) + assert source.intake_auth == (mode or "none") + + def test_settings_are_carried_onto_the_spec() -> None: spec = Http( port=8080, From 3675930a226d20e4e5a20f06568d00c4984fd0dd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:53:00 -0600 Subject: [PATCH 32/39] docs: an unknown intake_auth is refused when the connection is built (BACKLOG #6979) The intake_auth row in docs/CONNECTIONS.md now says any value outside the four modes is refused when the configuration loads and when the connection is built, with the value withheld. The 6979 changelog fragment gains a bullet for the listener-side refusal. Proposed PR title: HTTP listener refuses intake_auth_health='allow' under mtls_subject and an unknown intake_auth (BACKLOG #6979) Proposed vault banner: BUILT on b20054-6979b, stacked on b20054-6978b: intake_auth_health='allow' under mtls_subject is refused by Http() and by HttpSource, and HttpSource refuses an intake_auth mode it does not know. Awaiting PR. Verified-by: tests --- changelog.d/6979.security.md | 5 +++++ docs/CONNECTIONS.md | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/changelog.d/6979.security.md b/changelog.d/6979.security.md index ce2c3abb92..8dcf6788bd 100644 --- a/changelog.d/6979.security.md +++ b/changelog.d/6979.security.md @@ -5,3 +5,8 @@ refused when the configuration loads and when the connection is built, naming both settings; remove `intake_auth_health` to load. See the `intake_auth_health` row in [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) +- **The HTTP listener refuses an `intake_auth` value it does not know when the connection is + built.** `Http()` already refused one, but a source built any other way was served with no + intake authentication at all, so a typo such as `"API_KEY"` would have opened the intake socket + to every peer. Unset and empty still mean `none`. See the `intake_auth` row in + [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index d55d6341d7..3bab183016 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -914,7 +914,7 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `tls_ca_file` | — | trust anchor — opt-in **mTLS** (require + verify a client certificate). | | `tls_ca_pin` | - | the SHA-256 of `tls_ca_file`. Pins the CA's integrity (BACKLOG #1142): a pin that does not match always refuses. Under `[security].enforcement = enforce` the engine also refuses a CA another account can replace, or one whose permissions or path it cannot read; a matching pin lets the second kind load, with a warning and an `auth.trust_anchor` row. Under `enforce`, some Windows spellings refuse even with a matching pin, at least a DOS device name such as `NUL` as a folder; the Windows anchor-check paragraph under [Accepted `odbc_params` keywords](#accepted-odbc_params-keywords) says which (vault BACKLOG #5197). Each check writes its rows under `inbound:`. It pins `tls_ca_file` only. A `tls_crl_file` is read by path with no pin, and a certificate in it that `tls_ca_file` does not already hold refuses the build (BACKLOG #1890). Set without `tls` and `tls_ca_file`, it is refused, since nothing would check it. Set but empty or whitespace, it is refused too; leave it out for no pin. | | `tls_crl_file` | - (off) | opt-in revocation checking for the client certificates `tls_ca_file` verifies. The MLLP `tls_crl_file` row states what an inbound listener does with it. | -| `intake_auth` | `"none"` | **peer credential required to submit a message** ([ADR 0154](adr/0154-synchronous-captured-downstream-reply-and-intake-authentication-for-the-inbound-http-listener-adr-0023-deferred-tail.md) D6): `none` \| `api_key` \| `bearer` \| `mtls_subject`. A sibling of `source_ip_allowlist` — it authorises *submitting*, never *reading*; it mints no identity and opens no session. A missing or wrong credential is refused `401`. A request that sends the credential header twice gets `400` instead, before any comparison; [SECURITY.md](SECURITY.md) Table B has the rule. Under `mtls_subject`, a verified certificate whose subject is not in `intake_client_subjects` is refused `403`, and so is one whose subject is listed only under a CA that did not sign it. Each refusal comes **before any request body byte is read**, so it costs an anonymous peer nothing to be turned away. | +| `intake_auth` | `"none"` | **peer credential required to submit a message** ([ADR 0154](adr/0154-synchronous-captured-downstream-reply-and-intake-authentication-for-the-inbound-http-listener-adr-0023-deferred-tail.md) D6): `none` \| `api_key` \| `bearer` \| `mtls_subject`. Any other value is refused when the configuration loads and when the connection is built, with the value withheld. A sibling of `source_ip_allowlist` — it authorises *submitting*, never *reading*; it mints no identity and opens no session. A missing or wrong credential is refused `401`. A request that sends the credential header twice gets `400` instead, before any comparison; [SECURITY.md](SECURITY.md) Table B has the rule. Under `mtls_subject`, a verified certificate whose subject is not in `intake_client_subjects` is refused `403`, and so is one whose subject is listed only under a CA that did not sign it. Each refusal comes **before any request body byte is read**, so it costs an anonymous peer nothing to be turned away. | | `intake_api_key` | — | the credential for `api_key`/`bearer` — a **secret**, `env()` only (a literal, a `default=` or a `cast=` is refused at the factory). | | `intake_api_key_next` | — | rotation slot, accepted **alongside** `intake_api_key` so a partner key rotates with no outage: set it, have the partner cut over, promote it, then clear it. Leaving it set keeps a retired credential live. | | `intake_api_key_header` | `"x-api-key"` | which header carries the `api_key` credential. A header **name**, not a secret. | From 620581d21c41e51e9e09c98d5cc94b8ac33add6a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:11:45 -0600 Subject: [PATCH 33/39] http_listener: one intake_auth mode set, and a falsy mode refused (BACKLOG #6979) Repair round 1 after the code-review skill at xhigh. The listener's check read (intake_auth or "none"), so False or 0 passed as "none". Only unset and empty read as "none" now, and any other value outside the four modes is refused. The mode set was written out a second time in the listener. wiring.py now names it once, as the public INTAKE_AUTH_MODES derived from _INTAKE_KEY_MODES, and both the Http() factory and HttpSource read it; the listener imports no private config name. The test adds False and 0 to the refused values. Verified-by: tests --- messagefoundry/config/wiring.py | 5 ++++- messagefoundry/transports/http_listener.py | 15 +++++++-------- tests/test_inbound_http_intake_auth.py | 5 +++-- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index 8eb6d63fba..7415ac37a1 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -4117,6 +4117,9 @@ def _validate_sync_reply(settings: Mapping[str, Any]) -> None: #: The intake-auth modes that carry a shared-secret credential (as opposed to a client certificate). _INTAKE_KEY_MODES = ("api_key", "bearer") +#: Every intake-auth mode. Public because the HTTP listener refuses any other value too, for a +#: source built other than through ``Http()`` (BACKLOG #6979). +INTAKE_AUTH_MODES = ("none", *_INTAKE_KEY_MODES, "mtls_subject") def _validate_intake_auth(settings: Mapping[str, Any]) -> None: @@ -4144,7 +4147,7 @@ def _validate_intake_auth(settings: Mapping[str, Any]) -> None: ``File(credential_password=...)`` (ADR 0132): a fallback credential is a silent credential. """ mode = settings["intake_auth"] - if mode not in ("none", *_INTAKE_KEY_MODES, "mtls_subject"): + if mode not in INTAKE_AUTH_MODES: raise WiringError( "Http intake_auth must be one of none/api_key/bearer/mtls_subject (value withheld)" ) diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index b7ded564f2..4a1cccb2aa 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -60,6 +60,7 @@ read_trusted_proxies, ) from messagefoundry.config.models import ConnectorType, Source +from messagefoundry.config.wiring import INTAKE_AUTH_MODES from messagefoundry.credential import ( OTHERNAMES_INTACT_KEY, VERIFIED_ISSUER_KEY, @@ -159,9 +160,6 @@ #: The most body bytes one read takes while the budget is charged, so a share grows with the bytes #: actually received rather than with what a peer declared. _BODY_CHUNK_BYTES = 64 * 1024 -#: The intake_auth modes this listener knows, the set the ``Http()`` factory accepts. Any other value -#: is refused when the source is built (BACKLOG #6979). -_INTAKE_AUTH_MODES = ("none", "api_key", "bearer", "mtls_subject") #: The ``Retry-After`` seconds on the ``503`` refusing a body the in-flight budget has no room for. #: The budget frees as soon as the bodies ahead of it are committed, so a short wait is enough. BODY_BUDGET_RETRY_AFTER_SECONDS = 5 @@ -1109,13 +1107,14 @@ def __init__(self, config: Source) -> None: self.port: int = port_setting(s["port"], transport="HTTP source") #: How this source names itself in a log line. self._log_name: str = config.name or f"{self.host}:{self.port}" - if (s.get("intake_auth") or "none") not in _INTAKE_AUTH_MODES: - # As the Http() factory refuses it, for a Source built any other way: every check below - # reads a mode it does not know as no authentication, so a typo would open the intake - # socket to every peer. The value is withheld, as the factory withholds it. + if s.get("intake_auth") not in (None, "", *INTAKE_AUTH_MODES): + # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way: + # every check below reads a mode it does not know as no authentication, so a typo + # would check no credential. Only unset and empty read as "none", so a False or a 0 + # is refused too. The value is withheld, as the factory withholds it. raise ValueError( f"HTTP source {self._log_name}: intake_auth must be one of " - f"{'/'.join(_INTAKE_AUTH_MODES)} (value withheld)" + f"{'/'.join(INTAKE_AUTH_MODES)} (value withheld)" ) if s.get("intake_auth") == "mtls_subject" and s.get("intake_auth_health") == "allow": # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way, and diff --git a/tests/test_inbound_http_intake_auth.py b/tests/test_inbound_http_intake_auth.py index 56a643fb6b..3aefc39580 100644 --- a/tests/test_inbound_http_intake_auth.py +++ b/tests/test_inbound_http_intake_auth.py @@ -143,9 +143,10 @@ def test_credential_configured_without_a_mode_is_refused() -> None: @pytest.mark.parametrize( - "mode", ["API_KEY", "apikey", "api-key", "mtls", "basic", " bearer", "a-pasted-credential"] + "mode", + ["API_KEY", "apikey", "api-key", "mtls", "basic", " bearer", "a-pasted-credential", False, 0], ) -def test_the_listener_refuses_an_intake_auth_mode_it_does_not_know(mode: str) -> None: +def test_the_listener_refuses_an_intake_auth_mode_it_does_not_know(mode: object) -> None: """A Source built other than through ``Http()`` skips the factory's mode check, and the listener read any mode it did not know as no authentication at all: a typo opened the intake socket to every peer. It refuses instead, as the factory does, with the value withheld.""" From ffd39499faa9b6ccc0bfea316644cb5805264d9a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:12:58 -0600 Subject: [PATCH 34/39] docs: the unknown-intake_auth changelog states what bounded it (BACKLOG #6979) Repair round 1. The fragment said a typo would have opened the intake socket to every peer. The listener checked no credential, but at least source_ip_allowlist and the start-time peer-control gate still bounded who could submit; it now says so, and that only unset and empty mean none. The code commit before the guard's own message says the same thing too strongly; this fragment is the record a reader sees. Proposed PR title: HTTP listener refuses intake_auth_health='allow' under mtls_subject and an unknown intake_auth (BACKLOG #6979) Proposed vault banner: BUILT on b20054-6979b, stacked on b20054-6978b: intake_auth_health='allow' under mtls_subject is refused by Http() and by HttpSource, and HttpSource refuses an intake_auth mode outside the one set the factory reads. Awaiting PR. Verified-by: tests --- changelog.d/6979.security.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/changelog.d/6979.security.md b/changelog.d/6979.security.md index 8dcf6788bd..ffeca2ea0c 100644 --- a/changelog.d/6979.security.md +++ b/changelog.d/6979.security.md @@ -6,7 +6,8 @@ remove `intake_auth_health` to load. See the `intake_auth_health` row in [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) - **The HTTP listener refuses an `intake_auth` value it does not know when the connection is - built.** `Http()` already refused one, but a source built any other way was served with no - intake authentication at all, so a typo such as `"API_KEY"` would have opened the intake socket - to every peer. Unset and empty still mean `none`. See the `intake_auth` row in + built.** `Http()` already refused one, but on a source built any other way the listener checked + no credential for a typo such as `"API_KEY"`; at least `source_ip_allowlist` and the start-time + peer-control gate still bounded who could submit. Only unset and empty mean `none`. See the + `intake_auth` row in [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) From f7a84ab11b0de6eef73f12dfb727209352b8ef1c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:38:12 -0600 Subject: [PATCH 35/39] http_listener: refuse an explicit empty intake_auth; keep its own mode list (BACKLOG #6979) Repair round 2 after the code-review skill at xhigh. The listener read an explicit None or empty intake_auth as "none", which Http() refuses, so an env() resolving blank on a connection built outside the factory still checked no credential. Only an absent key reads as "none" now. The listener read the accepted modes from wiring, so a mode added there and not enforced by _authorize_head or _authorize_peer_cert would have been accepted and served unauthenticated. It keeps its own list, the modes it enforces, and a test pins that list equal to wiring's INTAKE_AUTH_MODES. The factory's refusal now names its modes from that constant rather than a second literal. Tests: the refusal message is pinned whole, so no part of a value can be in it; an explicit None or empty value is refused by both the factory and the listener; an absent key still builds as none. Verified-by: tests --- messagefoundry/config/wiring.py | 6 +-- messagefoundry/transports/http_listener.py | 15 ++++--- tests/test_inbound_http_intake_auth.py | 47 +++++++++++++++++----- 3 files changed, 51 insertions(+), 17 deletions(-) diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index 7415ac37a1..bb850a77c6 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -4117,8 +4117,8 @@ def _validate_sync_reply(settings: Mapping[str, Any]) -> None: #: The intake-auth modes that carry a shared-secret credential (as opposed to a client certificate). _INTAKE_KEY_MODES = ("api_key", "bearer") -#: Every intake-auth mode. Public because the HTTP listener refuses any other value too, for a -#: source built other than through ``Http()`` (BACKLOG #6979). +#: Every intake-auth mode ``Http()`` accepts. The HTTP listener keeps its own copy, the modes it +#: enforces, and refuses any other value too; a test pins the two equal (BACKLOG #6979). INTAKE_AUTH_MODES = ("none", *_INTAKE_KEY_MODES, "mtls_subject") @@ -4149,7 +4149,7 @@ def _validate_intake_auth(settings: Mapping[str, Any]) -> None: mode = settings["intake_auth"] if mode not in INTAKE_AUTH_MODES: raise WiringError( - "Http intake_auth must be one of none/api_key/bearer/mtls_subject (value withheld)" + f"Http intake_auth must be one of {'/'.join(INTAKE_AUTH_MODES)} (value withheld)" ) if settings["intake_auth_health"] not in ("require", "allow"): raise WiringError("Http intake_auth_health must be 'require' or 'allow' (value withheld)") diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 4a1cccb2aa..d56a17742f 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -60,7 +60,6 @@ read_trusted_proxies, ) from messagefoundry.config.models import ConnectorType, Source -from messagefoundry.config.wiring import INTAKE_AUTH_MODES from messagefoundry.credential import ( OTHERNAMES_INTACT_KEY, VERIFIED_ISSUER_KEY, @@ -160,6 +159,11 @@ #: The most body bytes one read takes while the budget is charged, so a share grows with the bytes #: actually received rather than with what a peer declared. _BODY_CHUNK_BYTES = 64 * 1024 +#: The intake_auth modes this listener enforces: ``_authorize_head`` checks the two key modes and +#: ``_authorize_peer_cert`` the certificate one. Any other value is refused when the source is built +#: (BACKLOG #6979). Written here rather than read from the config layer, so a mode added there and +#: not enforced here is refused rather than served unauthenticated; a test pins the two equal. +_INTAKE_AUTH_MODES = ("none", "api_key", "bearer", "mtls_subject") #: The ``Retry-After`` seconds on the ``503`` refusing a body the in-flight budget has no room for. #: The budget frees as soon as the bodies ahead of it are committed, so a short wait is enough. BODY_BUDGET_RETRY_AFTER_SECONDS = 5 @@ -1107,14 +1111,15 @@ def __init__(self, config: Source) -> None: self.port: int = port_setting(s["port"], transport="HTTP source") #: How this source names itself in a log line. self._log_name: str = config.name or f"{self.host}:{self.port}" - if s.get("intake_auth") not in (None, "", *INTAKE_AUTH_MODES): + if s.get("intake_auth", "none") not in _INTAKE_AUTH_MODES: # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way: # every check below reads a mode it does not know as no authentication, so a typo - # would check no credential. Only unset and empty read as "none", so a False or a 0 - # is refused too. The value is withheld, as the factory withholds it. + # would check no credential. Only an absent key reads as "none"; an explicit None, + # an empty value, a False or a 0 is refused, as the factory refuses it. The value is + # withheld, as the factory withholds it. raise ValueError( f"HTTP source {self._log_name}: intake_auth must be one of " - f"{'/'.join(INTAKE_AUTH_MODES)} (value withheld)" + f"{'/'.join(_INTAKE_AUTH_MODES)} (value withheld)" ) if s.get("intake_auth") == "mtls_subject" and s.get("intake_auth_health") == "allow": # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way, and diff --git a/tests/test_inbound_http_intake_auth.py b/tests/test_inbound_http_intake_auth.py index 3aefc39580..8ec78461bf 100644 --- a/tests/test_inbound_http_intake_auth.py +++ b/tests/test_inbound_http_intake_auth.py @@ -148,9 +148,9 @@ def test_credential_configured_without_a_mode_is_refused() -> None: ) def test_the_listener_refuses_an_intake_auth_mode_it_does_not_know(mode: object) -> None: """A Source built other than through ``Http()`` skips the factory's mode check, and the listener - read any mode it did not know as no authentication at all: a typo opened the intake socket to - every peer. It refuses instead, as the factory does, with the value withheld.""" - with pytest.raises(ValueError, match="intake_auth must be one of") as refused: + read any mode it did not know as no authentication: a typo checked no credential. It refuses + instead, as the factory does. The whole message is pinned, so no part of the value is in it.""" + with pytest.raises(ValueError) as refused: HttpSource( Source( type=ConnectorType.HTTP, @@ -158,17 +158,46 @@ def test_the_listener_refuses_an_intake_auth_mode_it_does_not_know(mode: object) settings={"host": "127.0.0.1", "port": 0, "intake_auth": mode}, ) ) - assert repr(mode) not in str(refused.value) - assert "a-pasted-credential" not in str(refused.value) + assert str(refused.value) == ( + "HTTP source IB_MODE: intake_auth must be one of " + "none/api_key/bearer/mtls_subject (value withheld)" + ) -@pytest.mark.parametrize("mode", [None, "", "none", "api_key", "bearer"]) -def test_the_listener_builds_every_intake_auth_mode_it_knows(mode: str | None) -> None: - settings: dict[str, Any] = {"host": "127.0.0.1", "port": 0, "intake_auth": mode} +@pytest.mark.parametrize("mode", [None, ""]) +def test_the_listener_refuses_an_explicit_empty_intake_auth(mode: str | None) -> None: + """Only an absent key reads as ``none``; ``Http()`` refuses an explicit None or empty value.""" + with pytest.raises(ValueError, match="intake_auth must be one of"): + HttpSource( + Source( + type=ConnectorType.HTTP, + name="IB_MODE", + settings={"host": "127.0.0.1", "port": 0, "intake_auth": mode}, + ) + ) + with pytest.raises(WiringError, match="intake_auth must be one of"): + Http(port=8080, intake_auth=mode) # type: ignore[arg-type] + + +@pytest.mark.parametrize("mode", ["absent", "none", "api_key", "bearer"]) +def test_the_listener_builds_every_intake_auth_mode_it_knows(mode: str) -> None: + settings: dict[str, Any] = {"host": "127.0.0.1", "port": 0} + if mode != "absent": + settings["intake_auth"] = mode if mode in ("api_key", "bearer"): settings["intake_api_key"] = KEY source = HttpSource(Source(type=ConnectorType.HTTP, name="IB_MODE", settings=settings)) - assert source.intake_auth == (mode or "none") + assert source.intake_auth == ("none" if mode == "absent" else mode) + + +def test_the_listener_accepts_exactly_the_modes_the_factory_accepts() -> None: + """The listener keeps its own list, the modes it enforces, so a mode added to the factory alone + is refused rather than served unauthenticated; this pins the two lists equal. ``mtls_subject`` + is built in ``tests/test_inbound_http_mtls_health.py``, which needs a TLS context.""" + from messagefoundry.config.wiring import INTAKE_AUTH_MODES + from messagefoundry.transports.http_listener import _INTAKE_AUTH_MODES + + assert _INTAKE_AUTH_MODES == INTAKE_AUTH_MODES def test_settings_are_carried_onto_the_spec() -> None: From 3cfefb14e338cb52b9a3e2e16647969853d4fd15 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 20:39:04 -0600 Subject: [PATCH 36/39] docs: an empty intake_auth is refused; leaving it out means none (BACKLOG #6979) Repair round 2. The intake_auth row in docs/CONNECTIONS.md now says an empty value is refused too and that leaving the setting out means none. The changelog bullet drops its claim about what else bounded the old behaviour, which held only under enforce, and names which connections were never affected: those written with Http() or in connections.toml. Proposed PR title: HTTP listener refuses intake_auth_health='allow' under mtls_subject and an unknown intake_auth (BACKLOG #6979) Proposed vault banner: BUILT on b20054-6979b, stacked on b20054-6978b: intake_auth_health='allow' under mtls_subject is refused by Http() and by HttpSource, and HttpSource refuses any intake_auth outside the modes it enforces, an explicit empty value included. Awaiting PR. Verified-by: tests --- changelog.d/6979.security.md | 9 ++++----- docs/CONNECTIONS.md | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/changelog.d/6979.security.md b/changelog.d/6979.security.md index ffeca2ea0c..6b3ac08738 100644 --- a/changelog.d/6979.security.md +++ b/changelog.d/6979.security.md @@ -6,8 +6,7 @@ remove `intake_auth_health` to load. See the `intake_auth_health` row in [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) - **The HTTP listener refuses an `intake_auth` value it does not know when the connection is - built.** `Http()` already refused one, but on a source built any other way the listener checked - no credential for a typo such as `"API_KEY"`; at least `source_ip_allowlist` and the start-time - peer-control gate still bounded who could submit. Only unset and empty mean `none`. See the - `intake_auth` row in - [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) + built.** A connection written with `Http()` or in `connections.toml` was already refused at load. + A connection built any other way reached the listener, which checked no credential for a typo + such as `"API_KEY"`, an empty value or an explicit null. Leaving `intake_auth` out still means + `none`. See the `intake_auth` row in [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 3bab183016..f481c77642 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -914,7 +914,7 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `tls_ca_file` | — | trust anchor — opt-in **mTLS** (require + verify a client certificate). | | `tls_ca_pin` | - | the SHA-256 of `tls_ca_file`. Pins the CA's integrity (BACKLOG #1142): a pin that does not match always refuses. Under `[security].enforcement = enforce` the engine also refuses a CA another account can replace, or one whose permissions or path it cannot read; a matching pin lets the second kind load, with a warning and an `auth.trust_anchor` row. Under `enforce`, some Windows spellings refuse even with a matching pin, at least a DOS device name such as `NUL` as a folder; the Windows anchor-check paragraph under [Accepted `odbc_params` keywords](#accepted-odbc_params-keywords) says which (vault BACKLOG #5197). Each check writes its rows under `inbound:`. It pins `tls_ca_file` only. A `tls_crl_file` is read by path with no pin, and a certificate in it that `tls_ca_file` does not already hold refuses the build (BACKLOG #1890). Set without `tls` and `tls_ca_file`, it is refused, since nothing would check it. Set but empty or whitespace, it is refused too; leave it out for no pin. | | `tls_crl_file` | - (off) | opt-in revocation checking for the client certificates `tls_ca_file` verifies. The MLLP `tls_crl_file` row states what an inbound listener does with it. | -| `intake_auth` | `"none"` | **peer credential required to submit a message** ([ADR 0154](adr/0154-synchronous-captured-downstream-reply-and-intake-authentication-for-the-inbound-http-listener-adr-0023-deferred-tail.md) D6): `none` \| `api_key` \| `bearer` \| `mtls_subject`. Any other value is refused when the configuration loads and when the connection is built, with the value withheld. A sibling of `source_ip_allowlist` — it authorises *submitting*, never *reading*; it mints no identity and opens no session. A missing or wrong credential is refused `401`. A request that sends the credential header twice gets `400` instead, before any comparison; [SECURITY.md](SECURITY.md) Table B has the rule. Under `mtls_subject`, a verified certificate whose subject is not in `intake_client_subjects` is refused `403`, and so is one whose subject is listed only under a CA that did not sign it. Each refusal comes **before any request body byte is read**, so it costs an anonymous peer nothing to be turned away. | +| `intake_auth` | `"none"` | **peer credential required to submit a message** ([ADR 0154](adr/0154-synchronous-captured-downstream-reply-and-intake-authentication-for-the-inbound-http-listener-adr-0023-deferred-tail.md) D6): `none` \| `api_key` \| `bearer` \| `mtls_subject`. Any other value, an empty one included, is refused when the configuration loads and when the connection is built, with the value withheld; leaving it out means `none`. A sibling of `source_ip_allowlist` — it authorises *submitting*, never *reading*; it mints no identity and opens no session. A missing or wrong credential is refused `401`. A request that sends the credential header twice gets `400` instead, before any comparison; [SECURITY.md](SECURITY.md) Table B has the rule. Under `mtls_subject`, a verified certificate whose subject is not in `intake_client_subjects` is refused `403`, and so is one whose subject is listed only under a CA that did not sign it. Each refusal comes **before any request body byte is read**, so it costs an anonymous peer nothing to be turned away. | | `intake_api_key` | — | the credential for `api_key`/`bearer` — a **secret**, `env()` only (a literal, a `default=` or a `cast=` is refused at the factory). | | `intake_api_key_next` | — | rotation slot, accepted **alongside** `intake_api_key` so a partner key rotates with no outage: set it, have the partner cut over, promote it, then clear it. Leaving it set keeps a retired credential live. | | `intake_api_key_header` | `"x-api-key"` | which header carries the `api_key` credential. A header **name**, not a secret. | From 9eac3dff1d51754bdf7824af80e6fab7e0a8b085 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:02:13 -0600 Subject: [PATCH 37/39] http_listener, Http(): refuse an intake_auth that is not a plain str (BACKLOG #6979) The mode check compared the raw value against the allowed set, but the listener stored str(raw). A (str, Enum) member equal to "api_key" passed the check, was stored as "Mode.API_KEY", and every authorisation check read that unknown mode as no authentication. Http() accepted the same member. Both now require type(value) is str as well as membership, so the value checked is the value stored and enforced; the listener stores the checked value unchanged. The refusal withholds the value, as before. Tests: a (str, Enum) member, a StrEnum member and a str subclass are refused by both the listener and the factory; the plain strings still build. Verified-by: tests --- messagefoundry/config/wiring.py | 4 +- messagefoundry/transports/http_listener.py | 14 +++-- tests/test_inbound_http_intake_auth.py | 65 ++++++++++++++++++++++ 3 files changed, 77 insertions(+), 6 deletions(-) diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index bb850a77c6..5a6361df23 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -4147,7 +4147,9 @@ def _validate_intake_auth(settings: Mapping[str, Any]) -> None: ``File(credential_password=...)`` (ADR 0132): a fallback credential is a silent credential. """ mode = settings["intake_auth"] - if mode not in INTAKE_AUTH_MODES: + # A plain str only: a str subclass, such as a (str, Enum) member equal to "api_key", passes + # membership yet renders as another string where the listener reads it (BACKLOG #6979). + if type(mode) is not str or mode not in INTAKE_AUTH_MODES: raise WiringError( f"Http intake_auth must be one of {'/'.join(INTAKE_AUTH_MODES)} (value withheld)" ) diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index d56a17742f..1601d16189 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -1111,17 +1111,21 @@ def __init__(self, config: Source) -> None: self.port: int = port_setting(s["port"], transport="HTTP source") #: How this source names itself in a log line. self._log_name: str = config.name or f"{self.host}:{self.port}" - if s.get("intake_auth", "none") not in _INTAKE_AUTH_MODES: + intake_auth = s.get("intake_auth", "none") + if type(intake_auth) is not str or intake_auth not in _INTAKE_AUTH_MODES: # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way: # every check below reads a mode it does not know as no authentication, so a typo # would check no credential. Only an absent key reads as "none"; an explicit None, - # an empty value, a False or a 0 is refused, as the factory refuses it. The value is - # withheld, as the factory withholds it. + # an empty value, a False or a 0 is refused, as the factory refuses it. Only a plain + # str passes: a str subclass, such as a (str, Enum) member equal to "api_key", is + # equal to a mode yet may render as another string, so the value checked here is + # exactly the value stored and enforced below. The value is withheld, as the factory + # withholds it. raise ValueError( f"HTTP source {self._log_name}: intake_auth must be one of " f"{'/'.join(_INTAKE_AUTH_MODES)} (value withheld)" ) - if s.get("intake_auth") == "mtls_subject" and s.get("intake_auth_health") == "allow": + if intake_auth == "mtls_subject" and s.get("intake_auth_health") == "allow": # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way, and # before the TLS build below can log or refuse first. `_authorize_peer_cert` runs at # accept, before the request method is read, so no probe could be exempted. @@ -1224,7 +1228,7 @@ def __init__(self, config: Source) -> None: # this inbound, mints no identity and opens no session. Defaults to "none", which makes every # path below a no-op and every shipped configuration byte-identical. The env() refs are already # resolved to strings by the time a Source reaches here (_source_config → resolve_env_settings). - self.intake_auth: str = str(s.get("intake_auth") or "none") + self.intake_auth: str = intake_auth self._intake_keys: tuple[str | None, str | None] = ( s.get("intake_api_key"), s.get("intake_api_key_next"), diff --git a/tests/test_inbound_http_intake_auth.py b/tests/test_inbound_http_intake_auth.py index 8ec78461bf..89bf82d0ce 100644 --- a/tests/test_inbound_http_intake_auth.py +++ b/tests/test_inbound_http_intake_auth.py @@ -15,6 +15,7 @@ import asyncio import datetime +import enum import inspect import json from typing import Any @@ -190,6 +191,70 @@ def test_the_listener_builds_every_intake_auth_mode_it_knows(mode: str) -> None: assert source.intake_auth == ("none" if mode == "absent" else mode) +class _Mode(str, enum.Enum): # noqa: UP042 -- the (str, Enum) shape is the case under test + API_KEY = "api_key" + + +class _StrMode(enum.StrEnum): + API_KEY = "api_key" + + +class _StrSubclass(str): + pass + + +@pytest.mark.parametrize( + "mode", + [ + _Mode.API_KEY, + _StrMode.API_KEY, + _StrSubclass("api_key"), + ], + ids=["str-enum-member", "StrEnum-member", "str-subclass"], +) +def test_an_intake_auth_mode_that_is_not_a_plain_str_is_refused(mode: str) -> None: + """A ``(str, Enum)`` member equal to ``"api_key"`` passed the membership check, but the listener + stored ``str(mode)``, which is ``"_Mode.API_KEY"``, a mode no check below knows, so the source + served unauthenticated (BACKLOG #6979). Both the listener and the factory now refuse anything + but a plain ``str``, so the value checked is the value stored and enforced.""" + with pytest.raises(ValueError) as refused: + HttpSource( + Source( + type=ConnectorType.HTTP, + name="IB_MODE", + settings={ + "host": "127.0.0.1", + "port": 0, + "intake_auth": mode, + "intake_api_key": KEY, + }, + ) + ) + assert str(refused.value) == ( + "HTTP source IB_MODE: intake_auth must be one of " + "none/api_key/bearer/mtls_subject (value withheld)" + ) + with pytest.raises(WiringError) as factory_refused: + Http(port=8080, intake_auth=mode, intake_api_key=env("acme_intake_key")) # type: ignore[arg-type] + assert str(factory_refused.value) == ( + "Http intake_auth must be one of none/api_key/bearer/mtls_subject (value withheld)" + ) + + +@pytest.mark.parametrize("mode", ["none", "api_key", "bearer"]) +def test_a_plain_str_intake_auth_mode_still_builds_and_is_stored_as_given(mode: str) -> None: + settings: dict[str, Any] = {"host": "127.0.0.1", "port": 0, "intake_auth": mode} + if mode != "none": + settings["intake_api_key"] = KEY + source = HttpSource(Source(type=ConnectorType.HTTP, name="IB_MODE", settings=settings)) + assert type(source.intake_auth) is str + assert source.intake_auth == mode + if mode == "none": + Http(port=8080, intake_auth=mode) # type: ignore[arg-type] + else: + Http(port=8080, intake_auth=mode, intake_api_key=env("acme_intake_key")) # type: ignore[arg-type] + + def test_the_listener_accepts_exactly_the_modes_the_factory_accepts() -> None: """The listener keeps its own list, the modes it enforces, so a mode added to the factory alone is refused rather than served unauthenticated; this pins the two lists equal. ``mtls_subject`` From ea56c1ae0676b1b9a02d78936d523f8ac14eda2b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:16:50 -0600 Subject: [PATCH 38/39] http_listener, Http(), gate: name the plain-str remedy; one reading in the gate (BACKLOG #6979) Review round 1 on the plain-str check. A str subclass equal to a mode is refused with a message that names the cause and the remedy, passing the string itself such as an enum member's .value, still withholding the value. Other refusals keep their message. The peer-control gate in wiring_runner read the mode through str(), so a StrEnum member equal to "api_key" was judged on its own though Http() and the listener refuse it. It now judges a mode alone only for a plain str, as its docstring promises. Tests: every mode, under each of a (str, Enum) member, a StrEnum member and a str subclass, is refused by the listener and by Http() with the full message pinned; the gate weighs the allow-list for each shape. The duplicate plain-string test is dropped, as two existing tests build the plain strings. Verified-by: tests --- messagefoundry/config/wiring.py | 16 +++-- messagefoundry/pipeline/wiring_runner.py | 5 +- messagefoundry/transports/http_listener.py | 13 ++-- tests/test_inbound_http_intake_auth.py | 79 ++++++++++++---------- 4 files changed, 70 insertions(+), 43 deletions(-) diff --git a/messagefoundry/config/wiring.py b/messagefoundry/config/wiring.py index 5a6361df23..294b5eff8e 100644 --- a/messagefoundry/config/wiring.py +++ b/messagefoundry/config/wiring.py @@ -4141,17 +4141,25 @@ def _validate_intake_auth(settings: Mapping[str, Any]) -> None: * ``intake_client_subjects`` under ``api_key`` or ``bearer`` — the same reason: only ``mtls_subject`` reads a client certificate (vault BACKLOG #2287); * ``intake_auth_health="allow"`` under ``mtls_subject`` — the certificate is checked before the - method is read, so the exemption would exempt nothing (BACKLOG #6979). + method is read, so the exemption would exempt nothing (BACKLOG #6979); + * an ``intake_auth`` that is not a plain ``str``, such as an enum member equal to a mode: the + listener refuses it at build, so this refuses it at load (BACKLOG #6979). The secret itself must be an ``env()`` reference with no default and no cast, mirroring ``File(credential_password=...)`` (ADR 0132): a fallback credential is a silent credential. """ mode = settings["intake_auth"] - # A plain str only: a str subclass, such as a (str, Enum) member equal to "api_key", passes - # membership yet renders as another string where the listener reads it (BACKLOG #6979). + # A plain str only, as the listener requires (BACKLOG #6979): a str subclass, such as a + # (str, Enum) member equal to "api_key", passes membership yet str() may render it as another + # string, so refusing it here reports at load what the listener would refuse at build. if type(mode) is not str or mode not in INTAKE_AUTH_MODES: + hint = ( + ", as a plain str: pass the string itself, such as an enum member's .value" + if isinstance(mode, str) and type(mode) is not str + else "" + ) raise WiringError( - f"Http intake_auth must be one of {'/'.join(INTAKE_AUTH_MODES)} (value withheld)" + f"Http intake_auth must be one of {'/'.join(INTAKE_AUTH_MODES)}{hint} (value withheld)" ) if settings["intake_auth_health"] not in ("require", "allow"): raise WiringError("Http intake_auth_health must be 'require' or 'allow' (value withheld)") diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index e0acedc25f..0e795a1424 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -17140,7 +17140,10 @@ def _allowlist_weighed(settings: Mapping[str, Any]) -> bool: ``intake_auth`` value but a mode judged alone, ``none`` or one ``Http()`` would have refused. One reading, so :func:`check_http_intake_auth` names the list's shortfall exactly when :func:`_has_effective_peer_control` weighed the list.""" - return str(settings.get("intake_auth") or "none") not in _INTAKE_MODES_JUDGED_ALONE + mode = settings.get("intake_auth") or "none" + # Only a plain str is judged alone, as only a plain str passes Http() and the listener + # (BACKLOG #6979); str() of an enum member equal to a mode may read as that mode. + return type(mode) is not str or mode not in _INTAKE_MODES_JUDGED_ALONE def _has_effective_peer_control(settings: Mapping[str, Any]) -> bool: diff --git a/messagefoundry/transports/http_listener.py b/messagefoundry/transports/http_listener.py index 1601d16189..dae9a0c939 100644 --- a/messagefoundry/transports/http_listener.py +++ b/messagefoundry/transports/http_listener.py @@ -164,6 +164,9 @@ #: (BACKLOG #6979). Written here rather than read from the config layer, so a mode added there and #: not enforced here is refused rather than served unauthenticated; a test pins the two equal. _INTAKE_AUTH_MODES = ("none", "api_key", "bearer", "mtls_subject") +#: Added to the unknown-mode refusal when the value is a ``str`` subclass, such as an enum member, +#: which is refused for its type alone; it names the remedy without naming the value. +_PLAIN_STR_HINT = ", as a plain str: pass the string itself, such as an enum member's .value" #: The ``Retry-After`` seconds on the ``503`` refusing a body the in-flight budget has no room for. #: The budget frees as soon as the bodies ahead of it are committed, so a short wait is enough. BODY_BUDGET_RETRY_AFTER_SECONDS = 5 @@ -1118,12 +1121,14 @@ def __init__(self, config: Source) -> None: # would check no credential. Only an absent key reads as "none"; an explicit None, # an empty value, a False or a 0 is refused, as the factory refuses it. Only a plain # str passes: a str subclass, such as a (str, Enum) member equal to "api_key", is - # equal to a mode yet may render as another string, so the value checked here is - # exactly the value stored and enforced below. The value is withheld, as the factory - # withholds it. + # equal to a mode yet str() may render it as another string, so the value checked + # here is exactly the value stored and enforced below, with no str() between them. + # The value is withheld, as the factory withholds it. + subclass = isinstance(intake_auth, str) and type(intake_auth) is not str + hint = _PLAIN_STR_HINT if subclass else "" raise ValueError( f"HTTP source {self._log_name}: intake_auth must be one of " - f"{'/'.join(_INTAKE_AUTH_MODES)} (value withheld)" + f"{'/'.join(_INTAKE_AUTH_MODES)}{hint} (value withheld)" ) if intake_auth == "mtls_subject" and s.get("intake_auth_health") == "allow": # BACKLOG #6979, as the Http() factory refuses it, for a Source built any other way, and diff --git a/tests/test_inbound_http_intake_auth.py b/tests/test_inbound_http_intake_auth.py index 89bf82d0ce..a064dbc02e 100644 --- a/tests/test_inbound_http_intake_auth.py +++ b/tests/test_inbound_http_intake_auth.py @@ -191,32 +191,49 @@ def test_the_listener_builds_every_intake_auth_mode_it_knows(mode: str) -> None: assert source.intake_auth == ("none" if mode == "absent" else mode) +#: Each shape a value equal to a mode can take without being a plain ``str``. The plain strings +#: themselves are built by ``test_the_listener_builds_every_intake_auth_mode_it_knows`` and +#: ``test_valid_configurations_build`` above. +_NOT_PLAIN_STR = { + "str-enum-member": lambda mode: _Mode(mode), + "StrEnum-member": lambda mode: _StrMode(mode), + "str-subclass": lambda mode: _StrSubclass(mode), +} +_PLAIN_STR_REFUSAL = ( + "intake_auth must be one of none/api_key/bearer/mtls_subject, as a plain str: pass the " + "string itself, such as an enum member's .value (value withheld)" +) + + class _Mode(str, enum.Enum): # noqa: UP042 -- the (str, Enum) shape is the case under test + NONE = "none" API_KEY = "api_key" + BEARER = "bearer" + MTLS_SUBJECT = "mtls_subject" class _StrMode(enum.StrEnum): + NONE = "none" API_KEY = "api_key" + BEARER = "bearer" + MTLS_SUBJECT = "mtls_subject" class _StrSubclass(str): pass -@pytest.mark.parametrize( - "mode", - [ - _Mode.API_KEY, - _StrMode.API_KEY, - _StrSubclass("api_key"), - ], - ids=["str-enum-member", "StrEnum-member", "str-subclass"], -) -def test_an_intake_auth_mode_that_is_not_a_plain_str_is_refused(mode: str) -> None: +@pytest.mark.parametrize("shape", sorted(_NOT_PLAIN_STR)) +@pytest.mark.parametrize("mode", ["none", "api_key", "bearer", "mtls_subject"]) +def test_an_intake_auth_mode_that_is_not_a_plain_str_is_refused(mode: str, shape: str) -> None: """A ``(str, Enum)`` member equal to ``"api_key"`` passed the membership check, but the listener - stored ``str(mode)``, which is ``"_Mode.API_KEY"``, a mode no check below knows, so the source - served unauthenticated (BACKLOG #6979). Both the listener and the factory now refuse anything - but a plain ``str``, so the value checked is the value stored and enforced.""" + stored ``str(mode)``, which is ``"_Mode.API_KEY"``, a mode no authorisation check knows, so the + source checked no credential (BACKLOG #6979); under ``mtls_subject`` no certificate was checked. + Both the listener and the factory now refuse any value that is not a plain ``str``, so the + value checked is the value stored and enforced. A ``StrEnum`` member and a ``str`` subclass + rendered correctly before; they are refused too, and the refusal names the remedy.""" + value = _NOT_PLAIN_STR[shape](mode) + assert value == mode and type(value) is not str with pytest.raises(ValueError) as refused: HttpSource( Source( @@ -225,34 +242,28 @@ def test_an_intake_auth_mode_that_is_not_a_plain_str_is_refused(mode: str) -> No settings={ "host": "127.0.0.1", "port": 0, - "intake_auth": mode, + "intake_auth": value, "intake_api_key": KEY, }, ) ) - assert str(refused.value) == ( - "HTTP source IB_MODE: intake_auth must be one of " - "none/api_key/bearer/mtls_subject (value withheld)" - ) + assert str(refused.value) == f"HTTP source IB_MODE: {_PLAIN_STR_REFUSAL}" with pytest.raises(WiringError) as factory_refused: - Http(port=8080, intake_auth=mode, intake_api_key=env("acme_intake_key")) # type: ignore[arg-type] - assert str(factory_refused.value) == ( - "Http intake_auth must be one of none/api_key/bearer/mtls_subject (value withheld)" - ) + Http(port=8080, intake_auth=value, intake_api_key=env("acme_intake_key")) # type: ignore[arg-type] + assert str(factory_refused.value) == f"Http {_PLAIN_STR_REFUSAL}" -@pytest.mark.parametrize("mode", ["none", "api_key", "bearer"]) -def test_a_plain_str_intake_auth_mode_still_builds_and_is_stored_as_given(mode: str) -> None: - settings: dict[str, Any] = {"host": "127.0.0.1", "port": 0, "intake_auth": mode} - if mode != "none": - settings["intake_api_key"] = KEY - source = HttpSource(Source(type=ConnectorType.HTTP, name="IB_MODE", settings=settings)) - assert type(source.intake_auth) is str - assert source.intake_auth == mode - if mode == "none": - Http(port=8080, intake_auth=mode) # type: ignore[arg-type] - else: - Http(port=8080, intake_auth=mode, intake_api_key=env("acme_intake_key")) # type: ignore[arg-type] +@pytest.mark.parametrize("shape", sorted(_NOT_PLAIN_STR)) +def test_the_peer_control_gate_weighs_the_allowlist_for_a_mode_that_is_not_a_plain_str( + shape: str, +) -> None: + """The gate judges a key mode alone only for a value ``Http()`` and the listener accept: a + ``StrEnum`` member equal to ``"api_key"`` reads as ``"api_key"`` through ``str()``, so the gate + judged it alone though both refuse it (BACKLOG #6979).""" + from messagefoundry.pipeline.wiring_runner import _allowlist_weighed + + assert _allowlist_weighed({"intake_auth": _NOT_PLAIN_STR[shape]("api_key")}) + assert not _allowlist_weighed({"intake_auth": "api_key"}) def test_the_listener_accepts_exactly_the_modes_the_factory_accepts() -> None: From 8f7ca3b550a1fec14c73f621ccebaf3331db73aa Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 21:17:56 -0600 Subject: [PATCH 39/39] docs: intake_auth must be a plain string; the changelog names the enum case (BACKLOG #6979) The intake_auth row in docs/CONNECTIONS.md says an enum member or other str subclass is refused even when it equals a mode, and to pass its .value. The changelog no longer says Http()-written connections were never affected: an enum member with a str base passed Http() and was then served with no credential checked. It names the new refusal, that a StrEnum member is refused though it was read correctly before, and the remedy. Proposed PR title: HTTP listener refuses intake_auth_health='allow' under mtls_subject and an unknown intake_auth (BACKLOG #6979) Proposed vault banner: BUILT on b20054-6979c, stacked on b20054-6979b and b20054-6978b: intake_auth_health='allow' under mtls_subject is refused by Http() and by HttpSource, and HttpSource and Http() refuse any intake_auth outside the modes the listener enforces, an explicit empty value and any value that is not a plain str included. Awaiting PR. Verified-by: none --- changelog.d/6979.security.md | 14 ++++++++++---- docs/CONNECTIONS.md | 2 +- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/changelog.d/6979.security.md b/changelog.d/6979.security.md index 6b3ac08738..93d080b8b0 100644 --- a/changelog.d/6979.security.md +++ b/changelog.d/6979.security.md @@ -6,7 +6,13 @@ remove `intake_auth_health` to load. See the `intake_auth_health` row in [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) - **The HTTP listener refuses an `intake_auth` value it does not know when the connection is - built.** A connection written with `Http()` or in `connections.toml` was already refused at load. - A connection built any other way reached the listener, which checked no credential for a typo - such as `"API_KEY"`, an empty value or an explicit null. Leaving `intake_auth` out still means - `none`. See the `intake_auth` row in [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) + built.** A connection written with `Http()` or in `connections.toml` was already refused at load + for a value that was not one of the modes. A connection built any other way reached the listener, + which checked no credential for a typo such as `"API_KEY"`, an empty value or an explicit null. + Leaving `intake_auth` out still means `none`. +- **`Http()` and the HTTP listener refuse an `intake_auth` that is not a plain string.** An enum + member with a `str` base, equal to a mode such as `"api_key"`, passed both checks, and the + listener then read it under another name, so it checked no credential. That held for + `Http()`-written connections too. Every `str` subclass is now refused, a `StrEnum` member + included, which was read correctly before; the refusal says to pass the string itself, such as + the member's `.value`. `connections.toml` always yields plain strings. See the `intake_auth` row in [CONNECTIONS.md](../docs/CONNECTIONS.md). (`BACKLOG #6979`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index f481c77642..d2d7d1d070 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -914,7 +914,7 @@ routes a `Message`; `json`/`xml`/`text`/`fhir` route a `RawMessage` the Handler | `tls_ca_file` | — | trust anchor — opt-in **mTLS** (require + verify a client certificate). | | `tls_ca_pin` | - | the SHA-256 of `tls_ca_file`. Pins the CA's integrity (BACKLOG #1142): a pin that does not match always refuses. Under `[security].enforcement = enforce` the engine also refuses a CA another account can replace, or one whose permissions or path it cannot read; a matching pin lets the second kind load, with a warning and an `auth.trust_anchor` row. Under `enforce`, some Windows spellings refuse even with a matching pin, at least a DOS device name such as `NUL` as a folder; the Windows anchor-check paragraph under [Accepted `odbc_params` keywords](#accepted-odbc_params-keywords) says which (vault BACKLOG #5197). Each check writes its rows under `inbound:`. It pins `tls_ca_file` only. A `tls_crl_file` is read by path with no pin, and a certificate in it that `tls_ca_file` does not already hold refuses the build (BACKLOG #1890). Set without `tls` and `tls_ca_file`, it is refused, since nothing would check it. Set but empty or whitespace, it is refused too; leave it out for no pin. | | `tls_crl_file` | - (off) | opt-in revocation checking for the client certificates `tls_ca_file` verifies. The MLLP `tls_crl_file` row states what an inbound listener does with it. | -| `intake_auth` | `"none"` | **peer credential required to submit a message** ([ADR 0154](adr/0154-synchronous-captured-downstream-reply-and-intake-authentication-for-the-inbound-http-listener-adr-0023-deferred-tail.md) D6): `none` \| `api_key` \| `bearer` \| `mtls_subject`. Any other value, an empty one included, is refused when the configuration loads and when the connection is built, with the value withheld; leaving it out means `none`. A sibling of `source_ip_allowlist` — it authorises *submitting*, never *reading*; it mints no identity and opens no session. A missing or wrong credential is refused `401`. A request that sends the credential header twice gets `400` instead, before any comparison; [SECURITY.md](SECURITY.md) Table B has the rule. Under `mtls_subject`, a verified certificate whose subject is not in `intake_client_subjects` is refused `403`, and so is one whose subject is listed only under a CA that did not sign it. Each refusal comes **before any request body byte is read**, so it costs an anonymous peer nothing to be turned away. | +| `intake_auth` | `"none"` | **peer credential required to submit a message** ([ADR 0154](adr/0154-synchronous-captured-downstream-reply-and-intake-authentication-for-the-inbound-http-listener-adr-0023-deferred-tail.md) D6): `none` \| `api_key` \| `bearer` \| `mtls_subject`. Any other value, an empty one included, is refused when the configuration loads and when the connection is built, with the value withheld; leaving it out means `none`. The value must be a plain string: an enum member or other `str` subclass is refused even when it equals a mode, so pass its `.value` (BACKLOG #6979). A sibling of `source_ip_allowlist` — it authorises *submitting*, never *reading*; it mints no identity and opens no session. A missing or wrong credential is refused `401`. A request that sends the credential header twice gets `400` instead, before any comparison; [SECURITY.md](SECURITY.md) Table B has the rule. Under `mtls_subject`, a verified certificate whose subject is not in `intake_client_subjects` is refused `403`, and so is one whose subject is listed only under a CA that did not sign it. Each refusal comes **before any request body byte is read**, so it costs an anonymous peer nothing to be turned away. | | `intake_api_key` | — | the credential for `api_key`/`bearer` — a **secret**, `env()` only (a literal, a `default=` or a `cast=` is refused at the factory). | | `intake_api_key_next` | — | rotation slot, accepted **alongside** `intake_api_key` so a partner key rotates with no outage: set it, have the partner cut over, promote it, then clear it. Leaving it set keeps a retired credential live. | | `intake_api_key_header` | `"x-api-key"` | which header carries the `api_key` credential. A header **name**, not a secret. |