From aad2b03f27c9067ae67afa592a1017bd57f454bc Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:19:26 +0100 Subject: [PATCH 1/7] Preserve proven technical literals during publication phone checks --- changelog.d/358.bugfix.md | 1 + docs/security.md | 8 +- src/ocr_toolkit/context/dlp/admission.py | 22 +++- src/ocr_toolkit/context/dlp/arithmetic.py | 55 ++++++++++ src/ocr_toolkit/context/dlp/datetimes.py | 77 ++++++++++++- src/ocr_toolkit/context/dlp/markup.py | 26 ++++- src/ocr_toolkit/context/dlp/numeric.py | 7 +- src/ocr_toolkit/context/dlp/projection.py | 14 ++- tests/test_dlp_arithmetic.py | 123 +++++++++++++++++++++ tests/test_dlp_audit.py | 40 +++++++ tests/test_dlp_date_ranges.py | 117 ++++++++++++++++++++ tests/test_review_runner.py | 127 ++++++++++++++++++++++ 12 files changed, 601 insertions(+), 16 deletions(-) create mode 100644 changelog.d/358.bugfix.md create mode 100644 src/ocr_toolkit/context/dlp/arithmetic.py create mode 100644 tests/test_dlp_arithmetic.py create mode 100644 tests/test_dlp_date_ranges.py diff --git a/changelog.d/358.bugfix.md b/changelog.d/358.bugfix.md new file mode 100644 index 00000000..5056b4f1 --- /dev/null +++ b/changelog.d/358.bugfix.md @@ -0,0 +1 @@ +Publication DLP keeps findings that quote supported ISO date ranges, dated local Markdown anchors and integer size calculations. Phone numbers and sensitive material elsewhere in the finding still prevent publication. diff --git a/docs/security.md b/docs/security.md index e2f422ae..0b1293a1 100644 --- a/docs/security.md +++ b/docs/security.md @@ -467,7 +467,13 @@ Unicode matches fail closed as `limit`. Source text and applicable normalized/decoded views are checked independently. A formatting boundary cannot silently join a contact into a bare identifier. Unproved formatted numbers retain conservative phone checks; arithmetic syntax alone -does not establish an executable-source role. Literal code +does not establish an executable-source role. Publication recognizes a range +when both ISO dates are calendar-valid and the entire phone candidate falls +inside the range. A dated local Markdown heading can retain Unicode letters in +its destination. A complete assignment such as `size = 16 * 1024 * 1024` +preserves its multiplication operators during phone checks, including when +quoted in a supported inline code span. Explicit contact context, adjacent +phone numbers and credential checks still apply. Literal code does not activate its markup, while its obfuscated sensitive material remains subject to checks. Diagnostic substitutions never establish credential material; complete empty/masked query values stay empty/masked in surrounding syntax. diff --git a/src/ocr_toolkit/context/dlp/admission.py b/src/ocr_toolkit/context/dlp/admission.py index 9701cf4d..c5b68501 100644 --- a/src/ocr_toolkit/context/dlp/admission.py +++ b/src/ocr_toolkit/context/dlp/admission.py @@ -20,7 +20,9 @@ ) from ocr_toolkit.context.code_text import CodeTextContext, TextSink from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp.arithmetic import binary_size_phone_view from ocr_toolkit.context.dlp.credentials import credential_reference_view +from ocr_toolkit.context.dlp.datetimes import dated_anchor_phone_view from ocr_toolkit.context.dlp.decoding import _html_decode, _mermaid_decode, bounded_nfkc from ocr_toolkit.context.dlp.email import contains_email from ocr_toolkit.context.dlp.markup import ( @@ -244,9 +246,13 @@ def _markup_phone(value: str, *, literal: bool) -> bool: # Visible formatting is interpreted by the parser. Hidden HTML material # needs an independent sweep; stripping it or joining its digits would # silently make an obfuscated contact look like an opaque identifier. + hidden = ( + markup.hidden + if literal + else (*markup.hidden_nonlinks, *(dated_anchor_phone_view(link) for link in markup.links)) + ) return (not literal and _contains_phone(_literal_normalize(markup.contacts))) or any( - _contains_phone(phone_markup_view(_literal_normalize(fragment))) - for fragment in markup.hidden + _contains_phone(phone_markup_view(_literal_normalize(fragment))) for fragment in hidden ) @@ -409,6 +415,11 @@ def _check_material( seen_secrets.add((candidate, secret_view)) if has_sensitive_material(candidate, credential_view=secret_view, values=secrets): return DLPResult(False, None, "secret", representation) + arithmetic_phone = ( + binary_size_phone_view(normalized, prose=sink == TextSink.PROSE and not literal) + if publication and sink != TextSink.DIAGRAM_LABEL + else normalized + ) seen_pii: set[str] = set() for representation, candidate in ( ("normalized", normalized), @@ -432,7 +443,10 @@ def _check_material( transform=email_transform, ): return DLPResult(False, None, "pii", f"email:{representation}") - if _contains_phone(candidate) or _markup_phone(candidate, literal=literal): + phone_candidate = candidate + if representation == "source" and not literal and arithmetic_phone != normalized: + phone_candidate = _source_normalize(arithmetic_phone) + if _contains_phone(phone_candidate) or _markup_phone(phone_candidate, literal=literal): return DLPResult(False, None, "pii", f"phone:{representation}") # Secret/email deobfuscation remains independent of literal rendering. # Strong contact signals also retain the stricter arbitrary-format sweep. @@ -444,6 +458,8 @@ def _check_material( if publication and literal: context = code_context if allow_opaque_code and sink != TextSink.DIAGRAM_LABEL else None phone_original = context.phone_view(normalized) if context is not None else normalized + if phone_original == normalized: + phone_original = arithmetic_phone phone_views = ( (phone_original, _html_decode(_mermaid_decode(_html_decode(phone_original)))) if has_mermaid diff --git a/src/ocr_toolkit/context/dlp/arithmetic.py b/src/ocr_toolkit/context/dlp/arithmetic.py new file mode 100644 index 00000000..2e893ee0 --- /dev/null +++ b/src/ocr_toolkit/context/dlp/arithmetic.py @@ -0,0 +1,55 @@ +"""Recognize complete literal binary-size assignments for phone interpretation.""" + +from __future__ import annotations + +import re + +from ocr_toolkit.context.dlp.contact_labels import _explicit_context +from ocr_toolkit.context.dlp.markup import interpret_markdown, strip_format_markers + +_INTEGER = r"[1-9][0-9]{0,4}" +_OPERATOR = r"[ \t]{1,8}\*\*?[ \t]{1,8}" +_ASSIGNMENT = re.compile( + rf"[A-Za-z_][A-Za-z0-9_]{{0,63}}[ \t]{{0,8}}=[ \t]{{0,8}}" + rf"(?P{_INTEGER}(?:{_OPERATOR}{_INTEGER}){{1,3}})" +) +_OPERATORS = re.compile(_OPERATOR) + + +def _assignment_phone_view(value: str) -> str: + assignment = _ASSIGNMENT.fullmatch(value) + if assignment is None or _explicit_context(value, assignment.start("expression")): + return value + expression = assignment["expression"] + operands = [int(token) for token in _OPERATORS.split(expression)] + # Require two four-digit-or-larger scale factors so short telephone groups + # cannot gain authority merely from ASCII stars in an assignment. + if sum(operand >= 1024 for operand in operands) < 2 or any( + operand & (operand - 1) for operand in operands + ): + return value + return value[: assignment.start("expression")] + expression.replace("*", "\u00d7") + + +def binary_size_phone_view(value: str, *, prose: bool) -> str: + """Keep operators in complete standalone or exact inline code assignments.""" + whole = _assignment_phone_view(value) + if whole != value or not prose or "`" not in value or "*" not in value: + return whole + parts = [] + cursor = 0 + for opening, start, end in interpret_markdown(value).exact_code_bodies: + if start < cursor or _explicit_context(value, opening): + continue + prefix = strip_format_markers(value[max(0, opening - 256) : opening]) + if _explicit_context(prefix, len(prefix)): + continue + fragment = value[start:end] + candidate = _assignment_phone_view(fragment) + if candidate != fragment: + parts.extend((value[cursor:start], candidate)) + cursor = end + if not parts: + return value + parts.append(value[cursor:]) + return "".join(parts) diff --git a/src/ocr_toolkit/context/dlp/datetimes.py b/src/ocr_toolkit/context/dlp/datetimes.py index b9ae12dc..27b56e07 100644 --- a/src/ocr_toolkit/context/dlp/datetimes.py +++ b/src/ocr_toolkit/context/dlp/datetimes.py @@ -5,8 +5,20 @@ import re import unicodedata from datetime import date, datetime +from urllib.parse import unquote -CALENDAR_DAY_PATTERN = r"(?:\d{4}-\d{2}-\d{2}|\d{2}\.\d{2}\.\d{4})" +_ISO_DAY = r"\d{4}-\d{2}-\d{2}" +CALENDAR_DAY_PATTERN = rf"(?:{_ISO_DAY}|\d{{2}}\.\d{{2}}\.\d{{4}})" +_DATE_RANGE = re.compile( + rf"(?P{_ISO_DAY})[ \t]{{0,16}}(?:\.\.\.?|\u2026|\u2013)[ \t]{{0,16}}" + rf"(?P{_ISO_DAY})" +) +_LOCAL_MARKDOWN_PATH = re.compile( + r"/?(?:(?:\.{1,2}|[A-Za-z0-9_-][A-Za-z0-9._-]{0,127})/)*" + r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}\.(?:md|markdown)\Z", + re.IGNORECASE | re.ASCII, +) +_HIGH_PERCENT_BYTE = re.compile(r"%(?:[89a-fA-F][0-9a-fA-F])") _DATETIME = re.compile( rf"(?P{CALENDAR_DAY_PATTERN})(?:T|[ \t]+)" r"(?P\d{2}:\d{2}(?::\d{2}(?:[.,]\d{1,9})?)?)" @@ -31,6 +43,69 @@ def _word_part(char: str) -> bool: return char.isalnum() or unicodedata.category(char).startswith("M") +def complete_date_range(value: str, start: int, end: int) -> bool: + """Prove both ISO days within one closed range around the phone candidate.""" + + for block in _DATE_RANGE.finditer( + value, max(0, start - _WINDOW), min(len(value), end + _WINDOW) + ): + if not block.start() <= start < end <= block.end(): + continue + left = value[block.start() - 1] if block.start() else "" + tail = value[block.end() : block.end() + 2] + right = tail[:1] + if left and (_word_part(left) or left in "_.:+/-"): + continue + if right and (_word_part(right) or right in "_:+/-\u2026\u2013"): + continue + if right == "." and len(tail) == 2 and (_word_part(tail[1]) or tail[1] in "_.:+/-"): + continue + try: + calendar_day(block["first"]) + calendar_day(block["last"]) + except ValueError: + continue + return True + return False + + +def dated_anchor_phone_view(value: str) -> str: + """Undo UTF-8 letter escaping in a parsed local Markdown date anchor only.""" + + if len(value) > 1024 or "%" not in value: + return value + path, separator, fragment = value.partition("#") + if not separator or (path and not _LOCAL_MARKDOWN_PATH.fullmatch(path)): + return value + # The date and any heading ordinal must be present in their literal form. + # Only the preceding word slug can contribute percent-encoded material. + raw_date = fragment[-10:] + if fragment[-11:-10] != "-" or not re.fullmatch(_ISO_DAY, raw_date): + return value + raw_slug = fragment[:-11] + if "%" in _HIGH_PERCENT_BYTE.sub("", raw_slug): + return value + try: + slug = unquote(raw_slug, errors="strict") + calendar_day(raw_date) + except ValueError: + return value + words = slug.split("-") + if re.fullmatch(r"[0-9]{1,3}", words[0]): + words = words[1:] + if not words or any( + not word + or not word[0].isalpha() + or any( + not char.isalpha() and not unicodedata.category(char).startswith("M") for char in word + ) + or word.casefold() in {"contact", "phone", "telephone", "tel", "call"} + for word in words + ): + return value + return f"{path}#{slug}-{raw_date}" + + def complete_datetime(value: str, start: int, end: int) -> bool: """Recognize a whole parsed timestamp containing this entire numeric candidate.""" diff --git a/src/ocr_toolkit/context/dlp/markup.py b/src/ocr_toolkit/context/dlp/markup.py index 08d1b2ce..99e64507 100644 --- a/src/ocr_toolkit/context/dlp/markup.py +++ b/src/ocr_toolkit/context/dlp/markup.py @@ -186,10 +186,12 @@ def finalize_tokens(self, tokens: list[dict[str, Any]], depth: int) -> list[dict def parse_codespan(self, match: re.Match[str], state: InlineState) -> int: end = super().parse_codespan(match, state) if state.tokens and state.tokens[-1]["type"] == "codespan" and "dlp_start" in state.env: + offset = state.env["dlp_start"] state.tokens[-1]["dlp_opening"] = ( - state.env["dlp_start"] + match.start(), + offset + match.start(), len(match[0]), ) + state.tokens[-1]["dlp_body"] = (offset + match.end(), offset + end - len(match[0])) return end @@ -238,6 +240,8 @@ class MarkupText: code_openings: tuple[tuple[int, int], ...] = () hidden: tuple[str, ...] = () links: tuple[str, ...] = () + hidden_nonlinks: tuple[str, ...] = () + exact_code_bodies: tuple[tuple[int, int, int], ...] = () _PARSER = _Markdown( @@ -259,20 +263,24 @@ def interpret_markdown(value: str) -> MarkupText: pieces: list[str] = [] contacts: list[str] = [] openings: list[tuple[int, int]] = [] + exact_code_bodies: list[tuple[int, int, int]] = [] hidden: dict[str, None] = {} links: dict[str, None] = {} + hidden_nonlinks: dict[str, None] = {} used = 0 hidden_used = 0 maximum = 4 * len(value) + 4096 hidden_maximum = 4 * len(value.encode("utf-8")) + 4096 - def hide(text: str) -> None: + def hide(text: str, *, destination: bool = False) -> None: nonlocal hidden_used if text and text not in hidden: hidden_used += len(text) if hidden_used > hidden_maximum: raise RepresentationLimit("hidden material expansion budget") hidden[text] = None + if text and not destination: + hidden_nonlinks[text] = None def add(text: str) -> None: nonlocal used @@ -295,7 +303,7 @@ def walk(items: list[dict[str, Any]]) -> None: if kind in {"link", "image"}: attrs = token["attrs"] links[attrs["url"]] = None - hide(attrs["url"]) + hide(attrs["url"], destination=True) hide(attrs.get("title", "")) formatted = kind in {"emphasis", "strong", "codespan"} if formatted: @@ -320,6 +328,14 @@ def walk(items: list[dict[str, Any]]) -> None: add(token.get("raw", "\n" if kind in {"softbreak", "linebreak"} else "")) if kind == "codespan" and "dlp_opening" in token: openings.append(token["dlp_opening"]) + opening, width = token["dlp_opening"] + start, end = token["dlp_body"] + if ( + 0 <= opening < start < end <= len(value) - width + and value[opening:start] == value[end : end + width] == "`" * width + and value[start:end] == token["raw"] + ): + exact_code_bodies.append((opening, start, end)) if formatted: boundary() if kind in {"paragraph", "block_code", "heading", "block_html"}: @@ -328,7 +344,7 @@ def walk(items: list[dict[str, Any]]) -> None: walk(tokens) for attrs in state.env["ref_links"].values(): links[attrs["url"]] = None - hide(attrs["url"]) + hide(attrs["url"], destination=True) hide(attrs.get("title", "")) return MarkupText( "".join(pieces), @@ -336,6 +352,8 @@ def walk(items: list[dict[str, Any]]) -> None: tuple(openings), tuple(hidden), tuple(links), + tuple(hidden_nonlinks), + tuple(exact_code_bodies), ) diff --git a/src/ocr_toolkit/context/dlp/numeric.py b/src/ocr_toolkit/context/dlp/numeric.py index dcb0b022..d7ba6cb5 100644 --- a/src/ocr_toolkit/context/dlp/numeric.py +++ b/src/ocr_toolkit/context/dlp/numeric.py @@ -14,6 +14,7 @@ CALENDAR_DAY_PATTERN, _word_part, calendar_day, + complete_date_range, complete_datetime, ) from ocr_toolkit.context.dlp.decoding import _technical_decode, bounded_nfkc @@ -230,8 +231,10 @@ def _technical_number(value: str, match: re.Match[str]) -> bool: or _explicit_context(value, match.start()) ): return False - if complete_datetime(value, *match.span()) or _complete_technical_block( - value, match.start(), match.end() + if ( + complete_datetime(value, *match.span()) + or complete_date_range(value, *match.span()) + or _complete_technical_block(value, *match.span()) ): return True # All contextual grammars below are bounded. Do not copy the complete diff --git a/src/ocr_toolkit/context/dlp/projection.py b/src/ocr_toolkit/context/dlp/projection.py index ebc0d65b..a25bf0f9 100644 --- a/src/ocr_toolkit/context/dlp/projection.py +++ b/src/ocr_toolkit/context/dlp/projection.py @@ -12,6 +12,7 @@ from mistune.renderers.markdown import MarkdownRenderer from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp.datetimes import dated_anchor_phone_view from ocr_toolkit.context.dlp.decoding import RepresentationLimit, _html_decode from ocr_toolkit.context.dlp.markup import _PARSER, interpret_markdown from ocr_toolkit.context.dlp.presentation import has_unsafe_controls @@ -167,17 +168,20 @@ def _project_once(value: str, budgets: TextBudgets) -> str: assert isinstance(tokens, list) stack = list(tokens) rewrite = False - validated: set[str] = set() + validated: dict[str, str] = {} - def validate(url: str) -> None: + def validate(attrs: dict[str, Any]) -> None: + url = attrs["url"] if url not in validated: validate_destination(url) - validated.add(url) + # Keep equivalent letter spelling through the rendered material recheck. + validated[url] = dated_anchor_phone_view(url) + attrs["url"] = validated[url] while stack: token = stack.pop() if token["type"] in {"link", "image"}: - validate(token["attrs"]["url"]) + validate(token["attrs"]) rewrite = ( rewrite or token["type"] in {"inline_html", "block_html", "image"} @@ -193,7 +197,7 @@ def validate(url: str) -> None: stack.extend(token.get("children", ())) # Unused definitions are still supplied material, not invisible exceptions. for attrs in state.env["ref_links"].values(): - validate(attrs["url"]) + validate(attrs) if not rewrite: # Keep existing harmless syntax and literal carriers exactly. Rewriting # them merely to canonicalize Markdown can invent credential material. diff --git a/tests/test_dlp_arithmetic.py b/tests/test_dlp_arithmetic.py new file mode 100644 index 00000000..614381cd --- /dev/null +++ b/tests/test_dlp_arithmetic.py @@ -0,0 +1,123 @@ +"""Verify narrow arithmetic interpretation and unchanged material checks.""" + +import pytest + +from ocr_toolkit import review_runner +from ocr_toolkit.context.code_text import TextSink +from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp import check_text +from ocr_toolkit.evidence.opaque_code import prove_opaque_code + +BUDGETS = TextBudgets(20_000, 80_000, 300) + + +@pytest.mark.parametrize( + "value", + [ + "MAX_SCAN_BYTES = 16 * 1024 * 1024", + "x = 1024 * 1024", + "x = 1024 ** 1024", + "cache_size=8 * 2 * 2048 * 4096", + ], +) +@pytest.mark.parametrize("sink", [TextSink.PROSE, TextSink.LITERAL_CODE]) +def test_complete_binary_size_assignment_preserves_published_text(value, sink): + result = check_text(value, budgets=BUDGETS, publication=True, sink=sink) + assert result.admitted + assert result.text == value + + +@pytest.mark.parametrize( + "value", + [ + "phone = 16 * 1024 * 1024", + "officePhoneNumber = 1024 * 1024", + "value = 202 * 555 * 1114", + "value = 256 * 512 * 1024", + "value = 1024 *555-0114", + "value = 1024 * 1024; +7 912 345-67-89", + "Contact 202 555-0114.\nvalue = 1024 * 1024", + "value = 1024 * 1024\n202 555-0114", + 'value = "1024 * 1024"', + "value: 1024 * 1024", + "1024 * 1024", + "value = 01024 * 1024", + "value = 1001 * 2001", + "value = 2 * 2 * 2 * 1024 * 1024", + ], +) +@pytest.mark.parametrize("sink", [TextSink.PROSE, TextSink.LITERAL_CODE]) +def test_ambiguous_numbers_and_separate_contacts_remain_phone_candidates(value, sink): + result = check_text(value, budgets=BUDGETS, publication=True, sink=sink) + assert (result.admitted, result.reason) == (False, "pii") + assert result.detector is not None and result.detector.startswith("phone:") + + +def test_binary_size_syntax_does_not_change_configured_value_checks(monkeypatch): + value = "MAX_SCAN_BYTES = 16 * 1024 * 1024" + monkeypatch.setenv("OCR_LLM_TOKEN", value) + result = check_text(value, budgets=BUDGETS, publication=True) + assert (result.admitted, result.reason) == (False, "secret") + + +@pytest.mark.parametrize( + "value", + [ + "Preserve the limit when changing `MAX_SCAN_BYTES = 16 * 1024 * 1024`.", + "Use `x = 1024 * 1024` and `y = 1024 ** 1024`.", + "The value uses **`x = 1024 * 1024`**.", + ], +) +def test_complete_inline_assignment_in_review_prose(value): + result = check_text(value, budgets=BUDGETS, publication=True) + assert result.admitted + assert result.text == value + + +@pytest.mark.parametrize( + "value", + [ + "Preserve the limit when changing `MAX_SCAN_BYTES = 16 * 1024 * 1024.", + "`x = 1024 *\n1024`", + "Phone: `x = 1024 * 1024`", + "Call **`x = 1024 * 1024`**", + "**Phone:** `x = 1024 * 1024`", + "`x = 1024 * 1024` and Contact 202 555-0114.", + "`x = 1024 * 1024` and `202 *555-0114`.", + ], +) +def test_inline_qualification_preserves_other_contacts_and_requires_exact_body(value): + result = check_text(value, budgets=BUDGETS, publication=True) + assert (result.admitted, result.reason) == (False, "pii") + + +def test_finding_preserves_prose_and_separate_proven_multiline_code(): + excerpt = " size = 16 * 1024 * 1024\n return size + 8" + source = f"def scan():\n{excerpt}\n" + finding = { + "path": "example.py", + "start_line": 2, + "end_line": 3, + "content": "Preserve the limit when changing `size = 16 * 1024 * 1024`.", + "existing_code": excerpt, + } + proof = prove_opaque_code(finding, "example.py", lambda _path: source) + assert proof.existing_context is not None and proof.existing_context.operator_spans + result, publication, filtered = review_runner._publication_projection( + {"status": "success", "warnings": [], "comments": [finding]}, + forbidden=(), + allowed_tools=frozenset(), + code_proof=lambda _finding: proof, + ) + assert not filtered and publication["state"] == "passed" + assert result["comments"] == [finding] + + +def test_diagram_label_has_no_literal_assignment_role(): + result = check_text( + "value = 1024 * 1024", + budgets=BUDGETS, + publication=True, + sink=TextSink.DIAGRAM_LABEL, + ) + assert (result.admitted, result.reason) == (False, "pii") diff --git a/tests/test_dlp_audit.py b/tests/test_dlp_audit.py index 33607735..ed6215f5 100644 --- a/tests/test_dlp_audit.py +++ b/tests/test_dlp_audit.py @@ -222,6 +222,46 @@ def test_real_worker_proof_projection_and_no_source_in_report(state) -> None: assert "parts" not in json.dumps(result) +def test_publication_literal_corpus_preserves_independent_protection(state) -> None: + """Track false positives and inverse controls through the offline audit worker.""" + technical = ( + "MAX_SCAN_BYTES = 16 * 1024 * 1024", + "x = 1024 * 1024", + "2026-11-03…2026-11-30", + "2026-11-03..2026-11-30", + "2026-11-03 \u2013 2026-11-30", + "[Budget](../../BUDGET.md#8-замер-2026-11-30)", + "[Budget](../../BUDGET.md#8-measured-2026-11-30)", + ) + phone = "+1 202 555 0114" + secret = "synthetic-private-value" + cases = ( + *((item, None) for item in technical), + *((f"{item}; contact {phone}", "pii") for item in technical), + *((f'password="{secret}"; {item}', "secret") for item in technical), + ("8-2026-11-30", "pii"), + ("[Budget](../../BUDGET.md#8-2026-11-30)", "pii"), + ("Contact 202 **555** 0114", "pii"), + ) + identity = captured(state, "\n".join(text for text, _reason in cases)) + result = scanner.supervised(request(state, identity), 30) + + assert result["units"] == len(cases) + 1 + text_rejections = { + hit["unit"]: hit["reason"] + for hit in result["hits"] + if hit["role"] == "text" and hit["unit"] > 0 + } + expected_rejections = { + number: reason for number, (_text, reason) in enumerate(cases, 1) if reason is not None + } + assert text_rejections == expected_rejections + assert not any( + hit["unit"] in (1, 2) and hit["role"] == "existing_code" for hit in result["hits"] + ) + assert all(value not in json.dumps(result) for value in (technical[0], phone, secret)) + + @pytest.mark.parametrize("secret", ["source", "Inspect", "excerpt"]) def test_real_worker_wrapper_text_cannot_turn_benign_input_into_failure(state, monkeypatch, secret): monkeypatch.setenv("OCR_LLM_TOKEN", secret) diff --git a/tests/test_dlp_date_ranges.py b/tests/test_dlp_date_ranges.py new file mode 100644 index 00000000..4510beff --- /dev/null +++ b/tests/test_dlp_date_ranges.py @@ -0,0 +1,117 @@ +"""Verify date ranges and dated destinations through publication admission.""" + +import pytest + +from ocr_toolkit.context.code_text import TextSink +from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp import check_text +from ocr_toolkit.context.dlp.datetimes import dated_anchor_phone_view + +_BUDGETS = TextBudgets(20_000, 80_000, 300) +_SINKS = (TextSink.PROSE, TextSink.LITERAL_CODE) + + +@pytest.mark.parametrize("sink", _SINKS) +@pytest.mark.parametrize( + "value", + ( + "| Period | 2026-11-03…2026-11-30 |", + "2026-11-03..2026-11-30", + "(2026-11-03 ... 2026-11-30).", + "2026-11-03 \u2013 2026-11-30", + "2024-02-29 … 2024-03-01", + "\uff12\uff10\uff12\uff16-\uff11\uff11-\uff10\uff13.." + "\uff12\uff10\uff12\uff16-\uff11\uff11-\uff13\uff10", + "\u0662\u0660\u0662\u0666-\u0661\u0661-\u0660\u0663.." + "\u0662\u0660\u0662\u0666-\u0661\u0661-\u0663\u0660", + ), +) +def test_complete_iso_date_ranges_survive_publication(value, sink): + assert check_text(value, budgets=_BUDGETS, publication=True, sink=sink).admitted + + +@pytest.mark.parametrize("sink", _SINKS) +@pytest.mark.parametrize( + "value", + ( + "2026-02-29..2026-11-30", + "2026-11-03…2026-13-30", + "2026-11-03....2026-11-30", + "2026-11-03..2026-11-30-555", + "2026-11-03..2026-11-30.555", + "12026-11-03..2026-11-30", + "phone: 2026-11-03..2026-11-30", + "telephone number 2026-11-03…2026-11-30", + "contact = '2026-11-03 ... 2026-11-30'", + "2026-11-03..2026-11-30, +7 912 345-67-89", + "2026-11-03..2026-11-30 912-345-6789", + "8-2026-11-30", + ), +) +def test_date_range_proof_preserves_ambiguous_values_and_contact_intent(value, sink): + result = check_text(value, budgets=_BUDGETS, publication=True, sink=sink) + assert (result.admitted, result.reason) == (False, "pii") + + +@pytest.mark.parametrize( + "value", + ( + "[§8](../../BUDGET.md#8-замер-2026-11-30)", + "[§8](../../BUDGET.md#8-measured-2026-11-30)", + "[Section](#замер-2024-02-29)", + "[Section][measurement]\n\n[measurement]: ./guide.markdown#8-замер-2026-11-30", + ), +) +def test_local_markdown_dates_survive_phone_views(value): + assert check_text(value, budgets=_BUDGETS, publication=True).admitted + + +@pytest.mark.parametrize( + "value", + ( + "[§8](../../BUDGET.md#8-замер-2026-11-30) Details", + "[Section][measurement] Details\n\n" + "[measurement]: ./guide.markdown#8-замер-2026-11-30", + ), +) +def test_dated_destinations_survive_rewritten_prose_and_its_material_recheck(value): + result = check_text(value, budgets=_BUDGETS, publication=True) + assert result.admitted and result.text is not None + assert "" not in result.text + assert "#8-замер-2026-11-30" in result.text + + +@pytest.mark.parametrize( + "value", + ( + "[§8](#8-2026-11-30)", + "[§8](#8-замер-2026-13-30)", + "[Section](https://example.invalid/guide.md#8-замер-2026-11-30)", + '[Section](#8-замер-2026-11-30 "+7 912 345-67-89")', + "[Section](#8-замер-2026-11-30); phone: 8-2026-11-30", + "[Section](#8-%D0%B7%D0%B0%D0%BC%D0%B5%D1%80-2026-11-30)", + "[Section](#8-%D0%B7%D0%B0%D0%BC%D0%B5%D1%80-%31-812-555-0114)", + ), +) +def test_markdown_dates_do_not_admit_other_contact_material(value): + result = check_text(value, budgets=_BUDGETS, publication=True) + assert (result.admitted, result.reason) == (False, "pii") + + +@pytest.mark.parametrize( + "value", + ( + "//example.invalid/guide.md#%D1%80-2026-11-30", + "guide.txt#%D1%80-2026-11-30", + "guide.md?q=lookup#%D1%80-2026-11-30", + "guide.md#%D1%80-%32%30%32%36-11-30", + "guide.md#%D1%80-2026-02-29", + "guide.md#%D1%80-2026-11-30-1", + "guide.md#%D1%80-phone-2026-11-30", + "guide.md#%FF-2026-11-30", + "guide.md#%E2%80%8B-2026-11-30", + "guide.md#%D1%80-555-2026-11-30", + ), +) +def test_date_anchor_phone_view_requires_a_closed_local_destination(value): + assert dated_anchor_phone_view(value) == value diff --git a/tests/test_review_runner.py b/tests/test_review_runner.py index c90bc04f..371219dd 100644 --- a/tests/test_review_runner.py +++ b/tests/test_review_runner.py @@ -19,6 +19,7 @@ import pytest from ocr_toolkit import ocr_result, review_runner +from ocr_toolkit.common.git import isolated_git_environment from ocr_toolkit.context.ci_outcomes import CIOutcomeSnapshot from ocr_toolkit.context.contracts import TextBudgets from ocr_toolkit.context.dlp import ForbiddenMatcher, ForbiddenValue @@ -2324,6 +2325,132 @@ def test_publication_dlp_retains_only_safe_local_findings_without_provider_recei assert "ocr_toolkit_evidence" in rendered +def test_publication_preserves_technical_findings_and_omits_sensitive_neighbors( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Run real immutable source proof, finalization and local Markdown delivery together.""" + root = tmp_path.resolve() / "source" + root.mkdir() + prefix = [ + "git", + "-C", + str(root), + "-c", + "core.hooksPath=/dev/null", + "-c", + "commit.gpgsign=false", + "-c", + "user.name=Synthetic Author", + "-c", + "user.email=author@example.invalid", + ] + environment = isolated_git_environment() + + def git(*args: str) -> str: + return subprocess.run( + [*prefix, *args], env=environment, check=True, capture_output=True, text=True + ).stdout.strip() + + git("init", "-q") + git("commit", "--allow-empty", "-qm", "base") + base = git("rev-parse", "HEAD") + product = "MAX_SCAN_BYTES = 16 * 1024 * 1024" + date_range = "2026-11-03…2026-11-30" + dated_link = "[§8](../../BUDGET.md#8-замер-2026-11-30)" + phone = "+1 202 555 0114" + secret = "synthetic-private-value" + path = "scan.py" + (root / path).write_text( + product + "\nwindow = None\nguide = None\nowner = None\nconfig = None\n", + encoding="utf-8", + ) + git("add", path) + git("commit", "-qm", "head") + head = git("rev-parse", "HEAD") + monkeypatch.chdir(root) + safe = [ + { + "path": path, + "start_line": 1, + "end_line": 1, + "content": f"Preserve the limit when changing `{product}`.", + "existing_code": product, + }, + {"path": path, "line": 2, "content": f"| Period | {date_range} |"}, + {"path": path, "line": 3, "content": f"Read {dated_link} for the budget."}, + ] + rejected = [ + { + "path": path, + "line": 4, + "content": f"Window {date_range}. Compare `{product}`. Contact {phone}.", + }, + {"path": path, "line": 5, "content": f'Read {dated_link}. password="{secret}"'}, + ] + result = tmp_path / "result.json" + result.write_text( + json.dumps( + { + "status": "complete", + "comments": [*safe, *rejected], + "warnings": [], + "tool_calls": {"total": 1, "by_tool": {"ocr_toolkit_evidence": 1}}, + "manifest": { + "schema_version": "ocr.run-manifest/v1", + "operation": "review", + "terminal_state": "complete", + "input": native_range_input(base, head), + "coverage": { + "selected": [{"item_id": "scan"}], + "completed": [{"item_id": "scan"}], + "reused": [], + "failed": [], + "waived": [], + }, + }, + } + ), + encoding="utf-8", + ) + composition = MCPComposition( + payload={}, + capabilities=(MCPCapability("ocr_toolkit_evidence", BUILTIN_EVIDENCE_TOOLS, True),), + external_servers=(), + secret_values=(), + ) + local_state = review_runner.ReviewRunState(local=True) + + _, blocked, publication = review_runner._finalize_ocr_result( + result, + composition, + replace(LOCAL_IDENTITY, source_sha=head), + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + report_consumer=local_state.admit_report, + state=local_state, + expected_range=ReviewRange(base, head), + ocr_exit_code=0, + ) + + assert blocked and publication["state"] == "publication-filtered" + assert publication["omitted"] == {"comments": 2, "warnings": 0, "fields": 2} + assert publication["reason_counts"]["pii"] == publication["reason_counts"]["secret"] == 1 + persisted = result.read_text(encoding="utf-8") + finalized = json.loads(persisted) + assert finalized["status"] == "completed_with_errors" + assert finalized["comments"] == safe + assert local_state.report is not None + assert list(local_state.report.comments) == safe + assert local_state.report.outcome.status == "complete" + markdown = tmp_path / "review.md" + review_runner.publish_local_report(local_state.report, markdown) + rendered = markdown.read_text(encoding="utf-8") + assert all(value in rendered for value in (product, date_range, dated_link)) + for private in (phone, secret, "Window", "Contact"): + assert private not in persisted and private not in rendered + + def test_background_preview_advisory_is_atomically_finalized_without_blocking_approval( tmp_path: Path, ) -> None: From d05c4266ca27686e0c03b6145d1893102fcf96de Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:24:24 +0100 Subject: [PATCH 2/7] Keep context admission and canonical contact labels protected --- docs/security.md | 8 ++++++-- src/ocr_toolkit/context/dlp/admission.py | 23 +++++++++++++++-------- src/ocr_toolkit/context/dlp/arithmetic.py | 8 ++++++-- src/ocr_toolkit/context/dlp/numeric.py | 8 ++++---- tests/test_dlp_arithmetic.py | 22 ++++++++++++++++++++++ tests/test_dlp_date_ranges.py | 19 +++++++++++++++++++ 6 files changed, 72 insertions(+), 16 deletions(-) diff --git a/docs/security.md b/docs/security.md index 0b1293a1..d79dddf5 100644 --- a/docs/security.md +++ b/docs/security.md @@ -469,10 +469,14 @@ boundary cannot silently join a contact into a bare identifier. Unproved formatted numbers retain conservative phone checks; arithmetic syntax alone does not establish an executable-source role. Publication recognizes a range when both ISO dates are calendar-valid and the entire phone candidate falls -inside the range. A dated local Markdown heading can retain Unicode letters in +inside the range. The separator can be two or three periods, an ellipsis, or +an en dash, with up to 16 spaces or tabs on either side. A dated local Markdown heading can retain Unicode letters in its destination. A complete assignment such as `size = 16 * 1024 * 1024` preserves its multiplication operators during phone checks, including when -quoted in a supported inline code span. Explicit contact context, adjacent +quoted in a supported inline code span. This form accepts two to four +power-of-two factors of up to five decimal digits, including at least two +factors of 1024 or greater, with spaces or tabs around `*` or `**`. +Explicit contact context, adjacent phone numbers and credential checks still apply. Literal code does not activate its markup, while its obfuscated sensitive material remains subject to checks. Diagnostic substitutions never establish credential material; diff --git a/src/ocr_toolkit/context/dlp/admission.py b/src/ocr_toolkit/context/dlp/admission.py index c5b68501..9bdf4df7 100644 --- a/src/ocr_toolkit/context/dlp/admission.py +++ b/src/ocr_toolkit/context/dlp/admission.py @@ -241,18 +241,22 @@ def _literal_contact_view(value: str, *, visible: bool, formatting: bool = True) return _source_normalize(normalized) -def _markup_phone(value: str, *, literal: bool) -> bool: +def _markup_phone(value: str, *, literal: bool, publication: bool) -> bool: markup = interpret_markdown(phone_markup_view(value, formatting=False)) # Visible formatting is interpreted by the parser. Hidden HTML material # needs an independent sweep; stripping it or joining its digits would # silently make an obfuscated contact look like an opaque identifier. hidden = ( - markup.hidden - if literal - else (*markup.hidden_nonlinks, *(dated_anchor_phone_view(link) for link in markup.links)) + (*markup.hidden_nonlinks, *(dated_anchor_phone_view(link) for link in markup.links)) + if publication and not literal + else markup.hidden ) - return (not literal and _contains_phone(_literal_normalize(markup.contacts))) or any( - _contains_phone(phone_markup_view(_literal_normalize(fragment))) for fragment in hidden + return ( + not literal + and _contains_phone(_literal_normalize(markup.contacts), publication=publication) + ) or any( + _contains_phone(phone_markup_view(_literal_normalize(fragment)), publication=publication) + for fragment in hidden ) @@ -446,7 +450,9 @@ def _check_material( phone_candidate = candidate if representation == "source" and not literal and arithmetic_phone != normalized: phone_candidate = _source_normalize(arithmetic_phone) - if _contains_phone(phone_candidate) or _markup_phone(phone_candidate, literal=literal): + if _contains_phone(phone_candidate, publication=publication) or _markup_phone( + phone_candidate, literal=literal, publication=publication + ): return DLPResult(False, None, "pii", f"phone:{representation}") # Secret/email deobfuscation remains independent of literal rendering. # Strong contact signals also retain the stricter arbitrary-format sweep. @@ -472,7 +478,8 @@ def _check_material( candidate, visible=visible, formatting=not (allow_opaque_code and sink == TextSink.LITERAL_CODE), - ) + ), + publication=True, ): return DLPResult(False, None, "pii", "phone:literal_markup") matcher = forbidden_matcher or ForbiddenMatcher.compile(forbidden) diff --git a/src/ocr_toolkit/context/dlp/arithmetic.py b/src/ocr_toolkit/context/dlp/arithmetic.py index 2e893ee0..4bdf3dd8 100644 --- a/src/ocr_toolkit/context/dlp/arithmetic.py +++ b/src/ocr_toolkit/context/dlp/arithmetic.py @@ -5,6 +5,7 @@ import re from ocr_toolkit.context.dlp.contact_labels import _explicit_context +from ocr_toolkit.context.dlp.decoding import _technical_decode, bounded_nfkc from ocr_toolkit.context.dlp.markup import interpret_markdown, strip_format_markers _INTEGER = r"[1-9][0-9]{0,4}" @@ -41,8 +42,11 @@ def binary_size_phone_view(value: str, *, prose: bool) -> str: for opening, start, end in interpret_markdown(value).exact_code_bodies: if start < cursor or _explicit_context(value, opening): continue - prefix = strip_format_markers(value[max(0, opening - 256) : opening]) - if _explicit_context(prefix, len(prefix)): + # Decode and normalize only the adjacent label window. Exact original + # delimiters and assignment bytes still supply the arithmetic proof. + prefix = value[max(0, opening - 256) : opening] + canonical = strip_format_markers(bounded_nfkc(_technical_decode(prefix), original=prefix)) + if _explicit_context(canonical, len(canonical)): continue fragment = value[start:end] candidate = _assignment_phone_view(fragment) diff --git a/src/ocr_toolkit/context/dlp/numeric.py b/src/ocr_toolkit/context/dlp/numeric.py index d7ba6cb5..e25cbc5a 100644 --- a/src/ocr_toolkit/context/dlp/numeric.py +++ b/src/ocr_toolkit/context/dlp/numeric.py @@ -123,7 +123,7 @@ def _complete_technical_block(value: str, start: int, end: int) -> bool: return False -def _contains_phone(value: str) -> bool: +def _contains_phone(value: str, *, publication: bool = False) -> bool: """Recognize formatted phone-like values without classifying bare identifiers.""" return any( @@ -133,7 +133,7 @@ def _contains_phone(value: str) -> bool: or any(separator in match.group(0) for separator in " .()/-") ) and _phone_shape(value, match) - and not _technical_number(value, match) + and not _technical_number(value, match, publication=publication) for match in PHONE_RE.finditer(value) ) @@ -221,7 +221,7 @@ def _decimal_partition(value: str, start: int, end: int) -> bool: return found and all(char in " ()" for char in value[cursor:end]) -def _technical_number(value: str, match: re.Match[str]) -> bool: +def _technical_number(value: str, match: re.Match[str], *, publication: bool = False) -> bool: """Exclude only bounded, parsed technical syntax from phone candidates.""" candidate = match.group(0) @@ -233,7 +233,7 @@ def _technical_number(value: str, match: re.Match[str]) -> bool: return False if ( complete_datetime(value, *match.span()) - or complete_date_range(value, *match.span()) + or (publication and complete_date_range(value, *match.span())) or _complete_technical_block(value, *match.span()) ): return True diff --git a/tests/test_dlp_arithmetic.py b/tests/test_dlp_arithmetic.py index 614381cd..59a552c9 100644 --- a/tests/test_dlp_arithmetic.py +++ b/tests/test_dlp_arithmetic.py @@ -91,6 +91,28 @@ def test_inline_qualification_preserves_other_contacts_and_requires_exact_body(v assert (result.admitted, result.reason) == (False, "pii") +@pytest.mark.parametrize( + "label", + [ + "Phone:", + "Phone:", + "\uff30\uff48\uff4f\uff4e\uff45\uff1a", + "**Ph&#111;ne\uff1a**", + ], +) +def test_inline_qualification_respects_canonical_contact_labels(label): + result = check_text(f"{label} `x = 1024 * 1024`", budgets=BUDGETS, publication=True) + assert (result.admitted, result.reason) == (False, "pii") + assert result.detector is not None and result.detector.startswith("phone:") + + +def test_canonical_noncontact_prose_keeps_exact_inline_assignment(): + value = "Size: `x = 1024 * 1024`" + result = check_text(value, budgets=BUDGETS, publication=True) + assert result.admitted + assert result.text == value + + def test_finding_preserves_prose_and_separate_proven_multiline_code(): excerpt = " size = 16 * 1024 * 1024\n return size + 8" source = f"def scan():\n{excerpt}\n" diff --git a/tests/test_dlp_date_ranges.py b/tests/test_dlp_date_ranges.py index 4510beff..704da4c2 100644 --- a/tests/test_dlp_date_ranges.py +++ b/tests/test_dlp_date_ranges.py @@ -66,6 +66,25 @@ def test_local_markdown_dates_survive_phone_views(value): assert check_text(value, budgets=_BUDGETS, publication=True).admitted +@pytest.mark.parametrize( + ("value", "sink"), + ( + ("2026-11-03…2026-11-30", TextSink.PROSE), + ("2026-11-03..2026-11-30", TextSink.LITERAL_CODE), + ("[§8](../../BUDGET.md#8-замер-2026-11-30)", TextSink.PROSE), + ( + "[Section][measurement]\n\n[measurement]: ./guide.markdown#8-замер-2026-11-30", + TextSink.PROSE, + ), + ("[measurement]: ./guide.markdown#8-замер-2026-11-30", TextSink.PROSE), + ), +) +def test_new_date_interpretation_applies_only_to_publication(value, sink): + context = check_text(value, budgets=_BUDGETS, publication=False, sink=sink) + assert (context.admitted, context.reason) == (False, "pii") + assert check_text(value, budgets=_BUDGETS, publication=True, sink=sink).admitted + + @pytest.mark.parametrize( "value", ( From 8679fdd12774acb900ffa597eed47b2fbd8cf3d9 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:29:27 +0100 Subject: [PATCH 3/7] Document the supported publication literal grammar --- docs/security.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/security.md b/docs/security.md index d79dddf5..3546a208 100644 --- a/docs/security.md +++ b/docs/security.md @@ -470,14 +470,16 @@ formatted numbers retain conservative phone checks; arithmetic syntax alone does not establish an executable-source role. Publication recognizes a range when both ISO dates are calendar-valid and the entire phone candidate falls inside the range. The separator can be two or three periods, an ellipsis, or -an en dash, with up to 16 spaces or tabs on either side. A dated local Markdown heading can retain Unicode letters in -its destination. A complete assignment such as `size = 16 * 1024 * 1024` -preserves its multiplication operators during phone checks, including when -quoted in a supported inline code span. This form accepts two to four -power-of-two factors of up to five decimal digits, including at least two -factors of 1024 or greater, with spaces or tabs around `*` or `**`. -Explicit contact context, adjacent -phone numbers and credential checks still apply. Literal code +an en dash, with up to 16 spaces or tabs on either side. A parsed link to a +fragment in the current document or a local `.md` or `.markdown` file can retain +Unicode letters in its heading. This requires a letter-based slug followed by a +literal ISO date and a destination without a query. +A standalone assignment such as `size = 16 * 1024 * 1024`, or that exact text +inside a supported inline code span, preserves its multiplication operators +during phone checks. This form accepts two to four power-of-two operands of up +to five decimal digits without leading zeros. At least two must be 1024 or +greater. Each `*` or `**` takes one to eight spaces or tabs on each side. +Explicit contact context, adjacent phone numbers and credential checks still apply. Literal code does not activate its markup, while its obfuscated sensitive material remains subject to checks. Diagnostic substitutions never establish credential material; complete empty/masked query values stay empty/masked in surrounding syntax. From dd8688cc5b0b5d3ae201a082b831d68342624ec5 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:34:20 +0100 Subject: [PATCH 4/7] Clarify remaining conservative publication cases --- changelog.d/358.bugfix.md | 2 +- docs/security.md | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/changelog.d/358.bugfix.md b/changelog.d/358.bugfix.md index 5056b4f1..978cceb9 100644 --- a/changelog.d/358.bugfix.md +++ b/changelog.d/358.bugfix.md @@ -1 +1 @@ -Publication DLP keeps findings that quote supported ISO date ranges, dated local Markdown anchors and integer size calculations. Phone numbers and sensitive material elsewhere in the finding still prevent publication. +Publication DLP keeps findings that quote supported ISO date ranges, dated local Markdown anchors and power-of-two size assignments. Phone numbers and sensitive material elsewhere in the finding still prevent publication. diff --git a/docs/security.md b/docs/security.md index 3546a208..d66e6f66 100644 --- a/docs/security.md +++ b/docs/security.md @@ -469,16 +469,21 @@ boundary cannot silently join a contact into a bare identifier. Unproved formatted numbers retain conservative phone checks; arithmetic syntax alone does not establish an executable-source role. Publication recognizes a range when both ISO dates are calendar-valid and the entire phone candidate falls -inside the range. The separator can be two or three periods, an ellipsis, or +inside the range. The range must have a clear token boundary on each side. +A colon immediately after the final date still prevents recognition. +The separator can be two or three periods, an ellipsis, or an en dash, with up to 16 spaces or tabs on either side. A parsed link to a fragment in the current document or a local `.md` or `.markdown` file can retain Unicode letters in its heading. This requires a letter-based slug followed by a -literal ISO date and a destination without a query. +literal ISO date and a destination without a query. An optional one- to +three-digit ordinal can precede the slug. A standalone assignment such as `size = 16 * 1024 * 1024`, or that exact text inside a supported inline code span, preserves its multiplication operators during phone checks. This form accepts two to four power-of-two operands of up to five decimal digits without leading zeros. At least two must be 1024 or greater. Each `*` or `**` takes one to eight spaces or tabs on each side. +Text that also requires Mermaid entity decoding can still be withheld during +the independent check of the decoded representation. Explicit contact context, adjacent phone numbers and credential checks still apply. Literal code does not activate its markup, while its obfuscated sensitive material remains subject to checks. Diagnostic substitutions never establish credential material; From 6ca67d63c3cb6a94d40a684bbc19774d42521123 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:49:47 +0100 Subject: [PATCH 5/7] Exercise publication, context readback and review recovery without native OCR --- tests/test_context_store.py | 44 ++ tests/test_dlp_publication_edges.py | 121 ++++++ ...st_review_runner_publication_boundaries.py | 375 ++++++++++++++++++ tests/test_review_runtime_cleanup.py | 337 ++++++++++++++++ 4 files changed, 877 insertions(+) create mode 100644 tests/test_dlp_publication_edges.py create mode 100644 tests/test_review_runner_publication_boundaries.py create mode 100644 tests/test_review_runtime_cleanup.py diff --git a/tests/test_context_store.py b/tests/test_context_store.py index 7c9bcb67..5902e6c2 100644 --- a/tests/test_context_store.py +++ b/tests/test_context_store.py @@ -547,3 +547,47 @@ def test_context_store_hostile_read_revalidates_projection_semantics(tmp_path: P expected_policy_digest=POLICY_DIGEST, now=150, ) + + +@pytest.mark.parametrize("anchor", ({"path": "docs/guide.md", "line": 8}, {"line": 1})) +def test_context_readback_keeps_admitted_anchor_in_model_projection(tmp_path, anchor): + path = tmp_path / "context.json" + commit(path) + document = json.loads(path.read_text()) + document["records"][0]["projections"]["model"]["anchor"] = anchor + rewrite_hostile_store(path, document) + + store = ContextStore.read( + path, expected_run_id=RUN_ID, expected_policy_digest=POLICY_DIGEST, now=150 + ) + record = store.get(store.records[0].handle, run_id=RUN_ID, policy_digest=POLICY_DIGEST, now=150) + assert record.projections["model"]["anchor"] == anchor + assert "anchor" not in record.projections["publish"] + + +@pytest.mark.parametrize( + ("field", "value", "error"), + ( + ("anchor", {"path": "docs/guide.md", "url": "unknown"}, "anchor"), + ("anchor", {"path": ""}, "anchor path"), + ("anchor", {"line": True}, "anchor line"), + ("anchor", {"line": 10_000_001}, "anchor line"), + ("resolved", 1, "boolean"), + ("count", True, "integer"), + ("count", 1_000_000_001, "integer"), + ("author_class", "maintainer", "author class"), + ("author_pseudonym", "raw-author", "author pseudonym"), + ("digest", "unknown", "digest"), + ), +) +def test_context_readback_revalidates_projection_metadata(tmp_path, field, value, error): + path = tmp_path / "context.json" + commit(path) + document = json.loads(path.read_text()) + document["records"][0]["projections"]["model"][field] = value + rewrite_hostile_store(path, document) + + with pytest.raises(ContextStoreError, match=error): + ContextStore.read( + path, expected_run_id=RUN_ID, expected_policy_digest=POLICY_DIGEST, now=150 + ) diff --git a/tests/test_dlp_publication_edges.py b/tests/test_dlp_publication_edges.py new file mode 100644 index 00000000..694d8f13 --- /dev/null +++ b/tests/test_dlp_publication_edges.py @@ -0,0 +1,121 @@ +"""Protect publication boundaries when input changes after decoding.""" + +from urllib.parse import quote + +import pytest + +from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp import ForbiddenValue, check_text + +_BUDGETS = TextBudgets(10_000, 40_000, 100) + + +@pytest.mark.parametrize( + ("value", "max_lines", "context", "publication"), + ( + ("first second", 1, ("admitted", None), ("limit", "lines")), + ("first#10;second", 1, ("limit", "lines"), ("limit", "lines")), + ("first#0;second", 2, ("invalid_text", "mermaid"), ("invalid_text", "mermaid")), + ("phase#65039;", 2, ("admitted", None), ("laundering", "display_control")), + ("flight \u2708#65039; ready", 2, ("admitted", None), ("admitted", None)), + ), +) +def test_decoded_controls_and_line_budgets_are_checked_at_their_sink( + value, max_lines, context, publication +): + budgets = TextBudgets(100, 400, max_lines) + for publishing, expected in ((False, context), (True, publication)): + result = check_text(value, budgets=budgets, publication=publishing, enabled=True) + assert (result.reason, result.detector) == expected + assert result.text == (value if result.admitted else None) + + +def test_forbidden_attribution_includes_independently_decoded_destinations(): + value = "[Guide](./covered%20private%20details) and #79;perator blind reference" + forbidden = ( + ForbiddenValue("covered private details", "forge_discussions"), + ForbiddenValue("Operator blind reference", "external_context"), + ) + for publication, sources in ( + (False, ("external_context",)), + (True, ("external_context", "forge_discussions")), + ): + result = check_text( + value, budgets=_BUDGETS, publication=publication, forbidden=forbidden, enabled=True + ) + assert (result.admitted, result.reason, result.detector, result.text) == ( + False, + "forbidden", + "forbidden_matcher", + None, + ) + assert result.source_classes == sources + + +def test_percent_decoding_and_unicode_compatibility_cannot_hide_a_credential(): + encoded = quote( + "\uff50\uff41\uff53\uff53\uff57\uff4f\uff52\uff44\uff1dmeridian-synthetic-value" + ) + value = f"[Guide](./{encoded})" + result = check_text(value, budgets=_BUDGETS, publication=True, enabled=True) + assert (result.admitted, result.reason, result.detector, result.text) == ( + False, + "secret", + "compatible_markup", + None, + ) + + +def test_forbidden_comparison_budget_fails_closed_before_publication(): + candidate = "a" * 8000 + result = check_text( + candidate, budgets=_BUDGETS, publication=True, forbidden=("b" * 8000,), enabled=True + ) + assert (result.admitted, result.reason, result.detector, result.text) == ( + False, + "limit", + "forbidden_matcher", + None, + ) + + +def test_malformed_url_escape_does_not_inherit_the_literal_percent_exception(): + malformed = "[Guide](reference%ZZ.md)" + literal = "[Guide](reference%25.md)" + result = check_text(malformed, budgets=_BUDGETS, publication=True, enabled=True) + assert (result.admitted, result.reason, result.detector) == ( + False, + "laundering", + "markdown_destination", + ) + assert check_text(literal, budgets=_BUDGETS, publication=True, enabled=True).text == literal + + +def test_dated_link_projection_still_budgets_the_escaped_html_token(): + url = "#8-замер-2026-11-30" + value = f"[Guide]({url}) " + tight = TextBudgets(len(value), _BUDGETS.max_bytes, _BUDGETS.max_lines) + rejected = check_text(value, budgets=tight, publication=True, enabled=True) + assert (rejected.admitted, rejected.reason, rejected.detector, rejected.text) == ( + False, + "limit", + "representation", + None, + ) + admitted = check_text(value, budgets=_BUDGETS, publication=True, enabled=True) + assert admitted.admitted and admitted.text is not None + assert url in admitted.text and "