diff --git a/PLANS.md b/PLANS.md index 63a367c6..8a03cc52 100644 --- a/PLANS.md +++ b/PLANS.md @@ -27,10 +27,11 @@ Review the new contributor's entire repository history, fix incremental qualific | --- | --- | --- | --- | | REQ-001 | Inspect external submissions and observed GitHub disclosure surfaces | WQ-01 | done | | REQ-002 | Protect dev intake and isolate privileged publication | WQ-02 | in_progress | -| REQ-003 | Qualify #351/#354 and implement #352–353 | WQ-03 | in_progress | +| REQ-003 | Qualify #351/#354 and implement #352–353 | WQ-03 | done | | REQ-004 | Review #346–350 and qualify #355 | WQ-04 | done | | REQ-005 | Document contribution rules and conditional release credit | WQ-02, WQ-05 | done | | REQ-006 | Deliver and reconcile 0.16.1 | WQ-06 | pending | +| REQ-007 | Retain proven technical literals during publication and increase default test coverage (#358) | WQ-07 | in_progress | ### Explicit Non-Goals @@ -68,10 +69,11 @@ At b93ec7d the three changed files cover local opt-in qualification, its tests a | --- | --- | --- | --- | | WQ-01 | Inventory submissions, review immutable diff, logs, token permissions, artifacts, CI triggers and settings. Record limits below. | REQ-001 | done | | WQ-02 | Target the maintainer bootstrap and external PR at protected dev; promote reviewed dev to main. Restrict both publishing environments to branch main only and verify the external Trusted Publishers. Scope site dispatch credentials to the trusted main workflow/environment. Configure approval for all outside collaborators. Set up native GitHub protections and required Build/CodeQL checks on dev. At merge the maintainer verifies external PRs target dev and main receives repository-owned promotions and release PRs. Account explicitly for maintenance bots and bootstrap. Verify the intended review and retargeting paths before retargeting #354. Synchronize contribution guide and template with rollout. | REQ-002, REQ-005 | in_progress | -| WQ-03 | Retarget and review #354 at the new merge base, retain author credit, replace premature issue closing keywords, address diagnostic bounds. #352 uses closed per-group reason counts with overlapping reasons and no paths/arguments. #353 extends file-level reuse to unchanged non-Python blobs and replays bounded deterministic searches on immutable inputs; qualify only complete equivalent observations including dependencies, result order, truncation and failures. Recheck uncertain groups. | REQ-003 | in_progress | +| WQ-03 | Retarget and review #354 at the new merge base, retain author credit, replace premature issue closing keywords, address diagnostic bounds. #352 uses closed per-group reason counts with overlapping reasons and no paths/arguments. #353 extends file-level reuse to unchanged non-Python blobs and replays bounded deterministic searches on immutable inputs; qualify only complete equivalent observations including dependencies, result order, truncation and failures. Recheck uncertain groups. | REQ-003 | done | | WQ-04 | Integrate development tooling #346, certifi #347, regex #348, httpx2 #349 and six action updates #350. Check upstream commit identities, permissions, cache defaults and artifact changes before updating action pins. Reconcile overlapping lock changes and test the combined tree. For #355 inspect upstream gitignore/preview semantics, verify exact assets, Linux and applicable native handoffs and consumer behavior before promotion to OCR 1.14.6. | REQ-004 | done | | WQ-05 | Add conditional Towncrier Contributors category, maintainer-reviewed public handle and accepted PR link once per contributor. Verify populated and empty releases, canonical changelog section and final comparison link. | REQ-005 | done | | WQ-06 | After the bootstrap draft and maintainer approval, merge the protected promotion, verify TestPyPI on the resulting push to main, then prepare the signed release/v0.16.1 PR and reconcile published artifacts. | REQ-006 | pending | +| WQ-07 | Qualify publication-only DLP handling for date ranges, dated headings and size assignments, retain phone and credential rejection, and integrate #359 through the twelve protected checks. | REQ-007 | in_progress | ### Locked Decisions @@ -121,15 +123,17 @@ Protect dev before admitting any external code. A PR from dev in the same reposi ### Resume Point -All three environments now select only the main branch. Both ref rulesets have twelve strict required checks, and outside collaborators require workflow approval. PR #357 is ready. Finish the site credential migration, remove its repository-level copy, create dev at current main and retarget #357 and #354. Verify fresh checks against dev and the reviewed base CI before approving fork execution. Two local signed promotion and synchronization cycles preserved ancestry and isolated the second change. +The maintainer bootstrap merged into protected `dev` in #357. All three environments select only `main`. The site dispatch credential is environment-scoped and the repository Actions secret list is empty. The fork workflow approval policy covers all external contributors. All twelve required checks passed on #354 at `75bedaf` against `ef5f376`. GitHub attributed its verified squash commit `feafbf7` to @ahmedpdf445-stack. + +#359 brings #358 and its default-running regression tests to that base. Complete all twelve required checks for its reviewed head, merge it into `dev`, and verify the resulting tree. Stop at that commit for the maintainer's explicit release-process authorization before promoting to `main`. Keep the milestone and issues open until the release receipt is verified. ### Plan Fidelity Check -REQ-001–006 cover the selected inputs, full release scope, public contributor guidance, CI isolation, verification and attribution. Queue items identify owners and acceptance evidence at each boundary. +REQ-001–007 cover the selected inputs, full release scope, public contributor guidance, CI isolation, verification and attribution. Queue items identify owners and acceptance evidence at each boundary. ### Reconciliation Check -The hosted settings above describe the observed pre-rollout state. Contributor instructions switch their target when dev admission is operational. No release authorization or external delivery has occurred. +The hosted settings above describe the observed pre-rollout state. The current intake target is protected `dev`. No release authorization or external delivery has occurred. ### Closure Gate diff --git a/changelog.d/354.contributor.md b/changelog.d/354.contributor.md new file mode 100644 index 00000000..097e8e05 --- /dev/null +++ b/changelog.d/354.contributor.md @@ -0,0 +1 @@ +Thanks to @ahmedpdf445-stack for fixing incremental local review when Git editor settings are present. diff --git a/changelog.d/358.bugfix.md b/changelog.d/358.bugfix.md new file mode 100644 index 00000000..978cceb9 --- /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 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 ec8a1128..a3844c3b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -475,7 +475,24 @@ 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. 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. 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; 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..9bdf4df7 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 ( @@ -239,14 +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. - 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 + hidden = ( + (*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), publication=publication) + ) or any( + _contains_phone(phone_markup_view(_literal_normalize(fragment)), publication=publication) + for fragment in hidden ) @@ -409,6 +419,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 +447,12 @@ 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, 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. @@ -444,6 +464,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 @@ -456,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 new file mode 100644 index 00000000..4bdf3dd8 --- /dev/null +++ b/src/ocr_toolkit/context/dlp/arithmetic.py @@ -0,0 +1,59 @@ +"""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.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}" +_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 + # 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) + 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..e25cbc5a 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 @@ -122,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( @@ -132,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) ) @@ -220,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) @@ -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 (publication and 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_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_arithmetic.py b/tests/test_dlp_arithmetic.py new file mode 100644 index 00000000..59a552c9 --- /dev/null +++ b/tests/test_dlp_arithmetic.py @@ -0,0 +1,145 @@ +"""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") + + +@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" + 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..704da4c2 --- /dev/null +++ b/tests/test_dlp_date_ranges.py @@ -0,0 +1,136 @@ +"""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", "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", + ( + "[§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_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 "