Skip to content
Merged
11 changes: 11 additions & 0 deletions changelog.d/5920-same-code-borrow-no-exemption.security.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
- **Strict validation checks MSH-9.2 against MSH-9.3 before a borrowed "any HL7 segment"
structure keeps its exemption.** This is a consistency check on what a message says about
itself, not a barrier: a sender controls all of MSH-9, and one that names a structure's own
event keeps the exemption. A message that names such a structure in MSH-9.3 under its own
message code, as `MFN^M02^MFN_M01` does, had dropped defined segments passed and listed in
`unvalidated_segments`. Where MSH-9.2, stripped and upper-cased, names the borrowed structure's
own event, that is unchanged. Otherwise the dropped segments are now refused where `hl7apy`'s
tables have a structure named for MSH-9.1 and MSH-9.2 (`MFN_M02`, or `QBP_Z73` in 2.5), or
where MSH-9.2 neither starts with Z nor is in the version's HL7 table 0003 as `hl7apy` ships
it. A site-defined Z event (`QBP^Z44^QBP_Q15`), an event in that table with no structure of
that name, and a message with no MSH-9.3 are unchanged. (`BACKLOG #5920`)
10 changes: 7 additions & 3 deletions docs/HL7-VALIDATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,13 @@ refused, and so is a dropped bare defined ID with no field separator (a lone `OR
`MFN_M01`); a bare line `hl7apy` placed is not. A dropped `MSH`, `DSC`, `MSA`, `ERR`, `QAK` or
`MFA` line is refused too. A batch or file envelope line (`BHS`, `BTS`, `FHS`, `FTS`) is exempted like any other
defined segment, because batch splitting can leave one on a message. Every dropped segment is refused where MSH-9.3
borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`); a structure
borrowed under the same message code (`MFN^M02^MFN_M01`) still gets the exemption, since MSH-9.2
is not compared. Where the slot is required and its group is present, `hl7apy`'s own check
borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`). Under the same
code, MSH-9.2 decides: a dropped segment in `MFN^M02^MFN_M01` is refused, because `MFN_M02` is a
structure of its own, while some same-code borrows keep the exemption, at least `PGL^PC7^PGL_PC6`
in 2.5, a Z event with no structure of that name in `hl7apy`, such as `QBP^Z44^QBP_Q15` in 2.5, and a
table 0003 event with none, such as `MFN^M14^MFN_M01` or even `MFN^A01^MFN_M01`. The exact
rule is in `_exempts_defined_segments` in [`validate.py`](../messagefoundry/parsing/validate.py).
Where the slot is required and its group is present, `hl7apy`'s own check
refuses at least some such messages, since the slot is never filled (`Missing required child ...
ANYHL7SEGMENT`; `MFN_M03` for one), but not where the slot is one alternative of a choice: a
`PRR_PC5` order with its `OBR` passes. Where the slot sits inside a nested group (at least the
Expand Down
51 changes: 47 additions & 4 deletions messagefoundry/parsing/split.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,18 @@
filled_default_collides,
)
from messagefoundry.parsing.message import COLLIDING_DELIMITERS_WRITE, Message
from messagefoundry.parsing.peek import enforce_expansion_budget, normalize, starts_with_msh
from messagefoundry.parsing.peek import (
enforce_expansion_budget,
normalize,
parse_or_refuse,
starts_with_msh,
)
from messagefoundry.parsing.sniff import _LEADING_WS_STR

__all__ = [
"batch_member_collides",
"encode_batch",
"head_control_id",
"split_batch",
"split_batch_bytes",
"one_message_bytes",
Expand Down Expand Up @@ -493,9 +499,10 @@ def _head_separators(norm: str) -> tuple[str, str, str, str, str]:
budget (:func:`~messagefoundry.parsing.peek.enforce_expansion_budget`, ASVS 1.3.3), run on
``norm`` itself, the text encode_batch frames: a head a parse refuses for its escapes raises
the same ``HL7PeekError`` here, whatever its caller checked. On the delivery path that text is
the hydrated head, and the caller's own parse of the head's stored payload checks the same
budget first, so there this is a second check, not the only one. What else a parse checks in the
rest of the head is not checked: at least a later header line too short to read."""
the hydrated head. The caller's own read (:func:`head_control_id`) checks the same budget on
the head's stored payload, which is other text wherever a document was re-attached, so on
the hydrated text this check is the one that runs. What else a parse checks in the rest of
the head is not checked: at least a later header line too short to read."""
line = _first_line_head(norm)
# The parse's _encoding_chars returns exactly what _extract_separators reads from this line,
# a short MSH-2 filled with the same defaults (BACKLOG #5972), so any MSH line the parse would
Expand All @@ -512,6 +519,42 @@ def _head_separators(norm: str) -> tuple[str, str, str, str, str]:
return field_sep, comp_sep, rep_sep, esc, sub_sep


#: A header line after the first that is too short for the parse to read (``_builtin_hl7.parse``
#: refuses one): a line that is a header ID alone, or the text's last line once the parse's strip
#: leaves only a header ID there. A literal, so the static ReDoS scanner can read it; a test
#: holds its IDs to HEADER_IDS.
_SHORT_LATER_HEADER = re.compile(r"\r(?:MSH|BHS|FHS)(?:\r|\s*\Z)")


def head_control_id(text: str) -> str | None:
"""MSH-10 of a batch's head member as stored, what ``Message.parse(text).control_id``
returns, read from its first line alone where that gives the same result (BACKLOG #5919).

A full parse of a large head to read one field copied the whole head. For a head whose first
line opens with ``MSH`` after whitespace and holds MSH-1 and one more character, the parse's
escape budget (:func:`~messagefoundry.parsing.peek.enforce_expansion_budget`) is checked on
the whole text, as the parse checks it first, and that one line is parsed. The MSH segment is
split from its own line and separators alone, so its MSH-10 is the full parse's. Every other
head, and one the full parse could refuse for a later line or read differently, is parsed in
full, so it reads or raises exactly as the parse does: at least an ``FHS``/``BHS``-led or
non-HL7 head, one with a later header line too short to read, and one whose first line ends in
whitespace, which the parse's strip keeps or drops depending on what follows."""
norm = normalize(text)
end = len(norm)
start = _whitespace_end(norm, 0, end)
cr = norm.find("\r", start)
stop = end if cr == -1 else cr
if (
norm.startswith(_MSH, start)
and stop - start >= _SEPARATORS_WIDTH
and not norm[stop - 1].isspace()
and _SHORT_LATER_HEADER.search(norm, stop) is None
):
enforce_expansion_budget(norm)
return Message(parse_or_refuse(norm[start:stop])).control_id
return Message.parse(norm).control_id


def _framed(text: str) -> tuple[str, ...]:
"""The pieces that frame one member's ``text`` in a batch: its segments with no leading or
trailing CR, then one CR. ``text`` itself when it already has that shape, so the common
Expand Down
60 changes: 51 additions & 9 deletions messagefoundry/parsing/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@
refused, and so is a dropped MSH, DSC, MSA, ERR, QAK or MFA line (``_NEVER_EXEMPT`` says why).
The exemption is per structure, not per slot: it does not count against the slot's
cardinality or position. It holds only where MSH-9.1 names the structure's own message code, so a
structure borrowed through MSH-9.3 under another message code (``ADT^A01^MFN_M01``) gets none; one
borrowed under the same code (``MFN^M02^MFN_M01``) still gets it. Where the slot sits inside a
structure borrowed through MSH-9.3 under another message code (``ADT^A01^MFN_M01``) gets none.
Under the same code, MSH-9.2 decides whether a borrow keeps it (``MFN^M02^MFN_M01`` does not;
some do), by the rule :func:`_exempts_defined_segments` states. Where the slot sits inside a
nested group (at least PRR_PC5 and PPV_PCA), such a segment can still break hl7apy's grouping of
what follows. Segment order is not checked as such: hl7apy keeps each segment where the message
has it, so an out-of-order message may pass.
Expand Down Expand Up @@ -351,18 +352,59 @@ def _has_any_segment_slot(name: str, classname: str, hl7_version: str) -> bool:


def _exempts_defined_segments(message: Any) -> bool:
"""True if ``message``'s structure has the "any HL7 segment" slot and is its own.
"""True if ``message``'s structure has the "any HL7 segment" slot and MSH-9 passes the
consistency check below, which some borrowed structures pass too.

hl7apy takes the structure from MSH-9.3 when one is given, so ``ADT^A01^MFN_M01`` would
borrow MFN_M01's slot for an ADT body. The exemption holds only where MSH-9.1 names the
structure's own message code, which fails closed on a structure borrowed under another code.
One borrowed under the same code (``MFN^M02^MFN_M01``) still gets it: MSH-9.2 is not
compared, since one structure can serve several trigger events (PGL_PC6 serves PC6 to PC8,
for one)."""
Under the same code, MSH-9.2 is compared too (BACKLOG #5920 step 1). A message with no
MSH-9.3 borrows nothing: hl7apy names its structure from MSH-9.1 and MSH-9.2. One with an
MSH-9.3 is checked in this order. Where the structure is ``<MSH-9.1>_<MSH-9.2>``, MSH-9.2
stripped and upper-cased, it keeps the exemption. Otherwise, where hl7apy's tables have a
structure named ``<MSH-9.1>_<MSH-9.2>``, it gets none: ``MFN^M02^MFN_M01``, since MFN_M02 is
a structure, and ``QBP^Z73^QBP_Q15`` in 2.5, since QBP_Z73 is one. Otherwise it keeps the
exemption where MSH-9.2 starts with Z, taken as a site-defined event (``QBP^Z44^QBP_Q15``)
that table 0003 need not list, or is a value in the version's HL7 table 0003 as hl7apy ships
it, and gets none for any other value (empty, lower-case, padded or made up, such as
``XY1``). Any Z-led value passes the Z test (``MFN^Zebra^MFN_M01``), and the table holds at
least one placeholder that is no event (``Varies`` from 2.4), which passes too. So ``PGL^PC7^PGL_PC6`` in 2.5 keeps it, one structure serving several trigger
events (PGL_PC6 serves PC6 to PC8, for one). So does an event in the table that the borrowed
structure does not serve in the standard, such as ``MFN^M14^MFN_M01``, or one of another
message's family, such as ``MFN^A01^MFN_M01``: hl7apy has no table of which structure serves
which event, and only ``<MSH-9.1>_<MSH-9.2>`` is looked up. A Z test is on the raw MSH-9.2, so
``MFN^Z44 ^MFN_M01`` keeps the exemption and ``MFN^z44^MFN_M01`` does not."""
code = message.msh.msh_9.msh_9_1.to_er7()
return code == message.name.split("_", 1)[0] and _has_any_segment_slot(
message.name, message.classname, message.version
)
if code != message.name.split("_", 1)[0]:
return False
if not _has_any_segment_slot(message.name, message.classname, message.version):
return False
if len(message.msh.msh_9.to_er7().split(message.encoding_chars["COMPONENT"])) < 3:
return True
event = message.msh.msh_9.msh_9_2.to_er7()
# Normalized so a padded or lower-case own event (``MFN^m01^MFN_M01``) keeps the exemption,
# as ``MFN^m01`` with no MSH-9.3 does.
own = f"{code}_{event.strip().upper()}"
if own == message.name:
return True
structures, events = _structures_and_events(message.version)
if own in structures:
return False
# A site-defined Z event borrows a structure by design, and table 0003 need not list it.
return event.startswith("Z") or event in events


# Keyed by version alone, so the cache holds none of a sender's MSH-9.2 text.
@cache
def _structures_and_events(hl7_version: str) -> tuple[frozenset[str], frozenset[str]]:
"""The message structures and the trigger events (HL7 table 0003) hl7apy's tables for
``hl7_version`` define; no events where hl7apy ships no tables for the version."""
import hl7apy

library = hl7apy.load_library(hl7_version)
tables = getattr(library, "TABLES", {})
events = tables["HL70003"][1] if "HL70003" in tables else ()
return frozenset(library.MESSAGES), frozenset(events)


# Six IDs a dropped line of which is refused even in a structure with the "any HL7 segment" slot
Expand Down
20 changes: 11 additions & 9 deletions messagefoundry/pipeline/wiring_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@
b64_head,
text_sniff_head,
)
from messagefoundry.parsing.split import batch_member_collides
from messagefoundry.parsing.split import batch_member_collides, head_control_id
from messagefoundry.pipeline.alerts import REMINDER_SECONDS, AlertSink, LoggingAlertSink
from messagefoundry.pipeline.cluster import ClusterCoordinator, NullCoordinator
from messagefoundry.pipeline.dryrun import TransformOutcome, route_only, transform_one
Expand Down Expand Up @@ -12078,7 +12078,7 @@ async def _deliver_coalesced_batch(
# payload-agnostic, ADR 0004, so a non-hl7v2 feed can reach here) routes to the internal-error
# policy below (dead-letter / STOP) instead of stranding every claimed row INFLIGHT forever with
# no send and no disposition. Members are carried VERBATIM (the head too — never re-encoded); only
# the head is PARSED here, for the BHS-11 control id. How encode_batch reads the BHS
# the head's MSH-10 is READ here, for the BHS-11 control id. How encode_batch reads the BHS
# separators, parsing the head where its MSH line alone does not hold them, is in
# parsing/split.py, _head_separators (BACKLOG #5919).
refused: list[_RefusedMember] = []
Expand Down Expand Up @@ -12169,11 +12169,13 @@ async def _deliver_coalesced_batch(
first = kept[0] # the envelope's head is the first member that survived
# The head's own fields: a non-HL7 head faults here, and it is this member's.
current = first.id
# This parse and encode_batch below each run in a thread (BACKLOG #5706). Both scale
# This read and encode_batch below each run in a thread (BACKLOG #5706). Both scale
# with the members' size, and on the event loop a large member would stall every
# lane, listener and the API while it parsed.
parsed = await asyncio.to_thread(Message.parse, first.payload)
control_id = parsed.control_id or first.id # stable
# lane, listener and the API while it was read. head_control_id reads MSH-10 as a
# parse of the head does, parsing only its first line where that reads the same
# (BACKLOG #5919).
head_id = await asyncio.to_thread(head_control_id, first.payload)
control_id = head_id or first.id # stable
timestamp = _hl7_batch_timestamp(first.created_at)
# encode_batch reads the HYDRATED head's MSH-1 and MSH-2 and frames every member in
# one call, so a fault inside it cannot be told apart by member; the send is the
Expand Down Expand Up @@ -12276,9 +12278,9 @@ async def _deliver_coalesced_batch(
# dead-letters the members still present (bad data can never frame/deliver —
# replayable from the DLQ) so a code bug or a mis-typed feed can't wedge the lane.
# A fault one member's own step raised (its re-attach, its frame check, or the head's
# parse) names that member by its outbox id, never its content, in the log, the stored
# error and the alert (vault BACKLOG #5100). One the send of a connector a reload
# retired raised is the reload's (BACKLOG #5718), as the single row.
# MSH-10 read) names that member by its outbox id, never its content, in the log,
# the stored error and the alert (vault BACKLOG #5100). One the send of a connector
# a reload retired raised is the reload's (BACKLOG #5718), as the single row.
if sending and self._connector_retired(name, connector):
return await self._release_retired(name, [it.id for it in items])
member = _batch_member(current)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_delivery_document_reattach.py
Original file line number Diff line number Diff line change
Expand Up @@ -884,8 +884,8 @@ async def _hydrate(payload: str, message_id: str) -> str:


async def test_a_non_hl7_head_names_the_head(store: MessageStore) -> None:
# Vault BACKLOG #5100: the head's parse for BHS-11 is that member's own step, so a non-HL7 head
# names the head, not the last member.
# Vault BACKLOG #5100: the head's MSH-10 read for BHS-11 is that member's own step, so a
# non-HL7 head, which that read parses in full and refuses, names the head, not the last member.
mids, ids = await _enqueue(store, ["not an HL7 message at all", _hl7_with_value("clean")])
col = _Collector()
runner, _ = _batch_runner(store, col)
Expand Down
Loading
Loading