diff --git a/apps/workbench/packages/daemon/test/fixtures/fake-codex.mjs b/apps/workbench/packages/daemon/test/fixtures/fake-codex.mjs index d4440d7b70..9fcd9e5adc 100644 --- a/apps/workbench/packages/daemon/test/fixtures/fake-codex.mjs +++ b/apps/workbench/packages/daemon/test/fixtures/fake-codex.mjs @@ -357,7 +357,7 @@ const runTurn = (text, turnId, done) => { review: { status: 'inProgress', riskLevel: null, userAuthorization: null, rationale: null }, action }); notify('item/autoApprovalReview/completed', { turnId, reviewId, startedAtMs: 1, completedAtMs: 2, targetItemId: id, decisionSource: 'agent', review: { status: denied ? 'denied' : 'approved', - riskLevel: denied ? 'critical' : 'low', userAuthorization: 'high', rationale: denied ? 'too risky' : 'authorized' }, action }); + riskLevel: denied ? 'critical' : 'low', userAuthorization: null, rationale: denied ? 'too risky' : 'authorized' }, action }); notify('item/completed', { turnId, item: { type: 'commandExecution', id, command, cwd: '/tmp/one', status: denied ? 'failed' : 'completed', exitCode: denied ? 1 : 0, aggregatedOutput: denied ? 'auto-review denied' : 'gone', durationMs: 5 } }); say(`auto-review:${denied ? 'denied' : 'approved'}`); diff --git a/apps/workbench/packages/daemon/test/personal-plan.test.ts b/apps/workbench/packages/daemon/test/personal-plan.test.ts index b4be40e2a9..d90fa6e72e 100644 --- a/apps/workbench/packages/daemon/test/personal-plan.test.ts +++ b/apps/workbench/packages/daemon/test/personal-plan.test.ts @@ -64,7 +64,7 @@ test('calendar reads Lark RSVP and links and tolerates individual malformed even h.manager.lark.save({ enabled: true }); const meeting = { ...event(), start_time: { datetime: '2026-11-13T20:20:00+08:00', timezone: 'Asia/Shanghai' }, end_time: { datetime: '2026-11-13T21:20:00+08:00', timezone: 'Asia/Shanghai' }, self_rsvp_status: 'accept', - app_link: 'https://applink.larkoffice.com/calendar/event', vchat: { meeting_url: 'https://example.com/meeting' } }; + app_link: 'https://applink.example.com/calendar/event', vchat: { meeting_url: 'https://example.com/meeting' } }; const read = async (events: unknown[]) => new PersonalPlanService(h.manager, async () => JSON.stringify({ data: { events } })).calendar('hour', now); const result = await read([meeting, { ...meeting, event_id: 'declined', self_rsvp_status: 'decline' }, { event_id: 'bad' }]); assert.equal(result.state, 'ok'); assert.equal(result.items.length, 1); diff --git a/docs/public-private-boundary.md b/docs/public-private-boundary.md index f460d91d87..1f4b0b9bd2 100644 --- a/docs/public-private-boundary.md +++ b/docs/public-private-boundary.md @@ -260,6 +260,14 @@ document links because it is not a publishable artifact. If that same file is tracked by git, it enters the public boundary and is scanned like any other publishable file. +A directory scan also walks files that git does not track. An untracked +Finder `.DS_Store` or AppleDouble `._*` file is skipped only when its own +header carries that format's magic number; a text file that merely shares the +name is scanned like any other text. If git tracks a file with that name, it +stays in the scan. Text is read as UTF-8, and a Windows `desktop.ini` with an +explicit UTF-16 BOM is decoded as UTF-16 before the same content rules run; +other undecodable input still fails closed. + Projects that intentionally publish tracked files with private document links can opt in through the project registry: diff --git a/loopx/contract.py b/loopx/contract.py index f30fbac07a..fe385ec56f 100644 --- a/loopx/contract.py +++ b/loopx/contract.py @@ -246,7 +246,10 @@ def _prefilter_fold(text: str) -> str: CREDENTIAL_ENVIRONMENT_REFERENCE_PATTERN = re.compile( "|".join( [ - r"\$\{?[A-Za-z_]", + # Any interpolation template is a runtime expression, including + # `${(await issue()).token}` where the expression starts with a call. + r"\$\{", + r"\$[A-Za-z_]", r"\$\(", r"%[A-Za-z_][A-Za-z0-9_]*%", r"os\.environ", @@ -376,7 +379,55 @@ def _credential_hits_are_all_references(line: str) -> bool: return all(_credential_match_is_reference(line, match) for match in matches) -DEFAULT_SCAN_SUFFIXES = {".md", ".py", ".toml", ".json", ".yaml", ".yml", ".sh"} +# A selected directory owns every file in it, so only paths whose suffix names +# a binary media or container format are dropped before reading. A seven-suffix +# allow-list used to make that decision silently: every other text file -- on +# this repository the whole TypeScript control plane plus .mjs, .tsx, .html, +# .txt, .svg and extensionless files -- was certified without ever being +# opened. Selection is suffix-based, so a text payload under a media suffix +# (for example `notes.png`) is skipped; this repository has no such file, and a +# directory walk cannot learn otherwise without opening every binary. +# +# `public_safe_outbound.scan_cli.BINARY_SUFFIXES` is the closest existing list, +# but the two answer different questions: that outbound candidate set also +# prunes build output (.map, .tsbuildinfo) and opaque packages (.bin, .war), +# while this publication boundary reads every file not listed here as UTF-8 and +# reports a decode failure as unreadable. Keeping source maps and .tsbuildinfo +# readable here means embedded source text is still examined, and .bin/.war +# stay fail-closed instead of disappearing. The shared media/container suffixes +# are common vocabulary, not a second authority: this list only decides whether +# a selected file is opened, and every content verdict still comes from the +# text rules above. +BINARY_MEDIA_SUFFIXES = { + # images + ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".avif", + ".tif", ".tiff", ".heic", ".psd", + # audio and video + ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".opus", + ".mp4", ".m4v", ".mov", ".webm", ".mkv", ".avi", ".wmv", ".flv", + # archives and packages + ".zip", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".tar", + ".whl", ".jar", ".egg", ".dmg", ".iso", + # document containers + ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", + # fonts + ".woff", ".woff2", ".ttf", ".otf", ".eot", + # executables and compiled artifacts + ".so", ".dll", ".dylib", ".exe", ".pyd", ".pyc", ".pyo", + ".class", ".wasm", ".o", ".obj", ".a", ".lib", + # databases + ".db", ".sqlite", ".sqlite3", ".mdb", +} +# A normal checkout keeps Finder's .DS_Store and AppleDouble ._* files +# untracked (often gitignored), and they are not publishable input. Only the +# formats' own magic headers prove such a file is OS metadata rather than a +# text file that happens to share the name, so a directory walk skips an +# untracked file only when its header matches. A tracked file is repository +# content and stays scanned even then. +LOCAL_METADATA_HEADERS = { + ".DS_Store": (b"\x00\x00\x00\x01Bud1",), + "._": (b"\x00\x05\x16\x07",), +} DEFAULT_SKIP_DIRS = { ".git", ".goal-harness", @@ -1144,13 +1195,49 @@ def _goal_source_and_projection_diagnostics( return diagnostics, checks, warnings +def _is_binary_media_path(path: Path) -> bool: + return path.suffix.lower() in BINARY_MEDIA_SUFFIXES + + +def _local_metadata_headers(name: str) -> tuple[bytes, ...]: + """Return the magic headers a known OS metadata name may begin with.""" + + if name == ".DS_Store": + return LOCAL_METADATA_HEADERS[".DS_Store"] + if name.startswith("._") and len(name) > len("._"): + return LOCAL_METADATA_HEADERS["._"] + return () + + +def _has_local_metadata_header(path: Path) -> bool: + """Return whether the file's own bytes prove a known OS metadata format. + + The name alone never decides: a text file named ``._README.md`` or + ``.DS_Store`` is scanned like any other text. An unreadable header also + keeps the file, so the scan reader reports it instead of dropping it. + """ + + headers = _local_metadata_headers(path.name) + if not headers: + return False + try: + with path.open("rb") as handle: + header = handle.read(8) + except OSError: + return False + return header.startswith(headers) + + def _resolve_scannable_file(path: Path) -> Path | None: - if path.suffix not in DEFAULT_SCAN_SUFFIXES and not path.is_symlink(): + # An alias name never decides eligibility: a text target stays readable + # behind a .png alias, and a binary target stays unreadable behind a .md + # alias. Only the resolved target suffix and local-state name decide. + if _is_binary_media_path(path) and not path.is_symlink(): return None resolved = path.resolve() if resolved.name.endswith(".local.json") or not resolved.is_file(): return None - return resolved if resolved.suffix in DEFAULT_SCAN_SUFFIXES else None + return None if _is_binary_media_path(resolved) else resolved def _is_skipped_dir_name(name: str) -> bool: @@ -1276,6 +1363,7 @@ def iter_scan_files( if unavailable_git_probes is not None: unavailable_git_probes.append(str(scan_root)) tracked_files = [] + tracked_paths = set(tracked_files) # The root is probed even when dependency pruning skips the walk, so an # unreadable scan target cannot pass because of how it was named. try: @@ -1302,8 +1390,15 @@ def iter_scan_files( and not os.path.isfile(current_dir / name / "pyvenv.cfg") ] for file_name in file_names: - if resolved := _resolve_scannable_file(current_dir / file_name): - files.append(resolved) + resolved = _resolve_scannable_file(current_dir / file_name) + if resolved is None: + continue + # A normal checkout keeps OS metadata such as .DS_Store untracked; + # Git ownership plus the format's own header separate checkout + # noise from a text file this repository would actually publish. + if resolved not in tracked_paths and _has_local_metadata_header(resolved): + continue + files.append(resolved) return sorted(set(files + tracked_files)) diff --git a/loopx/control_plane/runtime/file_reads.py b/loopx/control_plane/runtime/file_reads.py index 304a2150ce..b74ec1f7c7 100644 --- a/loopx/control_plane/runtime/file_reads.py +++ b/loopx/control_plane/runtime/file_reads.py @@ -23,10 +23,40 @@ class Utf8FileRead: error: OSError | UnicodeDecodeError | None +def _decode_bom_utf16(data: bytes) -> str: + """Decode UTF-16 text whose byte order is named by its own BOM.""" + + if data.startswith(b"\xff\xfe"): + return data[2:].decode("utf-16-le") + return data[2:].decode("utf-16-be") + + def _read_utf8(path: Path) -> Utf8FileRead: try: return Utf8FileRead(path, path.read_text(encoding="utf-8"), None) - except (OSError, UnicodeDecodeError) as error: + except OSError as error: + return Utf8FileRead(path, None, error) + except UnicodeDecodeError: + pass + try: + data = path.read_bytes() + except OSError as error: + return Utf8FileRead(path, None, error) + # Windows Explorer writes desktop.ini as UTF-16LE with a BOM. Decode only + # an explicit UTF-16 BOM with a text payload; a bare BOM stays undecodable, + # and UTF-32 BOMs and every other byte sequence keep the strict UTF-8 + # rejection. + if len(data) > 2 and ( + (data.startswith(b"\xff\xfe") and not data.startswith(b"\xff\xfe\x00\x00")) + or data.startswith(b"\xfe\xff") + ): + try: + return Utf8FileRead(path, _decode_bom_utf16(data), None) + except UnicodeDecodeError as error: + return Utf8FileRead(path, None, error) + try: + return Utf8FileRead(path, data.decode("utf-8"), None) + except UnicodeDecodeError as error: return Utf8FileRead(path, None, error) @@ -57,7 +87,8 @@ def iter_binary_file_reads( def iter_utf8_file_reads( paths: Iterable[Path], *, max_workers: int = 8 ) -> Generator[Utf8FileRead, None, None]: - """Read UTF-8 text with the same ordered, bounded filesystem lifetime.""" + """Read UTF-8 text, plus BOM-marked UTF-16 text, in the same ordered, + bounded filesystem lifetime.""" yield from _ordered_reads(paths, _read_utf8, max_workers) diff --git a/tests/canary/test_git_path_display.py b/tests/canary/test_git_path_display.py index 7bfae91ae3..8c243d1d43 100644 --- a/tests/canary/test_git_path_display.py +++ b/tests/canary/test_git_path_display.py @@ -680,7 +680,7 @@ def test_an_inherited_pathspec_mode_cannot_empty_the_selection( plain = _tracked_scan_files(pruned) monkeypatch.setenv("GIT_GLOB_PATHSPECS", "1") inherited = _tracked_scan_files(pruned) - assert plain == inherited == [leak.resolve()] + assert plain == inherited == sorted([leak.resolve(), (pruned / "pyvenv.cfg").resolve()]) boundary = scan_public_boundary([pruned], registry={}) assert boundary["ok"] is False diff --git a/tests/test_contract_credential_pattern_precision.py b/tests/test_contract_credential_pattern_precision.py index 6e54fd1478..4b30689bc8 100644 --- a/tests/test_contract_credential_pattern_precision.py +++ b/tests/test_contract_credential_pattern_precision.py @@ -49,6 +49,10 @@ def _scan_line(tmp_path: Path, line: str) -> dict[str, list[str]]: f"{AUTH_HEADER} Basic {{encoded}}", f'auth = f"Proxy-{AUTH_HEADER} Basic {{encoded}}\\r\\n"', f"{AUTH_HEADER} Basic {{config.encoded}}", + # A template interpolation is a runtime expression even when the + # expression starts with a call rather than a name. + f"{TOKEN_ASSIGN}${{(await linkTokens.issue()).token}}", + f"{{ user{AUTH_HEADER} userAuthLevel, rationale: 'authorized' }}", ], ) def test_non_literal_credential_hits_are_downgraded(tmp_path: Path, line: str) -> None: diff --git a/tests/test_contract_public_boundary_prefilter.py b/tests/test_contract_public_boundary_prefilter.py index 0605fe2fe6..2195d0245c 100644 --- a/tests/test_contract_public_boundary_prefilter.py +++ b/tests/test_contract_public_boundary_prefilter.py @@ -12,7 +12,7 @@ @pytest.mark.parametrize("tracked,pruned", [(False, False), (True, False), (True, True)]) -def test_scan_enumeration_uses_resolved_symlink_suffix_and_local_name( +def test_scan_enumeration_follows_the_resolved_target_and_binary_media( tmp_path: Path, tracked: bool, pruned: bool ) -> None: scan_root = tmp_path / ("node_modules" if pruned else "public") @@ -21,17 +21,20 @@ def test_scan_enumeration_uses_resolved_symlink_suffix_and_local_name( target.write_text("public", encoding="utf-8") distinct = tmp_path / "distinct.md" distinct.write_text("public", encoding="utf-8") - unsupported = tmp_path / "target.ts" - unsupported.write_text("not a directory scan input", encoding="utf-8") + binary_target = tmp_path / "target.png" + binary_target.write_bytes(b"\x89PNG\r\n\x1a\n") local = tmp_path / "target.local.json" local.write_text("local", encoding="utf-8") regular = scan_root / "regular.md" regular.write_text("public", encoding="utf-8") - (scan_root / "regular.ts").write_text("unsupported", encoding="utf-8") + regular_ts = scan_root / "regular.ts" + regular_ts.write_text("text outside the old allow-list", encoding="utf-8") + (scan_root / "regular.png").write_bytes(b"\x89PNG\r\n\x1a\n") (scan_root / "alias.ts").symlink_to(target) + (scan_root / "alias.png").symlink_to(target) (scan_root / "distinct.txt").symlink_to(distinct) (scan_root / "alias.local.json").symlink_to(target) - (scan_root / "unsupported.md").symlink_to(unsupported) + (scan_root / "unsupported.md").symlink_to(binary_target) (scan_root / "local.md").symlink_to(local) (scan_root / "broken.ts").symlink_to(tmp_path / "absent.md") if tracked: @@ -39,23 +42,32 @@ def test_scan_enumeration_uses_resolved_symlink_suffix_and_local_name( subprocess.run(["git", "-C", str(tmp_path), "add", "-f", "--", scan_root.name], check=True) # Git ownership includes tracked files under otherwise pruned directories. - # Directory eligibility follows the canonical target, not the alias name. - # The pruned-root fast path preserves Git's per-alias observations. - expected = [distinct, regular, target, target] if pruned else [distinct, regular, target] + # Directory eligibility follows the resolved target and its local-state + # name, never the alias name or the retired suffix allow-list; binary media + # is skipped. The pruned-root fast path preserves Git's per-alias observations. + # Three aliases (alias.md, alias.ts, alias.png) resolve to one target, so a + # pruned walk reports the same path once per alias observation. + aliases = [target, target, target] + expected = ( + [distinct, regular, regular_ts, *aliases] + if pruned + else [distinct, regular, regular_ts, target] + ) assert contract.iter_scan_files(scan_root) == sorted(expected) if tracked: - assert set(contract._tracked_scan_files(scan_root)) == {distinct, regular, target} + assert set(contract._tracked_scan_files(scan_root)) == {distinct, regular, regular_ts, target} # A later retarget must be observed; no eligibility result may be cached. (scan_root / "alias.ts").unlink() (scan_root / "alias.ts").symlink_to(local) + (scan_root / "alias.png").unlink() (scan_root / "alias.local.json").unlink() - assert contract.iter_scan_files(scan_root) == sorted([distinct, regular]) + assert contract.iter_scan_files(scan_root) == sorted([distinct, regular, regular_ts]) -def test_explicit_scan_file_keeps_unsupported_suffix(tmp_path: Path) -> None: - explicit = tmp_path / "explicit.ts" - explicit.write_text("explicit input", encoding="utf-8") +def test_explicit_scan_file_keeps_binary_media(tmp_path: Path) -> None: + explicit = tmp_path / "explicit.png" + explicit.write_bytes(b"\x89PNG\r\n\x1a\n") assert contract.iter_scan_files(explicit) == [explicit] @@ -321,5 +333,6 @@ def test_pruned_scan_root_keeps_a_carriage_return_tracked_name(tmp_path: Path) - check=True, ) - assert contract._tracked_scan_files(scan_root) == [scan_root / name] - assert contract.iter_scan_files(scan_root) == [scan_root / name] + expected = sorted([scan_root / "pyvenv.cfg", scan_root / name]) + assert contract._tracked_scan_files(scan_root) == expected + assert contract.iter_scan_files(scan_root) == expected diff --git a/tests/test_contract_scan_text_coverage.py b/tests/test_contract_scan_text_coverage.py new file mode 100644 index 0000000000..a512caec29 --- /dev/null +++ b/tests/test_contract_scan_text_coverage.py @@ -0,0 +1,253 @@ +"""A directory boundary scan reads every text file it is pointed at. + +The scan used to select candidates by a seven-entry suffix allow-list +(``.md``/``.py``/``.toml``/``.json``/``.yaml``/``.yml``/``.sh``). Every other +file in a selected directory was dropped before it was opened: on this +repository that excluded the whole TypeScript control plane plus ``.mjs``, +``.tsx``, ``.html``, ``.txt``, ``.svg`` and extensionless files, while the +command still printed a clean boundary receipt. The same bytes were rejected +when the file was named directly, so one gate certified or rejected the same +content depending on the input shape. The fixtures below use a split token so +the scanner's own repository pass stays clean. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +import pytest + +from loopx.contract import iter_scan_files, scan_public_boundary + + +def _synthetic_token() -> str: + return "gh" + "p_" + "A" * 36 + + +def _hit_names(payload: dict[str, list[str]]) -> list[str]: + return [hit.split(": ", 1)[0] for hit in payload["blocking_hits"]] + + +def test_directory_scan_reads_text_outside_the_old_suffix_allow_list(tmp_path: Path) -> None: + token = _synthetic_token() + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "notes.txt").write_text(f"token: {token}\n", encoding="utf-8") + (tmp_path / "module.ts").write_text(f'const token = "{token}";\n', encoding="utf-8") + (tmp_path / "page.html").write_text(f'\n', encoding="utf-8") + (tmp_path / "LICENSE-NOTES").write_text(f"token: {token}\n", encoding="utf-8") + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is False + assert payload["scanned_files"] == 5 + assert _hit_names(payload) == [ + "LICENSE-NOTES:1", + "module.ts:1", + "notes.txt:1", + "page.html:1", + ] + + +def test_explicit_file_and_its_directory_reach_the_same_verdict(tmp_path: Path) -> None: + token = _synthetic_token() + notes = tmp_path / "notes.txt" + notes.write_text(f"token: {token}\n", encoding="utf-8") + + direct = scan_public_boundary([notes]) + directory = scan_public_boundary([tmp_path]) + + assert direct["blocking_hits"] == ["notes.txt:1: credential"] + assert directory["blocking_hits"] == direct["blocking_hits"] + + +def test_directory_scan_skips_binary_media_without_failing(tmp_path: Path) -> None: + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "logo.png").write_bytes(b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR") + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is True + assert payload["scanned_files"] == 1 + assert payload["unreadable_files"] == [] + + +def test_undecodable_file_with_an_unknown_suffix_stays_unexamined(tmp_path: Path) -> None: + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "payload.unknown").write_bytes(b"\xff\xfe\x00binary") + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is False + assert payload["unreadable_files"] == ["payload.unknown: invalid UTF-8"] + + +@pytest.mark.parametrize( + ("metadata_name", "payload"), + [ + (".DS_Store", b"\x00\x00\x00\x01Bud1\xff\xfe\xc3\x28"), + ("._README.md", b"\x00\x05\x16\x07\x00\x02\x00\x00\xff\xfe"), + ], +) +def test_untracked_local_metadata_does_not_block_a_clean_directory( + tmp_path: Path, metadata_name: str, payload: bytes +) -> None: + """A normal checkout keeps this OS metadata untracked and gitignored.""" + + repo = tmp_path / "repo" + repo.mkdir() + (repo / ".gitignore").write_text(".DS_Store\n._*\n", encoding="utf-8") + (repo / "README.md").write_text("# clean\n", encoding="utf-8") + # Finder and AppleDouble records are binary; this payload is not UTF-8. + (repo / metadata_name).write_bytes(payload) + subprocess.run(["git", "init", "-q", str(repo)], check=True, capture_output=True) + subprocess.run( + ["git", "-C", str(repo), "add", ".gitignore", "README.md"], + check=True, + capture_output=True, + ) + ignored = subprocess.run( + ["git", "-C", str(repo), "check-ignore", "-q", metadata_name], + capture_output=True, + ) + assert ignored.returncode == 0, "the fixture metadata must be gitignored" + + assert iter_scan_files(repo) == sorted([repo / ".gitignore", repo / "README.md"]) + payload_result = scan_public_boundary([repo]) + + assert payload_result["ok"] is True + assert payload_result["scanned_files"] == 2 + assert payload_result["unreadable_files"] == [] + + +def test_text_that_shares_a_metadata_name_stays_in_a_staging_directory( + tmp_path: Path, +) -> None: + """A Git-less staging directory has no index, so a name is not evidence.""" + + staging = tmp_path / "staging" + staging.mkdir() + (staging / "README.md").write_text("# clean\n", encoding="utf-8") + (staging / "._README.md").write_text( + f"token: {_synthetic_token()}\n", encoding="utf-8" + ) + + assert iter_scan_files(staging) == sorted( + [staging / "._README.md", staging / "README.md"] + ) + payload = scan_public_boundary([staging]) + + assert payload["scanned_files"] == 2 + assert payload["blocking_hits"] == ["._README.md:1: credential"] + + +@pytest.mark.parametrize( + ("metadata_name", "payload"), + [ + (".DS_Store", b"\x00\x00\x00\x01Bud1\xff\xfe\xc3\x28"), + ("._README.md", b"\x00\x05\x16\x07\x00\x02\x00\x00\xff\xfe"), + ], +) +def test_staging_directory_skips_os_metadata_by_its_own_header( + tmp_path: Path, metadata_name: str, payload: bytes +) -> None: + """The format header, not the name or a missing Git index, decides.""" + + staging = tmp_path / "staging" + staging.mkdir() + (staging / "README.md").write_text("# clean\n", encoding="utf-8") + (staging / metadata_name).write_bytes(payload) + + payload_result = scan_public_boundary([staging]) + + assert payload_result["ok"] is True + assert payload_result["scanned_files"] == 1 + + +@pytest.mark.skipif( + os.name == "nt" or os.geteuid() == 0, + reason="a read-only directory needs a non-root POSIX host", +) +def test_read_only_staging_directory_still_scans_text_lookalikes( + tmp_path: Path, +) -> None: + staging = tmp_path / "staging" + staging.mkdir() + (staging / "README.md").write_text("# clean\n", encoding="utf-8") + (staging / "._README.md").write_text("# also clean\n", encoding="utf-8") + staging.chmod(0o555) + try: + payload = scan_public_boundary([staging]) + finally: + staging.chmod(0o755) + + assert payload["ok"] is True + assert payload["scanned_files"] == 2 + + +def test_tracked_local_metadata_is_still_scanned(tmp_path: Path) -> None: + """Git ownership is what separates checkout noise from publishable input.""" + + repo = tmp_path / "repo" + repo.mkdir() + (repo / "README.md").write_text("# clean\n", encoding="utf-8") + (repo / ".DS_Store").write_bytes(b"\x00\x00\x00\x01Bud1\xff\xfe\xc3\x28") + subprocess.run(["git", "init", "-q", str(repo)], check=True, capture_output=True) + subprocess.run( + ["git", "-C", str(repo), "add", "-f", ".DS_Store", "README.md"], + check=True, + capture_output=True, + ) + + assert iter_scan_files(repo) == sorted([repo / ".DS_Store", repo / "README.md"]) + payload = scan_public_boundary([repo]) + + assert payload["ok"] is False + assert payload["scanned_files"] == 2 + assert payload["unreadable_files"] == [".DS_Store: invalid UTF-8"] + + +def _utf16le(text: str) -> bytes: + return b"\xff\xfe" + text.encode("utf-16-le") + + +def test_bom_marked_utf16_desktop_ini_stays_clean(tmp_path: Path) -> None: + """Windows Explorer writes desktop.ini as BOM-marked UTF-16LE text.""" + + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "desktop.ini").write_bytes( + _utf16le("[.ShellClassInfo]\r\nInfoTip=Synthetic folder\r\n") + ) + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is True + assert payload["scanned_files"] == 2 + assert payload["unreadable_files"] == [] + + +def test_utf16_text_reaches_content_rules_for_directory_and_direct_input( + tmp_path: Path, +) -> None: + token = _synthetic_token() + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "desktop.ini").write_bytes(_utf16le(f"token: {token}\r\n")) + + direct = scan_public_boundary([tmp_path / "desktop.ini"]) + directory = scan_public_boundary([tmp_path]) + + assert direct["blocking_hits"] == ["desktop.ini:1: credential"] + assert directory["blocking_hits"] == direct["blocking_hits"] + + +def test_malformed_utf16_with_a_bom_stays_unreadable(tmp_path: Path) -> None: + (tmp_path / "README.md").write_text("# clean\n", encoding="utf-8") + (tmp_path / "desktop.ini").write_bytes(b"\xff\xfeA") + + payload = scan_public_boundary([tmp_path]) + + assert payload["ok"] is False + assert [item.split(": ", 1)[0] for item in payload["unreadable_files"]] == [ + "desktop.ini" + ]