diff --git a/changelog.d/5370.security.md b/changelog.d/5370.security.md new file mode 100644 index 0000000000..ca7f794864 --- /dev/null +++ b/changelog.d/5370.security.md @@ -0,0 +1,19 @@ +- **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 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`, 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`. 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` 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 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/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 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 1bc9965091..3637715927 100644 --- a/messagefoundry/parsing/x12/_deps.py +++ b/messagefoundry/parsing/x12/_deps.py @@ -13,13 +13,31 @@ 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 +import logging +import os.path +import threading +import time from collections.abc import Callable -from typing import Any +from importlib.resources import files +from typing import IO, TYPE_CHECKING, Any + +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() +_MAP_IDS_RETRY_SECONDS = 60.0 +_map_ids: frozenset[str] = frozenset() +_map_ids_retry_at = 0.0 def _missing_extra(feature: str) -> RuntimeError: @@ -28,6 +46,21 @@ 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.""" + 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. @@ -44,6 +77,82 @@ 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. + + 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. + + 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, 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. + 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: + _log_maps_unreadable(exc) + return frozenset() + if not ids: + _log.warning("pyx12's maps define no segment; X12 errors will carry no segment id") + return frozenset(ids) + + +def load_x12_map_segment_ids() -> frozenset[str]: + """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, 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. + + 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: + 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 + + 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/errors.py b/messagefoundry/parsing/x12/errors.py index 3edbbf5cab..47837e2fe8 100644 --- a/messagefoundry/parsing/x12/errors.py +++ b/messagefoundry/parsing/x12/errors.py @@ -31,12 +31,30 @@ 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 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 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.** 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. 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 + 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 - 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 62fb1d584a..db5f1da298 100644 --- a/messagefoundry/parsing/x12/validate.py +++ b/messagefoundry/parsing/x12/validate.py @@ -22,25 +22,36 @@ 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. - -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 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 +to parse that bundled, trusted XML — not attacker input. """ from __future__ import annotations import io import logging +import re +import threading +import time +from collections import Counter 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 +from messagefoundry.parsing.x12._deps import ( + is_x12_install_fault, + 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 @@ -49,14 +60,23 @@ @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; ``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 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 ``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: ``O~LE`` keeps ``LE``, with ``loop`` + naming the segment the name was in.""" code: str message: str @@ -70,16 +90,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 @@ -95,17 +119,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 value-free - 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: @@ -160,6 +187,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 +203,30 @@ 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 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, 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 ( + 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: + """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 +237,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 +273,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] = [] @@ -251,18 +301,85 @@ def _flatten_errors( return out +def _walk_refusal(failure: str, *, install_fault: bool, no_map: bool) -> Exception: + """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 + the ``except`` block, so a logging fault here cannot chain the pyx12 exception.""" + if install_fault: + return RuntimeError( + "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 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. ``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. - - 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).""" + 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 + 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, 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.""" if isinstance(raw, (bytes, bytearray)): # noqa: SIM108 text = bytes(raw).decode("utf-8", "replace") else: @@ -270,17 +387,33 @@ 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() _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: 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 - raise X12ValidationError( - "strict X12 validation could not run: the bytes are not a parseable X12 interchange" - ) from exc + walk_failure = type(exc).__name__ + 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") + # 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 _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_file_path_join_census.py b/tests/test_file_path_join_census.py index e1111f9ba6..a9941cdde6 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, 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." + ), "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_x12_validate.py b/tests/test_x12_validate.py index 1d0485e58b..388daebfc9 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 pyx12's bundled maps define it. A sender value equal to a real id (``LIN``) is still kept.""" from __future__ import annotations @@ -13,20 +14,33 @@ import io import logging import threading +import traceback +import zipfile +from collections import Counter from collections.abc import Callable, Iterator +from pathlib import Path +from types import SimpleNamespace from typing import Any import pytest 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, X12ValidationError, 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 _ISA = ( "ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER " @@ -589,16 +603,615 @@ 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_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) + + +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_shows_no_id() -> None: + result = validate(_270_with(f"ZZZ*{_PLANT}*ROBERT~")) + 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: 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} + + +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) + + +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] = [] + start = 1000.0 + now = [start] + + 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) + # 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 + + 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 + + +_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": ""}, + {"maps.xml": ""}, # LookupError + {"maps.xml": ""}, # plain ValueError + ], + ids=[ + "no-directory", + "no-index", + "empty-index", + "unparseable-index", + "listed-map-missing", + "listed-map-unparseable", + "no-segment", + "unknown-encoding", + "multibyte-encoding", + ], +) +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", 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 + ("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_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"}) + 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") + + +# --- 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), + 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", + ], +) +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) + + +@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 fault() + + 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 +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: + # 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 locked(*_args: Any, **_kwargs: Any) -> Any: + raise PermissionError(13, "denied", _PLANT) + + 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 X12ValidationError + _assert_no_plant(caught.value) + + +@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: + 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) + + [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() + + +@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) + + +@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"]) +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("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"), + [ + ("_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 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)