diff --git a/changelog.d/5540-anon-c0-escape-paths.security.md b/changelog.d/5540-anon-c0-escape-paths.security.md new file mode 100644 index 0000000000..1ce6c0b9c0 --- /dev/null +++ b/changelog.d/5540-anon-c0-escape-paths.security.md @@ -0,0 +1,14 @@ +- **The anonymizer refuses a C0 control byte that reached a rule-written field by an escape + route, on both adapters** (BACKLOG #5540). A field a surrogate rule writes was refused for a raw + C0 byte, but a byte the message's MSH-2 declared as its escape character was exempt, and an + escape sequence the engine's reader decodes to a C0 byte was not read, so sender text a rule + copies, such as a kept CX.4, could carry either one out. Both are now refused with the same + body-free `SurrogateSeparatorRefused`; the escape sequences refused include at least a hex + escape such as `\X07\` or `\X09\`, a line-break command such as `\.br\`, which decodes to CR, + and such a sequence spanning a subcomponent separator. A C0 byte written raw as an MSH-2 + separator the message declares still passes, as the field's structure. An OBX-5 value the free-text rule would + keep, a number or a code, is redacted when it holds such a byte, raw or escaped, rather than + kept. DEL and the C1 controls are still not refused. The check runs before the site-code scrub, + which, with a site prefix configured, can re-pair escapes so that one decodes to a C0 byte in the + output. On a message's last line the engine trims some trailing control bytes and keeps the OBX-5 + value. diff --git a/docs/PHI.md b/docs/PHI.md index 2920abe4fc..4d2690b80d 100644 --- a/docs/PHI.md +++ b/docs/PHI.md @@ -2779,7 +2779,7 @@ both are described below: | A known partner, vendor or site token, or a routable IPv4 address, survives | The whole message | | A routable IPv6 address appears. An IPv6 address the check can read counts unless it is unspecified, loopback, link-local, unique-local, multicast without the P flag, or in a documentation range (`2001:db8::/32`, `3fff::/20`). A multicast address with the P flag set is refused, whether or not it embeds a prefix: that includes the RFC 3306 and RFC 3956 forms and source-specific `ff3x::/32`. An IPv4-mapped or IPv4-compatible one counts when its IPv4 part is routable. An allowed address is not routable on the internet, but it can still name a site or a device: a unique-local address carries its site's random Global ID, and a link-local one built from a MAC carries that MAC. The forms it cannot read are below (BACKLOG #5654) | Fields no rule maps, what a retarget of a default field leaves past its first component, and the components an `id`, `mrn`, `ssn` or `dln` rule keeps past its first, as for the SSN and phone rows. In the MSH header, MSH-2 past its four encoding characters and every field from MSH-3 on that no rule rewrites, a field under a `keep` included, as written and decoded, and the part past component 1 of a header field an `id`, `mrn`, `ssn` or `dln` rule rewrites. Not checked, at least: MSH-1, the encoding characters, and component 1 of a field a rule rewrites, which holds the surrogate | | The header's `MSH-12` version is made of digits and dots, and one run of digits is longer than 32 (`AnonError`, raised by the anonymizer before the leak-check runs) | The header | -| A rule's surrogate would hold the message's own field separator, CR, LF, an MLLP frame byte, NUL or another C0 control character, TAB included, or what a surrogate writes itself could hold a component, repetition or subcomponent separator or the escape character the message's `MSH-2` declares (`AnonError`, raised by the anonymizer before the leak-check runs; BACKLOG #5540). A field a surrogate rule writes, sender text it copies included, is refused for a C0 control character the message does not declare as its field separator, an `MSH-2` separator or its escape character, on both adapters, with at least the exception at the end of the message listed below (BACKLOG #5533 item 14). Not checked, at least: a field no rule writes, such as one a keep leaves or an OBX-5 value the free-text rule preserves. Not refused, at least: DEL, a C1 control and an escape sequence such as `\X09\`. What it could write is judged, not the one value the salt picked: the whole pool a `name`, `address` or `provider` rule draws from, so a space component separator refuses every address; any digit, for a `phone` or `dob` rule; and the fill and offset placeholder of a date. A field separator a surrogate could write is judged the same way. Text a surrogate copies from the sender is not checked for the `MSH-2` delimiters, at least a kept CX component, an SSN's dashes and a date's year, except at least the date of birth's fraction dot, which is checked; a phone number's dashes are written at fixed places and are checked. A keep on that field would emit the captured value; an overlay that points the field at `drop` clears it | The fields a rule rewrites | +| A rule's surrogate would hold the message's own field separator, CR, LF, an MLLP frame byte, NUL or another C0 control character, TAB included, or what a surrogate writes itself could hold a component, repetition or subcomponent separator or the escape character the message's `MSH-2` declares (`AnonError`, raised by the anonymizer before the leak-check runs; BACKLOG #5540). A field a surrogate rule writes, sender text it copies included, is refused for a C0 control character written as one, unless it is an `MSH-2` separator the message declares, and for an escape sequence the engine's reader decodes to one, at least a hex escape such as `\X09\`, a line-break command such as `\.br\`, and such a sequence spanning a subcomponent separator, on both adapters, with at least the exception at the end of the message listed below (BACKLOG #5533 item 14, #5540). A C0 byte the message declares as its escape character is refused too. An OBX-5 value the free-text rule would keep is redacted instead when it holds any C0 byte this sentence's refusal would refuse, written or decoded. A sequence spanning a component or repetition separator is not judged, as the engine's reader never pairs across one. Not checked, at least: a field no rule writes, such as one a keep leaves, and what the site-code scrub writes after this check: with a site prefix configured, replacing a subcomponent that holds an unclosed escape character can re-pair later escapes, so a rule-written field or kept OBX-5 value can leave holding a sequence that decodes to a C0 byte. Not refused, at least: DEL and a C1 control. What it could write is judged, not the one value the salt picked: the whole pool a `name`, `address` or `provider` rule draws from, so a space component separator refuses every address; any digit, for a `phone` or `dob` rule; and the fill and offset placeholder of a date. A field separator a surrogate could write is judged the same way. Text a surrogate copies from the sender is not checked for the `MSH-2` delimiters, at least a kept CX component, an SSN's dashes and a date's year, except at least the date of birth's fraction dot, which is checked; a phone number's dashes are written at fixed places and are checked. A keep on that field would emit the captured value; an overlay that points the field at `drop` clears it | The fields a rule rewrites | | A dashed SSN (`NNN-NN-NNNN`) appears inside one field, or across fields the message's own field separator cut it into | Fields no rule maps, what a retarget of a default field leaves past its first component, and the components an `id`, `mrn`, `ssn` or `dln` rule keeps past its first. A cut shape counts when at least one of its fields is one no rule maps | | A punctuated US phone number (`NNN-NNN-NNNN` or `(NNN) NNN-NNNN`) appears inside one field, or across fields the message's own field separator cut it into | Fields no rule maps, what a retarget of a default field leaves past its first component, and the components an `id`, `mrn`, `ssn` or `dln` rule keeps past its first. A cut shape counts when at least one of its fields is one no rule maps | | A repetition with a non-empty first component and an `MR` or `MRN` id type: any component that is `MR` or `MRN` whole or as its first subcomponent, such as `12345^MR` or `12345^MR&L`, or components 5, 7 and 13, where CX.5, XON.7 and XCN.13 carry an id type, in any of their subcomponents too, such as `ID^^^AUTH^MR&local`. Those components are read so in every field whatever its type, so `70553^MRI^C4^^PET&MR` in `OBR-4`, a coded field and not a CX, is refused. An `MR` subcomponent past the first in any other component, such as the modality in `70553^PET&MR^C4`, does not count (BACKLOG #5654) | Fields no rule maps, except the header line, which this check skips whole | @@ -3017,15 +3017,18 @@ that line. - Whitespace after the last field of the last line. The engine's parser trims it before a rule reads the value, and the tee does not. So a date in that field is filled by the engine and emptied by the tee. A control byte there that the parser's trim removes, at least TAB, FF, - GS, RS and US, is trimmed by the engine the same way. Unless `MSH-1` or `MSH-2` declares it, - the tee refuses it where the surrogate copies it into the field it writes, at least in the + GS, RS and US, is trimmed by the engine the same way. Unless `MSH-1` or `MSH-2` declares it as + a separator, the tee refuses it where the surrogate copies it into the field it writes, at least in the first component under an `id`, `mrn` or `dln` rule and in a component an identifier rule keeps. It does not where the surrogate replaces or blanks that text, for example an `ssn` rule's first component or a component an identifier rule blanks, and there the two adapters can emit different surrogates: each keys its surrogate on the value it read, and the shape can - differ too, as for a dashed SSN the tee writes undashed. Where the message declares the byte, - neither adapter refuses it, and the two can emit different surrogates the same way. In a field - no rule maps, the tee emits the byte (BACKLOG #5533 item 14). + differ too, as for a dashed SSN the tee writes undashed. Where the message declares the byte as + a separator, neither adapter refuses it, and the two can emit different surrogates the same + way; a byte it declares as its escape character is refused as an undeclared one is. An OBX-5 + value the free-text rule would keep is kept by the engine without the byte and redacted by the + tee, which reads the byte. In a field no rule maps, the tee emits the byte (BACKLOG #5533 item + 14, #5540). **The coverage report is the record of those fields.** It lists the address of every present field that no rule mapped, never its value. A caller gets it through `on_report` on the clean path diff --git a/messagefoundry_toolkit/anon/surrogates.py b/messagefoundry_toolkit/anon/surrogates.py index 26e69d0926..6c42f92b04 100644 --- a/messagefoundry_toolkit/anon/surrogates.py +++ b/messagefoundry_toolkit/anon/surrogates.py @@ -22,6 +22,7 @@ from __future__ import annotations import functools +import itertools import os import random import re @@ -279,9 +280,10 @@ def _components(rep: str, seps: Seps) -> list[str]: class SurrogateSeparatorRefused(AnonError): """A rule's surrogate would hold a character that splits or ends a field, so writing it would add a field, a line or a component, or start an escape sequence, and move what follows past - its rule (BACKLOG #5540), or a C0 control character the message does not declare as its - field separator, an MSH-2 separator or its escape character (:func:`_no_control`, BACKLOG - #5533 item 14). What a surrogate writes itself is judged here, the same on both adapters + its rule (BACKLOG #5540), or a C0 control character, written as one that is not an MSH-2 + separator the message declares, or decoded from an escape sequence + (:func:`_holds_control`, :func:`_no_control`, BACKLOG #5533 item 14, #5540). What a surrogate + writes itself is judged here, the same on both adapters (:func:`_written`). The whole written field is checked by each adapter as it writes it: the tee raises this class, while the engine adapter's ``Message.set`` refusal comes out as a plain :class:`AnonError` with no address. Of the C0 bytes, those whole-field checks refuse NUL and a @@ -691,24 +693,74 @@ def surrogate_field_recorded( def _no_control(value: str, seps: Seps) -> None: - """Refuse (:class:`_HeldDelimiter`) a whole field a rule wrote that holds a C0 control - character, 0x00 to 0x1F, TAB included, unless the message declares that character as its - field separator, an MSH-2 separator or its escape character (:func:`_reserved`, BACKLOG #5533 - item 14). A declared escape character is exempt too, so a sender that declares a C0 byte as - its escape character gets that byte past this check in text a surrogate copies. Unlike - :func:`_written`, this judges the written value itself, so sender text a surrogate copies, - such as an identifier's punctuation or a kept CX.4, is checked with the rest. Both adapters - reach it through :func:`surrogate_field_recorded`, so where they read the same value they - refuse the same undeclared bytes with the same cause. A declared C0 character is passed on - to each adapter's own whole-field guard, which refuses it only when it is NUL or the field - separator, so a declared TAB, US, RS or C0 escape character is emitted by both. Not checked, - at least: DEL (0x7F), a C1 control, an escape sequence such as ``\\X09\\``, and a field no rule - writes, such as one a keep leaves or an OBX-5 value the free-text rule preserves.""" - reserved = _reserved(seps) - if any(char < " " and char not in reserved for char in value): + """Refuse (:class:`_HeldDelimiter`) a whole field a rule wrote that :func:`_holds_control` + finds a C0 control character in (BACKLOG #5533 item 14, #5540). Unlike :func:`_written`, this + judges the written value itself, so sender text a surrogate copies, such as an identifier's + punctuation or a kept CX.4, is checked with the rest. Both adapters reach it through + :func:`surrogate_field_recorded`, so where they read the same value they refuse the same + bytes with the same cause. A C0 separator the message declares is passed on to each adapter's + own whole-field guard, which refuses it only when it is NUL or the field separator, so a + declared TAB, US or RS separator is emitted by both. Not checked, at least: DEL (0x7F), a C1 + control, and a field no rule writes, such as one a keep leaves. An OBX-5 value the free-text + rule would keep is redacted instead when it holds one (:func:`preserve_obx5_value`).""" + if _holds_control(value, seps): raise _HeldDelimiter("a C0 control character") +def _holds_control(value: str, seps: Seps) -> bool: + """True if ``value`` holds a C0 control character, 0x00 to 0x1F, TAB included, as written, + unless it is an MSH-2 separator the message declares, which is the field's structure, or if + an escape sequence in it decodes to one (:func:`_escape_writes_control`). A C0 escape + character is not exempt: it is never needed outside an escape sequence, and the sequences it + opens carry no structure a rule must write (BACKLOG #5540). The field separator is not exempt + either: no field holds it, and each adapter refuses one a rule would write.""" + allowed = seps.component + seps.repetition + seps.subcomponent + if any(char < " " and char not in allowed for char in value): + return True + return _escape_writes_control(value, seps) + + +#: The dotted formatting commands the engine's parser decodes to a line break, CR, rather than to +#: spaces (``_builtin_hl7._RICH_TEXT_MAP``, which the tee cannot import). +_BREAK_FORMAT_COMMANDS = frozenset({".br", ".sp", ".ce"}) + + +def _escape_writes_control(value: str, seps: Seps) -> bool: + """True if an escape sequence in ``value`` decodes to a C0 control character for a receiver: + a hex escape such as ``\\X07\\``, a delimiter escape such as ``\\S\\`` whose delimiter is a C0 + byte, or a line-break command such as ``\\.br\\``, which the engine's parser writes as CR. + Each sequence is paired as the engine's reader pairs it, in both readings :func:`unescape` + names, a subcomponent at a time and a component at a time, so one that spans a subcomponent + separator, such as ``\\X07&\\``, is judged as the engine's component read decodes it + (BACKLOG #5540). One that spans a component or repetition separator is not judged: the + engine's reader never pairs across those, though a reader that decodes a whole field would. + A decoded byte is data, so a declared separator it decodes to is not exempt.""" + escape = seps.escape + if not escape or escape not in value: + return False + letters = _escape_letters(seps, seps.field) + # A component with no subcomponent separator reads the same both ways, so it is walked once. + spanning = ( + comp + for rep in value.split(seps.repetition) + for comp in _components(rep, seps) + if seps.subcomponent in comp + ) + for part in itertools.chain(_subcomponents(value, seps), spanning): + at = 0 + while (start := part.find(escape, at)) != -1: + end = part.find(escape, start + 1) + if end == -1: + break + body = part[start + 1 : end] + at = end + 1 + if body[:3] in _BREAK_FORMAT_COMMANDS and _spacing_command(body): + return True + if any(char < " " for char in _decode_escape(body, letters)): + return True + return False + + def _reads_as_site_code(part: str, seps: Seps, field_sep: str) -> bool: """True if ``part``, one component or one subcomponent, is a site code on any reading a consumer can take (BACKLOG #5632): as written, trimmed, with its invisible characters dropped @@ -974,6 +1026,20 @@ def _decode_escape(body: str, letters: dict[str, str]) -> str: return " " if _spacing_command(body) else "" +def _escape_letters(seps: Seps, field_sep: str) -> dict[str, str]: + """The single-letter escapes: F field, S component, T subcomponent, R repetition, E the escape + character itself, and H and N, highlighting on and off, which the engine writes as ``_``.""" + return { + "F": field_sep, + "S": seps.component, + "T": seps.subcomponent, + "R": seps.repetition, + "E": seps.escape, + "H": "_", + "N": "_", + } + + def unescape(value: str, seps: Seps, field_sep: str) -> str: """``value`` with every HL7 escape sequence decoded, by the message's own escape character and separators (BACKLOG #5532), as :func:`_decode_escape` reads each one. The tee cannot import the @@ -986,17 +1052,7 @@ def unescape(value: str, seps: Seps, field_sep: str) -> str: escape = seps.escape if not escape or escape not in value: return value - # The single-letter escapes: F field, S component, T subcomponent, R repetition, E the escape - # character itself, and H and N, highlighting on and off, which the engine writes as ``_``. - letters = { - "F": field_sep, - "S": seps.component, - "T": seps.subcomponent, - "R": seps.repetition, - "E": escape, - "H": "_", - "N": "_", - } + letters = _escape_letters(seps, field_sep) out: list[str] = [] at = 0 while (start := value.find(escape, at)) != -1: @@ -1388,8 +1444,8 @@ def scrub_message_site_codes(text: str, keyer: Keyer, rules: tuple[FieldRule, .. } -def _obx5_parts(value: str, seps: Seps) -> Iterator[str]: - """Every subcomponent of every component of every repetition of an OBX-5 value, split on the +def _subcomponents(value: str, seps: Seps) -> Iterator[str]: + """Every subcomponent of every component of every repetition of a field value, split on the message's own separators (never a hardcoded ``|^~\\&``). Lazy, so a caller's ``all()`` stops at the first part that fails — a narrative or base64 value is rejected without decomposing it.""" return ( @@ -1456,6 +1512,11 @@ def preserve_obx5_value(value_type: str | None, value: str | None, seps: Seps) - A grammar cannot tell a number from an identifier written as a number: an undashed nine or ten digit run is a valid ``NM`` and is kept. ``docs/PHI.md`` section 9 names that gap. + A value holding a C0 control character, as written or as an escape sequence decodes it + (:func:`_holds_control`), is not kept whatever its type: a grammar's ``strip`` and the + bare-token split would pass a TAB or a US, and a coded value passes a BEL or ``\\X07\\``, so + the byte would reach the output where no rule-written field's refusal sees it (BACKLOG #5540). + A date type (``DT``, ``TS``) is never preserved. :func:`obx5_kind` says what it gets instead. """ declared = (value_type or "").strip().upper() @@ -1467,12 +1528,15 @@ def preserve_obx5_value(value_type: str | None, value: str | None, seps: Seps) - if any(mark.isspace() for mark in (seps.component, seps.repetition, seps.subcomponent)): return False if (grammar := _NUMERIC_OBX_GRAMMAR.get(declared)) is not None: - return _fits_numeric_grammar(grammar, text, seps) - if declared in _CODED_OBX_TYPES: - return all(_is_bare_token(part) for part in _obx5_parts(text, seps)) - if declared in _CODED_ELEMENT_OBX_TYPES: - return _coded_element_is_bare(text, seps) - return False + fits = _fits_numeric_grammar(grammar, text, seps) + elif declared in _CODED_OBX_TYPES: + fits = all(_is_bare_token(part) for part in _subcomponents(text, seps)) + elif declared in _CODED_ELEMENT_OBX_TYPES: + fits = _coded_element_is_bare(text, seps) + else: + return False + # Judged last, so a narrative or base64 value that no type keeps is never scanned for it. + return fits and not _holds_control(text, seps) def obx5_kind(value_type: str | None) -> SurrogateKind: diff --git a/tee/anon/hl7.py b/tee/anon/hl7.py index fb1fbd2673..564c9b1e4e 100644 --- a/tee/anon/hl7.py +++ b/tee/anon/hl7.py @@ -25,9 +25,10 @@ ``Message.set`` refuses too. CR, LF and the frame bytes never reach a field: ``normalized_message`` turns CR and LF into segment breaks and strips the frame bytes, so of the five only NUL can reach :func:`_whole_field`. Under a rule other than a ``keep``, -``surrogate_field_recorded`` refuses an undeclared C0 byte in what the surrogate wrote first -(BACKLOG #5533 item 14), so there a NUL reaches :func:`_whole_field` only when the message -declares it. A ``keep`` rule passed straight to this adapter skips that shared C0 refusal, and +``surrogate_field_recorded`` refuses a C0 byte in what the surrogate wrote first: one written raw +that the message does not declare as its field separator or an MSH-2 separator, and one an escape +sequence decodes to (BACKLOG #5533 item 14, #5540), so there a NUL reaches :func:`_whole_field` +only when the message declares it as one of those separators. A ``keep`` rule passed straight to this adapter skips that shared C0 refusal, and the kept value is written back, so an undeclared NUL in it reaches :func:`_whole_field`, which refuses it. The shared site-code pass that runs after the rules writes no digit the message declares as a separator. diff --git a/tee/anon/surrogates.py b/tee/anon/surrogates.py index 26e69d0926..6c42f92b04 100644 --- a/tee/anon/surrogates.py +++ b/tee/anon/surrogates.py @@ -22,6 +22,7 @@ from __future__ import annotations import functools +import itertools import os import random import re @@ -279,9 +280,10 @@ def _components(rep: str, seps: Seps) -> list[str]: class SurrogateSeparatorRefused(AnonError): """A rule's surrogate would hold a character that splits or ends a field, so writing it would add a field, a line or a component, or start an escape sequence, and move what follows past - its rule (BACKLOG #5540), or a C0 control character the message does not declare as its - field separator, an MSH-2 separator or its escape character (:func:`_no_control`, BACKLOG - #5533 item 14). What a surrogate writes itself is judged here, the same on both adapters + its rule (BACKLOG #5540), or a C0 control character, written as one that is not an MSH-2 + separator the message declares, or decoded from an escape sequence + (:func:`_holds_control`, :func:`_no_control`, BACKLOG #5533 item 14, #5540). What a surrogate + writes itself is judged here, the same on both adapters (:func:`_written`). The whole written field is checked by each adapter as it writes it: the tee raises this class, while the engine adapter's ``Message.set`` refusal comes out as a plain :class:`AnonError` with no address. Of the C0 bytes, those whole-field checks refuse NUL and a @@ -691,24 +693,74 @@ def surrogate_field_recorded( def _no_control(value: str, seps: Seps) -> None: - """Refuse (:class:`_HeldDelimiter`) a whole field a rule wrote that holds a C0 control - character, 0x00 to 0x1F, TAB included, unless the message declares that character as its - field separator, an MSH-2 separator or its escape character (:func:`_reserved`, BACKLOG #5533 - item 14). A declared escape character is exempt too, so a sender that declares a C0 byte as - its escape character gets that byte past this check in text a surrogate copies. Unlike - :func:`_written`, this judges the written value itself, so sender text a surrogate copies, - such as an identifier's punctuation or a kept CX.4, is checked with the rest. Both adapters - reach it through :func:`surrogate_field_recorded`, so where they read the same value they - refuse the same undeclared bytes with the same cause. A declared C0 character is passed on - to each adapter's own whole-field guard, which refuses it only when it is NUL or the field - separator, so a declared TAB, US, RS or C0 escape character is emitted by both. Not checked, - at least: DEL (0x7F), a C1 control, an escape sequence such as ``\\X09\\``, and a field no rule - writes, such as one a keep leaves or an OBX-5 value the free-text rule preserves.""" - reserved = _reserved(seps) - if any(char < " " and char not in reserved for char in value): + """Refuse (:class:`_HeldDelimiter`) a whole field a rule wrote that :func:`_holds_control` + finds a C0 control character in (BACKLOG #5533 item 14, #5540). Unlike :func:`_written`, this + judges the written value itself, so sender text a surrogate copies, such as an identifier's + punctuation or a kept CX.4, is checked with the rest. Both adapters reach it through + :func:`surrogate_field_recorded`, so where they read the same value they refuse the same + bytes with the same cause. A C0 separator the message declares is passed on to each adapter's + own whole-field guard, which refuses it only when it is NUL or the field separator, so a + declared TAB, US or RS separator is emitted by both. Not checked, at least: DEL (0x7F), a C1 + control, and a field no rule writes, such as one a keep leaves. An OBX-5 value the free-text + rule would keep is redacted instead when it holds one (:func:`preserve_obx5_value`).""" + if _holds_control(value, seps): raise _HeldDelimiter("a C0 control character") +def _holds_control(value: str, seps: Seps) -> bool: + """True if ``value`` holds a C0 control character, 0x00 to 0x1F, TAB included, as written, + unless it is an MSH-2 separator the message declares, which is the field's structure, or if + an escape sequence in it decodes to one (:func:`_escape_writes_control`). A C0 escape + character is not exempt: it is never needed outside an escape sequence, and the sequences it + opens carry no structure a rule must write (BACKLOG #5540). The field separator is not exempt + either: no field holds it, and each adapter refuses one a rule would write.""" + allowed = seps.component + seps.repetition + seps.subcomponent + if any(char < " " and char not in allowed for char in value): + return True + return _escape_writes_control(value, seps) + + +#: The dotted formatting commands the engine's parser decodes to a line break, CR, rather than to +#: spaces (``_builtin_hl7._RICH_TEXT_MAP``, which the tee cannot import). +_BREAK_FORMAT_COMMANDS = frozenset({".br", ".sp", ".ce"}) + + +def _escape_writes_control(value: str, seps: Seps) -> bool: + """True if an escape sequence in ``value`` decodes to a C0 control character for a receiver: + a hex escape such as ``\\X07\\``, a delimiter escape such as ``\\S\\`` whose delimiter is a C0 + byte, or a line-break command such as ``\\.br\\``, which the engine's parser writes as CR. + Each sequence is paired as the engine's reader pairs it, in both readings :func:`unescape` + names, a subcomponent at a time and a component at a time, so one that spans a subcomponent + separator, such as ``\\X07&\\``, is judged as the engine's component read decodes it + (BACKLOG #5540). One that spans a component or repetition separator is not judged: the + engine's reader never pairs across those, though a reader that decodes a whole field would. + A decoded byte is data, so a declared separator it decodes to is not exempt.""" + escape = seps.escape + if not escape or escape not in value: + return False + letters = _escape_letters(seps, seps.field) + # A component with no subcomponent separator reads the same both ways, so it is walked once. + spanning = ( + comp + for rep in value.split(seps.repetition) + for comp in _components(rep, seps) + if seps.subcomponent in comp + ) + for part in itertools.chain(_subcomponents(value, seps), spanning): + at = 0 + while (start := part.find(escape, at)) != -1: + end = part.find(escape, start + 1) + if end == -1: + break + body = part[start + 1 : end] + at = end + 1 + if body[:3] in _BREAK_FORMAT_COMMANDS and _spacing_command(body): + return True + if any(char < " " for char in _decode_escape(body, letters)): + return True + return False + + def _reads_as_site_code(part: str, seps: Seps, field_sep: str) -> bool: """True if ``part``, one component or one subcomponent, is a site code on any reading a consumer can take (BACKLOG #5632): as written, trimmed, with its invisible characters dropped @@ -974,6 +1026,20 @@ def _decode_escape(body: str, letters: dict[str, str]) -> str: return " " if _spacing_command(body) else "" +def _escape_letters(seps: Seps, field_sep: str) -> dict[str, str]: + """The single-letter escapes: F field, S component, T subcomponent, R repetition, E the escape + character itself, and H and N, highlighting on and off, which the engine writes as ``_``.""" + return { + "F": field_sep, + "S": seps.component, + "T": seps.subcomponent, + "R": seps.repetition, + "E": seps.escape, + "H": "_", + "N": "_", + } + + def unescape(value: str, seps: Seps, field_sep: str) -> str: """``value`` with every HL7 escape sequence decoded, by the message's own escape character and separators (BACKLOG #5532), as :func:`_decode_escape` reads each one. The tee cannot import the @@ -986,17 +1052,7 @@ def unescape(value: str, seps: Seps, field_sep: str) -> str: escape = seps.escape if not escape or escape not in value: return value - # The single-letter escapes: F field, S component, T subcomponent, R repetition, E the escape - # character itself, and H and N, highlighting on and off, which the engine writes as ``_``. - letters = { - "F": field_sep, - "S": seps.component, - "T": seps.subcomponent, - "R": seps.repetition, - "E": escape, - "H": "_", - "N": "_", - } + letters = _escape_letters(seps, field_sep) out: list[str] = [] at = 0 while (start := value.find(escape, at)) != -1: @@ -1388,8 +1444,8 @@ def scrub_message_site_codes(text: str, keyer: Keyer, rules: tuple[FieldRule, .. } -def _obx5_parts(value: str, seps: Seps) -> Iterator[str]: - """Every subcomponent of every component of every repetition of an OBX-5 value, split on the +def _subcomponents(value: str, seps: Seps) -> Iterator[str]: + """Every subcomponent of every component of every repetition of a field value, split on the message's own separators (never a hardcoded ``|^~\\&``). Lazy, so a caller's ``all()`` stops at the first part that fails — a narrative or base64 value is rejected without decomposing it.""" return ( @@ -1456,6 +1512,11 @@ def preserve_obx5_value(value_type: str | None, value: str | None, seps: Seps) - A grammar cannot tell a number from an identifier written as a number: an undashed nine or ten digit run is a valid ``NM`` and is kept. ``docs/PHI.md`` section 9 names that gap. + A value holding a C0 control character, as written or as an escape sequence decodes it + (:func:`_holds_control`), is not kept whatever its type: a grammar's ``strip`` and the + bare-token split would pass a TAB or a US, and a coded value passes a BEL or ``\\X07\\``, so + the byte would reach the output where no rule-written field's refusal sees it (BACKLOG #5540). + A date type (``DT``, ``TS``) is never preserved. :func:`obx5_kind` says what it gets instead. """ declared = (value_type or "").strip().upper() @@ -1467,12 +1528,15 @@ def preserve_obx5_value(value_type: str | None, value: str | None, seps: Seps) - if any(mark.isspace() for mark in (seps.component, seps.repetition, seps.subcomponent)): return False if (grammar := _NUMERIC_OBX_GRAMMAR.get(declared)) is not None: - return _fits_numeric_grammar(grammar, text, seps) - if declared in _CODED_OBX_TYPES: - return all(_is_bare_token(part) for part in _obx5_parts(text, seps)) - if declared in _CODED_ELEMENT_OBX_TYPES: - return _coded_element_is_bare(text, seps) - return False + fits = _fits_numeric_grammar(grammar, text, seps) + elif declared in _CODED_OBX_TYPES: + fits = all(_is_bare_token(part) for part in _subcomponents(text, seps)) + elif declared in _CODED_ELEMENT_OBX_TYPES: + fits = _coded_element_is_bare(text, seps) + else: + return False + # Judged last, so a narrative or base64 value that no type keeps is never scanned for it. + return fits and not _holds_control(text, seps) def obx5_kind(value_type: str | None) -> SurrogateKind: diff --git a/tests/test_anon_c0_escape_paths_5540.py b/tests/test_anon_c0_escape_paths_5540.py new file mode 100644 index 0000000000..2ebd157e6a --- /dev/null +++ b/tests/test_anon_c0_escape_paths_5540.py @@ -0,0 +1,272 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""Three routes a C0 control byte took past the anonymizer's control-byte refusal, closed on BOTH +adapters alike (BACKLOG #5540, with #8392 items 1, 2 and 4). + +* A message may declare a C0 byte as its MSH-2 escape character. That byte was exempt from the + refusal, so a rule that copies sender text, such as the CX.4 an identifier rule keeps, wrote it + back. It is now refused like any undeclared C0 byte. A C0 byte declared as the field separator + or an MSH-2 separator is still the field's structure and still passes. +* An escape sequence such as ``\\X07\\`` or ``\\X09\\`` decodes to a C0 byte for any receiver that + decodes the field, so a rule-written field holding one is refused as the raw byte is. +* The OBX-5 free-text rule keeps a numeric or coded value whole. A value holding a C0 byte, raw or + as an escape sequence, does not look like the type it claims, so it is redacted like any other + value that fails the allowlist, never kept. + +Every value here is synthetic. +""" + +from __future__ import annotations + +from types import ModuleType + +import pytest + +import messagefoundry_toolkit.anon as engine_anon +import tee.anon as tee_anon +from messagefoundry_toolkit.anon import surrogates as engine_surrogates +from tee.anon import surrogates as tee_surrogates + +_SALT = "b5540-c0-escape-salt-0123456789abcdef-0123" +#: A value in a field no rule rewrites, after the scrubbed one, so a leaked body would show. +_MARK = "AFTERMARK" +#: Sender text in the kept assigning authority, so a refusal that quotes the value would show. +_NEEDLE = "HOSPQ" +_REDACTED = engine_surrogates.REDACTED + +_SIDES = pytest.mark.parametrize( + ("anon", "refused"), + [ + (engine_anon, engine_surrogates.SurrogateSeparatorRefused), + (tee_anon, tee_surrogates.SurrogateSeparatorRefused), + ], + ids=["engine", "tee"], +) +_SURROGATE_MODULES = pytest.mark.parametrize( + "surrogates", [engine_surrogates, tee_surrogates], ids=["engine", "tee"] +) + + +def _header(encoding: str = "^~\\&", kind: str = "ADT^A01") -> str: + return "|".join( + ("MSH", encoding, "APP", "FAC", "RCV", "RFAC", "20260101", "", kind, "M1", "P", "2.5.1") + ) + + +def _pid(cx4: str, encoding: str = "^~\\&") -> str: + """A message whose PID-3 keeps ``cx4`` as its assigning authority (CX.4).""" + comp = encoding[0] + return f"{_header(encoding)}\rPID|1||Q7734{comp * 3}{cx4}{comp}MR|||||{_MARK}" + + +def _obx(value_type: str, value: str) -> str: + return ( + f"{_header(kind='ORU^R01')}\rPID|1||Q7734^^^H^MR\r" + f"OBX|1|{value_type}|CODE^^L||{value}|||{_MARK}" + ) + + +def _outcomes(message: str) -> list[tuple[str, str]]: + outcomes = [] + for anon in (engine_anon, tee_anon): + try: + outcomes.append(("emitted", anon.anonymize(message, salt=_SALT))) + except anon.AnonError as exc: + outcomes.append((type(exc).__name__, str(exc))) + return outcomes + + +# --- a C0 byte declared as the escape character ------------------------------------------------ + + +@_SIDES +@pytest.mark.parametrize("escape", ["\x07", "\x1b", "\x00", "\t"], ids=["BEL", "ESC", "NUL", "TAB"]) +def test_a_declared_c0_escape_character_a_rule_copies_is_refused( + anon: ModuleType, refused: type[Exception], escape: str +) -> None: + encoding = f"^~{escape}&" + message = _pid(f"{_NEEDLE}{escape}T{escape}A", encoding) + with pytest.raises(refused, match="the surrogate for PID-3 would hold a C0") as caught: + anon.anonymize(message, salt=_SALT) + assert _NEEDLE not in str(caught.value) + assert _MARK not in str(caught.value) + + +@pytest.mark.parametrize("escape", ["\x07", "\x1b"], ids=["BEL", "ESC"]) +def test_a_declared_c0_escape_character_no_rule_writes_still_passes(escape: str) -> None: + """The refusal judges what a rule writes, not what MSH-2 declares: a message that declares a + C0 escape character, and whose ruled fields do not hold it, is anonymized alike on both + sides.""" + message = _pid(_NEEDLE, f"^~{escape}&") + outcomes = _outcomes(message) + assert outcomes[0] == outcomes[1] + assert outcomes[0][0] == "emitted" + assert _MARK in outcomes[0][1] + + +@pytest.mark.parametrize("encoding", ["\x1f~\\&", "^\x1e\\&", "^~\\\x1d"], ids=["US", "RS", "GS"]) +def test_a_c0_separator_the_message_declares_still_passes(encoding: str) -> None: + """A C0 byte declared as a component, repetition or subcomponent separator is the field's + structure, and the escape-character change leaves it exempt. The ruled PID-3 holds all three + separators, so each case writes its own declared byte.""" + comp, rep, sub = encoding[0], encoding[1], encoding[3] + cx = f"Q7734{comp * 3}HO{sub}SP{comp}MR" + message = f"{_header(encoding)}\rPID|1||{cx}{rep}{cx}|||||{_MARK}" + outcomes = _outcomes(message) + assert outcomes[0] == outcomes[1] + assert outcomes[0][0] == "emitted" + assert f"HO{sub}SP" in outcomes[0][1] + + +def test_an_escape_that_decodes_to_a_declared_c0_separator_is_refused() -> None: + """Decoded, a separator is data rather than structure, so ``\\S\\`` under a US component + separator writes a raw US into the value a receiver reads, and is refused.""" + outcomes = _outcomes(_pid(f"{_NEEDLE}\\S\\A", "\x1f~\\&")) + assert outcomes[0] == outcomes[1] + assert outcomes[0][0] == "SurrogateSeparatorRefused" + + +# --- an escape sequence that decodes to a C0 byte ---------------------------------------------- + + +@_SIDES +@pytest.mark.parametrize( + "escaped", + ["\\X07\\", "\\X09\\", "\\X4107\\", "\\X07&\\", "\\X0D&\\", "\\.br\\", "\\.sp3\\", "\\.ce\\"], + ids=["BEL", "TAB", "A-then-BEL", "BEL-across-sub", "CR-across-sub", "br", "sp3", "ce"], +) +def test_a_hex_escape_decoding_to_a_c0_byte_is_refused( + anon: ModuleType, refused: type[Exception], escaped: str +) -> None: + with pytest.raises(refused, match="the surrogate for PID-3 would hold a C0") as caught: + anon.anonymize(_pid(f"{_NEEDLE}{escaped}A"), salt=_SALT) + assert _NEEDLE not in str(caught.value) + assert _MARK not in str(caught.value) + + +@pytest.mark.parametrize( + "escaped", + [ + "\\X41\\", + "\\F\\", + "\\S\\", + "\\T\\", + "\\E\\", + "\\H\\", + "\\.in\\", + "\\.sk\\", + "\\.fi\\", + "\\.br0\\", + "\\.br513\\", + "\\.brX\\", + ], +) +def test_an_escape_that_decodes_to_no_c0_byte_still_passes(escaped: str) -> None: + """The engine's reader writes ``\\.in\\`` and ``\\.sk\\`` as spaces, ``\\.fi\\`` as nothing, + and a break command whose count is out of range or not a number as nothing too, so none of + these decodes to a C0 byte.""" + outcomes = _outcomes(_pid(f"{_NEEDLE}{escaped}A")) + assert outcomes[0] == outcomes[1] + assert outcomes[0][0] == "emitted" + assert f"{escaped}A" in outcomes[0][1] + + +@pytest.mark.parametrize("code", range(0x80), ids=lambda n: f"X{n:02X}") +def test_both_adapters_judge_every_one_byte_hex_escape_alike(code: int) -> None: + """Every one-byte hex escape in a kept component: the two adapters refuse alike, with the same + class and cause, or emit the same output, and a C0 byte is never emitted.""" + outcomes = _outcomes(_pid(f"{_NEEDLE}\\X{code:02X}\\A")) + assert outcomes[0] == outcomes[1] + assert outcomes[0][0] == ("SurrogateSeparatorRefused" if code < 0x20 else "emitted") + + +def test_the_break_commands_match_the_engine_reader() -> None: + """The commands the C0 check reads as a line break are the ones the engine's parser decodes + to a control byte; the tee cannot import that table, so this pins the copy.""" + from messagefoundry.parsing._builtin_hl7 import _RICH_TEXT_MAP + + writes_control = {cmd for cmd, text in _RICH_TEXT_MAP.items() if any(c < " " for c in text)} + assert writes_control == engine_surrogates._BREAK_FORMAT_COMMANDS + assert writes_control == tee_surrogates._BREAK_FORMAT_COMMANDS + + +@_SURROGATE_MODULES +def test_the_refusal_reads_each_part_apart(surrogates: ModuleType) -> None: + """An escape character no second one closes in its own component does not pair with one in + the next component, as a receiver that splits before it decodes reads it.""" + seps = surrogates.Seps() + # Read whole, ``\X07^\`` would decode its first pair to BEL; split first, neither part closes. + surrogates._no_control("A\\X07^\\B", seps) + with pytest.raises(surrogates.AnonError, match="C0 control character"): + surrogates._no_control("A^\\X07\\B", seps) + + +# --- an OBX-5 value the free-text rule would keep ---------------------------------------------- + + +@pytest.mark.parametrize( + ("value_type", "value"), + [ + ("CWE", "AB\x07C^^L"), + ("CE", "AB\\X07\\C^^L"), + ("ID", "A\x1bB"), + ("IS", "A\\X09\\B"), + ("NM", "12\t"), + ("NM", "\x1f12"), + ("SN", "<^12\x0c"), + ("TM", "1230\x07"), + ("CWE", "A\\X07&\\B^^L"), + ("ID", "A\\.br\\B"), + ], + ids=[ + "CWE-BEL", + "CE-hex-BEL", + "ID-ESC", + "IS-hex-TAB", + "NM-TAB", + "NM-US", + "SN-FF", + "TM-BEL", + "CWE-hex-across-sub", + "ID-br", + ], +) +def test_an_obx5_value_holding_a_c0_byte_is_redacted_not_kept(value_type: str, value: str) -> None: + outcomes = _outcomes(_obx(value_type, value)) + assert outcomes[0] == outcomes[1] + kind, out = outcomes[0] + assert kind == "emitted" + assert f"|{_REDACTED}|" in out + assert not any(char < " " and char != "\r" for char in out) + assert "\\X07\\" not in out + assert "\\X09\\" not in out + + +@pytest.mark.parametrize( + ("value_type", "value"), + [("CWE", "ABC^^L"), ("ID", "A\\X41\\B"), ("NM", "12"), ("SN", "<^12"), ("TM", "1230")], +) +def test_an_obx5_value_with_no_c0_byte_is_still_kept(value_type: str, value: str) -> None: + outcomes = _outcomes(_obx(value_type, value)) + assert outcomes[0] == outcomes[1] + assert f"|{value}|" in outcomes[0][1] + + +def test_a_control_byte_ending_the_last_obx5_is_a_known_difference() -> None: + """The engine's parser trims a TAB after the last field of the last line before the rule + reads it, so it keeps the number without the byte; the tee reads the byte and redacts the + value (``docs/PHI.md`` section 9 lists the difference). Neither emits the byte.""" + message = f"{_header(kind='ORU^R01')}\rPID|1||Q7734^^^H^MR\rOBX|1|NM|CODE^^L||12\t" + engine_out = engine_anon.anonymize(message, salt=_SALT) + tee_out = tee_anon.anonymize(message, salt=_SALT) + assert engine_out.endswith("||12") + assert tee_out.endswith(f"||{_REDACTED}") + + +@_SURROGATE_MODULES +def test_the_obx5_allowlist_refuses_a_c0_byte_itself(surrogates: ModuleType) -> None: + seps = surrogates.Seps() + assert surrogates.preserve_obx5_value("NM", "12", seps) + assert not surrogates.preserve_obx5_value("NM", "12\t", seps) + assert not surrogates.preserve_obx5_value("ID", "A\\X07\\", seps) + assert surrogates.preserve_obx5_value("ID", "A\\X41\\", seps)