Files

108 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""Run one git command for a bench review, confined to the clone: review_git.py <subcommand> <args>...
The bench's review runs no bare git: this wrapper is its one allowed shell command (bench.py's
permission_flags). bench.py names the clone in REVIEW_GIT_CLONE, and git runs there whatever the
working directory, with GIT_DIR and GIT_WORK_TREE pinned to it.
The wrapper refuses every subcommand and option ALLOWED does not list, so a cluster of short options
or a long option cut to a prefix is refused too. An option that takes a value takes it glued, as
`--grep=fix`. A commit needs `-m`, whose value is the one free-text argument. Every other argument
must name no path outside the clone. git runs with no global or system config, hook, pager or editor.
The wrapper checks the arguments git receives, after the shell has removed quotes and expanded `$`,
so no quoting hides a path from it. It lives outside the clone, so a module planted in the clone
cannot replace `os` or `subprocess`.
"""
from collections.abc import Callable
import os
import re
import subprocess
import sys
OUTPUT = {"--name-only", "--name-status", "--no-color", "--stat", "--unified="}
# An entry ending in "=" allows that option with any glued value.
ALLOWED = {
"add": {"-A", "--all", "-u", "--update"},
"commit": {"-a", "--all"},
"diff": OUTPUT | {"--cached", "--check", "--staged", "--word-diff"},
"log": OUTPUT | {"--author=", "--decorate", "--follow", "--graph", "--grep=", "--max-count=",
"--oneline", "-p", "--patch", "--reverse", "--since=", "--until="},
"ls-files": {"--cached", "--deleted", "--exclude-standard", "--modified", "--others"},
"show": OUTPUT | {"--no-patch", "--oneline", "-s"},
"status": {"-b", "--branch", "--porcelain", "-s", "--short"},
}
# The commit identity, since no config supplies one.
BENCH_IDENTITY = {"GIT_AUTHOR_NAME": "bench", "GIT_AUTHOR_EMAIL": "bench@localhost",
"GIT_COMMITTER_NAME": "bench", "GIT_COMMITTER_EMAIL": "bench@localhost"}
GIT = ["git", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "core.pager=cat"]
def allowed_option(sub: str, token: str) -> bool:
options = ALLOWED[sub]
glued = any(token.startswith(option) for option in options if option.endswith("="))
return token in options or glued or (sub == "log" and re.fullmatch(r"-[0-9]+", token) is not None)
def outside_clone(token: str, escapes: Callable[[str], bool]) -> bool:
# A revision range such as a..b is checked side by side, so `..` cannot climb out of the clone:
# ../x splits into "" and "/x". A leading ":" is pathspec magic, which can name the repository's top.
sides = re.split(r"\.\.\.?", token)
return token.startswith(":") or escapes(token) or any(side.startswith(("/", "~")) or escapes(side) for side in sides)
def refusal(argv: list[str], escapes: Callable[[str], bool]) -> str | None:
"""Why the wrapper refuses `git <argv>`, or None; escapes(path) is whether path names an existing file outside the clone."""
if not argv or argv[0] not in ALLOWED:
return f"subcommand must be one of {' '.join(sorted(ALLOWED))}"
sub = argv[0]
has_message = operands_only = message_next = False
for token in argv[1:]:
if message_next:
message_next = False
elif operands_only or not token.startswith("-"):
if outside_clone(token, escapes):
return f"argument names a path outside the clone: {token}"
elif token == "--":
operands_only = True
elif sub == "commit" and token in ("-m", "-am", "--message"):
has_message = message_next = True
elif sub == "commit" and token.startswith(("-m", "--message=")):
has_message = True
elif not allowed_option(sub, token):
return f"option not allowed: {token}; {sub} takes {' '.join(sorted(ALLOWED[sub]))}"
if sub == "commit" and not has_message:
return "commit needs -m <message>"
return None
def git_env(environ: dict[str, str], clone: str) -> dict[str, str]:
"""The inherited environment without any variable that names a program or a repository, with git pinned to the clone."""
kept = {name: value for name, value in environ.items()
if not name.startswith("GIT_") and name not in ("EDITOR", "PAGER", "SSH_ASKPASS", "VISUAL")}
return {**kept, **BENCH_IDENTITY, "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1", "GIT_DIR": os.path.join(clone, ".git"),
"GIT_EDITOR": "true", "GIT_PAGER": "cat", "GIT_TERMINAL_PROMPT": "0", "GIT_WORK_TREE": clone}
def escapes(clone: str, path: str) -> bool:
target = os.path.realpath(os.path.join(clone, path))
return os.path.lexists(target) and os.path.commonpath([clone, target]) != clone
def refuse(reason: str) -> int:
print(f"review_git.py: refused: {reason}", file=sys.stderr)
return 2
def main(argv: list[str], environ: dict[str, str]) -> int:
if not environ.get("REVIEW_GIT_CLONE"):
return refuse("REVIEW_GIT_CLONE must name the clone")
clone = os.path.realpath(environ["REVIEW_GIT_CLONE"])
reason = refusal(argv, lambda path: escapes(clone, path))
if reason is not None:
return refuse(reason)
return subprocess.run([*GIT, *argv], cwd=clone, env=git_env(environ, clone)).returncode
if __name__ == "__main__":
sys.exit(main(sys.argv[1:], dict(os.environ)))