Skip to content
Open
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
18 changes: 16 additions & 2 deletions infra/promote-main.sh
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,29 @@ trap cleanup_validate_dir EXIT
git worktree add --detach "$validate_dir" "$target" >/dev/null 2>&1 || \
fail "could not create a validation worktree for $target"

# The candidate suite must be hermetic: this host exports catalog connection
# settings for its own services, and a test that defaults to one of them would
# act on the production catalog. Drop every PG* and *DSN* variable for the
# suite only (names are logged, never values); the rest of the environment,
# PATH included, is unchanged.
validation_env_unset=()
unset_names=()
while IFS= read -r name; do
case "$name" in
PG*|*DSN*) validation_env_unset+=(-u "$name"); unset_names+=("$name") ;;
esac
done < <(compgen -e)

echo "validating_candidate: $target (isolated worktree: $validate_dir)"
if ! (cd "$validate_dir" && python3 tools/run_tests.py); then
echo "validation_env_unset: ${unset_names[*]:-none}"
if ! (cd "$validate_dir" && env ${validation_env_unset[@]+"${validation_env_unset[@]}"} python3 tools/run_tests.py); then
echo "promote-main: FATAL: candidate $target failed validation in an isolated worktree." >&2
echo " operational checkout was NOT moved." >&2
echo " previous_sha (still checked out) = $sha" >&2
echo " target_sha (rejected candidate) = $target" >&2
echo " next: inspect the candidate manually, e.g.:" >&2
echo " git worktree add --detach /tmp/promote-inspect $target" >&2
echo " cd /tmp/promote-inspect && python3 tools/run_tests.py" >&2
echo " cd /tmp/promote-inspect && env -u CATALOG_DSN python3 tools/run_tests.py # and every other PG*/*DSN* variable" >&2
exit 1
fi

Expand Down
39 changes: 38 additions & 1 deletion tests/test_l2_golden_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import dataclasses
import io
import json
import os
from pathlib import Path
import shutil
import sys
Expand Down Expand Up @@ -63,6 +64,13 @@ class Base(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp(prefix="l2-golden-"))
self.addCleanup(shutil.rmtree, self.tmp, True)
# Tripwire: nothing in this file may publish into a catalog (tests/integration_l2_golden_postgres.py owns that leg).
leg = mock.patch.object(
golden_module, "_catalog_leg",
side_effect=AssertionError("a unit test reached the catalog leg: a DSN leaked in from the environment"),
)
leg.start()
self.addCleanup(leg.stop)

def archive(self, messages, day=DAY, **kwargs):
return fixtures.make_archive(self.tmp, day, messages, **kwargs)
Expand Down Expand Up @@ -318,9 +326,14 @@ def test_a_conflicting_duplicate_is_refused_with_its_typed_code(self):


class ToolTests(Base):
EXPORTED_DSN = "host=catalog.invalid dbname=must_not_be_used"

def run_tool(self, *argv):
out, err = io.StringIO(), io.StringIO()
code = l2_golden_e2e.run(list(argv), out=out, err=err)
# The tool defaults --dsn to CATALOG_DSN: the shell that runs the suite must never choose the catalog.
with mock.patch.dict(os.environ):
os.environ.pop("CATALOG_DSN", None)
code = l2_golden_e2e.run(list(argv), out=out, err=err)
return code, out.getvalue(), err.getvalue()

def base_args(self, archive):
Expand Down Expand Up @@ -367,6 +380,30 @@ def fake(*args, **kwargs):
self.run_tool(*self.base_args(self.archive(fixtures.CLEAN)))
self.assertTrue(seen["reproduce"])

def test_the_tool_itself_still_defaults_the_dsn_to_catalog_dsn(self):
with mock.patch.dict(os.environ, {"CATALOG_DSN": self.EXPORTED_DSN}):
args = l2_golden_e2e.build_parser().parse_args(self.base_args(self.tmp / "x.zip"))
self.assertEqual(args.dsn, self.EXPORTED_DSN)

def test_an_exported_catalog_dsn_is_never_forwarded_by_the_tool_tests(self):
seen = {}

def fake(*args, **kwargs):
seen.update(kwargs)
return {"ok": True, "claims": []}

with mock.patch.dict(os.environ, {"CATALOG_DSN": self.EXPORTED_DSN}), mock.patch.object(l2_golden_e2e, "run_l2_golden", fake):
self.run_tool(*self.base_args(self.archive(fixtures.CLEAN)))
self.assertIsNone(seen["dsn"])

def test_the_real_success_path_with_an_exported_catalog_dsn_never_reaches_the_catalog_leg(self):
with mock.patch.dict(os.environ, {"CATALOG_DSN": self.EXPORTED_DSN}):
code, out, err = self.run_tool(*self.base_args(self.archive(fixtures.ONE_GAP)))
self.assertEqual(os.environ["CATALOG_DSN"], self.EXPORTED_DSN, "the test must restore the caller's environment")
self.assertEqual(code, 0, err)
self.assertIsNone(json.loads(out)["catalog"])
golden_module._catalog_leg.assert_not_called()


if __name__ == "__main__":
unittest.main()
52 changes: 52 additions & 0 deletions tests/test_promote_main_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,28 @@ def _write_candidate_commit_that_pushes_a_sneaky_commit_during_validation(
return _git(["rev-parse", "HEAD"], cwd=repo, env=env).stdout.strip()


def _write_candidate_commit_that_audits_its_validation_environment(repo: Path, *, message: str, env: dict[str, str]) -> str:
"""A candidate whose validation step passes only when no catalog connection variable reached it.

Any PG* or *DSN* variable fails it (named on stdout, never its value); the sentinel proves the rest of the
environment is passed through, so the check cannot pass because the environment was lost altogether."""
tools_dir = repo / "tools"
tools_dir.mkdir(parents=True, exist_ok=True)
(tools_dir / "run_tests.py").write_text(
"""import os, sys
leaked = sorted(name for name in os.environ if name.upper().startswith('PG') or 'DSN' in name.upper())
kept = os.environ.get('QP_PROMOTE_TEST_KEEP')
print('validation_environment leaked=%s kept=%s' % (','.join(leaked) or 'none', kept))
sys.exit(1 if leaked or kept != '1' else 0)
""",
encoding="utf-8",
)
shutil.copyfile(REPO_IDENTITY_SCRIPT, tools_dir / "repo_identity.py")
_git(["add", "-A"], cwd=repo, env=env)
_git(["commit", "-m", message], cwd=repo, env=env)
return _git(["rev-parse", "HEAD"], cwd=repo, env=env).stdout.strip()


class PromoteMainValidatesBeforeAdvancingTests(unittest.TestCase):
def setUp(self):
_require("bash")
Expand Down Expand Up @@ -256,6 +278,36 @@ def test_passing_candidate_is_validated_then_fast_forwarded(self):
self.assertIn("validating_candidate", result.stdout)
self.assertIn("post_promotion_identity", result.stdout)

def test_validation_runs_without_catalog_connection_variables(self):
"""The operational host exports its catalog settings; the candidate suite must not inherit them (#536)."""
candidate_sha = _write_candidate_commit_that_audits_its_validation_environment(
self.author_repo, message="audits the validation environment", env=self.env
)
_git(["push", "-q", str(self.origin_bare), "main"], cwd=self.author_repo, env=self.env)
secret = "must-not-appear-in-the-log"
exported = {
"CATALOG_DSN": f"host=catalog.invalid password={secret}",
"QP_RUNTIME_DSN": "host=runtime.invalid",
"DATA_GATEWAY_TEST_DSN": "host=test.invalid",
"PGHOST": "catalog.invalid",
"PGPASSWORD": secret,
"PGSERVICE": "production",
"QP_PROMOTE_TEST_KEEP": "1",
}
self.env.update(exported)

result = self._run_promote()

output = result.stdout + result.stderr
self.assertEqual(0, result.returncode, output)
self.assertEqual(candidate_sha, self._current_sha())
self.assertIn("validation_environment leaked=none kept=1", result.stdout)
unset_line = next(line for line in result.stdout.splitlines() if line.startswith("validation_env_unset:"))
for name in ("CATALOG_DSN", "QP_RUNTIME_DSN", "DATA_GATEWAY_TEST_DSN", "PGHOST", "PGPASSWORD", "PGSERVICE"):
self.assertIn(name, unset_line.split())
self.assertNotIn("QP_PROMOTE_TEST_KEEP", unset_line)
self.assertNotIn(secret, output, "only the names of the dropped variables may be logged")

def test_merge_stays_pinned_to_the_validated_oid_despite_a_concurrent_push(self):
"""Review-caught race: origin/main is a mutable local ref. If the
final merge re-resolved it instead of merging the already-validated
Expand Down
Loading