Files
OBLITERATUS/scripts/conditional_gate_metadata.py
T
Joseph MaglyandClaude Opus 5.5 ce9f7efd9b Allowlist the git environment instead of denylisting overrides
Review r4: inherited GIT_TRACE* survived sanitization, and a trace aimed at
/dev/stdout corrupted the captured SHA and status ("local", dirty). This
was the third surviving-GIT_* finding, so close the class: drop every
inherited GIT_* variable and set only GIT_OPTIONAL_LOCKS=0,
GIT_TERMINAL_PROMPT=0 and GIT_NO_LAZY_FETCH=1.

The sanitizer test now requires exactly those three GIT_* names (including
when an unknown GIT_* control is inherited). A real-git regression test
aims each of GIT_TRACE, GIT_TRACE_SETUP, GIT_TRACE2, GIT_TRACE2_EVENT and
GIT_TRACE2_PERF at /dev/stdout and requires the checkout's clean HEAD.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:32:16 -04:00

60 lines
2.2 KiB
Python

"""Shared Git metadata for conditional gate reports and workflow summaries."""
from __future__ import annotations
import os
import re
import subprocess
from pathlib import Path
def _git_environment() -> dict[str, str]:
# Allowlist, not a denylist: inherited GIT_* variables can redirect the
# repository, index or object store, inject config, redirect stdio or write
# trace output into captured stdout. Drop every one, then set only what this
# read-only metadata query needs. PATH, HOME, locale etc. are inherited.
environment = {
name: value for name, value in os.environ.items() if not name.startswith("GIT_")
}
environment["GIT_OPTIONAL_LOCKS"] = "0" # status must not refresh the on-disk index.
environment["GIT_TERMINAL_PROMPT"] = "0" # never block on a credential prompt.
environment["GIT_NO_LAZY_FETCH"] = "1" # partial clones must not fetch from a remote.
return environment
def _git_output(*arguments: str) -> str | None:
"""Read Git metadata from this script's repository, regardless of cwd."""
try:
result = subprocess.run(
["git", "-C", str(Path(__file__).resolve().parents[1]), *arguments],
env=_git_environment(),
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=5,
check=False,
)
except (OSError, subprocess.TimeoutExpired, UnicodeError):
return None
return result.stdout.strip() if result.returncode == 0 else None
def _resolve_git_sha() -> str:
candidate = os.environ.get("GITHUB_SHA")
if candidate and re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", candidate):
return candidate
candidate = _git_output("rev-parse", "HEAD")
if candidate and re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", candidate):
return candidate
return "local"
def git_metadata() -> dict[str, str | bool | None]:
"""Return a validated SHA and tracked-worktree status, when available."""
git_sha = _resolve_git_sha()
git_status = _git_output("status", "--porcelain", "--untracked-files=no")
return {
"git_sha": git_sha,
"git_dirty": None if git_status is None else bool(git_status),
}