fix(809,822): isolate the suite from the production hook-fire log by construction (#874)
Build ErsatzTV Image / CI toolchain image resolves (push) Successful in 8s
Build ErsatzTV Image / Delimiter ban (release path) (push) Successful in 26s
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 8m32s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 6m12s
Build ErsatzTV Image / Functional E2E (curl + UI contracts) (push) Successful in 6m14s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (push) Skipped
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (push) Skipped
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 4m32s
Build ErsatzTV Image / CI toolchain image resolves (push) Successful in 8s
Build ErsatzTV Image / Delimiter ban (release path) (push) Successful in 26s
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 8m32s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 6m12s
Build ErsatzTV Image / Functional E2E (curl + UI contracts) (push) Successful in 6m14s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (push) Skipped
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (push) Skipped
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 4m32s
Co-authored-by: Timothy <timothy@noreply.gitea.tblindustries.be>
This commit was merged in pull request #874.
This commit is contained in:
@@ -32,11 +32,20 @@ from __future__ import annotations
|
||||
import os
|
||||
import pty
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from scripts.tests.hook_fire_isolation import (
|
||||
ENV_VAR,
|
||||
SHARED_LOG_DIRS,
|
||||
isolation_violation,
|
||||
resolved_log_dir,
|
||||
)
|
||||
from scripts.tests.tracked_files import tracked_paths
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
@@ -47,6 +56,18 @@ HUSKY = (".husky", ("*",))
|
||||
HOOKS_DIR = REPO_ROOT / ".claude" / "hooks"
|
||||
SINK = REPO_ROOT / "scripts" / "hook-fire-log.sh"
|
||||
|
||||
# CAPTURED AT IMPORT TIME ON PURPOSE — this is a specimen, not an oversight.
|
||||
#
|
||||
# `{**os.environ}` at module level is the shape #785 shipped: a suite that snapshots the environment
|
||||
# once, at collection, and hands that stale mapping to every subprocess it launches. Because the
|
||||
# autouse isolation fixture runs at test SETUP, such a snapshot used to predate it and every hook
|
||||
# driven from it wrote to `$HOME/.cache/ersatztv/hook-fire/` — 58 records per run, with every
|
||||
# assertion green, since the fire-log library is fail-open by design.
|
||||
#
|
||||
# `test_the_suite_does_not_write_to_the_PRODUCTION_log` asserts this specimen is now SAFE, which is
|
||||
# the cross-suite claim that test has always made in its docstring and never checked in its body.
|
||||
_IMPORT_TIME_ENV = {**os.environ}
|
||||
|
||||
# The three lines a hook must carry. Matched structurally rather than as one frozen blob so that a
|
||||
# comment reflow does not redden the suite, but the two things that matter — sourcing the single
|
||||
# shared sink, and calling begin with this hook's own name — are both pinned.
|
||||
@@ -1102,22 +1123,49 @@ def test_the_session_id_cannot_ESCAPE_the_log_directory(sandbox, tmp_path):
|
||||
|
||||
|
||||
def test_the_suite_does_not_write_to_the_PRODUCTION_log(sandbox):
|
||||
"""`conftest.py` must isolate every test, not just this file's.
|
||||
"""`conftest.py` isolates every test, and every MODULE — not just this file, and not just tests.
|
||||
|
||||
Before it, running `pytest scripts/tests` put 115 synthetic fires into
|
||||
`$HOME/.cache/ersatztv/hook-fire/` — 96 merge-consent including two `deny`s — so
|
||||
`hook-fire-log.sh report` described the test suite while looking exactly like a record of real
|
||||
sessions. That is the inference problem this change exists to abolish, one layer up.
|
||||
WHAT THIS ASSERTED BEFORE, and why that had to go. It snapshotted the `st_mtime_ns` of every
|
||||
`~/.cache/ersatztv/hook-fire/*.jsonl`, drove one hook, and required the two lists equal. That
|
||||
directory is the production log EVERY live Claude Code session on the machine writes to, so the
|
||||
oracle was global mutable state: an unrelated session firing a hook inside the window failed
|
||||
this test with `a test run modified the production hook-fire log` — an accusation about the
|
||||
suite when the writer was another process. Observed on three separate branches, green on an
|
||||
immediate re-run each time, and corroborated by an independent reviewer who found a file in that
|
||||
directory written 13 seconds earlier by someone else (ersatztv#822). The misattribution was the
|
||||
expensive part: it points the next reader at the suite, and the honest diagnosis costs a re-run
|
||||
plus a directory listing.
|
||||
|
||||
WHAT IT ASSERTS NOW. The same invariant, structurally, reading nothing under `$HOME`.
|
||||
`_IMPORT_TIME_ENV` is the #785 defect's own shape — the environment as a module sees it at
|
||||
COLLECTION, before any fixture has run — and a real hook driven with it must land its records in
|
||||
the isolated directory that snapshot carries. That is the cross-suite claim: isolation has to be
|
||||
in place before a module is IMPORTED, not merely before a test runs, and the same ordering is
|
||||
what covers module- and session-scoped fixtures, which no autouse function fixture can reach.
|
||||
|
||||
It asserts the EFFECT — records in the isolated dir — rather than the shape of the fix. Pinning
|
||||
the shape is what `test_worktree_ownership_guard.py` had to correct once already: `_env()` can be
|
||||
perfectly correct while a call site passes something else.
|
||||
"""
|
||||
assert os.environ.get("ETV_HOOK_FIRE_LOG_DIR"), (
|
||||
"ETV_HOOK_FIRE_LOG_DIR is not set for this test, so any hook it drives writes to the real "
|
||||
"log. scripts/tests/conftest.py should be setting it for every test."
|
||||
)
|
||||
default = Path(os.path.expanduser("~/.cache/ersatztv/hook-fire"))
|
||||
assert Path(os.environ["ETV_HOOK_FIRE_LOG_DIR"]).resolve() != default.resolve()
|
||||
# Both violations are BOUND before being asserted on, never called inside the `assert`
|
||||
# expression: pytest rewrites the expression and prints the repr of every sub-expression, so
|
||||
# `assert isolation_violation(os.environ) is None` dumps the whole environment — API keys and
|
||||
# tokens included — into the failure output and from there into a CI log. Measured, not feared.
|
||||
here = isolation_violation(os.environ)
|
||||
assert here is None, here
|
||||
|
||||
before = sorted(p.stat().st_mtime_ns for p in default.glob("*.jsonl")) if default.exists() else []
|
||||
root, env = sandbox
|
||||
# THE CROSS-SUITE CLAUSE. An autouse fixture alone cannot satisfy this: it runs at test setup,
|
||||
# which is after every module in the session has been imported.
|
||||
snapshot_violation = isolation_violation(_IMPORT_TIME_ENV)
|
||||
assert snapshot_violation is None, (
|
||||
"a module-level `{**os.environ}` snapshot resolves to the production hook-fire log. "
|
||||
f"conftest.py's `pytest_configure` must set {ENV_VAR} BEFORE collection.\n{snapshot_violation}"
|
||||
)
|
||||
|
||||
snapshot_dir = resolved_log_dir(_IMPORT_TIME_ENV)
|
||||
before = {p.name for p in snapshot_dir.glob("*.jsonl")} if snapshot_dir.exists() else set()
|
||||
|
||||
root, _env = sandbox
|
||||
hook = root / "prod-check.sh"
|
||||
hook.write_text(
|
||||
"#!/usr/bin/env bash\nset -uo pipefail\n"
|
||||
@@ -1127,14 +1175,26 @@ def test_the_suite_does_not_write_to_the_PRODUCTION_log(sandbox):
|
||||
)
|
||||
subprocess.run(
|
||||
["bash", str(hook)],
|
||||
input=b'{"session_id":"s1","tool_name":"Bash"}',
|
||||
input=b'{"session_id":"import-time-snapshot","tool_name":"Bash"}',
|
||||
capture_output=True,
|
||||
cwd=str(root),
|
||||
env=env,
|
||||
env=dict(_IMPORT_TIME_ENV),
|
||||
timeout=60,
|
||||
)
|
||||
after = sorted(p.stat().st_mtime_ns for p in default.glob("*.jsonl")) if default.exists() else []
|
||||
assert before == after, "a test run modified the production hook-fire log"
|
||||
|
||||
# ANTI-VACUITY. Without this the test passes when the hook logged NOTHING AT ALL — which is also
|
||||
# what a broken sink looks like, and it would then be asserting the absence of a leak by
|
||||
# asserting the absence of any record.
|
||||
after = {p.name for p in snapshot_dir.glob("*.jsonl")} if snapshot_dir.exists() else set()
|
||||
# The EXACT record, not merely "a new file": the log file is named for the payload's session id,
|
||||
# so `after > before` would also be satisfied by an `unknown-session.jsonl` written because
|
||||
# payload parsing broke — a hook that logged the wrong thing, passing a test about isolation.
|
||||
assert "import-time-snapshot.jsonl" in after - before, (
|
||||
f"driving a hook with the import-time snapshot did not add `import-time-snapshot.jsonl` to "
|
||||
f"{snapshot_dir} (new files: {sorted(after - before)}). Either the instrumentation stopped "
|
||||
"firing — in which case this test proves nothing — or those records went somewhere else, "
|
||||
"and the only somewhere else is a shared log this suite must never write."
|
||||
)
|
||||
|
||||
|
||||
def test_DELETING_the_replay_makes_the_differential_go_RED(sandbox, positives, tmp_path):
|
||||
@@ -1494,7 +1554,12 @@ def test_an_INVALID_UTF8_byte_in_a_decision_is_still_classified(tmp_path, locale
|
||||
'printf \'{"hookSpecificOutput":{"permissionDecision":"deny",'
|
||||
'"permissionDecisionReason":"caf\\xe9"}}\'\n'
|
||||
)
|
||||
env = {"PATH": os.environ["PATH"], "HOME": os.environ["HOME"], "ETV_HOOK_FIRE_LOG_DIR": str(logdir), **locale_env}
|
||||
# HOME copied only if present, like the launch-guard test below: an environment without it is
|
||||
# legal (the sink has a `${HOME:-/tmp}` default) and indexing would redden this on a valid
|
||||
# checkout for a reason unrelated to what it tests. This is the twin of the site fixed there.
|
||||
env = {"PATH": os.environ["PATH"], "ETV_HOOK_FIRE_LOG_DIR": str(logdir), **locale_env}
|
||||
if os.environ.get("HOME"):
|
||||
env["HOME"] = os.environ["HOME"]
|
||||
p = subprocess.run(
|
||||
["bash", str(hook)],
|
||||
input=b'{"session_id":"s1","tool_name":"Bash"}',
|
||||
@@ -1653,3 +1718,326 @@ def test_the_field_helper_does_not_LEAK_into_the_hooks_namespace(sandbox):
|
||||
)
|
||||
assert b"LEAKED" not in p.stdout, f"a helper leaked into the hook's namespace: {p.stdout!r}"
|
||||
assert b"CLEAN" in p.stdout
|
||||
|
||||
|
||||
def test_the_resolver_agrees_with_the_SINKS_OWN_expansion(tmp_path):
|
||||
"""`resolved_log_dir` reimplements one shell expansion — so run both and compare, every run.
|
||||
|
||||
It is the guard's only model of where a child will write, so a disagreement fails OPEN: the
|
||||
guard clears a launch, and the sink then points it at the real log. The two `:-` defaults are
|
||||
exactly where a Python transliteration goes subtly wrong, because `dict.get(k, default)` returns
|
||||
`""` for an empty value and shell's `${k:-default}` does not — which is why the empty cases are
|
||||
here rather than only the obvious ones.
|
||||
|
||||
A differential against the real `scripts/hook-fire-log.sh`, not against a restatement of it: a
|
||||
test that asserted the resolver equals a hardcoded path would agree with itself forever after
|
||||
the sink moved.
|
||||
"""
|
||||
cases = [
|
||||
{"HOME": str(tmp_path), ENV_VAR: str(tmp_path / "explicit")},
|
||||
{"HOME": str(tmp_path)},
|
||||
{"HOME": str(tmp_path), ENV_VAR: ""}, # empty is ABSENT to `:-`
|
||||
{"HOME": ""}, # ... and so `${HOME:-/tmp}` takes /tmp
|
||||
{},
|
||||
# Normalisation: shell concatenates strings, `Path` collapses them. These agree on the
|
||||
# DIRECTORY and differ in spelling — `/tmp/x/` vs `/tmp/x`, `$HOME//.cache` vs `$HOME/.cache`
|
||||
# — which is exactly why the comparison below is the one the guard makes and not `==`.
|
||||
{"HOME": str(tmp_path), ENV_VAR: str(tmp_path / "explicit") + "/"},
|
||||
{"HOME": str(tmp_path) + "/"},
|
||||
{"HOME": str(tmp_path), ENV_VAR: str(tmp_path) + "//double"},
|
||||
]
|
||||
for case in cases:
|
||||
# The case is applied INSIDE the child, not through its launch environment.
|
||||
# `etv_hook_fire_log_dir` reads the shell's environment at call time either way, so the
|
||||
# differential is unchanged — but the launch itself then carries the isolated log dir like
|
||||
# every other launch in the suite, instead of this test needing the guard to make an
|
||||
# exception for it. (Several cases deliberately have no `ETV_HOOK_FIRE_LOG_DIR` at all,
|
||||
# which is precisely what the guard exists to reject.)
|
||||
setup = "\n".join(
|
||||
f"export {var}={shlex.quote(case[var])}" if var in case else f"unset {var}" for var in ("HOME", ENV_VAR)
|
||||
)
|
||||
res = subprocess.run(
|
||||
["bash", "-c", f'{setup}\n. "{SINK}"\netv_hook_fire_log_dir'],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env={"PATH": os.environ["PATH"], ENV_VAR: os.environ[ENV_VAR]},
|
||||
timeout=60,
|
||||
)
|
||||
assert res.returncode == 0, f"could not source the sink for {case}: {res.stderr}"
|
||||
# SAME DIRECTORY, not same string. `os.path.realpath` is the comparison `isolation_violation`
|
||||
# itself makes, so this asserts the contract the guard depends on; requiring byte equality
|
||||
# would redden on a trailing slash that changes nothing about where the records land, and a
|
||||
# guard nobody believes is the failure this file exists to avoid. A genuine divergence — a
|
||||
# DIFFERENT directory — still fails, because realpath does not collapse those.
|
||||
assert os.path.realpath(res.stdout) == os.path.realpath(resolved_log_dir(case)), (
|
||||
f"the Python resolver and `etv_hook_fire_log_dir` resolve to DIFFERENT directories for "
|
||||
f"{case}: the sink says {res.stdout!r}, resolved_log_dir says "
|
||||
f"{str(resolved_log_dir(case))!r}. The guard would clear a launch the sink then points "
|
||||
"somewhere else."
|
||||
)
|
||||
|
||||
|
||||
def test_a_launch_NOT_CARRYING_the_isolated_log_dir_FAILS_THE_LAUNCH():
|
||||
"""The launch guard, driven end to end — the route pre-collection isolation cannot reach.
|
||||
|
||||
An environment assembled from scratch rather than derived from `os.environ` carries no
|
||||
`ETV_HOOK_FIRE_LOG_DIR`, so the sink falls back to its own default. No snapshot is involved, so
|
||||
nothing about import ordering helps. This is not hypothetical: three suites build exactly that
|
||||
environment for the CI-shaped children they run, and they were found by MEASURING every launch
|
||||
the suite makes, not by reading it.
|
||||
|
||||
BOTH FALLBACK BRANCHES ARE PINNED, because a guard that compared against one resolved production
|
||||
path would pass the other. `${HOME:-/tmp}` means a child with no `HOME` lands in
|
||||
`/tmp/.cache/ersatztv/hook-fire` — just as shared, just as persistent, and on this suite that was
|
||||
the majority case: of the 83 from-scratch launches, 81 also carry no `HOME`.
|
||||
|
||||
The negative control is the last case — a guard that rejected every launch would satisfy all
|
||||
three assertions above it and be useless.
|
||||
"""
|
||||
guard = getattr(subprocess.Popen, "etv_production_log_guard", None)
|
||||
assert guard is not None, (
|
||||
"the launch guard is not installed, so this test would pass by never being consulted. "
|
||||
"conftest.py's `pytest_configure` should have installed it."
|
||||
)
|
||||
# INSTALLED IS NOT CONSULTED — but state precisely what this proves, because the obvious
|
||||
# reading is wider than the fact. `checked` counts launches the wrapper has already seen, and
|
||||
# this module's own `@pytest.mark.parametrize(... hook_scripts())` decorators shell out to
|
||||
# `git ls-files` at IMPORT, so it is >= 2 even when this test is selected alone. What that
|
||||
# establishes is that installation happened BEFORE this module was collected — i.e. the wrapper
|
||||
# is in the path of launches made outside this test. Run alone, those are this module's own
|
||||
# collection-time `git ls-files` calls, so it does order installation before collection; in a
|
||||
# whole-suite run the counted launches may all belong to other modules, and it establishes only
|
||||
# that the wrapper is consulted at all. It does NOT establish whole-suite coverage — nothing
|
||||
# here could, since a launch that never reaches `Popen` is invisible by construction.
|
||||
assert guard.checked > 0, (
|
||||
"the launch guard has been consulted for no launch at all before this test, so it was "
|
||||
"installed after this module was collected and cannot have seen collection-time launches"
|
||||
)
|
||||
|
||||
def launch(env, cwd=None):
|
||||
return subprocess.run(["bash", "-c", "true"], env=env, cwd=cwd, capture_output=True, timeout=60)
|
||||
|
||||
# HOME is COPIED IF PRESENT rather than read with `os.environ["HOME"]`: an environment without
|
||||
# it is legal — the sink has a `${HOME:-/tmp}` default precisely for that — and indexing would
|
||||
# raise KeyError, reddening this test on a valid checkout for a reason unrelated to the guard.
|
||||
scratch = {"PATH": os.environ["PATH"]}
|
||||
if os.environ.get("HOME"):
|
||||
scratch["HOME"] = os.environ["HOME"]
|
||||
|
||||
# (1) the `$HOME` branch
|
||||
with pytest.raises(AssertionError, match="carrying no ETV_HOOK_FIRE_LOG_DIR"):
|
||||
launch(scratch)
|
||||
|
||||
# (2) the `/tmp` branch — no HOME either. This is the one a production-path comparison misses.
|
||||
with pytest.raises(AssertionError, match="carrying no ETV_HOOK_FIRE_LOG_DIR"):
|
||||
launch({"PATH": os.environ["PATH"]})
|
||||
|
||||
# (3) the variable set, and set WRONG. Omitting it is not the only way to reach a shared log,
|
||||
# and BOTH shared logs are rejected — the likeliest wrong value is the sink's own default
|
||||
# transliterated into a `dict.get(k, "<default>")`, which reaches whichever branch that default
|
||||
# was copied from. Pinning only the `$HOME` one would leave the `/tmp` one clear.
|
||||
for shared in SHARED_LOG_DIRS:
|
||||
with pytest.raises(AssertionError, match="inside a shared hook-fire log"):
|
||||
launch({**scratch, ENV_VAR: str(shared)})
|
||||
|
||||
# (4) a SUBDIRECTORY of a shared log. `etv_hook_fire_report` reads its directory with a
|
||||
# recursive `find`, so records here are picked up by `hook-fire-log.sh report --dir <shared>`
|
||||
# exactly like ones at its root — verified by driving a real hook into a nested directory and
|
||||
# seeing it counted. An equality test would call this clean.
|
||||
with pytest.raises(AssertionError, match="inside a shared hook-fire log"):
|
||||
launch({**scratch, ENV_VAR: str(SHARED_LOG_DIRS[0] / "sub")})
|
||||
|
||||
# (5) the variable set RELATIVE, with a `cwd` that makes it land on a shared log. Found by
|
||||
# cross-family review as a live bypass: a relative value resolves against the CHILD's directory,
|
||||
# so a guard anchoring it at the parent's sees an unrelated path under the repo and clears it.
|
||||
# The guard raises before `Popen` runs anything, so this launch never enters that directory.
|
||||
shared = SHARED_LOG_DIRS[0]
|
||||
with pytest.raises(AssertionError, match="inside a shared hook-fire log"):
|
||||
launch({**scratch, ENV_VAR: ".cache/ersatztv/hook-fire"}, cwd=shared.parent.parent.parent)
|
||||
|
||||
# (6) NEGATIVE CONTROL: carrying the isolated dir, the same launch must go through.
|
||||
ok = launch({**scratch, ENV_VAR: os.environ[ENV_VAR]})
|
||||
assert ok.returncode == 0, "the guard rejected a correctly-isolated launch"
|
||||
|
||||
|
||||
# The specimen the mutation proof below runs in a nested pytest: #785's shape, reduced to the one
|
||||
# thing that matters. The hook it drives is written beside the sandbox rather than inline here, so
|
||||
# this source carries no nested escaping.
|
||||
_SPECIMEN_MODULE = """\
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
_ENV = {**os.environ} # snapshotted at IMPORT, before any fixture has run — this is the defect
|
||||
|
||||
HOOK = Path(__file__).resolve().parents[2] / "specimen-hook.sh"
|
||||
|
||||
|
||||
def test_specimen_drives_a_hook():
|
||||
subprocess.run(
|
||||
["bash", str(HOOK)],
|
||||
input=b'{"session_id":"specimen"}',
|
||||
capture_output=True,
|
||||
env=_ENV,
|
||||
timeout=60,
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
def test_the_guard_JUDGES_every_env_and_cwd_SHAPE_that_Popen_ACCEPTS(tmp_path):
|
||||
"""`env` and `cwd` each have several legal shapes; the guard must judge, not crash, on all.
|
||||
|
||||
`Popen` accepts `cwd` as str, bytes or `PathLike`. The first version of the relative-path
|
||||
anchoring called `os.fspath(cwd)` and then `os.path.join`, which raises `TypeError` on mixing
|
||||
str with bytes — a guard that raises `TypeError` on a legitimate launch is not a stricter guard,
|
||||
it is a broken one, and the failure names the wrong thing entirely.
|
||||
|
||||
THE PREMISE IS PINNED, not assumed. A file descriptor is NOT a fourth shape: `Popen` calls
|
||||
`os.fsencode(cwd)`, which rejects an int. A previous version of the guard added a branch for
|
||||
that case; the branch was dead — `os.fspath` already raises on an int — and deleting it left its
|
||||
own test green, so it was removed rather than proved. The assertion below is what makes that
|
||||
removal safe: if a future CPython starts accepting a descriptor, this goes red and says so.
|
||||
"""
|
||||
# A RELATIVE value, so the anchoring is actually REACHED. An absolute one short-circuits before
|
||||
# `cwd` is consulted at all — an earlier draft of this test used one and passed identically for
|
||||
# every shape, including shapes that crashed the guard the moment anything relative arrived.
|
||||
relative = {ENV_VAR: "isolated/log"}
|
||||
for cwd in (str(tmp_path), tmp_path, os.fsencode(str(tmp_path))):
|
||||
assert isolation_violation(relative, cwd) is None, (
|
||||
f"a relative log dir under {tmp_path} was rejected for cwd={cwd!r} — it resolves inside "
|
||||
"the test's own directory, so this is the guard failing rather than judging"
|
||||
)
|
||||
|
||||
isolated = {ENV_VAR: str(tmp_path / "log")}
|
||||
assert isolation_violation(isolated, None) is None, "an absolute isolated dir was rejected"
|
||||
|
||||
# AND THE ANCHOR MUST BIND TO THE LAUNCH'S cwd, for every shape — not merely fail to crash.
|
||||
# The same relative value judged against two different `cwd`s must give two different verdicts;
|
||||
# otherwise `cwd` is being ignored, which is the round-3 defect, and the shape loop above would
|
||||
# pass while it was.
|
||||
shared_parent = SHARED_LOG_DIRS[0].parent.parent.parent
|
||||
for shape in (str, Path, os.fsencode):
|
||||
onto_shared = shape(str(shared_parent))
|
||||
assert isolation_violation({ENV_VAR: ".cache/ersatztv/hook-fire"}, onto_shared) is not None, (
|
||||
f"a relative log dir was cleared for cwd={onto_shared!r} even though it resolves onto a "
|
||||
"shared log — the anchor is not binding to the launch's cwd for this shape"
|
||||
)
|
||||
assert isolation_violation({ENV_VAR: ".cache/ersatztv/hook-fire"}, shape(str(tmp_path))) is None, (
|
||||
f"the same relative log dir was rejected for cwd={tmp_path} — the anchor is not binding "
|
||||
"to the launch's cwd, so both verdicts come from somewhere else"
|
||||
)
|
||||
|
||||
# THE ENV HAS SHAPES TOO. `Popen` accepts a bytes-keyed and/or bytes-valued environment on
|
||||
# POSIX (verified: both launch). Unnormalised, a bytes KEY makes the lookup miss and the launch
|
||||
# is rejected as carrying no isolated dir; a bytes VALUE makes `Path(...)` raise. Both are reds
|
||||
# on a correctly isolated child.
|
||||
log = str(tmp_path / "log")
|
||||
for env in (
|
||||
{os.fsencode(ENV_VAR): os.fsencode(log), b"PATH": b"/usr/bin"},
|
||||
{ENV_VAR: os.fsencode(log), "PATH": "/usr/bin"},
|
||||
):
|
||||
assert isolation_violation(env) is None, (
|
||||
f"a correctly isolated child was rejected for a legal env encoding: {env!r}"
|
||||
)
|
||||
# ...and the decoding must not blunt the guard: the same encoding pointed at a shared log fails.
|
||||
assert isolation_violation({os.fsencode(ENV_VAR): os.fsencode(str(SHARED_LOG_DIRS[0]))}) is not None, (
|
||||
"normalising the env encoding also stopped the guard seeing a shared log through it"
|
||||
)
|
||||
|
||||
fd = os.open(str(tmp_path), os.O_RDONLY)
|
||||
try:
|
||||
with pytest.raises(TypeError):
|
||||
subprocess.run(
|
||||
["bash", "-c", "true"],
|
||||
cwd=fd,
|
||||
env={"PATH": os.environ["PATH"], **isolated},
|
||||
capture_output=True,
|
||||
timeout=60,
|
||||
)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def test_REMOVING_the_pre_collection_isolation_LETS_an_IMPORT_TIME_snapshot_LEAK(tmp_path):
|
||||
"""THE MUTATION PROOF FOR THE CROSS-SUITE CLAUSE — the #785 defect, reproduced and neutralised.
|
||||
|
||||
Both arms are a real nested pytest over an identical sandbox with a FAKE `HOME`, so nothing here
|
||||
touches the machine's own log. The specimen module is the #785 shape verbatim: `{**os.environ}`
|
||||
at module level, handed to a hook subprocess.
|
||||
|
||||
ONE clause differs between the arms — `os.environ[ENV_VAR] = _SESSION_LOG_DIR` in
|
||||
`pytest_configure`. Remove it and the specimen's records land in the fake production directory;
|
||||
restore it and they do not. That is what makes the pre-collection assignment load-bearing rather
|
||||
than decorative, and it is the red #809 asks to witness.
|
||||
|
||||
WHAT IT NO LONGER TRAVERSES, since the fake directory is handed over explicitly: the sink's
|
||||
`${ETV_HOOK_FIRE_LOG_DIR:-${HOME:-/tmp}/…}` fallback. The mutant arm now leaks by INHERITANCE
|
||||
rather than by fallback, so deleting that expansion outright leaves both arms unchanged —
|
||||
measured. That is covered instead by
|
||||
`test_the_resolver_agrees_with_the_SINKS_OWN_expansion`, which reddens on the same deletion.
|
||||
The proof remains sensitive to the weakening that matters here: replacing the assignment with
|
||||
`os.environ.setdefault(...)` makes the control arm leak.
|
||||
|
||||
THE MEASUREMENT ARRANGEMENT, stated because it is a deliberate weakening: the launch guard is
|
||||
disabled in BOTH arms. Left on, it would reject the specimen's launch in the mutant arm and the
|
||||
comparison would be about the guard rather than about the clause under test. Both arms are
|
||||
otherwise byte-identical, so the difference measured is the clause's alone.
|
||||
"""
|
||||
real_conftest = (REPO_ROOT / "scripts" / "tests" / "conftest.py").read_text()
|
||||
install_clause = " _GUARD.install()\n"
|
||||
isolate_clause = " os.environ[ENV_VAR] = _SESSION_LOG_DIR\n"
|
||||
for clause in (install_clause, isolate_clause):
|
||||
assert real_conftest.count(clause) == 1, (
|
||||
f"the clause {clause!r} has moved or changed in conftest.py, so this proof no longer "
|
||||
"targets it. RETARGET it rather than loosening the match — a mutation that silently "
|
||||
"stops mutating proves nothing, which is the failure class this file exists to catch."
|
||||
)
|
||||
|
||||
def arm(name: str, conftest_text: str) -> set[str]:
|
||||
sb = tmp_path / name
|
||||
(sb / "scripts" / "tests").mkdir(parents=True)
|
||||
(sb / "scripts" / "__init__.py").write_text("")
|
||||
(sb / "scripts" / "tests" / "__init__.py").write_text("")
|
||||
shutil.copy(SINK, sb / "scripts" / "hook-fire-log.sh")
|
||||
(sb / "specimen-hook.sh").write_text(
|
||||
"#!/usr/bin/env bash\nset -uo pipefail\n"
|
||||
f'. "{sb}/scripts/hook-fire-log.sh"\n'
|
||||
'etv_hook_fire_begin specimen "" capture || true\n'
|
||||
"input=$(cat)\n"
|
||||
)
|
||||
shutil.copy(REPO_ROOT / "scripts" / "tests" / "hook_fire_isolation.py", sb / "scripts" / "tests")
|
||||
(sb / "scripts" / "tests" / "conftest.py").write_text(conftest_text)
|
||||
(sb / "scripts" / "tests" / "test_specimen.py").write_text(_SPECIMEN_MODULE)
|
||||
home = sb / "home"
|
||||
home.mkdir()
|
||||
leaked = home / ".cache" / "ersatztv" / "hook-fire"
|
||||
res = subprocess.run(
|
||||
[sys.executable, "-m", "pytest", "-q", "scripts/tests/test_specimen.py"],
|
||||
cwd=str(sb),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
# The fake production dir is handed over EXPLICITLY, and `HOME` points at the same tree
|
||||
# as a backstop. Passing it explicitly is what lets this launch satisfy the launch guard
|
||||
# like every other one, and it sharpens the proof rather than weakening it: the mutant
|
||||
# arm inherits this value because its `pytest_configure` no longer overwrites it, the
|
||||
# control arm does not because its does. The clause under test IS that overwrite.
|
||||
env={"PATH": os.environ["PATH"], "HOME": str(home), ENV_VAR: str(leaked)},
|
||||
timeout=300,
|
||||
)
|
||||
assert res.returncode == 0, f"the {name} arm's specimen run did not pass:\n{res.stdout}\n{res.stderr}"
|
||||
return {f.name for f in leaked.glob("*.jsonl")} if leaked.exists() else set()
|
||||
|
||||
mutant = arm("mutant", real_conftest.replace(install_clause, "").replace(isolate_clause, ""))
|
||||
control = arm("control", real_conftest.replace(install_clause, ""))
|
||||
|
||||
# The mutant arm is also this proof's anti-vacuity check: if the specimen logged nowhere, the
|
||||
# control arm's emptiness would be about a dead hook rather than about the isolation.
|
||||
assert "specimen.jsonl" in mutant, (
|
||||
"removing the pre-collection isolation did NOT make an import-time snapshot leak, so this "
|
||||
f"proof establishes nothing about that clause. Fake-home log dir held: {sorted(mutant)}"
|
||||
)
|
||||
assert control == set(), (
|
||||
"an import-time `{**os.environ}` snapshot still reaches the production log with the "
|
||||
f"pre-collection isolation in place — it leaked {sorted(control)}. That is #785's defect, "
|
||||
"and the cross-suite claim in this file is false."
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user