Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 63 additions & 7 deletions loopx/presentation/static_site.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import codecs
import hashlib
import json
import os
Expand All @@ -14,6 +15,7 @@
from urllib.parse import quote, urljoin, urlparse
from urllib.request import urlopen

from ..capabilities.public_safe_outbound.scan_cli import BINARY_SUFFIXES
from ..control_plane.content_digest import BARE_SHA256_PATTERN
from .public_safety import (
PUBLIC_BOUNDARY_PATTERNS,
Expand All @@ -33,10 +35,43 @@
REVISION_DIR = "revisions"

_SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
_TEXT_SUFFIXES = {".css", ".html", ".js", ".json", ".md", ".svg", ".txt", ".xml"}
_PUBLIC_BOUNDARY_PATTERNS = PUBLIC_BOUNDARY_PATTERNS
_RESERVED_TOP_LEVEL = {MANIFEST_FILE, RECEIPT_FILE, REVISION_FILE, REVISION_DIR}

# Windows PowerShell 5.1 writes a `>` or `Out-File` capture as UTF-16LE with a
# BOM; reading those bytes as UTF-8 turns every character into NUL-interleaved
# mojibake that no boundary pattern can match. UTF-32 is checked before UTF-16
# because BOM_UTF32_LE starts with BOM_UTF16_LE.
_BOM_CODECS = (
(codecs.BOM_UTF32_LE, "utf-32"),
(codecs.BOM_UTF32_BE, "utf-32"),
(codecs.BOM_UTF8, "utf-8-sig"),
(codecs.BOM_UTF16_LE, "utf-16"),
(codecs.BOM_UTF16_BE, "utf-16"),
)

# The outbound scanner's deny-list is conservative for a tree walk and classifies
# these two JSON text formats as binary. A site bundle can copy them, and a
# source map can carry local source paths, so they stay reviewable here.
_TEXT_SUFFIXES_IN_BINARY_DENYLIST = frozenset({".map", ".tsbuildinfo"})

# Containers a browser decodes that the outbound tree deny-list does not name yet.
# That list answers "does a repository hold text a person wrote", not "can a
# browser load these bytes", so the publisher keeps its own media boundary instead
# of inheriting one: a suffix listed here is copied verbatim, and every asset not
# listed must still be reviewable text. `.avif` and `.apng` are verified against
# real encoder output; the rest are opaque audio/video/image containers of the same
# class. Subtitle and playlist formats (`.vtt`, `.m3u8`, `.mpd`) are text and
# deliberately stay outside, as does a further browser container until it is added
# here rather than to the repo scan's deny-list.
_STATIC_MEDIA_SUFFIXES = frozenset({
".apng", ".avif", ".avifs", ".heic", ".heif", ".jxl", # images
".m4v", ".ogv", ".opus", # audio and video
})
_BINARY_ASSET_SUFFIXES = (
BINARY_SUFFIXES - _TEXT_SUFFIXES_IN_BINARY_DENYLIST
) | _STATIC_MEDIA_SUFFIXES


class StaticSiteContractError(ValueError):
"""Raised when a static presentation input violates the publish contract."""
Expand Down Expand Up @@ -74,12 +109,33 @@ def _paths_overlap(left: Path, right: Path) -> bool:
)


def _scan_public_text(path: Path, relative_path: str) -> None:
if path.suffix.lower() not in _TEXT_SUFFIXES:
def _scan_public_text(path: Path, relative_path: str, content: bytes) -> None:
# A filename allow-list certified every text asset outside it (`.env`,
# `Dockerfile`, `.csv` data) without reading a byte. Excluding only the
# true binary formats leaves every other copied asset as reviewable text.
if path.suffix.lower() in _BINARY_ASSET_SUFFIXES:
Comment thread
JasonBuildAI marked this conversation as resolved.
Resolved
return
# A size exemption would certify the unscanned tail as public-safe; the caller
# already reads the whole file for its digest, so scan every text byte copied.
text = path.read_text(encoding="utf-8", errors="replace")
for bom, encoding in _BOM_CODECS:
if content.startswith(bom):
break
else:
encoding = "utf-8"
# A size exemption would certify an unscanned tail as public-safe, so scan
# every byte of the text the caller already read for this asset's digest.
# Replacement decoding would review a mangled copy while certifying the
# original, so undecodable bytes fail publication instead.
try:
text = content.decode(encoding)
except UnicodeDecodeError as exc:
raise StaticSiteContractError(
f"public boundary scan failed for {relative_path}: content is not decodable as {encoding}"
) from exc
if "\x00" in text:
# A BOM-less UTF-16 capture and a mislabelled binary asset both land
# here; neither is text this boundary can review, so neither is certified.
raise StaticSiteContractError(
f"public boundary scan failed for {relative_path}: content is not reviewable text"
)
for label, pattern in _PUBLIC_BOUNDARY_PATTERNS:
if pattern.search(text):
raise StaticSiteContractError(
Expand Down Expand Up @@ -108,8 +164,8 @@ def _collect_site_files(site_dir: Path, *, entry_path: str) -> list[dict[str, ob
raise StaticSiteContractError(
f"site bundle uses reserved path: {relative_path}"
)
_scan_public_text(path, relative_path)
content = path.read_bytes()
_scan_public_text(path, relative_path, content)
files.append(
{
"path": relative_path,
Expand Down
222 changes: 222 additions & 0 deletions tests/test_static_site_presentation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import base64
import hashlib
import json
from pathlib import Path
Expand All @@ -20,6 +21,37 @@
verify_static_site_readback,
)

# A real 16x16 AVIF written by Pillow's libavif encoder and read back at that size,
# so the media-compatibility case exercises bytes a browser decodes rather than a
# synthetic payload under a media suffix.
_AVIF_16X16 = base64.b64decode(
"AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADrbWV0YQAAAAAAAAAhaGRscgAA"
"AAAAAAAAcGljdAAAAAAAAAAAAAAAAAAAAAAOcGl0bQAAAAAAAQAAAB5pbG9jAAAAAEQAAAEAAQ"
"AAAAEAAAETAAAAOAAAAChpaW5mAAAAAAABAAAAGmluZmUCAAAAAAEAAGF2MDFDb2xvcgAAAABq"
"aXBycAAAAEtpcGNvAAAAFGlzcGUAAAAAAAAAEAAAABAAAAAQcGl4aQAAAAADCAgIAAAADGF2MU"
"OBAAwAAAAAE2NvbHJuY2x4AAEADQAGgAAAABdpcG1hAAAAAAAAAAEAAQQBAoMEAAAAQG1kYXQS"
"AAoJGAz/2iAhoNCAMikXh4eGIYSSSSZQAAAAOtUs5tqInBL0Pog/t6d/UvOhu9plDueWx8dawA=="
)


# A real 16x16 two-frame APNG written by Pillow and read back as two frames, so the
# animation container is exercised at its own `.apng` suffix rather than as a
# renamed still image.
_APNG_16X16 = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACGFjVEwAAAACAAAAAPON"
"k3AAAAAaZmNUTAAAAAAAAAAQAAAAEAAAAAAAAAAAAAEACgAAY0bPJQAAACNJREFUeJxj"
"PCEnx0AKYCJJNcOoBuIAE5Hq4GBUAzGA5FACAE8fASTP+Ap+AAAAGmZjVEwAAAABAAAA"
"EAAAABAAAAAAAAAAAAABAAoAAPg1JfEAAAAnZmRBVAAAAAJ4nGOUkzvBQApgIkk1w6gG"
"4gATkergYFQDMYDkUAIATcsBJE6yAzwAAAAASUVORK5CYII="
)

# The media containers that must survive the text scan. Each entry is real encoder
# output, which is why the parametrised cases cannot pass on synthetic bytes.
_REAL_MEDIA_ASSETS = (
pytest.param("assets/hero.avif", _AVIF_16X16, id="avif"),
pytest.param("assets/spinner.apng", _APNG_16X16, id="apng"),
)


def test_utc_timestamp_uses_the_legacy_compatible_timezone_alias() -> None:
timestamp = _utc_now()
Expand Down Expand Up @@ -242,6 +274,143 @@ def test_package_scans_large_text_assets_before_certifying_them_public_safe(
assert not destination.exists()


@pytest.mark.parametrize(
("asset", "payload"),
[
("data.csv", "name,value\napi,{token}\n"),
("assets/export.csv", "name,value\napi,{token}\n"),
("build.log", "export GITHUB_TOKEN={token}\n"),
("config.yaml", "token: {token}\n"),
(".env", "OPENAI_API_KEY={token}\n"),
("Dockerfile", "ENV GITHUB_TOKEN={token}\n"),
("app.js.map", '{"sourcesContent": ["const token = \\"{token}\\";"]}'),
("tsconfig.tsbuildinfo", '{"token": "{token}"}'),
],
)
def test_package_scans_text_assets_outside_the_former_suffix_allow_list(
tmp_path: Path, asset: str, payload: str
) -> None:
site = _site(tmp_path)
token = "ghp_" + "a" * 36
(site / asset).write_text(payload.replace("{token}", token), encoding="utf-8")
destination = tmp_path / "publish"

with pytest.raises(StaticSiteContractError, match="public boundary scan failed"):
_package(site, destination, tmp_path / "state")
assert not destination.exists()


def test_package_scans_a_bom_marked_utf16_capture_before_publication(
tmp_path: Path,
) -> None:
site = _site(tmp_path)
token = "ghp_" + "a" * 36
(site / "capture.txt").write_text(
"GITHUB_TOKEN=" + token + "\n", encoding="utf-16"
)
destination = tmp_path / "publish"

with pytest.raises(StaticSiteContractError, match="public boundary scan failed"):
_package(site, destination, tmp_path / "state")
assert not destination.exists()


def test_package_fails_closed_on_bomless_utf16_text(tmp_path: Path) -> None:
site = _site(tmp_path)
token = "ghp_" + "a" * 36
(site / "capture.txt").write_bytes(
("GITHUB_TOKEN=" + token + "\n").encode("utf-16-le")
)
destination = tmp_path / "publish"

with pytest.raises(
StaticSiteContractError, match="content is not reviewable text"
):
_package(site, destination, tmp_path / "state")
assert not destination.exists()


def test_package_fails_closed_on_nul_bearing_text(tmp_path: Path) -> None:
site = _site(tmp_path)
token = "ghp_" + "a" * 36
(site / "notes.txt").write_bytes(
("GITHUB_TOKEN=" + token + "\x00tail\n").encode("utf-8")
)
destination = tmp_path / "publish"

with pytest.raises(
StaticSiteContractError, match="content is not reviewable text"
):
_package(site, destination, tmp_path / "state")
assert not destination.exists()


def test_package_fails_closed_on_undecodable_text(tmp_path: Path) -> None:
site = _site(tmp_path)
token = "ghp_" + "a" * 36
(site / "notes.txt").write_bytes(
b"GITHUB_TOKEN=" + token.encode("utf-8") + b"\xff\n"
)
destination = tmp_path / "publish"

with pytest.raises(
StaticSiteContractError, match="content is not decodable as utf-8"
):
_package(site, destination, tmp_path / "state")
assert not destination.exists()


def test_package_still_copies_binary_assets_without_text_scanning(
tmp_path: Path,
) -> None:
site = _site(tmp_path)
(site / "render.png").write_bytes(b"\x89PNG\r\n\x1a\n" + bytes(range(32)))
result = _package(site, tmp_path / "publish", tmp_path / "state")

assert result["write_performed"] is True
assert (tmp_path / "publish" / "render.png").is_file()


@pytest.mark.parametrize(("asset", "content"), _REAL_MEDIA_ASSETS)
def test_package_copies_a_real_media_asset_byte_for_byte(
tmp_path: Path, asset: str, content: bytes
) -> None:
"""A browser-decodable container is media, not unreviewable text."""
site = _site(tmp_path)
(site / asset).write_bytes(content)
result = _package(site, tmp_path / "publish", tmp_path / "state")

assert result["write_performed"] is True
assert (tmp_path / "publish" / asset).read_bytes() == content
manifest = json.loads(
(tmp_path / "publish" / MANIFEST_FILE).read_text(encoding="utf-8")
)
files = {str(item["path"]): item for item in manifest["files"]}
assert files[asset]["sha256"] == hashlib.sha256(content).hexdigest()
assert files[asset]["size"] == len(content)


@pytest.mark.parametrize(("asset", "content"), _REAL_MEDIA_ASSETS)
def test_package_rejects_a_text_asset_next_to_real_media(
tmp_path: Path, asset: str, content: bytes
) -> None:
"""The media exemption must not disarm the text boundary in the same bundle."""
site = _site(tmp_path)
(site / asset).write_bytes(content)
token = "ghp_" + "a" * 36
(site / "assets" / "export.csv").write_text(
f"name,value\napi,{token}\n", encoding="utf-8"
)
destination = tmp_path / "publish"

with pytest.raises(
StaticSiteContractError,
match="public boundary scan failed for assets/export.csv",
):
_package(site, destination, tmp_path / "state")
assert not destination.exists()


def test_package_rejects_reserved_paths_symlinks_and_public_boundary_leaks(
tmp_path: Path,
) -> None:
Expand Down Expand Up @@ -353,3 +522,56 @@ 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


@pytest.mark.parametrize(("asset", "content"), _REAL_MEDIA_ASSETS)
def test_cli_package_copies_real_media_and_rejects_text_beside_it(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
asset: str,
content: bytes,
) -> None:
"""The shipped entrypoint must keep both halves of the boundary: media copies
byte for byte, and a text asset carrying a credential still fails the bundle."""
site = _site(tmp_path)
(site / asset).write_bytes(content)

def run(output: Path) -> int:
return main(
[
"--format",
"json",
"presentation",
"package",
"--site-dir",
str(site),
"--output-dir",
str(output),
"--site-id",
"media-cli-demo",
"--desktop-visual-check",
"passed",
"--mobile-visual-check",
"passed",
"--link-check",
"passed",
"--execute",
]
)

accepted_output = tmp_path / "publish"
assert run(accepted_output) == 0
accepted = json.loads(capsys.readouterr().out)
assert accepted["write_performed"] is True
assert (accepted_output / asset).read_bytes() == content

token = "ghp_" + "a" * 36
(site / "assets" / "export.csv").write_text(
f"name,value\napi,{token}\n", encoding="utf-8"
)
rejected_output = tmp_path / "publish-rejected"
assert run(rejected_output) == 2
rejected = json.loads(capsys.readouterr().out)
assert rejected["ok"] is False
assert "public boundary scan failed for assets/export.csv" in rejected["error"]
assert not rejected_output.exists()
Loading