diff --git a/loopx/presentation/public_safety.py b/loopx/presentation/public_safety.py index 0e3a6e9d5b..fd974f1a4b 100644 --- a/loopx/presentation/public_safety.py +++ b/loopx/presentation/public_safety.py @@ -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} diff --git a/loopx/public_safe_text.py b/loopx/public_safe_text.py index 2ac49459f1..390a0ad1e3 100644 --- a/loopx/public_safe_text.py +++ b/loopx/public_safe_text.py @@ -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"(?]+:[^/\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]], ... ] = ( @@ -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 diff --git a/tests/control_plane/test_presentation_credential_value_boundary.py b/tests/control_plane/test_presentation_credential_value_boundary.py new file mode 100644 index 0000000000..04e5c67857 --- /dev/null +++ b/tests/control_plane/test_presentation_credential_value_boundary.py @@ -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 ", + "https://example.com/a", + "

Password:

Sign in with the password you use for your email.

", + "

Token:

Ask your administrator to issue a token for this device.

", + "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= 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" + ) diff --git a/tests/test_static_site_presentation.py b/tests/test_static_site_presentation.py index b04014725e..3a682f7a68 100644 --- a/tests/test_static_site_presentation.py +++ b/tests/test_static_site_presentation.py @@ -353,3 +353,207 @@ def test_cli_package_preview_is_read_only_and_exposes_publisher_as_first_class_p assert payload["dry_run"] is True assert payload["publisher"]["kind"] == "github-pages" assert output.exists() is False + + +def _cli_package(site: Path, output: Path, state: Path) -> int: + return main( + [ + "--format", + "json", + "presentation", + "package", + "--site-dir", + str(site), + "--output-dir", + str(output), + "--state-dir", + str(state), + "--site-id", + "cli-demo", + "--publisher", + "local", + "--desktop-visual-check", + "passed", + "--mobile-visual-check", + "passed", + "--link-check", + "passed", + "--execute", + ] + ) + + +def test_cli_package_keeps_a_css_design_token_public( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + stylesheet = ( + ":root { --color-token: #3b82f6; --space-md: 16px; }\n" + "body { color: var(--color-token); }\n" + ) + site = _site(tmp_path) + (site / "styles.css").write_text(stylesheet, encoding="utf-8") + output = tmp_path / "publish" + + assert _cli_package(site, output, tmp_path / "state") == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["write_performed"] is True + assert (output / "styles.css").read_text(encoding="utf-8") == stylesheet + + +def test_cli_package_keeps_login_help_headings_public( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + site = _site(tmp_path) + help_page = ( + "

Account help

\n" + "

Password:

Sign in with the password you use for email.

\n" + "\n" + ) + token_page = ( + "

Device setup

\n" + "

Token:

Ask your administrator to issue a token for this device.

\n" + "\n" + ) + (site / "help.html").write_text(help_page, encoding="utf-8") + (site / "token-help.html").write_text(token_page, encoding="utf-8") + output = tmp_path / "publish" + + assert _cli_package(site, output, tmp_path / "state") == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["write_performed"] is True + assert (output / "help.html").read_text(encoding="utf-8") == help_page + assert (output / "token-help.html").read_text(encoding="utf-8") == token_page + + +def test_cli_package_keeps_numeric_account_rules_public( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + site = _site(tmp_path) + password_page = ( + "

Password requirements

\n" + "

Password: 12 characters minimum.

\n" + "\n" + ) + token_page = ( + "

Token lifetime

\n" + "

Token: 24 hours.

\n" + "\n" + ) + (site / "password-length.html").write_text(password_page, encoding="utf-8") + (site / "token-expiry.html").write_text(token_page, encoding="utf-8") + password_range = ( + "

Password requirements

\n" + "

Password: 8 to 64 characters.

\n" + "\n" + ) + token_business_days = ( + "

Token lifetime

\n" + "

Token: 2 business days.

\n" + "\n" + ) + (site / "password-range.html").write_text(password_range, encoding="utf-8") + (site / "token-business-days.html").write_text(token_business_days, encoding="utf-8") + output = tmp_path / "publish" + + assert _cli_package(site, output, tmp_path / "state") == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["write_performed"] is True + assert (output / "password-length.html").read_text(encoding="utf-8") == password_page + assert (output / "token-expiry.html").read_text(encoding="utf-8") == token_page + assert (output / "password-range.html").read_text(encoding="utf-8") == password_range + assert (output / "token-business-days.html").read_text(encoding="utf-8") == token_business_days + + +def test_cli_package_keeps_character_class_rules_public( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + site = _site(tmp_path) + alphanumeric_page = ( + "

Password requirements

\n" + "

Password: 12 alphanumeric characters.

\n" + "\n" + ) + ascii_page = ( + "

Password requirements

\n" + "

Password: 8 to 64 ASCII characters.

\n" + "\n" + ) + composition_page = ( + "

Password composition

\n" + "

Password: 1 uppercase, 1 lowercase, and 1 number.

\n" + "\n" + ) + code_points_page = ( + "

Password length

\n" + "

Password: 12 Unicode code points.

\n" + "\n" + ) + (site / "password-alphanumeric.html").write_text(alphanumeric_page, encoding="utf-8") + (site / "password-ascii.html").write_text(ascii_page, encoding="utf-8") + (site / "password-composition.html").write_text(composition_page, encoding="utf-8") + (site / "password-code-points.html").write_text(code_points_page, encoding="utf-8") + output = tmp_path / "publish" + + assert _cli_package(site, output, tmp_path / "state") == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["write_performed"] is True + assert (output / "password-alphanumeric.html").read_text(encoding="utf-8") == alphanumeric_page + assert (output / "password-ascii.html").read_text(encoding="utf-8") == ascii_page + assert (output / "password-composition.html").read_text(encoding="utf-8") == composition_page + assert (output / "password-code-points.html").read_text(encoding="utf-8") == code_points_page + + +def test_cli_package_keeps_quoted_button_labels_public( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + site = _site(tmp_path) + forgot_page = ( + "

Sign in help

\n" + '

Password: "Forgot password?" is the link to use.

\n' + "\n" + ) + copy_page = ( + "

Device setup

\n" + '

Token: "Copy token" is the button to use.

\n' + "\n" + ) + continue_page = ( + "

Device setup

\n" + '

Password: "Continue!" is the button to use.

\n' + "\n" + ) + (site / "forgot-password.html").write_text(forgot_page, encoding="utf-8") + (site / "copy-token.html").write_text(copy_page, encoding="utf-8") + (site / "continue-button.html").write_text(continue_page, encoding="utf-8") + output = tmp_path / "publish" + + assert _cli_package(site, output, tmp_path / "state") == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["write_performed"] is True + assert (output / "forgot-password.html").read_text(encoding="utf-8") == forgot_page + assert (output / "copy-token.html").read_text(encoding="utf-8") == copy_page + assert (output / "continue-button.html").read_text(encoding="utf-8") == continue_page + + +def test_cli_package_still_rejects_a_credential_value_in_an_asset( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + site = _site(tmp_path) + (site / "styles.css").write_text( + ":root { --color-token: #3b82f6; }\n" + "/* token=abc123 */\n", + encoding="utf-8", + ) + output = tmp_path / "publish" + + assert _cli_package(site, output, tmp_path / "state") == 2 + payload = json.loads(capsys.readouterr().out) + assert payload["ok"] is False + assert "credential value" in payload["error"] + assert not output.exists()