Skip to content
Closed
14 changes: 9 additions & 5 deletions loopx/presentation/public_safety.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,15 @@ def scan_public_boundary_text(text: str) -> dict[str, object]:
Returns ``{"ok": bool, "warnings": [label, ...]}``. The scanner is the
canonical public/private boundary check for generated presentation text;
the static-site exporter and the session dash generator share it.
Duplicate labels are collapsed because one value can satisfy overlapping
credential shapes.
"""

warnings = [
label
for label, pattern in PUBLIC_BOUNDARY_PATTERNS
if pattern.search(text)
]
warnings = list(
dict.fromkeys(
label
for label, pattern in PUBLIC_BOUNDARY_PATTERNS
if pattern.search(text)
)
)
return {"ok": not warnings, "warnings": warnings}
127 changes: 126 additions & 1 deletion loopx/public_safe_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,94 @@ def _mask(match: re.Match[str]) -> str:
r"\bpypi-[a-z0-9_-]{20,}|"
r"\beyj[a-z0-9_-]{10,}\.[a-z0-9_-]{10,}\.[a-z0-9_-]{10,}\b"
)
# Presentation packages whole public assets -- stylesheets, rendered pages,
# CLI help -- rather than one operational field. There a hyphen joins one
# identifier, so a design token such as `--color-token`, or a flag such as
# `--client-secret`, is a compound name and not a label beside an operator.
# `\b` alone fires after that hyphen, so the classifier's assignment arms read
# the suffix as a short credential and a valid site stopped packaging.
#
# A colon is also how an ordinary help page introduces a field, `Password:` or
# `Token:` followed by an explanatory sentence. Presentation therefore accepts
# `=` as an assignment without a shape check (a help heading does not spell
# `Password =`) but asks for value evidence after a colon: a quoted value, a
# token carrying a digit or base64 character, or a letter-only run long enough
# to be opaque. That keeps `password=hunter2`, `{"token": "abc123"}` and
# `secret: hunter2` while releasing `Password: sign in with the account you
# use for email`.
# The presentation policy asks these label sets at a token start; the
# free-standing `\b` form stays the classifier contract, and a field-name
# compound remains the owner's separate opt-in arm (Refs #5136).
_PRESENTATION_LABEL_TOKEN_START = r"(?<![A-Za-z0-9_-])"
_PRESENTATION_KEY_LABELS_SOURCE = (
r"(?:(?:aws[_-]?)?secret[_-]?access[_-]?key|secret[_-]?key|access[_-]?key)"
)
# Account help often states a rule as `Password: 12 characters` or
# `Token: 24 hours`. A bare number after a label is not by itself a secret;
# when it is a quantity with a length or time unit it is a public rule. The
# negative lookahead also covers word ranges (`8 to 64 characters`),
# qualified units (`2 business days`), character classes (`12 alphanumeric
# characters`), counted composition rules (`1 uppercase, 1 lowercase, and
# 1 number`) and encoded-length units (`12 Unicode code points`) while a bare
# number (`Password: 12345678`) and a mixed value (`token: abc123`) still fail
# closed.
_PRESENTATION_RULE_QUANTITY_SOURCE = (
r"(?![\"']?\d+(?:\.\d+)?"
r"(?:\s*[-\u2013\u2014]\s*\d+|\s+(?:to|through|and)\s+\d+|\+)?"
r"(?:\s+or\s+(?:more|fewer|less))?"
r"\s*[-\u2013\u2014]?\s*"
r"(?:[A-Za-z][A-Za-z-]*[-\s]+){0,2}"
r"(?:characters?|chars?|letters?|digits?|numbers?|symbols?"
r"|uppercase|lowercase"
r"|code[-\s]?points?|code[-\s]?units?"
r"|(?:utf-?8|utf-?16|utf-?32)\s+(?:code[-\s]?units?|bytes?)"
r"|bytes?"
r"|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s"
r"|days?|workdays?|d|weeks?|months?|years?)\b)"
)
_PRESENTATION_COLON_VALUE_SOURCE = (
_PRESENTATION_RULE_QUANTITY_SOURCE
+ r"(?:"
# A quoted value needs a single credential-shaped token: a digit or
# base64/symbol character, or a long opaque letters-only run. A quoted
# interface label (`"Forgot password?"`, `"Copy token"`) has spaces or
# ordinary Title Case words and stays public help.
r"[\"']"
+ _SHAPE_VALUE_TOKEN_SOURCE
+ r"[\"']|"
r"[\"'][A-Za-z]{16,}[\"']|"
+ _SHAPE_VALUE_TOKEN_SOURCE
+ r"|"
+ _OPAQUE_VALUE_RUN_SOURCE
+ r")"
)
PRESENTATION_CREDENTIAL_VALUE_PATTERN_SOURCE = (
r"\bbearer\s+[a-z0-9._~+/=-]{16,}|"
r"\b[a-z][a-z0-9+.-]*://[^/\s:@`'\"<>]+:[^/\s@`'\"<>]+@[^\s`'\"<>]*|"
+ _PRESENTATION_LABEL_TOKEN_START
+ _PRESENTATION_KEY_LABELS_SOURCE
+ r"[\"']?\s*=\s*"
r"[\"']?[^\s`'\"<>]+|"
+ _PRESENTATION_LABEL_TOKEN_START
+ _PRESENTATION_KEY_LABELS_SOURCE
+ r"[\"']?\s*:\s*"
+ _PRESENTATION_COLON_VALUE_SOURCE
+ r"|"
+ _PRESENTATION_LABEL_TOKEN_START
+ CREDENTIAL_LABEL_PATTERN_SOURCE
+ r"[\"']?\s*=\s*"
r"[\"']?[^\s`'\"<>]+|"
+ _PRESENTATION_LABEL_TOKEN_START
+ CREDENTIAL_LABEL_PATTERN_SOURCE
+ r"[\"']?\s*:\s*"
+ _PRESENTATION_COLON_VALUE_SOURCE
+ r"|"
+ _PRESENTATION_LABEL_TOKEN_START
+ r"refresh[_-]?token[\"']?\s*=\s*[\"']?[^\s`'\"<>]{12,}|"
+ _PRESENTATION_LABEL_TOKEN_START
+ r"refresh[_-]?token[\"']?\s*:\s*"
+ _PRESENTATION_COLON_VALUE_SOURCE
)
PRESENTATION_PUBLIC_BOUNDARY_PATTERNS: tuple[
tuple[str, re.Pattern[str]], ...
] = (
Expand Down Expand Up @@ -399,11 +487,48 @@ def _mask(match: re.Match[str]) -> str:
# An issuer prefix is its own label: a token carried in tool output or a
# pasted log rarely arrives as an assignment, so the assignment arm never
# sees it. Composed from the shared source the sibling scanners consume
# (#7636), case-folded like the presentation local-path arms.
# (#7636), case-folded like the presentation local-path arms. It stays ahead
# of the value arm so an issuer-prefixed token keeps its specific warning.
(
"provider token",
re.compile(r"(?i)(?:" + PROVIDER_TOKEN_SHAPE_PATTERN_SOURCE + r")"),
),
# A value-bearing credential is its own label. The assignment arm above only
# sees three key names; a dash page, a manager detail return or a peer
# conclusion can carry an Authorization Bearer/Basic header, a
# password/secret assignment, a URL with embedded userinfo, or a
# refresh/bare token instead.
# Those shapes were already known to the owning classifier
# (`SECRET_LIKE_SURFACE_PATTERN`); the presentation policy simply never
# consulted them, so it certified the raw values as public-safe. The
# presentation composition keeps that owner's value arms and asks the label
# arms at a token start, so a hyphenated design-token name is not read as a
# short assignment, while `password=hunter2` still needs no length floor.
(
"credential value",
re.compile(
r"(?i)(?:" + PRESENTATION_CREDENTIAL_VALUE_PATTERN_SOURCE + r")"
),
),
# Connector and quoted spellings are already owned by the text classifier;
# the presentation policy now consults those same shapes instead of releasing
# "password is hunter2hunter2" or `client secret is "abcd1234"` as prose. They
# share the "credential value" label; the scanner collapses duplicate labels.
(
"credential value",
CONNECTED_CREDENTIAL_VALUE_SHAPE_PATTERN,
),
(
"credential value",
QUOTED_CREDENTIAL_VALUE_SHAPE_PATTERN,
),
# The authorization header has a second standard scheme. `_BASIC_CREDENTIAL_VALUE`
# already owns that shape for the text classifier, so the presentation policy
# consults the same owner instead of restating a base64 shape here.
(
"basic-auth credential value",
_BASIC_CREDENTIAL_VALUE,
),
)
# Refs #5136: one definition for "this string carries a raw remote location".
# Three validators each restated the same scheme list, and the canonical
Expand Down
198 changes: 198 additions & 0 deletions tests/control_plane/test_presentation_credential_value_boundary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""The presentation boundary rejects raw credential values, not just key labels.

`scan_public_boundary_text` is the single gate used by the session dash, the
`loopx dash` HTML path, manager-channel detail returns and non-private peer
result publication. It carried labeled assignments for three key names and
issuer-prefixed provider tokens, but a live value could still arrive as an
`Authorization: Bearer` header, a password/secret assignment, a URL with
embedded userinfo, or a refresh/bare token. The owning classifier already named
those shapes as `credential`; the presentation policy now consumes the same
source, so the same bytes cannot be private to the owner and public here.
"""

from __future__ import annotations

import pytest

from loopx.chat.manager_details import _text as manager_text
from loopx.presentation import public_safety
from loopx.public_safe_text import classify_private_text


CREDENTIAL_VALUES = {
"authorization bearer header": (
"GET /v1/items\nAuthorization: Bearer 8f3a1c9e7b2d4f6a0c5e8b1d3f7a9c2e\n"
),
"password assignment": 'service password = "correct-horse-battery-staple"\n',
"secret access key assignment": (
"secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n"
),
"url userinfo": "https://deploy:sup3rsecret@internal.example.com/repo\n",
"refresh token assignment": "refresh_token=abcdefghijklmnop\n",
"bare token assignment": "token=abcdefghijklmnop\n",
}


@pytest.mark.parametrize("value", CREDENTIAL_VALUES.values(), ids=CREDENTIAL_VALUES.keys())
def test_a_raw_credential_value_fails_the_presentation_boundary(value: str) -> None:
assert public_safety.scan_public_boundary_text(value) == {
"ok": False,
"warnings": ["credential value"],
}
match = classify_private_text(value)
assert match is not None
assert match.category == "credential"


@pytest.mark.parametrize(
"text",
[
"Send a Bearer token in the Authorization header; never paste the value.",
"The password rotation policy applies to every service account.",
"Authorization: Bearer <redacted>",
"https://example.com/a",
"<h2>Password:</h2><p>Sign in with the password you use for your email.</p>",
"<h2>Token:</h2><p>Ask your administrator to issue a token for this device.</p>",
"Password: sign in with the account you use for email.\n",
"Token: contact your administrator for a new token.\n",
"Password: 12 characters minimum.\n",
"Password: 8+ characters\n",
"Password: 8 to 64 characters.\n",
"Password: 12 alphanumeric characters.\n",
"Password: 8 to 64 ASCII characters.\n",
"Password: 1 uppercase, 1 lowercase, and 1 number.\n",
"Password: 12 Unicode code points.\n",
"Password: 32 UTF-8 bytes.\n",
"Password: \"Forgot password?\" is the link to use.\n",
"Password: \"Continue!\" is the button to use.\n",
"Token: \"Copy token\" is the button to use.\n",
"Token: 24 hours.\n",
"Token: 24-hour expiry\n",
"Token: 2 business days.\n",
],
ids=(
"bearer prose",
"password prose",
"redacted bearer",
"plain url",
"password heading",
"token heading",
"password sentence",
"token sentence",
"password length rule",
"password length plus",
"password length range",
"password alphanumeric rule",
"password ascii range rule",
"password composition rule",
"password unicode code points rule",
"password utf8 bytes rule",
"forgot password button",
"punctuated action button",
"copy token button",
"token expiry rule",
"token expiry hyphen",
"token business days",
),
)
def test_credential_prose_stays_public(text: str) -> None:
assert public_safety.scan_public_boundary_text(text) == {
"ok": True,
"warnings": [],
}


SHORT_ASSIGNMENT_VALUES = [
"password=hunter2",
"token=abc123",
"secret: hunter2",
"token: abc123def456ghi",
"Password: 12345678",
'{"password": "hunter2"}',
'{"token": "abc123"}',
'{"secret": "abcd1234"}',
'Password: "hunter2"',
"refresh_token: abcdefghijklmnop",
]


@pytest.mark.parametrize("value", SHORT_ASSIGNMENT_VALUES)
def test_short_and_json_key_assignments_fail_the_boundary(value: str) -> None:
assert public_safety.scan_public_boundary_text(value) == {
"ok": False,
"warnings": ["credential value"],
}
match = classify_private_text(value)
assert match is not None
assert match.category == "credential"


def test_connector_and_quoted_credential_values_fail_the_boundary() -> None:
for value in (
"password is hunter2hunter2",
'client secret is "abcd1234"',
):
assert public_safety.scan_public_boundary_text(value) == {
"ok": False,
"warnings": ["credential value"],
}
match = classify_private_text(value)
assert match is not None
assert match.category == "credential"


@pytest.mark.parametrize(
"value",
[
":root { --color-token: #3b82f6; --space-md: 16px; }\n",
":root{--color-token:#3b82f6;--space-md:16px}\n",
":root { --color-token: var(--palette-blue-500); }\n",
"body { color: var(--color-token); }\n",
"Pass --client-secret=<value> to configure the connector.\n",
"Pass --access-key=EXAMPLEKEYVALUE to configure the provider.\n",
],
ids=("css token", "minified css", "css var value", "css var use", "flag secret", "flag access key"),
)
def test_hyphenated_design_names_are_not_credential_assignments(value: str) -> None:
# A hyphen joins one identifier in a stylesheet or CLI help. The suffix
# (`--color-token`) is a name, not a credential label beside an operator.
assert public_safety.scan_public_boundary_text(value) == {
"ok": True,
"warnings": [],
}


def test_basic_authorization_header_uses_the_owner_shape() -> None:
value = "GET /v1/items\nAuthorization: Basic dXNlcjpwYXNzd29yZA==\n"

assert public_safety.scan_public_boundary_text(value) == {
"ok": False,
"warnings": ["basic-auth credential value"],
}
match = classify_private_text(value)
assert match is not None
assert match.category == "credential"


def test_existing_labels_keep_one_warning_per_value() -> None:
token = "ghp_" + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4"

# The provider and labeled-assignment arms still own their warnings; the
# shared value source must not add a second label for the same bytes.
assert public_safety.scan_public_boundary_text(token) == {
"ok": False,
"warnings": ["provider token"],
}
assert public_safety.scan_public_boundary_text(f"deploy used access_token={token}") == {
"ok": False,
"warnings": ["credential assignment", "provider token"],
}


def test_manager_detail_return_omits_a_raw_bearer_value() -> None:
text = "next step: call the endpoint with Authorization: Bearer " + "8f3a" * 8

assert manager_text(text) == "[sensitive text omitted]"
assert manager_text("next step: rotate the expired Bearer credential") == (
"next step: rotate the expired Bearer credential"
)
Loading
Loading