Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
596ec91
X12 strict validate chains no pyx12 exception and keeps sender text o…
wshallwshall Nov 23, 2026
e5a2a7f
X12 validate docstrings state the segment id limit; add the changelog…
wshallwshall Nov 23, 2026
2ca19a7
X12 validate docstrings state what loop and the id pattern really do
wshallwshall Nov 23, 2026
4b56f6e
X12 errors keep a segment id only when an indexed pyx12 map defines it
wshallwshall Nov 23, 2026
e3aaf20
pyx12 4.1.0 changelog no longer says X12ValidationError chains the error
wshallwshall Nov 23, 2026
1ccf61f
X12 segment id set retries a failed read and states its real limit
wshallwshall Nov 23, 2026
f09f820
X12 validate prose states its real limits; retry test needs the deadline
wshallwshall Nov 23, 2026
b7984f6
X12 map reader registers its XML parse and path joins, and refuses a DTD
wshallwshall Nov 23, 2026
3a43663
X12 validate keeps a finished pass when the segment id read fails
wshallwshall Nov 23, 2026
cdf26f5
X12 validate keeps a damaged pyx12 install apart from a bad interchange
wshallwshall Nov 23, 2026
62839c8
X12 map reader refuses an index name that is not a bare file name
wshallwshall Nov 23, 2026
c0e5747
X12 validate classifies an install fault by exception type, with no p…
wshallwshall Nov 23, 2026
87b8783
X12 params failure is an install fault; refusal and chain prose made …
wshallwshall Nov 23, 2026
cec084c
X12 changelog states what each failure raised before
wshallwshall Nov 23, 2026
0605442
X12 prose drops two false claims and names what logs
wshallwshall Nov 23, 2026
caa1ae8
X12 prose stops pointing at a damage account it lacks
wshallwshall Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions changelog.d/5370.security.md
Original file line number Diff line number Diff line change
@@ -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`)
8 changes: 4 additions & 4 deletions changelog.d/pyx12-4-1-0.security.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 11 additions & 7 deletions messagefoundry/parsing/x12/__init__.py
Original file line number Diff line number Diff line change
@@ -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):

Expand Down
113 changes: 111 additions & 2 deletions messagefoundry/parsing/x12/_deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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.
Expand All @@ -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 ``<segment>`` 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.
Expand Down
30 changes: 24 additions & 6 deletions messagefoundry/parsing/x12/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Loading