From 596ec9195efb4a5d36a4afc7ff841115afe3cd62 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 02:06:26 -0600 Subject: [PATCH 01/16] X12 strict validate chains no pyx12 exception and keeps sender text out of its reprs BACKLOG #5370. On a deploying site, a traceback or a logged result would have carried interchange text. - validate() raises X12ValidationError outside the except block, so neither __cause__ nor __context__ holds the pyx12 exception. Only its class name is kept. - X12ValidationResult.ack is out of the repr. The other fields stay: valid is a bool, ack_transaction comes from a fixed table, and each error holds only locators. - A segment_id is kept only when shaped like an X12 segment id, in both error builders and both message forms. A two- or three-character sender value of that exact shape cannot be told from an id and is still kept; the docstring says so. Tests fail on the old code at the locked pyx12 4.1.0. The existing unterminated-segment test read the pyx12 error from __cause__; it now reads it from a spy and also pins the severed chain. Proposed PR title: X12 strict validate chains no pyx12 exception and keeps sender text out of its reprs (BACKLOG #5370) Proposed ledger banner: SHIPPED. The row's own finding and added items 1, 2 and 3 are settled by this change. Nothing stays open on this row. --- messagefoundry/parsing/x12/validate.py | 94 ++++++++++----- tests/test_x12_validate.py | 160 ++++++++++++++++++++++++- 2 files changed, 217 insertions(+), 37 deletions(-) diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index 62fb1d584a..dbefa3d565 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -22,11 +22,13 @@ well-formed; see :class:`X12ValidationResult`. **PHI rule (do not break).** A failing X12 element error from pyx12 embeds the *offending data value* -(potential PHI) in its raw error string. This module **never** surfaces that: each -:class:`X12SegmentError` carries only structural locators — the error code, the segment/element id, a -schema-label *type name*, and the line/position — never the input value. The full interchange goes only -to the secured store (CLAUDE.md §9). The pyx12 logger tree (which logs the raw, value-bearing strings -at ERROR) is muted from the first validation pass on, and never unmuted. +(potential PHI) in its raw error string, and an exception pyx12 raises can quote the interchange. This +module does not surface either: each :class:`X12SegmentError` carries only structural locators — the +error code, a segment id only when it has a segment id's shape (:class:`X12SegmentError` states what a +shape cannot rule out), the element position, a schema-label *type name*, and the line — and a refusal +chains no pyx12 exception. The ack does echo sender values, so it is left out of the result's repr. The +full interchange goes only to the secured store (CLAUDE.md §9). The pyx12 logger tree (which logs the +raw, value-bearing strings at ERROR) is muted from the first validation pass on, and never unmuted. Pure: no I/O to disk/network, no engine imports. ``pyx12``'s sole runtime dependency is ``defusedxml`` (already in tree), used to parse its bundled, trusted map XML — not attacker input. @@ -36,8 +38,9 @@ import io import logging +import re from collections.abc import Callable -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any from messagefoundry.parsing.x12._deps import load_x12_code_resolver, load_x12_validator @@ -49,14 +52,18 @@ @dataclass(frozen=True) class X12SegmentError: - """One conformance violation, reduced to **PHI-safe structural locators only**. + """One conformance violation, reduced to **structural locators**. ``code`` is the X12 error code pyx12 maps it to in one code list, chosen by the last group's GS08: the 997 AK list for 004010, also when no ack is generated, and the 999 IK list otherwise (e.g. ``"8"``). pyx12's own error name stands in where that list has no code for it; - ``message`` is a synthesized, value-free description; - ``segment_id`` / ``element_position`` / ``line`` / ``loop`` locate it; ``element_name`` is the - *schema* data-element label (e.g. ``"Transaction Set Creation Date"``), never the input value.""" + ``message`` is synthesized from the code and the locators below; + ``element_position`` / ``line`` are numbers and ``loop`` is the *schema* name of the map node; + ``element_name`` is the *schema* data-element label (e.g. ``"Transaction Set Creation Date"``). + + ``segment_id`` comes from the input, so it is kept only when shaped like an X12 segment id (a + capital, then one or two capitals or digits) and is ``None`` otherwise (BACKLOG #5370). A sender + value of that exact shape, standing where the id goes, cannot be told from an id and is kept.""" code: str message: str @@ -70,16 +77,20 @@ class X12SegmentError: @dataclass(frozen=True) class X12ValidationResult: """The outcome of a strict pass. ``valid`` is True iff pyx12 found no errors. ``errors`` is the - flattened, PHI-safe violation list (empty when valid). ``ack`` is the generated 997/999 - Functional Acknowledgment, complete to its closing IEA, or ``None`` when pyx12 emitted none (e.g. - for an already-FA transaction) or its ack writer failed before the closing IEA. A fragment such a - writer left is dropped, with a WARNING; a writer that failed before writing anything leaves no - fragment and no WARNING. ``ack_transaction`` names which (``"997"``/``"999"``), ``None`` - with no ack. A complete ack echoes sender values unescaped, so it is not thereby well-formed.""" + flattened violation list of structural locators (empty when valid). ``ack`` is the generated + 997/999 Functional Acknowledgment, complete to its closing IEA, or ``None`` when pyx12 emitted + none (e.g. for an already-FA transaction) or its ack writer failed before the closing IEA. A + fragment such a writer left is dropped, with a WARNING; a writer that failed before writing + anything leaves no fragment and no WARNING. ``ack_transaction`` names which + (``"997"``/``"999"``), ``None`` with no ack. A complete ack echoes sender values unescaped, so + it is not thereby well-formed. + + ``ack`` is left out of the repr because those echoed values can be PHI, for example a date of + birth in AK404, and logging a result would otherwise write them (BACKLOG #5370).""" valid: bool errors: tuple[X12SegmentError, ...] = () - ack: str | None = None + ack: str | None = field(default=None, repr=False) ack_transaction: str | None = None @@ -160,6 +171,9 @@ def complete(self) -> bool: # pyx12's ack choice by the last GS08's first six characters; any other version gets no ack. _ACK_FOR_VERSION = {"004010": "997", "005010": "999"} +#: Used with ``fullmatch``, since ``$`` would also accept a trailing newline. +_SEGMENT_ID = re.compile(r"[A-Z][A-Z0-9]{1,2}") + def _last_group_version(report: dict[str, Any]) -> str: """The GS08 of the last group pyx12 walked, from its report. pyx12 picks the ack from exactly that @@ -173,10 +187,20 @@ def _last_group_version(report: dict[str, Any]) -> str: return vriic -def _segment_error(code: str, seg: dict[str, Any], err: dict[str, Any]) -> X12SegmentError: - """A PHI-safe :class:`X12SegmentError` from a pyx12 segment-level error dict (drops ``err_str`` / - ``err_val`` — they can embed the input value — keeping only structural locators).""" +def _structural_segment_id(seg: dict[str, Any]) -> str | None: + """pyx12's ``seg_id`` when it is shaped like an X12 segment id, otherwise ``None``. + + pyx12 takes everything before the first element separator as the id, so a wrongly delimited + segment (``NM1|IL|1|DOE|ROBERT``) puts the sender's whole segment there. The shape is the one + pyx12's own id check applies, and every segment id in its bundled maps has it.""" seg_id = seg.get("seg_id") + return seg_id if isinstance(seg_id, str) and _SEGMENT_ID.fullmatch(seg_id) else None + + +def _segment_error(code: str, seg: dict[str, Any], err: dict[str, Any]) -> X12SegmentError: + """A :class:`X12SegmentError` from a pyx12 segment-level error dict. It drops ``err_str`` / + ``err_val``, which can embed the input value.""" + seg_id = _structural_segment_id(seg) return X12SegmentError( code=code, message=f"segment {seg_id or '?'}: error {code}", @@ -187,9 +211,9 @@ def _segment_error(code: str, seg: dict[str, Any], err: dict[str, Any]) -> X12Se def _element_error(code: str, seg: dict[str, Any], ele: dict[str, Any]) -> X12SegmentError: - """A PHI-safe :class:`X12SegmentError` from a pyx12 element-level error dict. ``name`` is the - data-element *type* label (schema), not the value; ``err_str``/``err_val`` are dropped.""" - seg_id = seg.get("seg_id") + """A :class:`X12SegmentError` from a pyx12 element-level error dict. ``name`` is the data-element + *type* label (schema), not the value; ``err_str``/``err_val`` are dropped.""" + seg_id = _structural_segment_id(seg) pos = ele.get("ele_pos") name = ele.get("name") return X12SegmentError( @@ -223,7 +247,7 @@ def _flatten_errors( report: dict[str, Any], resolve: Callable[..., str | None], prefer_5010: bool ) -> list[X12SegmentError]: """Walk pyx12's nested JSON error report (interchange → group → transaction → segment → element), - flattening every recorded error into a PHI-safe :class:`X12SegmentError`. ``prefer_5010`` is False + flattening every recorded error into an :class:`X12SegmentError`. ``prefer_5010`` is False when the last group is ``004010``: pyx12 picks one ack per document (from the last GS08), so the codes follow that ack rather than each group's own version.""" out: list[X12SegmentError] = [] @@ -256,13 +280,14 @@ def validate(raw: str | bytes) -> X12ValidationResult: ``raw`` is the interchange text (bytes are decoded UTF-8/replace, matching :meth:`X12Message.parse`). Returns an :class:`X12ValidationResult` carrying the conformance verdict, - the PHI-safe error list, and the generated 997/999 acknowledgment. + the structural error list, and the generated 997/999 acknowledgment. Raises :class:`~messagefoundry.parsing.x12.errors.X12ValidationError` only when no validation pass - could run at all (e.g. the bytes are not a parseable X12 data file — there is no envelope to walk); - a *failed* validation of a parseable interchange is returned as data (``valid=False``), not raised, - so a Handler can still emit the negative ack. Raises :class:`RuntimeError` if the ``[x12]`` extra - is absent (a deploy/config error, distinct from the ``ValueError``-rooted data errors).""" + could run at all (e.g. the bytes are not a parseable X12 data file — there is no envelope to walk). + It chains no pyx12 exception. A *failed* validation of a parseable interchange is returned as data + (``valid=False``), not raised, so a Handler can still emit the negative ack. Raises + :class:`RuntimeError` if the ``[x12]`` extra is absent (a deploy/config error, distinct from the + ``ValueError``-rooted data errors).""" if isinstance(raw, (bytes, bytearray)): # noqa: SIM108 text = bytes(raw).decode("utf-8", "replace") else: @@ -275,12 +300,19 @@ def validate(raw: str | bytes) -> X12ValidationResult: fd_json = io.StringIO() _mute_pyx12_logger() + walk_failure: str | None = None try: valid = bool(x12n_document(params, io.StringIO(text), fd_ack, None, None, fd_json)) except Exception as exc: # pyx12 raises bare Exception/EngineError on unwalkable input + walk_failure = type(exc).__name__ + # Raised out here, because pyx12's messages quote the interchange (a whole ISA, GS08, GE01): + # `from exc` puts that on __cause__, and `from None` still leaves it on __context__ (BACKLOG + # #5370, the pattern of json_loads_or_refusal, #2085). Only the class name is kept. + if walk_failure is not None: raise X12ValidationError( - "strict X12 validation could not run: the bytes are not a parseable X12 interchange" - ) from exc + "strict X12 validation could not run: the bytes are not a parseable X12 interchange " + f"({walk_failure})" + ) raw_json = fd_json.getvalue() if not raw_json.strip(): diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 1d0485e58b..8b3a0910a3 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -13,6 +13,7 @@ import io import logging import threading +import traceback from collections.abc import Callable, Iterator from typing import Any @@ -27,6 +28,8 @@ validate, ) from messagefoundry.parsing.x12._deps import load_x12_code_resolver # noqa: E402 +from messagefoundry.redaction import safe_traceback # noqa: E402 +from tests._content_free import assert_chain_severed # noqa: E402 _ISA = ( "ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER " @@ -589,16 +592,161 @@ def spy(self: Any, seg_data: Any) -> None: assert "20*6" not in caplog.text and "20*6" not in _rendered(result) -def test_an_unterminated_segment_past_pyx12s_limit_is_a_validation_error() -> None: +def test_an_unterminated_segment_past_pyx12s_limit_is_a_validation_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: # pyx12 4.1.0 can raise X12Error on a segment longer than about 1,040,000 characters, as it # does on this unterminated one; 4.0.1 could stop reading at a much shorter segment. The pass - # raises X12ValidationError, and neither its message nor the message of the pyx12 error it - # chains shows the segment's text. + # raises X12ValidationError, and neither its message nor the pyx12 error's message shows the + # segment's text. The pyx12 error is read from a spy, because it is no longer chained (#5370). import pyx12.errors + seen: list[Exception] = [] + monkeypatch.setattr(_X12_VALIDATE, "load_x12_validator", _spying_validator(seen)) body = "Q" * (1024 * 1024 + 100) with pytest.raises(X12ValidationError) as caught: validate(_ISA + _GS + "ST*837*0001*005010X222A1~BHT*0019*00*" + body) - cause = caught.value.__cause__ - assert isinstance(cause, pyx12.errors.X12Error) and "terminator" in str(cause) - assert "QQQQ" not in str(caught.value) and "QQQQ" not in str(cause) + assert len(seen) == 1 + assert isinstance(seen[0], pyx12.errors.X12Error) and "terminator" in str(seen[0]) + assert "QQQQ" not in str(caught.value) and "QQQQ" not in str(seen[0]) + assert_chain_severed(caught.value) + + +# --- BACKLOG #5370: no interchange text through the exception chain, the repr or a segment id. --- + +_PLANT = "PLANTEDNAME" +_PLANT_ISA02 = "AUTHPLANT1" +_PLANT_ISA04 = "SECPLANT22" +# 17 elements inside ISA's fixed 106 characters: ISA06 gives up padding for one more separator, so +# pyx12 finds its terminators, reads the segment, and refuses it with the whole segment quoted. +_ISA_17_ELEMENTS = ( + f"ISA*00*{_PLANT_ISA02}*00*{_PLANT_ISA04}*ZZ*SENDER*X *ZZ*RECEIVER " + "*060501*1200*U*00401*000000001*0*P*:~" +) +_TAIL_270 = "ST*270*0001~SE*2*0001~GE*1*1~IEA*1*000000001~" +# Each makes pyx12 raise an exception that quotes the planted values: X12Error, EngineError +# ("Map not found", which quotes GS08) and ValueError (int() of GE01). +_RAISING_INTERCHANGES = { + "isa17": (_ISA_17_ELEMENTS + _GS_270 + _TAIL_270, (_PLANT_ISA02, _PLANT_ISA04)), + "gs08": ( + _ISA_270 + "GS*HS*SENDERAPP*RECVAPP*20060501*1200*1*X*PLANTGS08~" + _TAIL_270, + ("PLANTGS08",), + ), + "ge01": ( + _ISA_270 + _GS_270 + "ST*270*0001~SE*2*0001~GE*PLANTGE01*1~IEA*1*000000001~", + ("PLANTGE01",), + ), +} + + +def _spying_validator(seen: list[Exception]) -> Callable[[], tuple[Any, Callable[[], Any]]]: + """A ``load_x12_validator`` whose walk records what pyx12 raised. The engine no longer chains it, + so this is how a test proves the fixture really made pyx12 quote the planted text.""" + from messagefoundry.parsing.x12._deps import load_x12_validator + + def load() -> tuple[Any, Callable[[], Any]]: + x12n_document, make_params = load_x12_validator() + + def spy(*args: Any) -> Any: + try: + return x12n_document(*args) + except Exception as exc: + seen.append(exc) + raise + + return spy, make_params + + return load + + +@pytest.mark.parametrize( + ("raw", "plants"), list(_RAISING_INTERCHANGES.values()), ids=list(_RAISING_INTERCHANGES) +) +def test_a_refused_interchange_chains_no_pyx12_text( + raw: str, plants: tuple[str, ...], monkeypatch: pytest.MonkeyPatch +) -> None: + seen: list[Exception] = [] + monkeypatch.setattr(_X12_VALIDATE, "load_x12_validator", _spying_validator(seen)) + with pytest.raises(X12ValidationError) as caught: + validate(raw) + + # Control: pyx12's own message holds the values, so their absence below is the engine's doing. + assert len(seen) == 1 + assert all(plant in str(seen[0]) for plant in plants) + + exc = caught.value + assert_chain_severed(exc) + for text in ( + safe_traceback((type(exc), exc, exc.__traceback__)), + "".join(traceback.format_exception(exc)), + ): + assert not any(plant in text for plant in plants) + # What is kept of the pyx12 error is its class name, so a refusal can still be told apart. + assert type(seen[0]).__name__ in str(exc) + + +def _270_with(segment: str) -> str: + """The conformant 270 with one extra segment ahead of the subscriber's NM1.""" + return _conformant_270().replace("NM1*IL*", f"{segment}NM1*IL*", 1) + + +def test_the_repr_of_a_result_leaves_out_the_ack_that_echoes_a_value() -> None: + result = validate(_270_with(f"NM1|IL|1|{_PLANT}|ROBERT~")) + assert result.ack is not None and _PLANT in result.ack # control: this ack echoes the value + assert _PLANT not in repr(result) + # Exact, so a field added to the result later has to be read for the same exposure. + assert repr(result) == ( + f"X12ValidationResult(valid=False, errors={result.errors!r}, " + f"ack_transaction={result.ack_transaction!r})" + ) + + +@pytest.mark.parametrize( + "segment", + [ + f"NM1|IL|1|{_PLANT}|ROBERT~", # the wrong element separator + f"NM1{_PLANT}~", # no separator after the id + f"{_PLANT}~", # the value alone + f"{_PLANT}*IL*1~", # a value where the id goes + ], +) +def test_a_wrongly_delimited_segment_puts_no_value_in_an_error(segment: str) -> None: + result = validate(_270_with(segment)) + assert result.valid is False + assert _PLANT not in repr(result) # holds every field of every error + # The violation is still reported and located, without the id it could not trust. + dropped = [e for e in result.errors if e.segment_id is None and e.line is not None] + assert dropped, "the bad segment must still be reported" + assert all(e.message.startswith("segment ?: error ") for e in dropped) + + +def test_a_well_delimited_unknown_segment_keeps_its_id() -> None: + result = validate(_270_with(f"ZZZ*{_PLANT}*ROBERT~")) + assert [e.message for e in result.errors if e.segment_id == "ZZZ"] == ["segment ZZZ: error 1"] + assert _PLANT not in _rendered(result) + + +@pytest.mark.parametrize( + ("seg_id", "kept"), + [ + ("NM1", "NM1"), + ("N1", "N1"), + ("ZZZ", "ZZZ"), + ("nm1", None), # lower case + ("A", None), # too short + ("NM1X", None), # too long + ("1NM", None), # pyx12's own check requires a leading letter + ("N1\n", None), # ``$`` would match before this newline + ("NM" + chr(0x661), None), # a non-ASCII digit + ("", None), + (None, None), + (7, None), + ], +) +def test_only_a_segment_id_shaped_value_is_kept(seg_id: Any, kept: str | None) -> None: + seg = {"seg_id": seg_id, "cur_line": 3, "name": "Subscriber Name"} + seg_err = _X12_VALIDATE._segment_error("1", seg, {}) + ele_err = _X12_VALIDATE._element_error("8", seg, {"ele_pos": 2, "name": "Date"}) + shown = kept or "?" + assert (seg_err.segment_id, seg_err.message) == (kept, f"segment {shown}: error 1") + assert (ele_err.segment_id, ele_err.message) == (kept, f"element {shown}02: error 8") From e5a2a7fe367716311f01c8a64708cc349a7c18ea Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 02:24:10 -0600 Subject: [PATCH 02/16] X12 validate docstrings state the segment id limit; add the changelog fragment BACKLOG #5370, review round one. The docstrings no longer call the error rows value-free or say a short sender value cannot be told from an id: the check reads shape alone, so such a value is kept even when it matches no map segment. The module docstring points at the class rather than listing its fields. Proposed PR title: X12 strict validate chains no pyx12 exception and keeps sender text out of its reprs (BACKLOG #5370) Proposed ledger banner: SHIPPED. The row's own finding and added items 1, 2 and 3 are settled as each closing text states. One residual is named on the PR: the required shape check keeps a two- or three-character sender value that stands where a segment id goes. --- changelog.d/5370.security.md | 7 +++++++ messagefoundry/parsing/x12/validate.py | 20 ++++++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-) create mode 100644 changelog.d/5370.security.md diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md new file mode 100644 index 0000000000..3fad1b14c8 --- /dev/null +++ b/changelog.d/5370.security.md @@ -0,0 +1,7 @@ +- **Strict X12 validation keeps more interchange text out of tracebacks and logs.** A refusal no + longer chains the pyx12 exception, whose message can quote a whole ISA, so a traceback would have + carried ISA02 and ISA04 on a deploying site. `X12ValidationError` now names only the exception's + class. `X12ValidationResult`'s repr leaves out `ack`, which echoes sender values. + `X12SegmentError.segment_id` is `None` unless the value is shaped like an X12 segment id, so a + wrongly delimited segment no longer lands in `segment_id` or `message`. A two- or three-character + sender value of that shape is still kept. (`BACKLOG #5370`) diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index dbefa3d565..3073e7ab00 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -23,12 +23,11 @@ **PHI rule (do not break).** A failing X12 element error from pyx12 embeds the *offending data value* (potential PHI) in its raw error string, and an exception pyx12 raises can quote the interchange. This -module does not surface either: each :class:`X12SegmentError` carries only structural locators — the -error code, a segment id only when it has a segment id's shape (:class:`X12SegmentError` states what a -shape cannot rule out), the element position, a schema-label *type name*, and the line — and a refusal -chains no pyx12 exception. The ack does echo sender values, so it is left out of the result's repr. The -full interchange goes only to the secured store (CLAUDE.md §9). The pyx12 logger tree (which logs the -raw, value-bearing strings at ERROR) is muted from the first validation pass on, and never unmuted. +module surfaces neither: an :class:`X12SegmentError` holds structural locators (its docstring names +them, and the one limit on its segment id), and a refusal chains no pyx12 exception. The ack does echo +sender values, so it is left out of the result's repr. The full interchange goes only to the secured +store (CLAUDE.md §9). The pyx12 logger tree (which logs the raw, value-bearing strings at ERROR) is +muted from the first validation pass on, and never unmuted. Pure: no I/O to disk/network, no engine imports. ``pyx12``'s sole runtime dependency is ``defusedxml`` (already in tree), used to parse its bundled, trusted map XML — not attacker input. @@ -62,8 +61,9 @@ class X12SegmentError: ``element_name`` is the *schema* data-element label (e.g. ``"Transaction Set Creation Date"``). ``segment_id`` comes from the input, so it is kept only when shaped like an X12 segment id (a - capital, then one or two capitals or digits) and is ``None`` otherwise (BACKLOG #5370). A sender - value of that exact shape, standing where the id goes, cannot be told from an id and is kept.""" + capital, then one or two capitals or digits) and is ``None`` otherwise (BACKLOG #5370). The check + reads shape alone, so a two- or three-character sender value of that shape standing where the id + goes is kept, in ``segment_id`` and in ``message``, even when it matches no segment in the map.""" code: str message: str @@ -107,8 +107,8 @@ def _mute_pyx12_logger() -> None: """Mute the whole ``pyx12`` logger tree, and never unmute it (BACKLOG #1603). pyx12 logs each violation's *raw* error string, which embeds the offending data value (potential - PHI), at ERROR from child loggers such as ``pyx12.error_handler``. We build our own value-free - errors from pyx12's structured JSON instead, so nothing pyx12 logs is wanted anywhere. + PHI), at ERROR from child loggers such as ``pyx12.error_handler``. We build our own errors from + pyx12's structured JSON instead, so nothing pyx12 logs is wanted anywhere. **No restore step, on purpose.** The old context manager raised the level for one pass and put the previous level back afterwards. Two overlapping passes on two threads would interleave: the From 2ca19a7272ec0e202538f57c96355d758d5ef172 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 02:42:08 -0600 Subject: [PATCH 03/16] X12 validate docstrings state what loop and the id pattern really do BACKLOG #5370, review round two. For a segment that matched no map node, loop names the last node matched. The id pattern is pyx12's, matched more strictly. A terminator inside a name can put the name's tail where the id goes. The test module header no longer says no value appears. Proposed PR title: X12 strict validate chains no pyx12 exception and keeps sender text out of its reprs (BACKLOG #5370) Proposed ledger banner: SHIPPED. The row's own finding and added items 1, 2 and 3 are settled as each closing text states. One residual is named on the PR: the required shape check keeps a two- or three-character sender value that stands where a segment id goes. --- messagefoundry/parsing/x12/validate.py | 10 ++++++---- tests/test_x12_validate.py | 3 ++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index 3073e7ab00..e5f170f522 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -57,13 +57,15 @@ class X12SegmentError: the 997 AK list for 004010, also when no ack is generated, and the 999 IK list otherwise (e.g. ``"8"``). pyx12's own error name stands in where that list has no code for it; ``message`` is synthesized from the code and the locators below; - ``element_position`` / ``line`` are numbers and ``loop`` is the *schema* name of the map node; + ``element_position`` / ``line`` are numbers; ``loop`` is the *schema* name of the map node the + walk was at, which for a segment that matched no node is the last node it did match; ``element_name`` is the *schema* data-element label (e.g. ``"Transaction Set Creation Date"``). ``segment_id`` comes from the input, so it is kept only when shaped like an X12 segment id (a capital, then one or two capitals or digits) and is ``None`` otherwise (BACKLOG #5370). The check reads shape alone, so a two- or three-character sender value of that shape standing where the id - goes is kept, in ``segment_id`` and in ``message``, even when it matches no segment in the map.""" + goes is kept, in ``segment_id`` and in ``message``, even when it matches no segment in the map. + A terminator inside a name can put the name's tail there, with ``loop`` naming the field before.""" code: str message: str @@ -191,8 +193,8 @@ def _structural_segment_id(seg: dict[str, Any]) -> str | None: """pyx12's ``seg_id`` when it is shaped like an X12 segment id, otherwise ``None``. pyx12 takes everything before the first element separator as the id, so a wrongly delimited - segment (``NM1|IL|1|DOE|ROBERT``) puts the sender's whole segment there. The shape is the one - pyx12's own id check applies, and every segment id in its bundled maps has it.""" + segment (``NM1|IL|1|DOE|ROBERT``) puts the sender's whole segment there. The pattern is pyx12's + own, matched more strictly (:data:`_SEGMENT_ID`), and every segment id in its bundled maps has it.""" seg_id = seg.get("seg_id") return seg_id if isinstance(seg_id, str) and _SEGMENT_ID.fullmatch(seg_id) else None diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 8b3a0910a3..93972e9f45 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -5,7 +5,8 @@ Covers: a clean interchange validates; a conformance-violating interchange reports structural errors + emits a 999 ack; non-X12 input raises X12ValidationError (not a generic crash); and the PHI guard — -the offending data *value* never appears in the surfaced errors (only schema-label locators).""" +an offending element *value* does not appear in the surfaced errors, and a segment id is kept only +when shaped like one, so a two- or three-character sender value of that shape is the one exception.""" from __future__ import annotations From 4b56f6e3d121b45ef515c22aa1d37d139af39850 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 03:22:10 -0600 Subject: [PATCH 04/16] X12 errors keep a segment id only when an indexed pyx12 map defines it The shape check alone kept sender text: NM1*IL*1*O~LEE*A*B~, KIM~ and XYZ*A~ each put it in segment_id and message on pyx12 4.1.0. An id must now have the shape AND be defined by a map that pyx12's bundled maps.xml lists. The set is read once, under a lock, from the map files, and any read failure or empty set keeps no id. This tightens the check. The row's closing (b), "only when shaped like", is a necessary condition this stricter test still meets. So the old test that an unknown well-delimited id is kept now expects "?". The index is used rather than every bundled file because comp_test.xml, which pyx12 cannot select, is the only source of TST and UNU. A sender value equal to a real id (LIN) is still kept. Docstrings now say so and drop claims that were false or falsely complete. BACKLOG #5370 --- changelog.d/5370.security.md | 7 +- messagefoundry/parsing/x12/_deps.py | 56 ++++++++++++++- messagefoundry/parsing/x12/validate.py | 61 ++++++++++------ tests/test_x12_validate.py | 98 ++++++++++++++++++++++++-- 4 files changed, 189 insertions(+), 33 deletions(-) diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md index 3fad1b14c8..70a68e07a7 100644 --- a/changelog.d/5370.security.md +++ b/changelog.d/5370.security.md @@ -2,6 +2,7 @@ longer chains the pyx12 exception, whose message can quote a whole ISA, so a traceback would have carried ISA02 and ISA04 on a deploying site. `X12ValidationError` now names only the exception's class. `X12ValidationResult`'s repr leaves out `ack`, which echoes sender values. - `X12SegmentError.segment_id` is `None` unless the value is shaped like an X12 segment id, so a - wrongly delimited segment no longer lands in `segment_id` or `message`. A two- or three-character - sender value of that shape is still kept. (`BACKLOG #5370`) + `X12SegmentError.segment_id` is `None` unless the value has an X12 segment id's shape and a map + in pyx12's bundled index defines it, so a wrongly delimited segment, or a name's tail standing + where the id goes, no longer lands in `segment_id` or `message`. A sender value equal to such an + id, for example `LIN`, is still kept. (`BACKLOG #5370`) diff --git a/messagefoundry/parsing/x12/_deps.py b/messagefoundry/parsing/x12/_deps.py index 1bc9965091..82122d6f10 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -18,8 +18,21 @@ from __future__ import annotations +import functools +import logging +import threading from collections.abc import Callable -from typing import Any +from importlib.resources import files +from typing import TYPE_CHECKING, Any + +from messagefoundry._vendor.defusedxml.common import DefusedXmlException +from messagefoundry._vendor.defusedxml.ElementTree import ParseError, parse + +if TYPE_CHECKING: + from importlib.resources.abc import Traversable + +_log = logging.getLogger(__name__) +_MAP_IDS_LOCK = threading.Lock() def _missing_extra(feature: str) -> RuntimeError: @@ -44,6 +57,47 @@ def load_x12_validator() -> tuple[Any, Any]: return pyx12.x12n_document.x12n_document, pyx12.params.params +def _read_map_segment_ids(map_dir: Traversable) -> frozenset[str]: + """The ``xid`` of every ```` in the maps that ``maps.xml`` under ``map_dir`` lists. + + pyx12 selects its maps from that index, so a bundled file it omits (``comp_test.xml``, the only + source of ``TST`` and ``UNU``) adds no id. All or nothing: an index or listed map that cannot be + read or parsed, or a set with no id, gives the empty set, so a caller keeps no id rather than + trusting the shape alone.""" + ids: set[str] = set() + try: + with map_dir.joinpath("maps.xml").open("rb") as fd: + map_files = {name for m in parse(fd).iter("map") if (name := (m.text or "").strip())} + for map_file in map_files: + with map_dir.joinpath(map_file).open("rb") as fd: + ids.update(xid for seg in parse(fd).iter("segment") if (xid := seg.get("xid"))) + except (OSError, ParseError, DefusedXmlException) as exc: + _log.warning( + "pyx12's maps could not be read (%s); X12 errors will carry no segment id", + type(exc).__name__, + ) + return frozenset() + if not ids: + _log.warning("pyx12's maps define no segment; X12 errors will carry no segment id") + return frozenset(ids) + + +@functools.cache +def _bundled_map_segment_ids() -> frozenset[str]: + return _read_map_segment_ids(files("pyx12").joinpath("map")) + + +def load_x12_map_segment_ids() -> frozenset[str]: + """Every segment id the maps in pyx12's bundled index define, read once, on first use. + + ``validate()`` passes pyx12 no map path, so pyx12 selects from this same index. The read takes + a noticeable fraction of a second, so it runs only when a violation has an id-shaped value to + check. The lock is there because ``functools.cache`` alone lets each thread that misses at once + repeat the read.""" + with _MAP_IDS_LOCK: + return _bundled_map_segment_ids() + + def load_x12_code_resolver() -> Callable[..., str | None]: """Return a resolver over ``pyx12.error_codes``, or a clear :class:`RuntimeError` if the ``[x12]`` extra is absent or older than pyx12 4.0.1, which added that module. diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index e5f170f522..94b5f7ddb8 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -22,15 +22,16 @@ well-formed; see :class:`X12ValidationResult`. **PHI rule (do not break).** A failing X12 element error from pyx12 embeds the *offending data value* -(potential PHI) in its raw error string, and an exception pyx12 raises can quote the interchange. This -module surfaces neither: an :class:`X12SegmentError` holds structural locators (its docstring names -them, and the one limit on its segment id), and a refusal chains no pyx12 exception. The ack does echo -sender values, so it is left out of the result's repr. The full interchange goes only to the secured -store (CLAUDE.md §9). The pyx12 logger tree (which logs the raw, value-bearing strings at ERROR) is -muted from the first validation pass on, and never unmuted. - -Pure: no I/O to disk/network, no engine imports. ``pyx12``'s sole runtime dependency is ``defusedxml`` -(already in tree), used to parse its bundled, trusted map XML — not attacker input. +(potential PHI) in its raw error string, and an exception pyx12 raises can quote the interchange. An +:class:`X12SegmentError` drops those strings and holds structural locators (its docstring names them, +and a limit on its segment id), and a refusal chains no pyx12 exception. The ack does echo sender +values, so it is left out of the result's repr. The full interchange goes only to the secured store +(CLAUDE.md §9). The pyx12 logger tree (which logs the raw, value-bearing strings at ERROR) is muted +from the first validation pass on, and never unmuted. + +No network I/O and no engine imports. Disk reads include pyx12's bundled map XML, by pyx12 and by +the segment id check. ``pyx12``'s sole runtime dependency is ``defusedxml`` (already in tree), used +to parse that bundled, trusted XML — not attacker input. """ from __future__ import annotations @@ -42,7 +43,11 @@ from dataclasses import dataclass, field from typing import Any -from messagefoundry.parsing.x12._deps import load_x12_code_resolver, load_x12_validator +from messagefoundry.parsing.x12._deps import ( + load_x12_code_resolver, + load_x12_map_segment_ids, + load_x12_validator, +) from messagefoundry.parsing.x12.errors import X12ValidationError from messagefoundry.redaction import json_loads_or_refusal @@ -61,11 +66,11 @@ class X12SegmentError: walk was at, which for a segment that matched no node is the last node it did match; ``element_name`` is the *schema* data-element label (e.g. ``"Transaction Set Creation Date"``). - ``segment_id`` comes from the input, so it is kept only when shaped like an X12 segment id (a - capital, then one or two capitals or digits) and is ``None`` otherwise (BACKLOG #5370). The check - reads shape alone, so a two- or three-character sender value of that shape standing where the id - goes is kept, in ``segment_id`` and in ``message``, even when it matches no segment in the map. - A terminator inside a name can put the name's tail there, with ``loop`` naming the field before.""" + ``segment_id`` comes from the input, so it is kept only when it has an X12 segment id's shape (a + capital, then one or two capitals or digits) and a map in pyx12's bundled index defines it, and + is ``None`` otherwise (BACKLOG #5370). A sender value equal to such an id, for example the surname + ``LIN``, standing where the id goes is still kept, in ``segment_id`` and in ``message``. A + terminator inside a name can put the name's tail there, with ``loop`` naming the field before.""" code: str message: str @@ -190,13 +195,22 @@ def _last_group_version(report: dict[str, Any]) -> str: def _structural_segment_id(seg: dict[str, Any]) -> str | None: - """pyx12's ``seg_id`` when it is shaped like an X12 segment id, otherwise ``None``. + """pyx12's ``seg_id`` when it has an X12 segment id's shape and a map in pyx12's bundled index + defines it, otherwise ``None``. pyx12 takes everything before the first element separator as the id, so a wrongly delimited - segment (``NM1|IL|1|DOE|ROBERT``) puts the sender's whole segment there. The pattern is pyx12's - own, matched more strictly (:data:`_SEGMENT_ID`), and every segment id in its bundled maps has it.""" + segment (``NM1|IL|1|DOE|ROBERT``) puts the sender's whole segment there, and a terminator inside + a name (``NM1*IL*1*O~LEE*A*B~``) puts the name's tail there, in an id's shape. The error code + cannot tell those apart: pyx12 emits code 1 for sender text and for a real id in the wrong place. + The shape is checked first, so text without it never makes this read the maps.""" seg_id = seg.get("seg_id") - return seg_id if isinstance(seg_id, str) and _SEGMENT_ID.fullmatch(seg_id) else None + if ( + isinstance(seg_id, str) + and _SEGMENT_ID.fullmatch(seg_id) + and seg_id in load_x12_map_segment_ids() + ): + return seg_id + return None def _segment_error(code: str, seg: dict[str, Any], err: dict[str, Any]) -> X12SegmentError: @@ -284,10 +298,11 @@ def validate(raw: str | bytes) -> X12ValidationResult: :meth:`X12Message.parse`). Returns an :class:`X12ValidationResult` carrying the conformance verdict, the structural error list, and the generated 997/999 acknowledgment. - Raises :class:`~messagefoundry.parsing.x12.errors.X12ValidationError` only when no validation pass - could run at all (e.g. the bytes are not a parseable X12 data file — there is no envelope to walk). - It chains no pyx12 exception. A *failed* validation of a parseable interchange is returned as data - (``valid=False``), not raised, so a Handler can still emit the negative ack. Raises + Raises :class:`~messagefoundry.parsing.x12.errors.X12ValidationError` when pyx12 could not finish + a pass: at least when the bytes are not a parseable X12 data file, and when pyx12 raises partway + through a walk, as a non-numeric GE01 makes it do. It chains no pyx12 exception. A pass that + finishes with violations is returned as data (``valid=False``), not raised, so a Handler can still + emit the negative ack. Raises :class:`RuntimeError` if the ``[x12]`` extra is absent (a deploy/config error, distinct from the ``ValueError``-rooted data errors).""" if isinstance(raw, (bytes, bytearray)): # noqa: SIM108 diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 93972e9f45..707e48b86c 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -6,7 +6,7 @@ Covers: a clean interchange validates; a conformance-violating interchange reports structural errors + emits a 999 ack; non-X12 input raises X12ValidationError (not a generic crash); and the PHI guard — an offending element *value* does not appear in the surfaced errors, and a segment id is kept only -when shaped like one, so a two- or three-character sender value of that shape is the one exception.""" +when pyx12's bundled maps define it. A sender value equal to a real id (``LIN``) is still kept.""" from __future__ import annotations @@ -16,6 +16,7 @@ import threading import traceback from collections.abc import Callable, Iterator +from pathlib import Path from typing import Any import pytest @@ -28,7 +29,11 @@ X12ValidationResult, validate, ) -from messagefoundry.parsing.x12._deps import load_x12_code_resolver # noqa: E402 +from messagefoundry.parsing.x12._deps import ( # noqa: E402 + _read_map_segment_ids, + load_x12_code_resolver, + load_x12_map_segment_ids, +) from messagefoundry.redaction import safe_traceback # noqa: E402 from tests._content_free import assert_chain_severed # noqa: E402 @@ -721,18 +726,99 @@ def test_a_wrongly_delimited_segment_puts_no_value_in_an_error(segment: str) -> assert all(e.message.startswith("segment ?: error ") for e in dropped) -def test_a_well_delimited_unknown_segment_keeps_its_id() -> None: +def test_a_well_delimited_unknown_segment_shows_no_id() -> None: result = validate(_270_with(f"ZZZ*{_PLANT}*ROBERT~")) - assert [e.message for e in result.errors if e.segment_id == "ZZZ"] == ["segment ZZZ: error 1"] + assert "ZZZ" not in {e.segment_id for e in result.errors} + assert "segment ?: error 1" in [e.message for e in result.errors] assert _PLANT not in _rendered(result) +@pytest.mark.parametrize("template", ["NM1*IL*1*O~{}*A*B~", "{}~", "{}*A~"]) +@pytest.mark.parametrize("name", ["LEE", "KIM", "WU", "NG", "ZZZ", "DOE"]) +def test_sender_text_shaped_like_an_id_is_not_kept( + name: str, template: str, monkeypatch: pytest.MonkeyPatch +) -> None: + raw = _270_with(template.format(name)) + # Control: with the name in the map set it is kept, so pyx12 really put it where the id goes. + with monkeypatch.context() as patched: + patched.setattr(_X12_VALIDATE, "load_x12_map_segment_ids", lambda: frozenset({name})) + assert name in {e.segment_id for e in validate(raw).errors} + + errors = validate(raw).errors + assert name not in {e.segment_id for e in errors} + assert not any(e.message.startswith((f"segment {name}:", f"element {name}")) for e in errors) + assert any(e.message.startswith("segment ?: error ") for e in errors) + + +def test_a_sender_value_equal_to_a_real_id_is_still_kept() -> None: + # The known limit: LIN is a segment the maps define, so nothing tells this value from that id. + assert "LIN" in {e.segment_id for e in validate(_270_with("LIN*A~")).errors} + + +def test_no_id_is_kept_when_the_map_set_is_empty(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(_X12_VALIDATE, "load_x12_map_segment_ids", frozenset) + assert _X12_VALIDATE._structural_segment_id({"seg_id": "NM1"}) is None + + +def test_the_bundled_index_gives_real_ids_of_the_id_shape() -> None: + ids = load_x12_map_segment_ids() + assert {"ISA", "GS", "ST", "NM1", "N1", "SE", "GE", "IEA"} <= ids + assert all(_X12_VALIDATE._SEGMENT_ID.fullmatch(seg_id) for seg_id in ids) + + +_MAP_INDEX = "a.xmlb.xml" + + +def test_the_map_reader_reads_only_the_maps_the_index_lists(tmp_path: Path) -> None: + (tmp_path / "maps.xml").write_text(_MAP_INDEX, encoding="utf-8") + (tmp_path / "a.xml").write_text("", encoding="utf-8") + (tmp_path / "b.xml").write_text("", "utf-8") + (tmp_path / "unlisted.xml").write_text("", encoding="utf-8") + assert _read_map_segment_ids(tmp_path) == {"NM1", "N1"} + + +@pytest.mark.parametrize( + "contents", + [ + None, + {}, + {"maps.xml": ""}, + {"maps.xml": ""}, + {"maps.xml": _MAP_INDEX, "a.xml": "", "b.xml": "", "b.xml": ""}, + ], + ids=[ + "no-directory", + "no-index", + "empty-index", + "unparseable-index", + "listed-map-missing", + "listed-map-unparseable", + "no-segment", + ], +) +def test_maps_that_cannot_be_read_give_no_ids( + contents: dict[str, str] | None, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + map_dir = tmp_path / "map" + if contents is not None: + map_dir.mkdir() + for name, text in contents.items(): + (map_dir / name).write_text(text, encoding="utf-8") + with caplog.at_level(logging.WARNING): + assert _read_map_segment_ids(map_dir) == frozenset() + assert "no segment id" in caplog.text + + @pytest.mark.parametrize( ("seg_id", "kept"), [ ("NM1", "NM1"), ("N1", "N1"), - ("ZZZ", "ZZZ"), + ("ZZZ", None), # the shape of an id, but no map defines it + ("TST", None), # only in comp_test.xml, which pyx12's index does not list + ("UNU", None), # likewise ("nm1", None), # lower case ("A", None), # too short ("NM1X", None), # too long @@ -744,7 +830,7 @@ def test_a_well_delimited_unknown_segment_keeps_its_id() -> None: (7, None), ], ) -def test_only_a_segment_id_shaped_value_is_kept(seg_id: Any, kept: str | None) -> None: +def test_only_a_segment_id_the_maps_define_is_kept(seg_id: Any, kept: str | None) -> None: seg = {"seg_id": seg_id, "cur_line": 3, "name": "Subscriber Name"} seg_err = _X12_VALIDATE._segment_error("1", seg, {}) ele_err = _X12_VALIDATE._element_error("8", seg, {"ele_pos": 2, "name": "Date"}) From e3aaf20da84df85822f5779805b5e5129461c2fe Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 03:24:11 -0600 Subject: [PATCH 05/16] pyx12 4.1.0 changelog no longer says X12ValidationError chains the error This branch stops the chain, so the fragment's claim that the engine's error "chains that error as its cause" would be false on merge. It now says the error is not chained and only its class name is kept. Net prose lines: 0. BACKLOG #5370 --- changelog.d/pyx12-4-1-0.security.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/changelog.d/pyx12-4-1-0.security.md b/changelog.d/pyx12-4-1-0.security.md index 5b79500a7a..9a5b5cbca6 100644 --- a/changelog.d/pyx12-4-1-0.security.md +++ b/changelog.d/pyx12-4-1-0.security.md @@ -8,10 +8,10 @@ 4.1.0 does not close either class. At least these remain: a 997 copies the sender's ISA11 as-is; a 997 splits an `*` in an echoed GS06 into extra AK1 elements, and both writers split one in an echoed segment ID; and an error pyx12 raises can quote input, a whole ISA segment included. The - engine's `X12ValidationError` chains that error as its cause, so a traceback of it can carry - those values. The engine's own guards are narrower than that. Among them, it reads the ack type - from pyx12's report rather than the ack text, returns no ack whose last write was not its IEA, - and mutes the `pyx12` logger tree. + engine's `X12ValidationError` does not chain that error and keeps only its class name. The + engine's other guards are narrower. Among them, it reads the ack type from pyx12's report rather + than the ack text, returns no ack whose last write was not its IEA, and mutes the `pyx12` logger + tree. - **Long X12 segments read differently.** pyx12 4.0.1 could stop reading at a segment longer than about 8K characters. `validate()` then returned `valid=False` with interchange error `023` among its errors, and that segment and everything after it went unvalidated. 4.1.0 reads much longer From 1ccf61f6c15daf90fae0303ff283ab70b66fbb10 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 03:40:42 -0600 Subject: [PATCH 06/16] X12 segment id set retries a failed read and states its real limit Review repairs on the id check: - An empty read is no longer cached for the process. It is retried at most once a minute, so a passing fault cannot remove every id. - A good read is returned without taking the lock. - An unknown or multi-byte XML encoding declaration now fails closed. - The limit is stated correctly: the set is the union of the indexed maps, so LIN is kept even in a 270, whose map does not define it. - X12ValidationError's docstring no longer says no pass could run. Net prose lines: +6. BACKLOG #5370 Proposed PR title: X12 strict validate chains no pyx12 exception and keeps sender text out of its reprs (BACKLOG #5370) Proposed banner: SHIPPED. X12ValidationError chains no pyx12 exception; the result's repr omits ack; segment_id needs the id shape and a map in pyx12's index. Stays open: (1) a sender value equal to any id in the union of those maps (LIN, PAT, LE) is still kept; (2) asdict(result) still carries ack; (3) the refusal text blames the input for EngineError and resource errors; (4) validate(RawMessage(...)); (5) the X12Error class-name wording; (6) the third _SEGMENT_ID copy; (7) X12Message.add_segment. #8164, #6119 and #7068 are untouched. --- changelog.d/5370.security.md | 5 +++-- messagefoundry/parsing/x12/_deps.py | 31 ++++++++++++++++---------- messagefoundry/parsing/x12/errors.py | 11 ++++----- messagefoundry/parsing/x12/validate.py | 7 +++--- tests/test_x12_validate.py | 31 +++++++++++++++++++++++++- 5 files changed, 62 insertions(+), 23 deletions(-) diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md index 70a68e07a7..bc4d20d3c4 100644 --- a/changelog.d/5370.security.md +++ b/changelog.d/5370.security.md @@ -4,5 +4,6 @@ class. `X12ValidationResult`'s repr leaves out `ack`, which echoes sender values. `X12SegmentError.segment_id` is `None` unless the value has an X12 segment id's shape and a map in pyx12's bundled index defines it, so a wrongly delimited segment, or a name's tail standing - where the id goes, no longer lands in `segment_id` or `message`. A sender value equal to such an - id, for example `LIN`, is still kept. (`BACKLOG #5370`) + where the id goes, no longer lands in `segment_id` or `message`. A sender value equal to any id + in those maps, for example `LIN`, is still kept, even in a transaction whose own map does not + define it. (`BACKLOG #5370`) diff --git a/messagefoundry/parsing/x12/_deps.py b/messagefoundry/parsing/x12/_deps.py index 82122d6f10..6872521830 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -18,14 +18,13 @@ from __future__ import annotations -import functools import logging import threading +import time from collections.abc import Callable from importlib.resources import files from typing import TYPE_CHECKING, Any -from messagefoundry._vendor.defusedxml.common import DefusedXmlException from messagefoundry._vendor.defusedxml.ElementTree import ParseError, parse if TYPE_CHECKING: @@ -33,6 +32,9 @@ _log = logging.getLogger(__name__) _MAP_IDS_LOCK = threading.Lock() +_MAP_IDS_RETRY_SECONDS = 60.0 +_map_ids: frozenset[str] = frozenset() +_map_ids_retry_at = 0.0 def _missing_extra(feature: str) -> RuntimeError: @@ -71,7 +73,9 @@ def _read_map_segment_ids(map_dir: Traversable) -> frozenset[str]: for map_file in map_files: with map_dir.joinpath(map_file).open("rb") as fd: ids.update(xid for seg in parse(fd).iter("segment") if (xid := seg.get("xid"))) - except (OSError, ParseError, DefusedXmlException) as exc: + # ValueError covers defusedxml's refusals and a multi-byte encoding declaration; LookupError an + # unknown one. + except (OSError, ParseError, ValueError, LookupError) as exc: _log.warning( "pyx12's maps could not be read (%s); X12 errors will carry no segment id", type(exc).__name__, @@ -82,20 +86,23 @@ def _read_map_segment_ids(map_dir: Traversable) -> frozenset[str]: return frozenset(ids) -@functools.cache -def _bundled_map_segment_ids() -> frozenset[str]: - return _read_map_segment_ids(files("pyx12").joinpath("map")) - - def load_x12_map_segment_ids() -> frozenset[str]: - """Every segment id the maps in pyx12's bundled index define, read once, on first use. + """Every segment id the maps in pyx12's bundled index define, read on first use. ``validate()`` passes pyx12 no map path, so pyx12 selects from this same index. The read takes a noticeable fraction of a second, so it runs only when a violation has an id-shaped value to - check. The lock is there because ``functools.cache`` alone lets each thread that misses at once - repeat the read.""" + check, and the lock keeps threads that miss together to one read. A good read is kept for the + process. An empty one is not, so a passing fault cannot remove every id until a restart; it is + retried at most once per :data:`_MAP_IDS_RETRY_SECONDS`, and until then no id is kept.""" + global _map_ids, _map_ids_retry_at + if _map_ids: + return _map_ids with _MAP_IDS_LOCK: - return _bundled_map_segment_ids() + if not _map_ids and time.monotonic() >= _map_ids_retry_at: + _map_ids = _read_map_segment_ids(files("pyx12").joinpath("map")) + if not _map_ids: + _map_ids_retry_at = time.monotonic() + _MAP_IDS_RETRY_SECONDS + return _map_ids def load_x12_code_resolver() -> Callable[..., str | None]: diff --git a/messagefoundry/parsing/x12/errors.py b/messagefoundry/parsing/x12/errors.py index 3edbbf5cab..93f2486c68 100644 --- a/messagefoundry/parsing/x12/errors.py +++ b/messagefoundry/parsing/x12/errors.py @@ -31,11 +31,12 @@ class X12FrameError(X12Error): class X12ValidationError(X12Error): - """The opt-in strict validator (``pyx12``, ADR 0012) could not run a structural validation pass at - all — e.g. the bytes are not a parseable X12 data file, so there is no envelope to walk. The X12 - analog of :class:`~messagefoundry.parsing.fhir.errors.FhirValidationError`. A *failed validation* - (a parseable interchange that violates its implementation guide) is **not** this — it is reported - as data on :class:`~messagefoundry.parsing.x12.validate.X12ValidationResult` (``valid=False`` + + """The opt-in strict validator (``pyx12``, ADR 0012) could not finish a structural validation + pass: at least when the bytes are not a parseable X12 data file, and when pyx12 raises partway + through a walk, as a non-numeric GE01 makes it do. The X12 analog of + :class:`~messagefoundry.parsing.fhir.errors.FhirValidationError`. A *failed validation* (a pass + that finishes with violations of the implementation guide) is **not** this — it is reported as + data on :class:`~messagefoundry.parsing.x12.validate.X12ValidationResult` (``valid=False`` + structural :class:`~messagefoundry.parsing.x12.validate.X12SegmentError` items + a 997/999 ack), so a Handler can route the *message* to the error path while still emitting the negative ack (the ack is ``None`` if pyx12 did not complete it). Its message is **PHI-safe**: it names only the failure diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index 94b5f7ddb8..5d54f9c3a6 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -68,9 +68,10 @@ class X12SegmentError: ``segment_id`` comes from the input, so it is kept only when it has an X12 segment id's shape (a capital, then one or two capitals or digits) and a map in pyx12's bundled index defines it, and - is ``None`` otherwise (BACKLOG #5370). A sender value equal to such an id, for example the surname - ``LIN``, standing where the id goes is still kept, in ``segment_id`` and in ``message``. A - terminator inside a name can put the name's tail there, with ``loop`` naming the field before.""" + is ``None`` otherwise (BACKLOG #5370). The set is the union of those maps, so a sender value equal + to any id in it, for example the surname ``LIN``, standing where the id goes is still kept, in + ``segment_id`` and in ``message``, even in a transaction whose own map does not define that id. + A terminator inside a name can put the name's tail there, with ``loop`` naming the field before.""" code: str message: str diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 707e48b86c..01db112d33 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -751,7 +751,8 @@ def test_sender_text_shaped_like_an_id_is_not_kept( def test_a_sender_value_equal_to_a_real_id_is_still_kept() -> None: - # The known limit: LIN is a segment the maps define, so nothing tells this value from that id. + # The known limit: the set is the union of every indexed map, so LIN is kept here although the + # 270's own map does not define it. assert "LIN" in {e.segment_id for e in validate(_270_with("LIN*A~")).errors} @@ -766,6 +767,30 @@ def test_the_bundled_index_gives_real_ids_of_the_id_shape() -> None: assert all(_X12_VALIDATE._SEGMENT_ID.fullmatch(seg_id) for seg_id in ids) +def test_a_failed_map_read_is_not_kept_and_is_retried_after_a_pause( + monkeypatch: pytest.MonkeyPatch, +) -> None: + deps = importlib.import_module("messagefoundry.parsing.x12._deps") + results = iter([frozenset[str](), frozenset({"NM1"})]) + reads: list[object] = [] + + def read(map_dir: object) -> frozenset[str]: + reads.append(map_dir) + return next(results) + + monkeypatch.setattr(deps, "_read_map_segment_ids", read) + monkeypatch.setattr(deps, "_map_ids", frozenset()) + monkeypatch.setattr(deps, "_map_ids_retry_at", 0.0) + assert load_x12_map_segment_ids() == frozenset() + assert load_x12_map_segment_ids() == frozenset() # inside the pause: no second read + assert len(reads) == 1 + + monkeypatch.setattr(deps, "_map_ids_retry_at", 0.0) # the pause is over + assert load_x12_map_segment_ids() == {"NM1"} + assert load_x12_map_segment_ids() == {"NM1"} # a good read is kept + assert len(reads) == 2 + + _MAP_INDEX = "a.xmlb.xml" @@ -787,6 +812,8 @@ def test_the_map_reader_reads_only_the_maps_the_index_lists(tmp_path: Path) -> N {"maps.xml": _MAP_INDEX, "a.xml": ""}, {"maps.xml": _MAP_INDEX, "a.xml": "", "b.xml": "", "b.xml": ""}, + {"maps.xml": ""}, # LookupError + {"maps.xml": ""}, # plain ValueError ], ids=[ "no-directory", @@ -796,6 +823,8 @@ def test_the_map_reader_reads_only_the_maps_the_index_lists(tmp_path: Path) -> N "listed-map-missing", "listed-map-unparseable", "no-segment", + "unknown-encoding", + "multibyte-encoding", ], ) def test_maps_that_cannot_be_read_give_no_ids( From f09f820c297f7c517e31cf5a6a0807cc24e2023b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 04:17:40 -0600 Subject: [PATCH 07/16] X12 validate prose states its real limits; retry test needs the deadline BACKLOG #5370. Comments, docstrings, changelog text and one test. No production code changes. Proposed PR title: X12 strict validate chains no pyx12 exception and keeps sender text out of its reprs (BACKLOG #5370) Proposed banner: PARTIAL. The chain, the ack repr and the segment id check are built. Open: a sender value equal to any indexed id is still kept (scoping the set to the group's map); dataclasses.asdict carries ack; the refusal wording for EngineError; a checked-in id set; validate(RawMessage(...)); the third _SEGMENT_ID copy; X12Message.add_segment; ADR 0012 and three docs still call the whole codec pure. #8164, #6119 and #7068 stay open on their own rows. --- changelog.d/5370.security.md | 12 +++++------ messagefoundry/parsing/x12/__init__.py | 18 +++++++++------- messagefoundry/parsing/x12/_deps.py | 4 +++- messagefoundry/parsing/x12/errors.py | 3 ++- messagefoundry/parsing/x12/validate.py | 29 +++++++++++++++----------- tests/test_x12_validate.py | 12 ++++++++++- 6 files changed, 50 insertions(+), 28 deletions(-) diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md index bc4d20d3c4..f2450618b3 100644 --- a/changelog.d/5370.security.md +++ b/changelog.d/5370.security.md @@ -1,9 +1,9 @@ - **Strict X12 validation keeps more interchange text out of tracebacks and logs.** A refusal no longer chains the pyx12 exception, whose message can quote a whole ISA, so a traceback would have - carried ISA02 and ISA04 on a deploying site. `X12ValidationError` now names only the exception's - class. `X12ValidationResult`'s repr leaves out `ack`, which echoes sender values. + carried ISA02 and ISA04 on a deploying site. `X12ValidationError` now keeps only that exception's + class name. `X12ValidationResult`'s repr leaves out `ack`, which echoes sender values. `X12SegmentError.segment_id` is `None` unless the value has an X12 segment id's shape and a map - in pyx12's bundled index defines it, so a wrongly delimited segment, or a name's tail standing - where the id goes, no longer lands in `segment_id` or `message`. A sender value equal to any id - in those maps, for example `LIN`, is still kept, even in a transaction whose own map does not - define it. (`BACKLOG #5370`) + in pyx12's bundled index defines it. So a wrongly delimited segment, or a name's tail standing + where the id goes, no longer lands in `segment_id` or `message`, unless it equals an indexed id, + for example `LIN`, `PAT`, or the `LE` of a name written `O~LE`. Such a value is kept in both even + in a transaction whose own map does not define it. (`BACKLOG #5370`) diff --git a/messagefoundry/parsing/x12/__init__.py b/messagefoundry/parsing/x12/__init__.py index a363ea1310..546763ec08 100644 --- a/messagefoundry/parsing/x12/__init__.py +++ b/messagefoundry/parsing/x12/__init__.py @@ -1,14 +1,18 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""Pure ASC X12 EDI codec (ADR 0012) — a tolerant routing peek, an interchange splitter/assembler, and +"""ASC X12 EDI codec (ADR 0012) — a tolerant routing peek, an interchange splitter/assembler, and a mutable message model, mirroring the HL7 :mod:`messagefoundry.parsing` library. -It is **pure and side-effect-free** (no I/O, no engine state) and imports nothing from -``messagefoundry.config`` / ``pipeline`` / ``store`` / ``transports`` — so the console may import it, -and a code-first Router/Handler calls it **on demand** against a -:class:`~messagefoundry.parsing.message.RawMessage` (``content_type="x12"``, ADR 0004): X12 is **not** -pushed through the engine pipeline as a bespoke object. The X12 content type is referred to by the -literal string ``"x12"`` (never imported from ``config``) to keep this purity. +The tolerant tier is **pure and side-effect-free** (no I/O, no engine state). The opt-in strict +:func:`~messagefoundry.parsing.x12.validate.validate` path has no engine state, database or network +access either, but it is not pure: it reads at least pyx12's bundled package files, keeps the +segment ids it reads from them in process-wide state, and mutes the ``pyx12`` logger tree. + +Neither tier imports anything from ``messagefoundry.config`` / ``pipeline`` / ``store`` / +``transports`` — so the console may import it, and a code-first Router/Handler calls it **on demand** +against a :class:`~messagefoundry.parsing.message.RawMessage` (``content_type="x12"``, ADR 0004): X12 +is **not** pushed through the engine pipeline as a bespoke object. The X12 content type is referred +to by the literal string ``"x12"`` (never imported from ``config``) to keep that import boundary. Two tiers, mirroring HL7 v2's built-in tolerant parser / hl7apy (strict): diff --git a/messagefoundry/parsing/x12/_deps.py b/messagefoundry/parsing/x12/_deps.py index 6872521830..64c4e8a027 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -13,7 +13,9 @@ swallow a deploy/config error. This module imports ``pyx12`` (third-party, not an engine package) and nothing from -``messagefoundry.config``/``pipeline``/``store``/``transports`` — the codec's purity is preserved. +``messagefoundry.config``/``pipeline``/``store``/``transports``, so that import boundary holds. It +is not pure: :mod:`messagefoundry.parsing.x12` says what the strict path reads and keeps, and +:func:`load_x12_map_segment_ids` how it keeps it. """ from __future__ import annotations diff --git a/messagefoundry/parsing/x12/errors.py b/messagefoundry/parsing/x12/errors.py index 93f2486c68..f606aac734 100644 --- a/messagefoundry/parsing/x12/errors.py +++ b/messagefoundry/parsing/x12/errors.py @@ -40,4 +40,5 @@ class X12ValidationError(X12Error): structural :class:`~messagefoundry.parsing.x12.validate.X12SegmentError` items + a 997/999 ack), so a Handler can route the *message* to the error path while still emitting the negative ack (the ack is ``None`` if pyx12 did not complete it). Its message is **PHI-safe**: it names only the failure - mode, never the input bytes.""" + mode and, where pyx12 raised, that exception's class, never the input bytes, and it chains no + pyx12 exception.""" diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index 5d54f9c3a6..d5e0236ed6 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -26,8 +26,8 @@ :class:`X12SegmentError` drops those strings and holds structural locators (its docstring names them, and a limit on its segment id), and a refusal chains no pyx12 exception. The ack does echo sender values, so it is left out of the result's repr. The full interchange goes only to the secured store -(CLAUDE.md §9). The pyx12 logger tree (which logs the raw, value-bearing strings at ERROR) is muted -from the first validation pass on, and never unmuted. +(CLAUDE.md §9). The pyx12 logger tree is muted from the first validation pass on, and never +unmuted, because its ERROR records can carry those values (:func:`_mute_pyx12_logger` says when). No network I/O and no engine imports. Disk reads include pyx12's bundled map XML, by pyx12 and by the segment id check. ``pyx12``'s sole runtime dependency is ``defusedxml`` (already in tree), used @@ -69,9 +69,10 @@ class X12SegmentError: ``segment_id`` comes from the input, so it is kept only when it has an X12 segment id's shape (a capital, then one or two capitals or digits) and a map in pyx12's bundled index defines it, and is ``None`` otherwise (BACKLOG #5370). The set is the union of those maps, so a sender value equal - to any id in it, for example the surname ``LIN``, standing where the id goes is still kept, in + to any id in it, for example ``LIN`` or ``PAT``, standing where the id goes is still kept, in ``segment_id`` and in ``message``, even in a transaction whose own map does not define that id. - A terminator inside a name can put the name's tail there, with ``loop`` naming the field before.""" + A terminator inside a name can put the name's tail there: ``O~LE`` keeps ``LE``, with ``loop`` + naming the segment the name was in.""" code: str message: str @@ -114,17 +115,20 @@ class X12ValidationResult: def _mute_pyx12_logger() -> None: """Mute the whole ``pyx12`` logger tree, and never unmute it (BACKLOG #1603). - pyx12 logs each violation's *raw* error string, which embeds the offending data value (potential - PHI), at ERROR from child loggers such as ``pyx12.error_handler``. We build our own errors from - pyx12's structured JSON instead, so nothing pyx12 logs is wanted anywhere. + pyx12 logs each violation at ERROR from child loggers such as ``pyx12.error_handler``. The + record embeds the *raw* error string, with the offending data value (potential PHI), under + pyx12 4.0.1, and under 4.1.0 when ``log_data_values`` is on, which a pyx12 config file can set. + We build our own errors from pyx12's structured JSON instead, so nothing pyx12 logs is wanted + anywhere. **No restore step, on purpose.** The old context manager raised the level for one pass and put the previous level back afterwards. Two overlapping passes on two threads would interleave: the - first to finish would unmute the logger while the second was still logging. No caller runs - passes concurrently today (a Handler calls :func:`validate` synchronously on its transform - worker). But the fix costs nothing: every call writes the same muted state, so concurrent calls - cannot disagree. Calling it on every pass, not once at import, also re-mutes a tree that a later - logging reconfiguration has reset. + first to finish would unmute the logger while the second was still logging. Passes can overlap: + without a subprocess sandbox, the transform workers of two inbound connections run their + Handlers on ``asyncio.to_thread`` threads, and a Handler calls :func:`validate` synchronously + there. Every call writes the same muted state, so concurrent calls cannot disagree. Calling it + on every pass, not once at import, also re-mutes a tree that a later logging reconfiguration + has reset. Two layers, in this order: @@ -203,6 +207,7 @@ def _structural_segment_id(seg: dict[str, Any]) -> str | None: segment (``NM1|IL|1|DOE|ROBERT``) puts the sender's whole segment there, and a terminator inside a name (``NM1*IL*1*O~LEE*A*B~``) puts the name's tail there, in an id's shape. The error code cannot tell those apart: pyx12 emits code 1 for sender text and for a real id in the wrong place. + The map check drops ``LEE``; :class:`X12SegmentError` states what it cannot drop. The shape is checked first, so text without it never makes this read the maps.""" seg_id = seg.get("seg_id") if ( diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 01db112d33..70d693bdd2 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -17,6 +17,7 @@ import traceback from collections.abc import Callable, Iterator from pathlib import Path +from types import SimpleNamespace from typing import Any import pytest @@ -773,6 +774,8 @@ def test_a_failed_map_read_is_not_kept_and_is_retried_after_a_pause( deps = importlib.import_module("messagefoundry.parsing.x12._deps") results = iter([frozenset[str](), frozenset({"NM1"})]) reads: list[object] = [] + start = 1000.0 + now = [start] def read(map_dir: object) -> frozenset[str]: reads.append(map_dir) @@ -781,11 +784,18 @@ def read(map_dir: object) -> frozenset[str]: monkeypatch.setattr(deps, "_read_map_segment_ids", read) monkeypatch.setattr(deps, "_map_ids", frozenset()) monkeypatch.setattr(deps, "_map_ids_retry_at", 0.0) + # A clock only this module sees. The test moves the clock and never the deadline, so the + # deadline the failed read wrote is what decides whether the retry fires. + monkeypatch.setattr(deps, "time", SimpleNamespace(monotonic=lambda: now[0])) + pause = deps._MAP_IDS_RETRY_SECONDS + assert pause > 0 + assert load_x12_map_segment_ids() == frozenset() + now[0] = start + pause - 0.001 assert load_x12_map_segment_ids() == frozenset() # inside the pause: no second read assert len(reads) == 1 - monkeypatch.setattr(deps, "_map_ids_retry_at", 0.0) # the pause is over + now[0] = start + pause # the pause is over assert load_x12_map_segment_ids() == {"NM1"} assert load_x12_map_segment_ids() == {"NM1"} # a good read is kept assert len(reads) == 2 From b7984f6d5c5857f732632e976462b5bee81cac28 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:18:30 -0600 Subject: [PATCH 08/16] X12 map reader registers its XML parse and path joins, and refuses a DTD The segment id check added a parse of pyx12's bundled maps and three path joins without recording them, which turned test and test shard 3 red on all three platforms. The parse now sits in _parse_map_xml with every defusedxml flag on, is driven by the shared hostile corpus, and has its allowlist and census rows. BACKLOG #5370 --- messagefoundry/parsing/x12/_deps.py | 19 ++++++++++++++++--- tests/test_file_path_join_census.py | 9 +++++++++ tests/test_security_static.py | 7 +++++++ tests/test_xml_parser_consistency.py | 27 +++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 3 deletions(-) diff --git a/messagefoundry/parsing/x12/_deps.py b/messagefoundry/parsing/x12/_deps.py index 64c4e8a027..7c9cf04f99 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -25,7 +25,7 @@ import time from collections.abc import Callable from importlib.resources import files -from typing import TYPE_CHECKING, Any +from typing import IO, TYPE_CHECKING, Any from messagefoundry._vendor.defusedxml.ElementTree import ParseError, parse @@ -61,6 +61,15 @@ def load_x12_validator() -> tuple[Any, Any]: return pyx12.x12n_document.x12n_document, pyx12.params.params +def _parse_map_xml(source: IO[bytes]) -> Any: + """THE XML parse surface of this module: the vendored defusedxml with every hardening flag on. + + pyx12's bundled maps carry no DTD, so refusing one costs nothing. Isolated so that + ``tests/test_xml_parser_consistency.py`` drives this parse directly: the reader below turns a + refusal into an empty set, which its hostile corpus could not tell from a document with no ids.""" + return parse(source, forbid_dtd=True, forbid_entities=True, forbid_external=True) + + def _read_map_segment_ids(map_dir: Traversable) -> frozenset[str]: """The ``xid`` of every ```` in the maps that ``maps.xml`` under ``map_dir`` lists. @@ -71,10 +80,14 @@ def _read_map_segment_ids(map_dir: Traversable) -> frozenset[str]: ids: set[str] = set() try: with map_dir.joinpath("maps.xml").open("rb") as fd: - map_files = {name for m in parse(fd).iter("map") if (name := (m.text or "").strip())} + index = _parse_map_xml(fd) + map_files = {name for m in index.iter("map") if (name := (m.text or "").strip())} for map_file in map_files: with map_dir.joinpath(map_file).open("rb") as fd: - ids.update(xid for seg in parse(fd).iter("segment") if (xid := seg.get("xid"))) + # Inside the `with`, unbound, so one map's tree is freed before the next is parsed. + ids.update( + xid for seg in _parse_map_xml(fd).iter("segment") if (xid := seg.get("xid")) + ) # ValueError covers defusedxml's refusals and a multi-byte encoding declaration; LookupError an # unknown one. except (OSError, ParseError, ValueError, LookupError) as exc: diff --git a/tests/test_file_path_join_census.py b/tests/test_file_path_join_census.py index e1111f9ba6..630e17abf0 100644 --- a/tests/test_file_path_join_census.py +++ b/tests/test_file_path_join_census.py @@ -724,6 +724,15 @@ def derived_script_sites() -> dict[str, int]: "messagefoundry/log_spool.py::LogSpool.open": Site( 1, INTERNAL, "A fixed lock name in the spool directory." ), + "messagefoundry/parsing/x12/_deps.py::_read_map_segment_ids": Site( + 2, + INTERNAL, + "The fixed index name, and map names read from that index inside the installed pyx12 " + "package; no interchange value reaches either.", + ), + "messagefoundry/parsing/x12/_deps.py::load_x12_map_segment_ids": Site( + 1, INTERNAL, "The fixed name map under the installed pyx12 package." + ), "messagefoundry/parsing/xml/schema.py::_bundled_root": Site( 1, INTERNAL, "A fixed name, schemas, beside the installed xmlschema package's own file." ), diff --git a/tests/test_security_static.py b/tests/test_security_static.py index 745e10e857..170065ac04 100644 --- a/tests/test_security_static.py +++ b/tests/test_security_static.py @@ -1502,6 +1502,13 @@ def test_single_url_parser() -> None: "the single lazy loader for the [xml] extra (lxml, xmlschema, signxml) — every consumer in " "parsing/xml/ goes through it, and lxml parsing is hardened once in harden.py" ), + "messagefoundry/parsing/x12/_deps.py": ( + "the vendored defusedxml copy's ElementTree.parse with forbid_dtd/forbid_entities/" + "forbid_external, isolated in _parse_map_xml() so tests/test_xml_parser_consistency.py " + "drives THAT surface directly (the reader around it turns a refusal into an empty set). Its " + "input is the map XML inside the installed pyx12 package, never interchange data; the " + "ParseError import beside it is the exception type" + ), "messagefoundry/transports/soap.py": ( "xml.sax well-formedness gate with external general/parameter entities off; it has no " "extraction API (a no-op ContentHandler), so it accepts or refuses and returns nothing" diff --git a/tests/test_xml_parser_consistency.py b/tests/test_xml_parser_consistency.py index 09f69e2f6b..393d168c54 100644 --- a/tests/test_xml_parser_consistency.py +++ b/tests/test_xml_parser_consistency.py @@ -50,6 +50,7 @@ import io import xml.sax +from typing import Any from xml.sax.handler import ContentHandler, feature_external_ges, feature_external_pes from xml.sax.xmlreader import InputSource @@ -181,6 +182,19 @@ def _corepoint_parse(document: str) -> object: return _hardened_fromstring(document) +def _x12_map_parse(document: str) -> Any: + """Surface 5 — the X12 map reader (``parsing/x12/_deps.py``): defusedxml, all flags ON. + + Driven at ``_parse_map_xml`` because the reader around it turns a refusal into an empty set, and + no document in this corpus holds a segment id, so aiming at the reader could not fail. Its real + input is a file's bytes, so a document is encoded the way its own declaration says. + """ + from messagefoundry.parsing.x12._deps import _parse_map_xml + + encoding = "iso-8859-1" if 'encoding="iso-8859-1"' in document else "utf-8" + return _parse_map_xml(io.BytesIO(document.encode(encoding))).getroot() + + def _lxml_parse(document: str | bytes) -> object: """Surface 3 — ``parsing/xml/harden.py``: the hardened lxml parser + post-parse DOCTYPE refusal. @@ -273,6 +287,18 @@ def test_corepoint_import_refuses_every_hostile_document(name: str) -> None: assert not _accepts(_corepoint_parse, HOSTILE[name]) +@pytest.mark.parametrize("name", sorted(HOSTILE)) +def test_x12_map_reader_refuses_every_hostile_document(name: str) -> None: + assert not _accepts(_x12_map_parse, HOSTILE[name]) + + +@pytest.mark.parametrize("name", sorted(BENIGN)) +def test_x12_map_reader_reads_benign_text_like_its_siblings(name: str) -> None: + # Anti-vacuity for the refusals above: a surface that refused everything would pass them. + document, expected = BENIGN[name] + assert "".join(_x12_map_parse(document).itertext()) == expected + + @pytest.mark.parametrize("name", sorted(HOSTILE)) def test_no_parser_accepts_what_a_sibling_refuses(name: str) -> None: # THE consistency assertion — the reason the cell exists. Stated as a per-document unanimity check @@ -282,6 +308,7 @@ def test_no_parser_accepts_what_a_sibling_refuses(name: str) -> None: "defusedxml": _accepts(_defusedxml_parse, document), "xml.sax (soap gate)": _accepts(_soap_gate, document), "defusedxml (corepoint import)": _accepts(_corepoint_parse, document), + "defusedxml (x12 map reader)": _accepts(_x12_map_parse, document), } if _lxml_available(): verdicts["lxml (harden.py)"] = _accepts(_lxml_parse, document) From 3a436630a0e0143c71f07bf9af0ff10efaf42ecb Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:22:36 -0600 Subject: [PATCH 09/16] X12 validate keeps a finished pass when the segment id read fails An exception outside the map reader's tuple, such as MemoryError or BadZipFile, or a failure in files() itself, escaped after the walk had finished. That would discard the verdict and the ack and skip the retry pause. The read now fails closed to no id, logs only the class name, and still waits out the pause. BACKLOG #5370 --- messagefoundry/parsing/x12/_deps.py | 25 ++++++++++++---- tests/test_x12_validate.py | 46 +++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/messagefoundry/parsing/x12/_deps.py b/messagefoundry/parsing/x12/_deps.py index 7c9cf04f99..1e86d9f50f 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -61,6 +61,14 @@ def load_x12_validator() -> tuple[Any, Any]: return pyx12.x12n_document.x12n_document, pyx12.params.params +def _log_maps_unreadable(exc: Exception) -> None: + """The one warning for a failed map-id read. It holds the class name and nothing else.""" + _log.warning( + "pyx12's maps could not be read (%s); X12 errors will carry no segment id", + type(exc).__name__, + ) + + def _parse_map_xml(source: IO[bytes]) -> Any: """THE XML parse surface of this module: the vendored defusedxml with every hardening flag on. @@ -91,10 +99,7 @@ def _read_map_segment_ids(map_dir: Traversable) -> frozenset[str]: # ValueError covers defusedxml's refusals and a multi-byte encoding declaration; LookupError an # unknown one. except (OSError, ParseError, ValueError, LookupError) as exc: - _log.warning( - "pyx12's maps could not be read (%s); X12 errors will carry no segment id", - type(exc).__name__, - ) + _log_maps_unreadable(exc) return frozenset() if not ids: _log.warning("pyx12's maps define no segment; X12 errors will carry no segment id") @@ -108,13 +113,21 @@ def load_x12_map_segment_ids() -> frozenset[str]: a noticeable fraction of a second, so it runs only when a violation has an id-shaped value to check, and the lock keeps threads that miss together to one read. A good read is kept for the process. An empty one is not, so a passing fault cannot remove every id until a restart; it is - retried at most once per :data:`_MAP_IDS_RETRY_SECONDS`, and until then no id is kept.""" + retried at most once per :data:`_MAP_IDS_RETRY_SECONDS`, and until then no id is kept. + + No failed read raises. This runs after a pass has finished, so an exception here would discard + that pass's verdict and ack over a locator it can do without.""" global _map_ids, _map_ids_retry_at if _map_ids: return _map_ids with _MAP_IDS_LOCK: if not _map_ids and time.monotonic() >= _map_ids_retry_at: - _map_ids = _read_map_segment_ids(files("pyx12").joinpath("map")) + try: + _map_ids = _read_map_segment_ids(files("pyx12").joinpath("map")) + # Broad on purpose: at least MemoryError and a zip import's BadZipFile get past the + # reader's own tuple, and the class name is all that is logged. + except Exception as exc: # noqa: BLE001 + _log_maps_unreadable(exc) if not _map_ids: _map_ids_retry_at = time.monotonic() + _MAP_IDS_RETRY_SECONDS return _map_ids diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 70d693bdd2..20c5b08178 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -15,6 +15,7 @@ import logging import threading import traceback +import zipfile from collections.abc import Callable, Iterator from pathlib import Path from types import SimpleNamespace @@ -876,3 +877,48 @@ def test_only_a_segment_id_the_maps_define_is_kept(seg_id: Any, kept: str | None shown = kept or "?" assert (seg_err.segment_id, seg_err.message) == (kept, f"segment {shown}: error 1") assert (ele_err.segment_id, ele_err.message) == (kept, f"element {shown}02: error 8") + + +@pytest.mark.parametrize( + ("target", "fault"), + [ + ("_read_map_segment_ids", MemoryError), + ("_read_map_segment_ids", lambda: zipfile.BadZipFile(_PLANT)), + ("files", lambda: ModuleNotFoundError(_PLANT)), + ("files", lambda: TypeError(_PLANT)), + ], + ids=["read-memory", "read-badzip", "files-module", "files-type"], +) +def test_a_finished_pass_survives_a_failed_map_read( + target: str, + fault: Callable[[], Exception], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + deps = importlib.import_module("messagefoundry.parsing.x12._deps") + calls: list[object] = [] + + def failing(*args: object) -> Any: + calls.append(args) + raise fault() + + start = 1000.0 + monkeypatch.setattr(deps, target, failing) + monkeypatch.setattr(deps, "_map_ids", frozenset()) + monkeypatch.setattr(deps, "_map_ids_retry_at", 0.0) + monkeypatch.setattr(deps, "time", SimpleNamespace(monotonic=lambda: start)) + + with caplog.at_level(logging.WARNING, logger=deps.__name__): + result = validate(_270_with("LIN*A~")) + + # The pass's verdict and ack are kept; the id it could not check fails closed to `?`. + assert result.valid is False and result.ack is not None + assert "LIN" not in {e.segment_id for e in result.errors} + assert "segment ?: error 1" in [e.message for e in result.errors] + assert type(fault()).__name__ in caplog.text and "no segment id" in caplog.text + assert _PLANT not in caplog.text + # The retry pause still ran: inside it, a later use reads nothing. + assert deps._map_ids_retry_at == start + deps._MAP_IDS_RETRY_SECONDS + assert len(calls) == 1 + assert load_x12_map_segment_ids() == frozenset() + assert len(calls) == 1 From cdf26f502338504d0312db7e913fea3178fe7415 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:26:50 -0600 Subject: [PATCH 10/16] X12 validate keeps a damaged pyx12 install apart from a bad interchange A broken install and an unknown GS08 were both reported as "not a parseable X12 interchange", so a Handler's except ValueError would dead-letter good messages on a damaged install. A walk that fails on an install fault now raises RuntimeError, as a missing extra does. That is OSError, ImportError, an XML ParseError, or any failure while pyx12's own loaders cannot load the index, a control map and the code tables. An unknown version stays an X12ValidationError and now says there is no map. Only the class name is kept. Proposed PR title: X12 strict validate chains no pyx12 exception and keeps sender text out of its reprs (BACKLOG #5370) BACKLOG #5370 --- changelog.d/5370.security.md | 5 +- messagefoundry/parsing/x12/_deps.py | 28 +++++ messagefoundry/parsing/x12/errors.py | 6 +- messagefoundry/parsing/x12/validate.py | 49 +++++++-- tests/test_x12_validate.py | 137 +++++++++++++++++++++++-- 5 files changed, 207 insertions(+), 18 deletions(-) diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md index f2450618b3..350e0384cc 100644 --- a/changelog.d/5370.security.md +++ b/changelog.d/5370.security.md @@ -6,4 +6,7 @@ in pyx12's bundled index defines it. So a wrongly delimited segment, or a name's tail standing where the id goes, no longer lands in `segment_id` or `message`, unless it equals an indexed id, for example `LIN`, `PAT`, or the `LE` of a name written `O~LE`. Such a value is kept in both even - in a transaction whose own map does not define it. (`BACKLOG #5370`) + in a transaction whose own map does not define it. A walk that fails on a damaged pyx12 install + now raises `RuntimeError` rather than `X12ValidationError`, so a Handler's `except ValueError` + would not dead-letter a good message over it, and a failed read of the segment id set no longer + discards a finished pass. (`BACKLOG #5370`) diff --git a/messagefoundry/parsing/x12/_deps.py b/messagefoundry/parsing/x12/_deps.py index 1e86d9f50f..acc33a781a 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -38,6 +38,11 @@ _map_ids: frozenset[str] = frozenset() _map_ids_retry_at = 0.0 +#: What a pyx12 walk raises when the install, not the interchange, is at fault. The walk's source and +#: outputs are in-memory streams, so its only file reads are pyx12's bundled maps, and only those +#: maps reach an XML parser. +X12_INSTALL_FAULTS: tuple[type[Exception], ...] = (OSError, ImportError, ParseError) + def _missing_extra(feature: str) -> RuntimeError: return RuntimeError( @@ -69,6 +74,29 @@ def _log_maps_unreadable(exc: Exception) -> None: ) +def x12_install_loads() -> bool: + """Whether pyx12 can still load what every walk loads: its map index, a control map, and the + code and data-element tables that building a map reads. Called only after a walk has raised, to + tell a damaged install from a bad interchange, and through pyx12's own loaders so it reads those + files the way the walk does. Not cached, so it sees damage done since the last pass. It adds at + most the setup that failed pass already ran. A damaged transaction map that still parses is out + of its reach. It never raises, and logs only the class name.""" + try: + import pyx12.map_if + import pyx12.map_index + import pyx12.params + + if not pyx12.map_index.map_index().maps: + _log.warning("pyx12's map index lists no map") + return False + pyx12.map_if.load_map_file("x12.control.00501.xml", pyx12.params.params()) + # Broad on purpose: a damaged table can raise at least ValueError or TypeError. + except Exception as exc: # noqa: BLE001 + _log.warning("pyx12's maps could not be loaded (%s)", type(exc).__name__) + return False + return True + + def _parse_map_xml(source: IO[bytes]) -> Any: """THE XML parse surface of this module: the vendored defusedxml with every hardening flag on. diff --git a/messagefoundry/parsing/x12/errors.py b/messagefoundry/parsing/x12/errors.py index f606aac734..6825bf7d2b 100644 --- a/messagefoundry/parsing/x12/errors.py +++ b/messagefoundry/parsing/x12/errors.py @@ -32,8 +32,10 @@ class X12FrameError(X12Error): class X12ValidationError(X12Error): """The opt-in strict validator (``pyx12``, ADR 0012) could not finish a structural validation - pass: at least when the bytes are not a parseable X12 data file, and when pyx12 raises partway - through a walk, as a non-numeric GE01 makes it do. The X12 analog of + pass over this interchange: at least when the bytes are not a parseable X12 data file, when it + names a version pyx12 has no map for, and when pyx12 raises partway through a walk, as a + non-numeric GE01 makes it do. A damaged pyx12 install raises :class:`RuntimeError` instead, so + ``except ValueError`` does not dead-letter a good message over it. The X12 analog of :class:`~messagefoundry.parsing.fhir.errors.FhirValidationError`. A *failed validation* (a pass that finishes with violations of the implementation guide) is **not** this — it is reported as data on :class:`~messagefoundry.parsing.x12.validate.X12ValidationResult` (``valid=False`` + diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index d5e0236ed6..4455c58898 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -44,9 +44,11 @@ from typing import Any from messagefoundry.parsing.x12._deps import ( + X12_INSTALL_FAULTS, load_x12_code_resolver, load_x12_map_segment_ids, load_x12_validator, + x12_install_loads, ) from messagefoundry.parsing.x12.errors import X12ValidationError from messagefoundry.redaction import json_loads_or_refusal @@ -297,6 +299,24 @@ def _flatten_errors( return out +def _walk_refusal(failure: str, *, install_fault: bool, no_map: bool) -> Exception: + """The exception for a walk that raised, holding only that exception's class name. An install + fault is a :class:`RuntimeError`, so a Handler's ``except ValueError`` does not dead-letter a + good message on a damaged install. An interchange naming a version pyx12 has no map for is a + fault of that interchange, so it stays an :class:`X12ValidationError`.""" + if install_fault: + return RuntimeError( + f"strict X12 validation could not run: pyx12's maps or modules could not be loaded " + f"({failure}); reinstall the optional 'x12' extra: pip install 'messagefoundry[x12]'" + ) + reason = ( + "pyx12 has no map for this interchange's ISA12, GS01 and GS08" + if no_map + else "pyx12 stopped partway through this interchange" + ) + return X12ValidationError(f"strict X12 validation could not run: {reason} ({failure})") + + def validate(raw: str | bytes) -> X12ValidationResult: """Strictly validate an X12 interchange against pyx12's bundled implementation-guide maps. @@ -305,12 +325,17 @@ def validate(raw: str | bytes) -> X12ValidationResult: the structural error list, and the generated 997/999 acknowledgment. Raises :class:`~messagefoundry.parsing.x12.errors.X12ValidationError` when pyx12 could not finish - a pass: at least when the bytes are not a parseable X12 data file, and when pyx12 raises partway - through a walk, as a non-numeric GE01 makes it do. It chains no pyx12 exception. A pass that - finishes with violations is returned as data (``valid=False``), not raised, so a Handler can still - emit the negative ack. Raises - :class:`RuntimeError` if the ``[x12]`` extra is absent (a deploy/config error, distinct from the - ``ValueError``-rooted data errors).""" + a pass over this interchange: at least when the bytes are not a parseable X12 data file, when it + names a version pyx12 has no map for, and when pyx12 raises partway through a walk, as a + non-numeric GE01 makes it do. It chains no pyx12 exception. A pass that finishes with violations + is returned as data (``valid=False``), not raised, so a Handler can still emit the negative ack. + + Raises :class:`RuntimeError`, a deploy/config error distinct from the ``ValueError``-rooted data + errors and chaining nothing from pyx12, if the ``[x12]`` extra is absent or a walk fails on a + damaged install: one of :data:`~messagefoundry.parsing.x12._deps.X12_INSTALL_FAULTS`, or any + failure while :func:`~messagefoundry.parsing.x12._deps.x12_install_loads` is false. A transaction + map that still parses but is wrong can raise some other class, which reads as a refusal of the + interchange, and an index that has lost a map's entry reads as having no map for it.""" if isinstance(raw, (bytes, bytearray)): # noqa: SIM108 text = bytes(raw).decode("utf-8", "replace") else: @@ -324,17 +349,23 @@ def validate(raw: str | bytes) -> X12ValidationResult: _mute_pyx12_logger() walk_failure: str | None = None + install_fault = no_map = False try: valid = bool(x12n_document(params, io.StringIO(text), fd_ack, None, None, fd_json)) except Exception as exc: # pyx12 raises bare Exception/EngineError on unwalkable input walk_failure = type(exc).__name__ + install_fault = isinstance(exc, X12_INSTALL_FAULTS) + # By name, because an import here could raise and chain this exception. The text is compared + # with pyx12's own fixed prefix and not kept. + no_map = walk_failure == "EngineError" and str(exc).startswith("Map not found") # Raised out here, because pyx12's messages quote the interchange (a whole ISA, GS08, GE01): # `from exc` puts that on __cause__, and `from None` still leaves it on __context__ (BACKLOG # #5370, the pattern of json_loads_or_refusal, #2085). Only the class name is kept. if walk_failure is not None: - raise X12ValidationError( - "strict X12 validation could not run: the bytes are not a parseable X12 interchange " - f"({walk_failure})" + raise _walk_refusal( + walk_failure, + install_fault=install_fault or not x12_install_loads(), + no_map=no_map, ) raw_json = fd_json.getvalue() diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 20c5b08178..9a2b4a1a8b 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -25,6 +25,7 @@ pytest.importorskip("pyx12") +from messagefoundry._vendor.defusedxml.ElementTree import ParseError # noqa: E402 from messagefoundry.parsing.x12 import ( # noqa: E402 - after importorskip X12SegmentError, X12ValidationError, @@ -35,6 +36,7 @@ _read_map_segment_ids, load_x12_code_resolver, load_x12_map_segment_ids, + x12_install_loads, ) from messagefoundry.redaction import safe_traceback # noqa: E402 from tests._content_free import assert_chain_severed # noqa: E402 @@ -683,12 +685,7 @@ def test_a_refused_interchange_chains_no_pyx12_text( assert all(plant in str(seen[0]) for plant in plants) exc = caught.value - assert_chain_severed(exc) - for text in ( - safe_traceback((type(exc), exc, exc.__traceback__)), - "".join(traceback.format_exception(exc)), - ): - assert not any(plant in text for plant in plants) + _assert_no_plant(exc, plants) # What is kept of the pyx12 error is its class name, so a refusal can still be told apart. assert type(seen[0]).__name__ in str(exc) @@ -879,6 +876,134 @@ def test_only_a_segment_id_the_maps_define_is_kept(seg_id: Any, kept: str | None assert (ele_err.segment_id, ele_err.message) == (kept, f"element {shown}02: error 8") +# --- An install fault is not a parse fault, and a failed map read cannot cost a finished pass. --- + + +def _walk_raising( + fault: Callable[[], Exception], +) -> Callable[[], tuple[Any, Callable[[], Any]]]: + """A ``load_x12_validator`` whose walk raises ``fault()``.""" + + def document(*_args: Any) -> bool: + raise fault() + + return lambda: (document, object) + + +def _assert_no_plant(exc: BaseException, plants: tuple[str, ...] = (_PLANT,)) -> None: + assert_chain_severed(exc) + for text in ( + safe_traceback((type(exc), exc, exc.__traceback__)), + "".join(traceback.format_exception(exc)), # holds str(exc) too + ): + assert not any(plant in text for plant in plants) + + +@pytest.mark.parametrize( + "fault", + [ + lambda: FileNotFoundError(2, "no such map", _PLANT), + lambda: PermissionError(13, "denied", _PLANT), + lambda: ImportError(_PLANT), + lambda: ModuleNotFoundError(_PLANT), + lambda: ParseError(_PLANT), + ], + ids=["missing-map", "denied-map", "import", "module", "damaged-xml"], +) +def test_a_damaged_install_is_not_reported_as_a_data_fault( + fault: Callable[[], Exception], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(_X12_VALIDATE, "load_x12_validator", _walk_raising(fault)) + with pytest.raises(RuntimeError) as caught: + validate(_conformant_270()) + exc = caught.value + # Exactly RuntimeError: a Handler's `except ValueError` must not dead-letter a good message. + assert type(exc) is RuntimeError + assert type(fault()).__name__ in str(exc) + assert "messagefoundry[x12]" in str(exc) + _assert_no_plant(exc) + + +def test_a_map_file_gone_from_the_real_walk_is_an_install_fault( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import pyx12.map_if + + def gone(*_args: Any, **_kwargs: Any) -> Any: + raise FileNotFoundError(2, "no such map", _PLANT) + + monkeypatch.setattr(pyx12.map_if, "load_map_file", gone) + with pytest.raises(RuntimeError, match="FileNotFoundError") as caught: + validate(_conformant_270()) + assert type(caught.value) is RuntimeError + _assert_no_plant(caught.value) + + +def test_any_walk_failure_is_an_install_fault_while_the_install_cannot_load( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # AttributeError is a class X12_INSTALL_FAULTS does not name. + walk = _walk_raising(lambda: AttributeError(_PLANT)) + monkeypatch.setattr(_X12_VALIDATE, "load_x12_validator", walk) + # Control: with a loading install the same class is a refusal of this interchange. + monkeypatch.setattr(_X12_VALIDATE, "x12_install_loads", lambda: True) + with pytest.raises(X12ValidationError) as refused: + validate(_conformant_270()) + _assert_no_plant(refused.value) + + monkeypatch.setattr(_X12_VALIDATE, "x12_install_loads", lambda: False) + with pytest.raises(RuntimeError) as caught: + validate(_conformant_270()) + assert type(caught.value) is RuntimeError + _assert_no_plant(caught.value) + + +def test_a_table_that_parses_but_is_damaged_is_an_install_fault( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + # What a bad value in dataele.xml does: the map build raises a class no install-fault list + # names, on the real walk and on the probe alike, while the segment id read still succeeds. + import pyx12.map_if + + def damaged(*_args: Any, **_kwargs: Any) -> Any: + raise ValueError(_PLANT) + + monkeypatch.setattr(pyx12.map_if, "load_map_file", damaged) + with caplog.at_level(logging.WARNING), pytest.raises(RuntimeError) as caught: + validate(_conformant_270()) + assert type(caught.value) is RuntimeError + _assert_no_plant(caught.value) + assert "ValueError" in caplog.text and _PLANT not in caplog.text + + +def test_the_install_probe_passes_on_a_good_install_and_never_raises( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import pyx12.map_index + + assert x12_install_loads() is True + + def broken(*_args: Any) -> Any: + raise MemoryError + + monkeypatch.setattr(pyx12.map_index, "map_index", broken) + assert x12_install_loads() is False + monkeypatch.setattr(pyx12.map_index, "map_index", lambda: SimpleNamespace(maps=[])) + assert x12_install_loads() is False + + +def test_an_unknown_gs08_is_named_as_no_map_and_stays_a_data_error() -> None: + with pytest.raises(X12ValidationError, match="no map"): + validate(_RAISING_INTERCHANGES["gs08"][0]) + + +@pytest.mark.parametrize("name", ["isa17", "ge01"]) +def test_a_refusal_with_a_map_does_not_claim_there_is_none(name: str) -> None: + with pytest.raises(X12ValidationError) as caught: + validate(_RAISING_INTERCHANGES[name][0]) + assert "no map" not in str(caught.value) + + @pytest.mark.parametrize( ("target", "fault"), [ From 62839c845b2f31f00a5ce01964ab51ebc410b6b0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:09:00 -0600 Subject: [PATCH 11/16] X12 map reader refuses an index name that is not a bare file name pyx12's own load_map_file refuses such a name. Without the same check, a tampered index entry would make the segment id read open a file outside pyx12's map directory and trust the ids in it. The names are checked before any map is opened, and a bad one gives the empty set. BACKLOG #5370 --- messagefoundry/parsing/x12/_deps.py | 9 +++++++-- tests/test_file_path_join_census.py | 2 +- tests/test_x12_validate.py | 24 ++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/messagefoundry/parsing/x12/_deps.py b/messagefoundry/parsing/x12/_deps.py index acc33a781a..4db075392c 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -21,6 +21,7 @@ from __future__ import annotations import logging +import os.path import threading import time from collections.abc import Callable @@ -111,13 +112,17 @@ def _read_map_segment_ids(map_dir: Traversable) -> frozenset[str]: pyx12 selects its maps from that index, so a bundled file it omits (``comp_test.xml``, the only source of ``TST`` and ``UNU``) adds no id. All or nothing: an index or listed map that cannot be - read or parsed, or a set with no id, gives the empty set, so a caller keeps no id rather than - trusting the shape alone.""" + read or parsed, a listed name that is not a bare file name (the check pyx12's ``load_map_file`` + makes), or a set with no id, gives the empty set, so a caller keeps no id rather than trusting + the shape alone.""" ids: set[str] = set() try: with map_dir.joinpath("maps.xml").open("rb") as fd: index = _parse_map_xml(fd) map_files = {name for m in index.iter("map") if (name := (m.text or "").strip())} + # Before any map is opened. An absolute name has a separator, so this refuses it too. + if any(name != os.path.basename(name) for name in map_files): + raise ValueError("a name in pyx12's map index is not a bare file name") for map_file in map_files: with map_dir.joinpath(map_file).open("rb") as fd: # Inside the `with`, unbound, so one map's tree is freed before the next is parsed. diff --git a/tests/test_file_path_join_census.py b/tests/test_file_path_join_census.py index 630e17abf0..a9941cdde6 100644 --- a/tests/test_file_path_join_census.py +++ b/tests/test_file_path_join_census.py @@ -728,7 +728,7 @@ def derived_script_sites() -> dict[str, int]: 2, INTERNAL, "The fixed index name, and map names read from that index inside the installed pyx12 " - "package; no interchange value reaches either.", + "package, each refused unless a bare file name; no interchange value reaches either.", ), "messagefoundry/parsing/x12/_deps.py::load_x12_map_segment_ids": Site( 1, INTERNAL, "The fixed name map under the installed pyx12 package." diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 9a2b4a1a8b..335569f448 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -1004,6 +1004,30 @@ def test_a_refusal_with_a_map_does_not_claim_there_is_none(name: str) -> None: assert "no map" not in str(caught.value) +@pytest.mark.parametrize("kind", ["parent", "subdirectory", "absolute"]) +def test_a_map_name_that_is_not_a_bare_file_name_gives_no_ids( + kind: str, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + # pyx12's own load_map_file refuses these. Without the same check the reader would open a file + # outside the map directory and trust the ids in it. + map_dir = tmp_path / "map" + (map_dir / "sub").mkdir(parents=True) + for target in (tmp_path / "outside.xml", map_dir / "sub" / "inner.xml"): + target.write_text("", encoding="utf-8") + name = { + "parent": "../outside.xml", + "subdirectory": "sub/inner.xml", + "absolute": str(tmp_path / "outside.xml"), + }[kind] + (map_dir / "maps.xml").write_text( + f"{name}", encoding="utf-8" + ) + with caplog.at_level(logging.WARNING): + assert _read_map_segment_ids(map_dir) == frozenset() + assert "no segment id" in caplog.text + assert name not in caplog.text + + @pytest.mark.parametrize( ("target", "fault"), [ From c0e5747237a1b99daa14448ab404b9e8479117b9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:11:17 -0600 Subject: [PATCH 12/16] X12 validate classifies an install fault by exception type, with no probe The install probe misclassified in both directions, so it is gone. A walk failure is a RuntimeError only for a type a sender's bytes cannot raise there: OSError, ImportError, XML ParseError or a defusedxml refusal. make_params now runs inside the walk's try, since it reads pyx12's config file. Every other failure stays X12ValidationError and logs only its class name and a count at WARNING, limited per class, with no-map refusals on their own key. A damaged map that raises an ordinary error reads as a refusal, and the docstrings and changelog now say so. A no-map refusal no longer blames named elements or calls the interchange bad. Proposed PR title: X12 strict validate chains no pyx12 exception and keeps sender text out of its reprs (BACKLOG #5370) BACKLOG #5370 --- changelog.d/5370.security.md | 13 +- messagefoundry/parsing/x12/_deps.py | 46 +++--- messagefoundry/parsing/x12/errors.py | 20 ++- messagefoundry/parsing/x12/validate.py | 91 ++++++++---- tests/test_x12_validate.py | 198 ++++++++++++++++++++----- 5 files changed, 271 insertions(+), 97 deletions(-) diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md index 350e0384cc..8d3cd9537b 100644 --- a/changelog.d/5370.security.md +++ b/changelog.d/5370.security.md @@ -6,7 +6,12 @@ in pyx12's bundled index defines it. So a wrongly delimited segment, or a name's tail standing where the id goes, no longer lands in `segment_id` or `message`, unless it equals an indexed id, for example `LIN`, `PAT`, or the `LE` of a name written `O~LE`. Such a value is kept in both even - in a transaction whose own map does not define it. A walk that fails on a damaged pyx12 install - now raises `RuntimeError` rather than `X12ValidationError`, so a Handler's `except ValueError` - would not dead-letter a good message over it, and a failed read of the segment id set no longer - discards a finished pass. (`BACKLOG #5370`) + in a transaction whose own map does not define it. A walk that fails with a type a sender's bytes + cannot raise (`OSError`, `ImportError`, an XML `ParseError` or a defusedxml refusal) now raises + `RuntimeError` rather than `X12ValidationError`. A Handler's `except ValueError` does not catch + it, but left uncaught it takes the `internal_error` policy, whose default also dead-letters the + row. A damaged map or table that still parses raises an ordinary error, so it still reads as a + refusal; each refusal logs its exception class at WARNING, rate-limited per class, with no + message or sender text. A refusal for an interchange pyx12 has no map for now says so, since it + may follow a guide pyx12 does not bundle. A failed read of the segment id set no longer discards + a finished pass. (`BACKLOG #5370`) diff --git a/messagefoundry/parsing/x12/_deps.py b/messagefoundry/parsing/x12/_deps.py index 4db075392c..ae6a8790bd 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -39,11 +39,6 @@ _map_ids: frozenset[str] = frozenset() _map_ids_retry_at = 0.0 -#: What a pyx12 walk raises when the install, not the interchange, is at fault. The walk's source and -#: outputs are in-memory streams, so its only file reads are pyx12's bundled maps, and only those -#: maps reach an XML parser. -X12_INSTALL_FAULTS: tuple[type[Exception], ...] = (OSError, ImportError, ParseError) - def _missing_extra(feature: str) -> RuntimeError: return RuntimeError( @@ -51,6 +46,24 @@ def _missing_extra(feature: str) -> RuntimeError: ) +def is_x12_install_fault(exc: Exception) -> bool: + """Whether a failed pyx12 walk raised a type that a sender's bytes cannot raise there. + + The walk gets in-memory streams, so it opens only pyx12's map directory and config file, under + names from pyx12's code and index, and only those files reach an XML parser. So ``OSError``, + ``ImportError``, XML ``ParseError`` and a defusedxml refusal each mean the install or its config + is at fault. That is read from pyx12 4.1.0's source. A refusal is matched by class name because + pyx12 raises the upstream package's class, which is not the engine's vendored one, and an import + here could raise and chain the exception being classified. + + It is a statement about types only, so it does not catch every damaged install: + :class:`~messagefoundry.parsing.x12.errors.X12ValidationError` says what the rest do.""" + return isinstance(exc, (OSError, ImportError, ParseError)) or any( + cls.__name__ == "DefusedXmlException" and cls.__module__.endswith("defusedxml.common") + for cls in type(exc).__mro__ + ) + + def load_x12_validator() -> tuple[Any, Any]: """Return ``(x12n_document, params_factory)`` from ``pyx12``, or a clear :class:`RuntimeError` if the ``[x12]`` extra is absent. @@ -75,29 +88,6 @@ def _log_maps_unreadable(exc: Exception) -> None: ) -def x12_install_loads() -> bool: - """Whether pyx12 can still load what every walk loads: its map index, a control map, and the - code and data-element tables that building a map reads. Called only after a walk has raised, to - tell a damaged install from a bad interchange, and through pyx12's own loaders so it reads those - files the way the walk does. Not cached, so it sees damage done since the last pass. It adds at - most the setup that failed pass already ran. A damaged transaction map that still parses is out - of its reach. It never raises, and logs only the class name.""" - try: - import pyx12.map_if - import pyx12.map_index - import pyx12.params - - if not pyx12.map_index.map_index().maps: - _log.warning("pyx12's map index lists no map") - return False - pyx12.map_if.load_map_file("x12.control.00501.xml", pyx12.params.params()) - # Broad on purpose: a damaged table can raise at least ValueError or TypeError. - except Exception as exc: # noqa: BLE001 - _log.warning("pyx12's maps could not be loaded (%s)", type(exc).__name__) - return False - return True - - def _parse_map_xml(source: IO[bytes]) -> Any: """THE XML parse surface of this module: the vendored defusedxml with every hardening flag on. diff --git a/messagefoundry/parsing/x12/errors.py b/messagefoundry/parsing/x12/errors.py index 6825bf7d2b..afe419af30 100644 --- a/messagefoundry/parsing/x12/errors.py +++ b/messagefoundry/parsing/x12/errors.py @@ -32,10 +32,22 @@ class X12FrameError(X12Error): class X12ValidationError(X12Error): """The opt-in strict validator (``pyx12``, ADR 0012) could not finish a structural validation - pass over this interchange: at least when the bytes are not a parseable X12 data file, when it - names a version pyx12 has no map for, and when pyx12 raises partway through a walk, as a - non-numeric GE01 makes it do. A damaged pyx12 install raises :class:`RuntimeError` instead, so - ``except ValueError`` does not dead-letter a good message over it. The X12 analog of + pass over this interchange: at least when the bytes are not a parseable X12 data file, when + pyx12 has no map that selects it, which a conformant interchange under a guide pyx12 does not + bundle also meets, and when pyx12 raises partway through a walk, as a non-numeric GE01 makes it + do. So this does not always mean the interchange is bad. + + A walk failure of a type a sender's bytes cannot raise + (:func:`~messagefoundry.parsing.x12._deps.is_x12_install_fault`) is a :class:`RuntimeError` + instead. A Handler's ``except ValueError`` does not catch that, but left uncaught it takes the + ``internal_error`` policy, whose default, ``CONTINUE``, also dead-letters the row. + + **A damaged install can land here too.** A map or table that still parses but is wrong raises + an ordinary error, and an index that lost a map's entry reads as having no map, so each is this + error, which a Handler's ``except ValueError`` would dead-letter. Each refusal logs its exception + class at WARNING, rate-limited, so a run of one class shows an operator the damage. + + The X12 analog of :class:`~messagefoundry.parsing.fhir.errors.FhirValidationError`. A *failed validation* (a pass that finishes with violations of the implementation guide) is **not** this — it is reported as data on :class:`~messagefoundry.parsing.x12.validate.X12ValidationResult` (``valid=False`` + diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index 4455c58898..635e9a01e0 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -39,16 +39,18 @@ import io import logging import re +import threading +import time +from collections import Counter from collections.abc import Callable from dataclasses import dataclass, field from typing import Any from messagefoundry.parsing.x12._deps import ( - X12_INSTALL_FAULTS, + is_x12_install_fault, load_x12_code_resolver, load_x12_map_segment_ids, load_x12_validator, - x12_install_loads, ) from messagefoundry.parsing.x12.errors import X12ValidationError from messagefoundry.redaction import json_loads_or_refusal @@ -301,22 +303,64 @@ def _flatten_errors( def _walk_refusal(failure: str, *, install_fault: bool, no_map: bool) -> Exception: """The exception for a walk that raised, holding only that exception's class name. An install - fault is a :class:`RuntimeError`, so a Handler's ``except ValueError`` does not dead-letter a - good message on a damaged install. An interchange naming a version pyx12 has no map for is a - fault of that interchange, so it stays an :class:`X12ValidationError`.""" + fault is a :class:`RuntimeError`, which a Handler's ``except ValueError`` does not catch. Every + other failure is an :class:`X12ValidationError`, which says what pyx12 could not do and does not + claim the interchange is bad: it can conform to a guide pyx12 does not bundle. Called outside + the ``except`` block, so a logging fault here cannot chain the pyx12 exception.""" if install_fault: return RuntimeError( - f"strict X12 validation could not run: pyx12's maps or modules could not be loaded " - f"({failure}); reinstall the optional 'x12' extra: pip install 'messagefoundry[x12]'" + "strict X12 validation could not run: pyx12's maps, modules or config could not be " + f"loaded ({failure}); check pyx12's config file or reinstall the optional 'x12' " + "extra: pip install 'messagefoundry[x12]'" ) + _note_walk_refusal(failure, no_map=no_map) reason = ( - "pyx12 has no map for this interchange's ISA12, GS01 and GS08" + "pyx12 has no map that selects this interchange, which may follow a guide it does not " + "bundle" if no_map else "pyx12 stopped partway through this interchange" ) return X12ValidationError(f"strict X12 validation could not run: {reason} ({failure})") +#: How often one exception class's refusal line is written. A sender chooses how often a refusal +#: runs, so the log is bounded the way :class:`~messagefoundry.transports.admission.RefusalLog` +#: bounds a listener's, which ``parsing`` cannot import. +_WALK_REFUSAL_LOG_SECONDS = 60.0 +_WALK_REFUSAL_LOCK = threading.Lock() +# Keyed by exception class name and the no-map flag, a set pyx12's code fixes and no input can grow. +_walk_refusal_counts: Counter[tuple[str, bool]] = Counter() +_walk_refusal_logged_at: dict[tuple[str, bool], float] = {} + + +def _note_walk_refusal(failure: str, *, no_map: bool) -> None: + """Count one refused walk, and log its class at WARNING at most once per + :data:`_WALK_REFUSAL_LOG_SECONDS` per key, so a flood of one kind cannot hide another. No-map + refusals have their own key because a sender can raise them at will with the ``EngineError`` + that a damaged map also raises. The line holds the class name and the running count, never the + exception's message, arguments or chain, which can quote the interchange.""" + key = (failure, no_map) + now = time.monotonic() + with _WALK_REFUSAL_LOCK: + _walk_refusal_counts[key] += 1 + count = _walk_refusal_counts[key] + logged_at = _walk_refusal_logged_at.get(key) + if logged_at is not None and now - logged_at < _WALK_REFUSAL_LOG_SECONDS: + return + _walk_refusal_logged_at[key] = now + _log.warning( + "strict X12 validation refused an interchange pyx12 has no map for (%s, %d in all since " + "start, logged at most once every %gs)" + if no_map + else "strict X12 validation refused an interchange after pyx12 raised %s (%d in all since " + "start, logged at most once every %gs per class); a run of one class can mean a damaged " + "pyx12 install", + failure, + count, + _WALK_REFUSAL_LOG_SECONDS, + ) + + def validate(raw: str | bytes) -> X12ValidationResult: """Strictly validate an X12 interchange against pyx12's bundled implementation-guide maps. @@ -325,17 +369,18 @@ def validate(raw: str | bytes) -> X12ValidationResult: the structural error list, and the generated 997/999 acknowledgment. Raises :class:`~messagefoundry.parsing.x12.errors.X12ValidationError` when pyx12 could not finish - a pass over this interchange: at least when the bytes are not a parseable X12 data file, when it - names a version pyx12 has no map for, and when pyx12 raises partway through a walk, as a - non-numeric GE01 makes it do. It chains no pyx12 exception. A pass that finishes with violations - is returned as data (``valid=False``), not raised, so a Handler can still emit the negative ack. + a pass over this interchange: at least when the bytes are not a parseable X12 data file, when + pyx12 has no map that selects it, which a conformant interchange under a guide pyx12 does not + bundle also meets, and when pyx12 raises partway through a walk, as a non-numeric GE01 makes it + do. It chains no pyx12 exception. A pass that finishes with violations is returned as data + (``valid=False``), not raised, so a Handler can still emit the negative ack. Raises :class:`RuntimeError`, a deploy/config error distinct from the ``ValueError``-rooted data - errors and chaining nothing from pyx12, if the ``[x12]`` extra is absent or a walk fails on a - damaged install: one of :data:`~messagefoundry.parsing.x12._deps.X12_INSTALL_FAULTS`, or any - failure while :func:`~messagefoundry.parsing.x12._deps.x12_install_loads` is false. A transaction - map that still parses but is wrong can raise some other class, which reads as a refusal of the - interchange, and an index that has lost a map's entry reads as having no map for it.""" + errors and chaining nothing from pyx12, if the ``[x12]`` extra is absent or the walk raises a + type :func:`~messagefoundry.parsing.x12._deps.is_x12_install_fault` names. + + **A damaged install does not always reach that path**: :class:`X12ValidationError` says when it + does not, and :func:`_note_walk_refusal` what an operator then sees.""" if isinstance(raw, (bytes, bytearray)): # noqa: SIM108 text = bytes(raw).decode("utf-8", "replace") else: @@ -343,7 +388,6 @@ def validate(raw: str | bytes) -> X12ValidationResult: x12n_document, make_params = load_x12_validator() resolve = load_x12_code_resolver() # before the walk, so a pyx12 older than 4.0.1 fails first - params = make_params() fd_ack = _AckBuffer() fd_json = io.StringIO() @@ -351,10 +395,11 @@ def validate(raw: str | bytes) -> X12ValidationResult: walk_failure: str | None = None install_fault = no_map = False try: - valid = bool(x12n_document(params, io.StringIO(text), fd_ack, None, None, fd_json)) + # The params are built in here because they read pyx12's config file, which can be damaged. + valid = bool(x12n_document(make_params(), io.StringIO(text), fd_ack, None, None, fd_json)) except Exception as exc: # pyx12 raises bare Exception/EngineError on unwalkable input walk_failure = type(exc).__name__ - install_fault = isinstance(exc, X12_INSTALL_FAULTS) + install_fault = is_x12_install_fault(exc) # By name, because an import here could raise and chain this exception. The text is compared # with pyx12's own fixed prefix and not kept. no_map = walk_failure == "EngineError" and str(exc).startswith("Map not found") @@ -362,11 +407,7 @@ def validate(raw: str | bytes) -> X12ValidationResult: # `from exc` puts that on __cause__, and `from None` still leaves it on __context__ (BACKLOG # #5370, the pattern of json_loads_or_refusal, #2085). Only the class name is kept. if walk_failure is not None: - raise _walk_refusal( - walk_failure, - install_fault=install_fault or not x12_install_loads(), - no_map=no_map, - ) + raise _walk_refusal(walk_failure, install_fault=install_fault, no_map=no_map) raw_json = fd_json.getvalue() if not raw_json.strip(): diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 335569f448..d732af60f1 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -16,6 +16,7 @@ import threading import traceback import zipfile +from collections import Counter from collections.abc import Callable, Iterator from pathlib import Path from types import SimpleNamespace @@ -25,6 +26,7 @@ pytest.importorskip("pyx12") +from messagefoundry._vendor.defusedxml.common import DTDForbidden # noqa: E402 from messagefoundry._vendor.defusedxml.ElementTree import ParseError # noqa: E402 from messagefoundry.parsing.x12 import ( # noqa: E402 - after importorskip X12SegmentError, @@ -36,7 +38,6 @@ _read_map_segment_ids, load_x12_code_resolver, load_x12_map_segment_ids, - x12_install_loads, ) from messagefoundry.redaction import safe_traceback # noqa: E402 from tests._content_free import assert_chain_severed # noqa: E402 @@ -907,8 +908,22 @@ def _assert_no_plant(exc: BaseException, plants: tuple[str, ...] = (_PLANT,)) -> lambda: ImportError(_PLANT), lambda: ModuleNotFoundError(_PLANT), lambda: ParseError(_PLANT), + lambda: DTDForbidden(_PLANT, None, None), # the engine's vendored copy + lambda: importlib.import_module("defusedxml.common").DTDForbidden(_PLANT, None, None), + lambda: importlib.import_module("defusedxml.common").EntitiesForbidden( + _PLANT, _PLANT, None, None, None, None + ), + ], + ids=[ + "missing-map", + "denied-map", + "import", + "module", + "damaged-xml", + "vendored-refusal", + "pyx12s-dtd-refusal", + "pyx12s-entity-refusal", ], - ids=["missing-map", "denied-map", "import", "module", "damaged-xml"], ) def test_a_damaged_install_is_not_reported_as_a_data_fault( fault: Callable[[], Exception], monkeypatch: pytest.MonkeyPatch @@ -939,62 +954,173 @@ def gone(*_args: Any, **_kwargs: Any) -> Any: _assert_no_plant(caught.value) -def test_any_walk_failure_is_an_install_fault_while_the_install_cannot_load( - monkeypatch: pytest.MonkeyPatch, -) -> None: - # AttributeError is a class X12_INSTALL_FAULTS does not name. - walk = _walk_raising(lambda: AttributeError(_PLANT)) - monkeypatch.setattr(_X12_VALIDATE, "load_x12_validator", walk) - # Control: with a loading install the same class is a refusal of this interchange. - monkeypatch.setattr(_X12_VALIDATE, "x12_install_loads", lambda: True) - with pytest.raises(X12ValidationError) as refused: - validate(_conformant_270()) - _assert_no_plant(refused.value) +def test_a_damaged_pyx12_config_is_an_install_fault(monkeypatch: pytest.MonkeyPatch) -> None: + def make_params() -> Any: + raise ParseError(_PLANT) - monkeypatch.setattr(_X12_VALIDATE, "x12_install_loads", lambda: False) + monkeypatch.setattr( + _X12_VALIDATE, "load_x12_validator", lambda: (lambda *_args: True, make_params) + ) with pytest.raises(RuntimeError) as caught: validate(_conformant_270()) assert type(caught.value) is RuntimeError _assert_no_plant(caught.value) -def test_a_table_that_parses_but_is_damaged_is_an_install_fault( - monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +@pytest.fixture +def fresh_refusal_log(monkeypatch: pytest.MonkeyPatch) -> None: + """An empty per-class throttle, so a line an earlier test wrote cannot hold this test's back.""" + monkeypatch.setattr(_X12_VALIDATE, "_walk_refusal_counts", Counter()) + monkeypatch.setattr(_X12_VALIDATE, "_walk_refusal_logged_at", {}) + + +def _refusal_records(caplog: pytest.LogCaptureFixture) -> list[logging.LogRecord]: + return [r for r in caplog.records if r.name == _X12_VALIDATE.__name__] + + +# BHT02 alone fails to select a map here: this GS01 and GS08 have index entries for 11 and 13. +_BHT02_NO_MAP = ( + _ISA_270 + "GS*HI*SENDERAPP*RECVAPP*20060501*1200*1*X*004010X094A1~ST*278*0001~" + "BHT*0078*99*1*20060501*1200~SE*3*0001~GE*1*1~IEA*1*000000001~" +) + + +@pytest.mark.parametrize( + "raw", + [*(raw for raw, _plants in _RAISING_INTERCHANGES.values()), _BHT02_NO_MAP], + ids=[*_RAISING_INTERCHANGES, "bht02"], +) +def test_a_sender_caused_failure_is_not_an_install_fault(raw: str) -> None: + with pytest.raises(X12ValidationError) as caught: + validate(raw) + assert type(caught.value) is X12ValidationError + assert "reinstall" not in str(caught.value) + + +def test_a_passing_load_fault_cannot_turn_a_bad_interchange_into_an_install_fault( + monkeypatch: pytest.MonkeyPatch, ) -> None: - # What a bad value in dataele.xml does: the map build raises a class no install-fault list - # names, on the real walk and on the probe alike, while the segment id read still succeeds. + # The classification reads the walk's own exception and loads nothing more, so a map file held + # by a scanner at that moment cannot change the answer for an interchange that was bad anyway. import pyx12.map_if - def damaged(*_args: Any, **_kwargs: Any) -> Any: - raise ValueError(_PLANT) + def locked(*_args: Any, **_kwargs: Any) -> Any: + raise PermissionError(13, "denied", _PLANT) - monkeypatch.setattr(pyx12.map_if, "load_map_file", damaged) - with caplog.at_level(logging.WARNING), pytest.raises(RuntimeError) as caught: + monkeypatch.setattr(pyx12.map_if, "load_map_file", locked) + walk = _walk_raising(lambda: ValueError(_PLANT)) + monkeypatch.setattr(_X12_VALIDATE, "load_x12_validator", walk) + with pytest.raises(X12ValidationError) as caught: validate(_conformant_270()) - assert type(caught.value) is RuntimeError + assert type(caught.value) is X12ValidationError _assert_no_plant(caught.value) - assert "ValueError" in caplog.text and _PLANT not in caplog.text -def test_the_install_probe_passes_on_a_good_install_and_never_raises( +@pytest.mark.parametrize( + "fault", + [ + lambda: AttributeError(_PLANT), + lambda: ValueError(_PLANT), + lambda: KeyError(_PLANT), + lambda: TypeError(_PLANT), + MemoryError, + lambda: RecursionError(_PLANT), + ], + ids=["attribute", "value", "key", "type", "memory", "recursion"], +) +@pytest.mark.usefixtures("fresh_refusal_log") +def test_an_ordinary_error_reads_as_a_refusal_with_only_its_class_logged( + fault: Callable[[], Exception], monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, ) -> None: - import pyx12.map_index + # This is also what a damaged map or table that still parses does: a refusal, its class logged. + monkeypatch.setattr(_X12_VALIDATE, "load_x12_validator", _walk_raising(fault)) + with caplog.at_level(logging.WARNING), pytest.raises(X12ValidationError) as caught: + validate(_conformant_270()) + assert type(caught.value) is X12ValidationError + _assert_no_plant(caught.value) - assert x12_install_loads() is True + [record] = _refusal_records(caplog) + assert record.levelno == logging.WARNING + assert record.exc_info is None and record.stack_info is None + assert type(fault()).__name__ in record.getMessage() + assert _PLANT not in record.getMessage() - def broken(*_args: Any) -> Any: - raise MemoryError - monkeypatch.setattr(pyx12.map_index, "map_index", broken) - assert x12_install_loads() is False - monkeypatch.setattr(pyx12.map_index, "map_index", lambda: SimpleNamespace(maps=[])) - assert x12_install_loads() is False +@pytest.mark.parametrize( + ("raw", "plants"), list(_RAISING_INTERCHANGES.values()), ids=list(_RAISING_INTERCHANGES) +) +@pytest.mark.usefixtures("fresh_refusal_log") +def test_nothing_in_the_refusal_log_line_is_sender_text( + raw: str, plants: tuple[str, ...], caplog: pytest.LogCaptureFixture +) -> None: + with caplog.at_level(logging.WARNING), pytest.raises(X12ValidationError): + validate(raw) + [record] = _refusal_records(caplog) + # Each argument is the class name, a count or the fixed interval, never a value from the input. + assert isinstance(record.args, tuple) + assert isinstance(record.args[0], str) and record.args[0].isidentifier() + assert all(isinstance(arg, (int, float)) for arg in record.args[1:]) + assert record.exc_info is None + assert not any(plant in record.getMessage() for plant in plants) -def test_an_unknown_gs08_is_named_as_no_map_and_stays_a_data_error() -> None: - with pytest.raises(X12ValidationError, match="no map"): - validate(_RAISING_INTERCHANGES["gs08"][0]) +@pytest.mark.usefixtures("fresh_refusal_log") +def test_the_refusal_log_line_is_limited_per_key( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + # A sender chooses how often a refusal runs, so it must not choose how much is logged, and a + # flood of one kind must not hide the first line of another. + now = [1000.0] + monkeypatch.setattr(_X12_VALIDATE, "time", SimpleNamespace(monotonic=lambda: now[0])) + pause = _X12_VALIDATE._WALK_REFUSAL_LOG_SECONDS + + def note(failure: str, *, no_map: bool = False) -> list[Any]: + caplog.clear() + _X12_VALIDATE._note_walk_refusal(failure, no_map=no_map) + return [r.args for r in _refusal_records(caplog)] + + with caplog.at_level(logging.WARNING): + assert note("ValueError") == [("ValueError", 1, pause)] + assert note("ValueError") == [] + now[0] += pause - 0.001 + assert note("ValueError") == [] + assert note("AttributeError") == [("AttributeError", 1, pause)] + now[0] += 0.001 # the window is over, and the line carries the volume it held back + assert note("ValueError") == [("ValueError", 4, pause)] + + +@pytest.mark.usefixtures("fresh_refusal_log") +def test_a_flood_of_no_map_refusals_cannot_hide_a_damaged_map( + caplog: pytest.LogCaptureFixture, +) -> None: + # A sender can raise EngineError at will with an unknown GS08, and a damaged map raises it too. + with caplog.at_level(logging.WARNING): + for _ in range(3): + _X12_VALIDATE._note_walk_refusal("EngineError", no_map=True) + _X12_VALIDATE._note_walk_refusal("EngineError", no_map=False) + no_map_line, damage_line = _refusal_records(caplog) + assert "no map" in no_map_line.getMessage() and "damaged" not in no_map_line.getMessage() + assert "damaged" in damage_line.getMessage() + assert damage_line.args == ("EngineError", 1, _X12_VALIDATE._WALK_REFUSAL_LOG_SECONDS) + + +@pytest.mark.parametrize( + "raw", + [ + _RAISING_INTERCHANGES["gs08"][0], + _BHT02_NO_MAP, + _conformant_270().replace("004010X092A1", "005010X279A1"), # conformant, but not bundled + ], + ids=["gs08", "bht02", "unbundled-guide"], +) +def test_a_no_map_refusal_says_so_and_blames_no_element(raw: str) -> None: + with pytest.raises(X12ValidationError, match="no map") as caught: + validate(raw) + message = str(caught.value) + assert "does not bundle" in message and "stopped partway" not in message + assert not any(name in message for name in ("ISA12", "GS01", "GS08", "BHT02")) @pytest.mark.parametrize("name", ["isa17", "ge01"]) From 87b878342ad47079a386ddd932554f85776e02ef Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:36:03 -0600 Subject: [PATCH 13/16] X12 params failure is an install fault; refusal and chain prose made true make_params reads no sender data, but inside the walk's try a failure such as IndexError on an empty sys.argv became a data refusal. It now has its own try, and any failure there is a RuntimeError holding only the class name. errors.py and the changelog no longer say every refusal logs: the no-report and unreadable-report refusals do not. The validate docstring now says the missing-extra error chains its ImportError, raised before any interchange is read. Proposed PR title: X12 strict validate chains no pyx12 exception and keeps sender text out of its reprs (BACKLOG #5370) BACKLOG #5370 --- changelog.d/5370.security.md | 16 +++++++------ messagefoundry/parsing/x12/errors.py | 10 +++++---- messagefoundry/parsing/x12/validate.py | 19 +++++++++++----- tests/test_x12_validate.py | 31 +++++++++++++++++++++----- 4 files changed, 54 insertions(+), 22 deletions(-) diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md index 8d3cd9537b..237417e5c0 100644 --- a/changelog.d/5370.security.md +++ b/changelog.d/5370.security.md @@ -6,12 +6,14 @@ in pyx12's bundled index defines it. So a wrongly delimited segment, or a name's tail standing where the id goes, no longer lands in `segment_id` or `message`, unless it equals an indexed id, for example `LIN`, `PAT`, or the `LE` of a name written `O~LE`. Such a value is kept in both even - in a transaction whose own map does not define it. A walk that fails with a type a sender's bytes - cannot raise (`OSError`, `ImportError`, an XML `ParseError` or a defusedxml refusal) now raises - `RuntimeError` rather than `X12ValidationError`. A Handler's `except ValueError` does not catch - it, but left uncaught it takes the `internal_error` policy, whose default also dead-letters the - row. A damaged map or table that still parses raises an ordinary error, so it still reads as a - refusal; each refusal logs its exception class at WARNING, rate-limited per class, with no - message or sender text. A refusal for an interchange pyx12 has no map for now says so, since it + in a transaction whose own map does not define it. A failure building pyx12's params, or a walk + that fails with a type a sender's bytes cannot raise (`OSError`, `ImportError`, an XML + `ParseError` or a defusedxml refusal), now raises `RuntimeError` rather than + `X12ValidationError`. A Handler's `except ValueError` does not catch it, but left uncaught it + takes the `internal_error` policy, whose default also dead-letters the row. A damaged map or + table that still parses raises an ordinary error, so it still reads as a refusal. A refusal from + a walk that raised logs its exception class at WARNING, rate-limited, with no message or sender + text. The refusals for a missing or unreadable pyx12 report log nothing. A refusal for an + interchange pyx12 has no map for now says so, since it may follow a guide pyx12 does not bundle. A failed read of the segment id set no longer discards a finished pass. (`BACKLOG #5370`) diff --git a/messagefoundry/parsing/x12/errors.py b/messagefoundry/parsing/x12/errors.py index afe419af30..282b3b72cb 100644 --- a/messagefoundry/parsing/x12/errors.py +++ b/messagefoundry/parsing/x12/errors.py @@ -37,15 +37,17 @@ class X12ValidationError(X12Error): bundle also meets, and when pyx12 raises partway through a walk, as a non-numeric GE01 makes it do. So this does not always mean the interchange is bad. - A walk failure of a type a sender's bytes cannot raise - (:func:`~messagefoundry.parsing.x12._deps.is_x12_install_fault`) is a :class:`RuntimeError` + A failure building pyx12's params, and a walk failure of a type a sender's bytes cannot raise + (:func:`~messagefoundry.parsing.x12._deps.is_x12_install_fault`), is a :class:`RuntimeError` instead. A Handler's ``except ValueError`` does not catch that, but left uncaught it takes the ``internal_error`` policy, whose default, ``CONTINUE``, also dead-letters the row. **A damaged install can land here too.** A map or table that still parses but is wrong raises an ordinary error, and an index that lost a map's entry reads as having no map, so each is this - error, which a Handler's ``except ValueError`` would dead-letter. Each refusal logs its exception - class at WARNING, rate-limited, so a run of one class shows an operator the damage. + error, which a Handler's ``except ValueError`` would dead-letter. A refusal from a walk that + raised logs its exception class at WARNING, rate-limited, so a run of one class can show an + operator the damage. The two refusals with no exception to name log nothing: pyx12 wrote no + report ("does not look like an X12 data file"), or its report could not be read. The X12 analog of :class:`~messagefoundry.parsing.fhir.errors.FhirValidationError`. A *failed validation* (a pass diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index 635e9a01e0..d90cd7a7e4 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -302,7 +302,7 @@ def _flatten_errors( def _walk_refusal(failure: str, *, install_fault: bool, no_map: bool) -> Exception: - """The exception for a walk that raised, holding only that exception's class name. An install + """The exception for a walk, or its params, that raised, holding only the class name. An install fault is a :class:`RuntimeError`, which a Handler's ``except ValueError`` does not catch. Every other failure is an :class:`X12ValidationError`, which says what pyx12 could not do and does not claim the interchange is bad: it can conform to a guide pyx12 does not bundle. Called outside @@ -376,8 +376,10 @@ def validate(raw: str | bytes) -> X12ValidationResult: (``valid=False``), not raised, so a Handler can still emit the negative ack. Raises :class:`RuntimeError`, a deploy/config error distinct from the ``ValueError``-rooted data - errors and chaining nothing from pyx12, if the ``[x12]`` extra is absent or the walk raises a - type :func:`~messagefoundry.parsing.x12._deps.is_x12_install_fault` names. + errors, if the ``[x12]`` extra is absent or too old, if pyx12's params cannot be built, or if + the walk raises a type :func:`~messagefoundry.parsing.x12._deps.is_x12_install_fault` names. The + last two keep only the exception's class name and chain nothing. The first chains its + ``ImportError``, which is raised before any interchange is read. **A damaged install does not always reach that path**: :class:`X12ValidationError` says when it does not, and :func:`_note_walk_refusal` what an operator then sees.""" @@ -392,11 +394,18 @@ def validate(raw: str | bytes) -> X12ValidationResult: fd_json = io.StringIO() _mute_pyx12_logger() + params_failure: str | None = None + try: + params = make_params() + except Exception as exc: # it reads pyx12's config and no sender data, so never a refusal + params_failure = type(exc).__name__ + if params_failure is not None: # raised out here so that nothing is chained + raise _walk_refusal(params_failure, install_fault=True, no_map=False) + walk_failure: str | None = None install_fault = no_map = False try: - # The params are built in here because they read pyx12's config file, which can be damaged. - valid = bool(x12n_document(make_params(), io.StringIO(text), fd_ack, None, None, fd_json)) + valid = bool(x12n_document(params, io.StringIO(text), fd_ack, None, None, fd_json)) except Exception as exc: # pyx12 raises bare Exception/EngineError on unwalkable input walk_failure = type(exc).__name__ install_fault = is_x12_install_fault(exc) diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index d732af60f1..8ba668ee49 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -954,17 +954,36 @@ def gone(*_args: Any, **_kwargs: Any) -> Any: _assert_no_plant(caught.value) -def test_a_damaged_pyx12_config_is_an_install_fault(monkeypatch: pytest.MonkeyPatch) -> None: +@pytest.mark.parametrize( + "fault", + [ + lambda: ParseError(_PLANT), + lambda: IndexError(_PLANT), # what pyx12's params raise on an empty sys.argv + lambda: ValueError(_PLANT), + lambda: AttributeError(_PLANT), + lambda: type("EngineError", (Exception,), {})("Map not found " + _PLANT), + ], + ids=["parse", "index", "value", "attribute", "no-map-text"], +) +def test_any_failure_building_pyx12s_params_is_an_install_fault( + fault: Callable[[], Exception], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + # The params read no sender data, so none of their failures is a refusal of the interchange. def make_params() -> Any: - raise ParseError(_PLANT) + raise fault() - monkeypatch.setattr( - _X12_VALIDATE, "load_x12_validator", lambda: (lambda *_args: True, make_params) - ) - with pytest.raises(RuntimeError) as caught: + def walk(*_args: Any) -> bool: + raise AssertionError("the walk must not run without its params") + + monkeypatch.setattr(_X12_VALIDATE, "load_x12_validator", lambda: (walk, make_params)) + with caplog.at_level(logging.WARNING), pytest.raises(RuntimeError) as caught: validate(_conformant_270()) assert type(caught.value) is RuntimeError + assert type(fault()).__name__ in str(caught.value) _assert_no_plant(caught.value) + assert _refusal_records(caplog) == [] # counted as an install fault, not as a refusal @pytest.fixture From cec084c6812fbedc07b01ec6ab20c5da1fd884ae Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 14:53:39 -0600 Subject: [PATCH 14/16] X12 changelog states what each failure raised before A params failure raised pyx12's raw exception on main, because make_params() sat outside any try. Only a walk failure of an install-fault type moved from X12ValidationError to RuntimeError. BACKLOG #5370 --- changelog.d/5370.security.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md index 237417e5c0..82bb6ccfd6 100644 --- a/changelog.d/5370.security.md +++ b/changelog.d/5370.security.md @@ -6,10 +6,11 @@ in pyx12's bundled index defines it. So a wrongly delimited segment, or a name's tail standing where the id goes, no longer lands in `segment_id` or `message`, unless it equals an indexed id, for example `LIN`, `PAT`, or the `LE` of a name written `O~LE`. Such a value is kept in both even - in a transaction whose own map does not define it. A failure building pyx12's params, or a walk - that fails with a type a sender's bytes cannot raise (`OSError`, `ImportError`, an XML - `ParseError` or a defusedxml refusal), now raises `RuntimeError` rather than - `X12ValidationError`. A Handler's `except ValueError` does not catch it, but left uncaught it + in a transaction whose own map does not define it. A failure building pyx12's params, which + raised pyx12's raw exception before, now raises `RuntimeError`. Of a walk's failures, only one + of a type a sender's bytes cannot raise (`OSError`, `ImportError`, an XML `ParseError` or a + defusedxml refusal) moved from `X12ValidationError` to `RuntimeError`. A Handler's + `except ValueError` does not catch it, but left uncaught it takes the `internal_error` policy, whose default also dead-letters the row. A damaged map or table that still parses raises an ordinary error, so it still reads as a refusal. A refusal from a walk that raised logs its exception class at WARNING, rate-limited, with no message or sender From 0605442e955554ff80f4d5ffab089a4a4d2ebb06 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 15:06:49 -0600 Subject: [PATCH 15/16] X12 prose drops two false claims and names what logs A map whose content is wrong can return a wrong verdict and raise nothing, so the claim that it reads as a refusal is deleted from the fragment, the X12ValidationError docstring and a test comment. The fragment also drops a fix for a read no shipped code had, says which refusal logs at WARNING, and limits the sender claim to pyx12 4.1.0. Comments and prose only. BACKLOG #5370 --- changelog.d/5370.security.md | 16 +++++++--------- messagefoundry/parsing/x12/errors.py | 11 +++++------ tests/test_x12_validate.py | 1 - 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md index 82bb6ccfd6..caccbf6320 100644 --- a/changelog.d/5370.security.md +++ b/changelog.d/5370.security.md @@ -7,14 +7,12 @@ where the id goes, no longer lands in `segment_id` or `message`, unless it equals an indexed id, for example `LIN`, `PAT`, or the `LE` of a name written `O~LE`. Such a value is kept in both even in a transaction whose own map does not define it. A failure building pyx12's params, which - raised pyx12's raw exception before, now raises `RuntimeError`. Of a walk's failures, only one - of a type a sender's bytes cannot raise (`OSError`, `ImportError`, an XML `ParseError` or a + raised pyx12's raw exception before, now raises `RuntimeError`. Only a walk failure of a type a + sender's bytes cannot raise in pyx12 4.1.0 (`OSError`, `ImportError`, an XML `ParseError` or a defusedxml refusal) moved from `X12ValidationError` to `RuntimeError`. A Handler's - `except ValueError` does not catch it, but left uncaught it - takes the `internal_error` policy, whose default also dead-letters the row. A damaged map or - table that still parses raises an ordinary error, so it still reads as a refusal. A refusal from - a walk that raised logs its exception class at WARNING, rate-limited, with no message or sender + `except ValueError` catches neither `RuntimeError`, but left uncaught each takes the + `internal_error` policy, whose default also dead-letters the row. An `X12ValidationError` from a + walk that raised logs its exception class at WARNING, rate-limited, with no message or sender text. The refusals for a missing or unreadable pyx12 report log nothing. A refusal for an - interchange pyx12 has no map for now says so, since it - may follow a guide pyx12 does not bundle. A failed read of the segment id set no longer discards - a finished pass. (`BACKLOG #5370`) + interchange pyx12 has no map for now says so, since it may follow a guide pyx12 does not bundle. + (`BACKLOG #5370`) diff --git a/messagefoundry/parsing/x12/errors.py b/messagefoundry/parsing/x12/errors.py index 282b3b72cb..4447b60f9a 100644 --- a/messagefoundry/parsing/x12/errors.py +++ b/messagefoundry/parsing/x12/errors.py @@ -42,12 +42,11 @@ class X12ValidationError(X12Error): instead. A Handler's ``except ValueError`` does not catch that, but left uncaught it takes the ``internal_error`` policy, whose default, ``CONTINUE``, also dead-letters the row. - **A damaged install can land here too.** A map or table that still parses but is wrong raises - an ordinary error, and an index that lost a map's entry reads as having no map, so each is this - error, which a Handler's ``except ValueError`` would dead-letter. A refusal from a walk that - raised logs its exception class at WARNING, rate-limited, so a run of one class can show an - operator the damage. The two refusals with no exception to name log nothing: pyx12 wrote no - report ("does not look like an X12 data file"), or its report could not be read. + **A damaged install can land here too.** An index that lost a map's entry reads as having no + map, so it is this error, which a Handler's ``except ValueError`` would dead-letter. A refusal + from a walk that raised logs its exception class at WARNING, rate-limited, so a run of one class + can show an operator the damage. The two refusals with no exception to name log nothing: pyx12 + wrote no report ("does not look like an X12 data file"), or its report could not be read. The X12 analog of :class:`~messagefoundry.parsing.fhir.errors.FhirValidationError`. A *failed validation* (a pass diff --git a/tests/test_x12_validate.py b/tests/test_x12_validate.py index 8ba668ee49..388daebfc9 100644 --- a/tests/test_x12_validate.py +++ b/tests/test_x12_validate.py @@ -1053,7 +1053,6 @@ def test_an_ordinary_error_reads_as_a_refusal_with_only_its_class_logged( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, ) -> None: - # This is also what a damaged map or table that still parses does: a refusal, its class logged. monkeypatch.setattr(_X12_VALIDATE, "load_x12_validator", _walk_raising(fault)) with caplog.at_level(logging.WARNING), pytest.raises(X12ValidationError) as caught: validate(_conformant_270()) From caa1ae88b4547dfd6ed9c6b4a6696f5b1ba2f6db Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 15:21:14 -0600 Subject: [PATCH 16/16] X12 prose stops pointing at a damage account it lacks Two docstrings sent readers to X12ValidationError for what a damaged install does, and one clause promised a log run would show the damage. All three are deleted. A private pyx12 4.1.0 copy with one BHT01 code changed returned a wrong valid=True with no exception or log record, so the docstring and the fragment now say a wrong map can do that. Docstrings and the fragment only. BACKLOG #5370 --- changelog.d/5370.security.md | 3 ++- messagefoundry/parsing/x12/_deps.py | 5 +---- messagefoundry/parsing/x12/errors.py | 7 ++++--- messagefoundry/parsing/x12/validate.py | 5 +---- 4 files changed, 8 insertions(+), 12 deletions(-) diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md index caccbf6320..ca7f794864 100644 --- a/changelog.d/5370.security.md +++ b/changelog.d/5370.security.md @@ -15,4 +15,5 @@ walk that raised logs its exception class at WARNING, rate-limited, with no message or sender text. The refusals for a missing or unreadable pyx12 report log nothing. A refusal for an interchange pyx12 has no map for now says so, since it may follow a guide pyx12 does not bundle. - (`BACKLOG #5370`) + A map whose content is wrong but still parses can produce a wrong validation result, with no + exception or log line. (`BACKLOG #5370`) diff --git a/messagefoundry/parsing/x12/_deps.py b/messagefoundry/parsing/x12/_deps.py index ae6a8790bd..3637715927 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -54,10 +54,7 @@ def is_x12_install_fault(exc: Exception) -> bool: ``ImportError``, XML ``ParseError`` and a defusedxml refusal each mean the install or its config is at fault. That is read from pyx12 4.1.0's source. A refusal is matched by class name because pyx12 raises the upstream package's class, which is not the engine's vendored one, and an import - here could raise and chain the exception being classified. - - It is a statement about types only, so it does not catch every damaged install: - :class:`~messagefoundry.parsing.x12.errors.X12ValidationError` says what the rest do.""" + here could raise and chain the exception being classified.""" return isinstance(exc, (OSError, ImportError, ParseError)) or any( cls.__name__ == "DefusedXmlException" and cls.__module__.endswith("defusedxml.common") for cls in type(exc).__mro__ diff --git a/messagefoundry/parsing/x12/errors.py b/messagefoundry/parsing/x12/errors.py index 4447b60f9a..47837e2fe8 100644 --- a/messagefoundry/parsing/x12/errors.py +++ b/messagefoundry/parsing/x12/errors.py @@ -44,9 +44,10 @@ class X12ValidationError(X12Error): **A damaged install can land here too.** An index that lost a map's entry reads as having no map, so it is this error, which a Handler's ``except ValueError`` would dead-letter. A refusal - from a walk that raised logs its exception class at WARNING, rate-limited, so a run of one class - can show an operator the damage. The two refusals with no exception to name log nothing: pyx12 - wrote no report ("does not look like an X12 data file"), or its report could not be read. + from a walk that raised logs its exception class at WARNING, rate-limited. The two refusals with + no exception to name log nothing: pyx12 wrote no report ("does not look like an X12 data file"), + or its report could not be read. A map whose content is wrong but still parses can produce a + wrong validation result, with no exception or log line. The X12 analog of :class:`~messagefoundry.parsing.fhir.errors.FhirValidationError`. A *failed validation* (a pass diff --git a/messagefoundry/parsing/x12/validate.py b/messagefoundry/parsing/x12/validate.py index d90cd7a7e4..db5f1da298 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -379,10 +379,7 @@ def validate(raw: str | bytes) -> X12ValidationResult: errors, if the ``[x12]`` extra is absent or too old, if pyx12's params cannot be built, or if the walk raises a type :func:`~messagefoundry.parsing.x12._deps.is_x12_install_fault` names. The last two keep only the exception's class name and chain nothing. The first chains its - ``ImportError``, which is raised before any interchange is read. - - **A damaged install does not always reach that path**: :class:`X12ValidationError` says when it - does not, and :func:`_note_walk_refusal` what an operator then sees.""" + ``ImportError``, which is raised before any interchange is read.""" if isinstance(raw, (bytes, bytearray)): # noqa: SIM108 text = bytes(raw).decode("utf-8", "replace") else: