Skip to content
14 changes: 9 additions & 5 deletions PLANS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions changelog.d/354.contributor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Thanks to @ahmedpdf445-stack for fixing incremental local review when Git editor settings are present.
1 change: 1 addition & 0 deletions changelog.d/358.bugfix.md
Original file line number Diff line number Diff line change
@@ -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.
19 changes: 18 additions & 1 deletion docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
35 changes: 29 additions & 6 deletions src/ocr_toolkit/context/dlp/admission.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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
)


Expand Down Expand Up @@ -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),
Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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)
Expand Down
59 changes: 59 additions & 0 deletions src/ocr_toolkit/context/dlp/arithmetic.py
Original file line number Diff line number Diff line change
@@ -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<expression>{_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)
77 changes: 76 additions & 1 deletion src/ocr_toolkit/context/dlp/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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<first>{_ISO_DAY})[ \t]{{0,16}}(?:\.\.\.?|\u2026|\u2013)[ \t]{{0,16}}"
rf"(?P<last>{_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<day>{CALENDAR_DAY_PATTERN})(?:T|[ \t]+)"
r"(?P<clock>\d{2}:\d{2}(?::\d{2}(?:[.,]\d{1,9})?)?)"
Expand All @@ -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."""

Expand Down
Loading