diff --git a/repo-stats/README.adoc b/repo-stats/README.adoc index 3c9a686..e86da45 100644 --- a/repo-stats/README.adoc +++ b/repo-stats/README.adoc @@ -63,6 +63,7 @@ Repositories that rebase-merge with no PR number in the message show few or no P Lines of code, churn and release data always come from the local clone. A shallow clone gives incomplete history, and the dashboard warns about it. Run `git fetch --unshallow` first. +repo-stats never downloads missing objects of a partial clone (`--filter`, or the `filter` input of `actions/checkout`), so on such a clone it warns, and stops if the history it needs is not local. Clone without a filter. == Time window @@ -130,21 +131,29 @@ jobs: steps: - uses: actions/checkout@v4 with: + path: repo # the repository to analyse fetch-depth: 0 # full history and tags + persist-credentials: false # keep the job token out of repo/.git/config - uses: actions/checkout@v4 with: repository: husam-e/scripts ref: # pin a commit you have reviewed: it runs next to the token path: tools - - run: python3 tools/repo-stats/repo_stats.py . -o repo-stats.html + persist-credentials: false + - run: python3 tools/repo-stats/repo_stats.py repo -o "$RUNNER_TEMP/repo-stats.html" env: GH_TOKEN: ${{ github.token }} # read by gh only; expires when the job ends - uses: actions/upload-artifact@v4 with: name: repo-stats - path: repo-stats.html + path: ${{ runner.temp }}/repo-stats.html ---- +* Update the pinned `ref:` on purpose, after reading the changes. For stricter pinning, also pin `actions/checkout` and `actions/upload-artifact` to commit SHAs. +* `persist-credentials: false` stops `actions/checkout` from saving the job token in the checkout's git config, where any later process could read it. +* The analysed repository is checked out in its own directory (`repo`), and the dashboard is written to `$RUNNER_TEMP`, outside it. + Never write outputs into a checkout you do not trust: it could contain a symlink at the output path. (repo-stats refuses to write through a symlink, but the safest output is one outside the checkout.) + Set `GH_TOKEN` on this step only, so other steps never see it. On GitHub Enterprise Server, set `GH_ENTERPRISE_TOKEN: ${{ github.token }}` instead; `gh` ignores `GH_TOKEN` there. To analyse another private repository, use a GitHub App installation token (for example from `actions/create-github-app-token`), not a personal token. @@ -154,7 +163,8 @@ To analyse another private repository, use a GitHub App installation token (for [source,yaml] ---- repo-stats: - image: registry.gitlab.com/gitlab-org/cli:v1.124.0 # glab and git; pin a version + # glab and git. Replace with the image's digest (see below), so the tag cannot be moved under you. + image: registry.gitlab.com/gitlab-org/cli:v1.124.0@sha256: variables: GIT_DEPTH: 0 # full history GLAB_ENABLE_CI_AUTOLOGIN: "true" # glab signs in with the job's CI_JOB_TOKEN @@ -164,11 +174,16 @@ repo-stats: - git init -q /tmp/tools - git -C /tmp/tools fetch -q --depth 1 https://github.com/husam-e/scripts.git "$REPO_STATS_SHA" - git -C /tmp/tools checkout -q FETCH_HEAD - - python3 /tmp/tools/repo-stats/repo_stats.py . -o repo-stats.html + - mkdir repo-stats-out # new directory: fails if the repository has this path + - python3 /tmp/tools/repo-stats/repo_stats.py . -o repo-stats-out/repo-stats.html artifacts: - paths: [repo-stats.html] + paths: [repo-stats-out/repo-stats.html] ---- +* Get the image digest with `docker buildx imagetools inspect registry.gitlab.com/gitlab-org/cli:v1.124.0` (or `crane digest`), and update tag and digest together. +* GitLab collects artifacts only from inside the project directory, so the dashboard goes into a directory the job creates. + `mkdir` fails if the analysed repository already contains that path, for example as a symlink. + The job token expires when the job ends. It can list merge requests and read their comments, but not their commits. repo-stats then takes first-commit times from local merge commits and says so on the dashboard; squash-merged MRs have no coding time. For full data, add a project access token with only the `read_api` scope and a short expiry as a masked, protected CI/CD variable named `GITLAB_TOKEN`. @@ -195,7 +210,8 @@ Avoid `gh auth login` and `glab auth login` on servers: with no keychain, they s repo-stats only reads: * API requests go through `gh api` and `glab api` and pass a fixed allowlist: GraphQL queries only (never a mutation) for GitHub, and `GET` on the merge request list, commits and notes endpoints for GitLab. Anything else is refused before a process starts. -* git is run only with read commands (`log`, `rev-parse`, `for-each-ref`, `symbolic-ref`, `remote get-url`). +* git is run only with read commands (`log`, `rev-parse`, `for-each-ref`, `symbolic-ref`, `remote get-url`, `config --get-regexp`). + It never fetches: missing objects of a partial clone are not downloaded (`GIT_NO_LAZY_FETCH=1`, and `protocol.allow=never` for older git). * The tests enforce both rules. Only a read-only token makes this a guarantee: with a `gh auth login` or `glab auth login` token, the rules protect against bugs, not against a modified copy of the script. @@ -205,12 +221,18 @@ repo-stats never handles a credential: * It never reads a token variable. `gh` and `glab` read their own. * The API host is `github.com` or `gitlab.com` from the remote, or the `--hostname` you pass. It is never taken from any other remote, because `gh` and `glab` send environment tokens to whatever host they are given. A lookalike remote such as `github.evil.example` starts no CLI at all. * The CLI always gets `--hostname` and runs from a new, empty, private temporary directory (mode 0700), never the analysed repository or the shared temp directory, so `glab` cannot pick up a host or config from a repository's `.git`. glab telemetry (which sends its own request with the credential) and the CLIs' request-logging debug switches are turned off for these calls. -* git runs without the credential variables (`GH_TOKEN`, `GITLAB_TOKEN`, `CI_JOB_TOKEN` and the like), so hooks or filters in the analysed repository cannot read them. +* The CLI gets an allowlisted environment: its login variables, config and keyring locations, GitLab CI autologin, proxy and TLS settings, and basics such as `PATH`, `HOME` and the locale. + Host and repository overrides (`GH_HOST`, `GH_REPO`, `GITLAB_HOST`, `GL_HOST`, `GITLAB_URI`, `GITLAB_API_HOST`, `GLAB_API_PROTOCOL` and the like) are not passed, so the token goes only to the `--hostname` host. + Telemetry (glab's sends its own request with the credential), update checks, prompts and the request-logging debug switches are turned off. +* git, `gh` and `glab` are run by absolute path, found on `PATH` without the current directory or relative entries (on Windows, a bare program name would also run `gh.exe` from the current directory, which is often the checkout). +* git gets an allowlisted environment without any credential variable (`GH_TOKEN`, `GITLAB_TOKEN`, `CI_JOB_TOKEN` and the like), and without `GIT_DIR`, `GIT_WORK_TREE` or injected configuration. This stops accidental leaks to programs that git runs; it is not a boundary against them, because a program running as you can read the environment of repo-stats itself. Prefer read-only, short-lived tokens. +* git runs with `core.fsmonitor` off and without textconv or external diff drivers, so the analysed repository's configuration cannot start them for `log --numstat`. * No token is written to any output. Other protections: -* `--serve` binds to 127.0.0.1, serves only the dashboard file, and rejects any request whose Host header is not `127.0.0.1` or `localhost` on the serving port. +* `--serve` binds to 127.0.0.1, serves only the dashboard file, and rejects any request whose Host header is not `127.0.0.1` or `localhost` on the serving port. It forbids framing (`frame-ancestors 'none'`) and sets same-origin resource and opener policies. +* Output files are written to a new temp file and then moved into place, and repo-stats refuses to write to a path that is a symlink, so a symlink in an untrusted checkout cannot redirect the write. * The dashboard carries a Content-Security-Policy that allows no network access, so it cannot send data anywhere even when opened from a mail attachment. * Commit messages are read in a separate, NUL-delimited git call, so their text cannot change diff statistics. * If a GitLab per-MR lookup fails, the review status and timings for that MR are left empty and the dashboard warns; they are never counted as "unreviewed". diff --git a/repo-stats/repo_stats.py b/repo-stats/repo_stats.py index cf12d73..4069a55 100644 --- a/repo-stats/repo_stats.py +++ b/repo-stats/repo_stats.py @@ -16,6 +16,7 @@ import calendar import collections import concurrent.futures +import contextlib import csv import datetime as dt import email.utils @@ -23,7 +24,6 @@ import json import os import re -import shutil import subprocess import sys import tempfile @@ -32,7 +32,7 @@ import urllib.parse import webbrowser from pathlib import Path -from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Set, Tuple, TypedDict, cast +from typing import IO, Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Set, Tuple, TypedDict, cast __version__ = "0.1.0" @@ -223,21 +223,99 @@ def language_of(path: str) -> Tuple[str, str]: # Git access # --------------------------------------------------------------------------- -# Names of variables that may hold an API credential. repo-stats never reads their values. It removes them -# from git's environment, because git needs none of them, so hooks, filters and textconv drivers that git -# runs inside the analysed repository cannot read them. +# Names of variables that may hold an API credential. repo-stats never reads their values. git gets none of +# them (its environment is built from GIT_ENV_ALLOW, which lists none), so they do not leak to git by +# accident. This is not a boundary against code that git runs: a program running as the same user can read +# the parent process's environment. CREDENTIAL_VARS = ("GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN", "GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "GITLAB_PRIVATE_TOKEN", "OAUTH_TOKEN", "CI_JOB_TOKEN") +# What any child process needs: the search path, home and user, locale, temp dirs, and Windows essentials. +BASE_ENV_ALLOW = { + "PATH", "HOME", "USER", "LOGNAME", "USERNAME", "LANG", "LANGUAGE", "TZ", "TMPDIR", "TMP", "TEMP", + "SYSTEMROOT", "SYSTEMDRIVE", "WINDIR", "COMSPEC", "PATHEXT", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", + "APPDATA", "LOCALAPPDATA", "PROGRAMDATA", +} +# git also reads its own config files. GIT_DIR, GIT_WORK_TREE, GIT_CONFIG_PARAMETERS and the like are left +# out on purpose: they would override `-C repo` or inject configuration. +GIT_ENV_ALLOW = BASE_ENV_ALLOW | {"XDG_CONFIG_HOME", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_CONFIG_NOSYSTEM"} + + +def allowed_env(environ: Mapping[str, str], names: Set[str], prefixes: Tuple[str, ...] = ()) -> Dict[str, str]: + """Return the variables of environ whose upper-cased name is in `names` or starts with one of `prefixes`.""" + prefixes = ("LC_",) + prefixes + return {k: v for k, v in environ.items() if k.upper() in names or k.upper().startswith(prefixes)} + def git_env() -> Dict[str, str]: - """Return os.environ without the credential variables, for git subprocesses.""" - return {k: v for k, v in os.environ.items() if k not in CREDENTIAL_VARS} + """Return the environment for git subprocesses: an allowlist of os.environ, never a credential. + + Missing objects of a partial clone are never fetched (GIT_NO_LAZY_FETCH, git 2.44+; protocol.allow=never + in git_cmd also blocks the fetch on older versions), and git never prompts. + """ + env = allowed_env(os.environ, GIT_ENV_ALLOW) + env.update({"GIT_NO_LAZY_FETCH": "1", "GIT_TERMINAL_PROMPT": "0"}) + if os.name == "nt": + env["NoDefaultCurrentDirectoryInExePath"] = "1" # child processes never run programs from the cwd + return env + + +def find_executable(name: str, path: Optional[str] = None) -> Optional[str]: + """Return the absolute path of program `name` on `path` (default: os.environ's PATH), or None. + + Unlike shutil.which, never looks in the current directory, which is often the analysed checkout: empty, + "." and other relative PATH entries are skipped. (On Windows, CreateProcess with a bare name and + shutil.which before Python 3.12 both search the current directory first.) + """ + if path is None: + path = os.environ.get("PATH", os.defpath) + exts = [""] + if os.name == "nt" and not os.path.splitext(name)[1]: + exts = [e for e in os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(os.pathsep) if e] + for d in path.split(os.pathsep): + if not d or not os.path.isabs(d): + continue + for ext in exts: + cand = os.path.join(d, name + ext) + if os.path.isfile(cand) and os.access(cand, os.X_OK): + return cand + return None + + +def git_exe() -> str: + """Return the absolute path of git, or raise ToolError.""" + git = find_executable("git") + if not git: + raise ToolError("git was not found on PATH (relative PATH entries are ignored)") + return git def git_cmd(repo: str, *args: str) -> List[str]: - """Build a git argv for `repo` with stable, unquoted path output.""" - return ["git", "-C", repo, "-c", "core.quotepath=off", "-c", "log.showSignature=false", *args] + """Build a git argv for `repo` with stable, unquoted path output and no fsmonitor or fetch.""" + return [git_exe(), "-C", os.path.abspath(repo), "-c", "core.quotepath=off", "-c", "log.showSignature=false", + "-c", "core.fsmonitor=false", "-c", "protocol.allow=never", *args] + + +_git_version: Optional[Tuple[int, int]] = None + + +def git_version() -> Tuple[int, int]: + """Return git's (major, minor) version, or (0, 0) if it cannot be read. Cached.""" + global _git_version + if _git_version is None: + p = subprocess.run([git_exe(), "--version"], capture_output=True, text=True, env=git_env()) + m = re.search(r"(\d+)\.(\d+)", p.stdout) + _git_version = (int(m.group(1)), int(m.group(2))) if m else (0, 0) + return _git_version + + +def revs(*names: str) -> List[str]: + """Return revision arguments for `git log` / `git rev-parse`, after --end-of-options where supported. + + rev-parse accepts --end-of-options from git 2.30 (log from 2.24). On older git, collect() still refuses + a branch that starts with "-", so a revision can never be read as an option. + """ + return (["--end-of-options"] if git_version() >= (2, 30) else []) + list(names) def run_git(repo: str, *args: str, check: bool = True) -> str: @@ -272,12 +350,27 @@ def detect_branch(repo: str, remote: str = "origin") -> str: if head: return head for cand in (f"{remote}/main", f"{remote}/master", "main", "master"): - if run_git(repo, "rev-parse", "--verify", "-q", cand + "^{commit}", check=False).strip(): + if run_git(repo, "rev-parse", "--verify", "-q", *revs(cand + "^{commit}"), check=False).strip(): return cand # Fall back to the checked-out branch (e.g. "trunk"), or HEAD when detached. return run_git(repo, "symbolic-ref", "--short", "-q", "HEAD", check=False).strip() or "HEAD" +PARTIAL_CLONE_HINT = ("This is a partial clone (made with --filter, or actions/checkout's `filter`). repo-stats " + "never downloads missing objects, so history that needs them cannot be read. Clone without " + "a filter for full results.") + + +def is_partial_clone(repo: str) -> bool: + """Return True if the repository has a promisor remote, i.e. objects that git would fetch on demand.""" + out = run_git(repo, "config", "--get-regexp", r"^(extensions\.partialclone|remote\..*\.promisor)$", check=False) + for line in out.splitlines(): + key, _, value = line.partition(" ") + if key == "extensions.partialclone" or value.strip().lower() in ("true", "yes", "on", "1"): + return True + return False + + def strip_remote_prefix(repo: str, branch: str) -> str: """'upstream/main' -> 'main' when it names a remote-tracking ref (and no local branch of that name).""" if branch.startswith("refs/remotes/"): @@ -294,11 +387,16 @@ def strip_remote_prefix(repo: str, branch: str) -> str: def parse_remote(url: str) -> Optional[Tuple[str, str]]: - """Return (host, path) from an https, ssh or scp-style git remote URL, or None.""" + """Return (host, path) from an https, ssh or scp-style git remote URL, or None. + + Any user name or token before the host is dropped. A URL with a scheme but no path gives None: it is + never read as scp-style, which would put the user info into the path (and so into the dashboard name). + """ url = url.strip() - m = re.match(r"^[\w.+-]+://(?:[^@/]+@)?([^/:]+)(?::\d+)?/(.+?)(?:\.git)?/?$", url) - if not m: - m = re.match(r"^(?:[^@/]+@)?([^/:]+):(.+?)(?:\.git)?/?$", url) + if "://" in url: + m = re.match(r"[\w.+-]+://(?:[^/]*@)?([^/:@]+)(?::\d+)?/(.+?)(?:\.git)?/?\Z", url) + else: + m = re.match(r"(?:[^@/]+@)?([^/:@]+):(.+?)(?:\.git)?/?\Z", url) if not m: return None return m.group(1).lower(), m.group(2) @@ -496,7 +594,7 @@ def scan(self, repo: str, branch: str) -> List[Commit]: meta_fmt = "%H%x00%P%x00%at%x00%ct%x00%an%x00%s%x00%b" commits: list[Commit] = [] by_sha: dict[str, Commit] = {} - fields = run_git(repo, "log", "-z", "--first-parent", "--reverse", f"--format={meta_fmt}", branch).split("\0") + fields = run_git(repo, "log", "-z", "--first-parent", "--reverse", f"--format={meta_fmt}", *revs(branch)).split("\0") n = 7 for i in range(0, len(fields) - n + 1, n): sha, parents, at, ct, author, subject, body = fields[i:i + n] @@ -511,8 +609,8 @@ def scan(self, repo: str, branch: str) -> List[Commit]: # %x00 cannot appear in a path or in git's numstat output, so it safely marks each commit header. stats: dict[str, list[str]] = {} cur: Optional[list[str]] = None - for line in stream_git(repo, "log", "--first-parent", "-m", "--numstat", "--no-renames", - "--format=%x00%H", branch): + for line in stream_git(repo, "log", "--first-parent", "-m", "--numstat", "--no-renames", "--no-textconv", + "--no-ext-diff", "--format=%x00%H", *revs(branch)): if line.startswith("\0"): cur = stats.setdefault(line[1:].strip(), []) elif cur is not None: @@ -529,7 +627,7 @@ def scan(self, repo: str, branch: str) -> List[Commit]: def load_graph(repo: str, branch: str) -> Graph: """Return sha -> (parents, author time, committer time) for every commit reachable from branch.""" graph: Graph = {} - for line in stream_git(repo, "log", "--format=%H %P|%at|%ct", branch): + for line in stream_git(repo, "log", "--format=%H %P|%at|%ct", *revs(branch)): left, at, ct = line.rstrip("\n").split("|") parts = left.split() graph[parts[0]] = (tuple(parts[1:]), int(at), int(ct)) @@ -539,7 +637,7 @@ def load_graph(repo: str, branch: str) -> Graph: def load_reverts(repo: str, branch: str) -> Dict[str, str]: """Return sha -> sha (or prefix) of the commit it reverts, from 'This reverts commit' lines.""" out: dict[str, str] = {} - text = run_git(repo, "log", "--format=%x1e%H%x1f%b", "--grep=This reverts commit", branch, check=False) + text = run_git(repo, "log", "--format=%x1e%H%x1f%b", "--grep=This reverts commit", *revs(branch), check=False) for rec in text.split("\x1e"): if "\x1f" not in rec: continue @@ -761,16 +859,41 @@ def ci_login_hint(tool: str, host: str) -> str: return "GH_TOKEN" if host == "github.com" or host.endswith(".ghe.com") else "GH_ENTERPRISE_TOKEN" -# Debug switches that make the CLIs dump requests to stderr, which repo-stats may quote in an error. -CLI_DEBUG_VARS = ("GH_DEBUG", "DEBUG", "GLAB_DEBUG", "GLAB_DEBUG_HTTP") +# The gh/glab environment is an allowlist: what they need to find their login (token variables, config and +# keyring locations, GitLab CI autologin), reach the API (proxy and TLS settings) and run. Host and repo +# overrides (GH_HOST, GH_REPO, GITLAB_HOST, GL_HOST, GITLAB_URI, GITLAB_API_HOST, GLAB_API_PROTOCOL, ...), +# TLS-verification switches and request-dumping debug switches (GH_DEBUG, DEBUG, GLAB_DEBUG, GLAB_DEBUG_HTTP) +# are left out, so the API host is always the --hostname that repo-stats passes. +# Sources: `gh help environment` and https://docs.gitlab.com/cli/configuration/#environment-variables +CLI_ENV_ALLOW = BASE_ENV_ALLOW | { + "GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN", + "GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN", + "GLAB_ENABLE_CI_AUTOLOGIN", "GITLAB_CI", "CI_JOB_TOKEN", + "GH_CONFIG_DIR", "GLAB_CONFIG_DIR", "GLAB_USE_KEYRING", "USE_KEYRING", "DBUS_SESSION_BUS_ADDRESS", + "GITLAB_SUBFOLDER", + "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "ALL_PROXY", "GLAB_PROXY", "PROXY", + "SSL_CERT_FILE", "SSL_CERT_DIR", "GLAB_CA_CERT", "CA_CERT", "GLAB_CLIENT_CERT", "CLIENT_CERT", + "GLAB_CLIENT_KEY", "CLIENT_KEY", +} +# CI_SERVER_* for glab's CI autologin; XDG_* for config and keyring locations. REPO_STATS_FAKE_* is read +# only by the test suite's fake gh/glab (tests/fake_cli), which needs its mock server URL and call log +# passed through this allowlist; the real CLIs ignore it. +CLI_ENV_PREFIXES = ("CI_SERVER_", "XDG_", "REPO_STATS_FAKE_") +# Set for every call: no prompts, no update checks or telemetry (extra requests, glab's with the credential). +CLI_ENV_SET = { + "GH_PROMPT_DISABLED": "1", "GH_NO_UPDATE_NOTIFIER": "1", "GH_TELEMETRY": "false", + "GLAB_NO_PROMPT": "true", "GLAB_CHECK_UPDATE": "false", "GLAB_SEND_TELEMETRY": "false", +} CLI_TIMEOUT = 120 CLI_RETRIES = 4 -HOSTNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$") +HOSTNAME_RE = re.compile(r"^(?!.*\.\.)[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?\Z") # The read-only allowlist. A GraphQL query cannot change anything (only a mutation can), and the GitLab # endpoints are the three list endpoints repo-stats reads, always with GET. READ_ONLY_GRAPHQL = re.compile(r"^\s*query\b") WRITE_GRAPHQL = re.compile(r"\b(?:mutation|subscription)\b") -GITLAB_READ_ENDPOINT = re.compile(r"^projects/[^/?#\s]+/merge_requests(?:/\d+/(?:commits|notes))?$") +GITLAB_READ_ENDPOINT = re.compile(r"^projects/(?!\.\.?/)[^/?#\s]+/merge_requests(?:/[0-9]+/(?:commits|notes))?\Z") +# Upper bound on top-level list pages (50 PRs or 100 MRs each), so a broken API cannot page forever. +MAX_LIST_PAGES = 2000 def _backoff(seconds: float) -> None: @@ -815,25 +938,42 @@ def parse_cli_response(out: bytes) -> Tuple[Optional[int], Dict[str, str], bytes return int(m.group(1)), headers, body +def next_page(value: str, page: int) -> int: + """Return GitLab's X-Next-Page as an int; raise ApiError unless it is a plain number above `page`.""" + value = value.strip() + if not re.fullmatch(r"[1-9][0-9]{0,8}", value) or int(value) <= page: + raise ApiError(f"GitLab returned an invalid next page {value[:20]!r} after page {page}") + return int(value) + + class Cli: """Read-only access to one GitHub or GitLab host through `gh api` or `glab api`. Every request passes the read-only allowlist, gets an explicit --hostname, runs from a private temp - directory (removed by close() or at the end of a `with` block), and runs without debug switches and - (for glab) without telemetry, which would send its own request with the credential. + directory (removed by close() or at the end of a `with` block) with an allowlisted environment, and runs + without debug switches, update checks and telemetry (glab's would send its own request with the credential). """ def __init__(self, tool: str, host: str, environ: Optional[Mapping[str, str]] = None) -> None: """Find the CLI on PATH and prepare its environment; raise CliUnavailable if it is not installed.""" - env = {k: v for k, v in (os.environ if environ is None else environ).items() if k not in CLI_DEBUG_VARS} - env["GLAB_SEND_TELEMETRY"] = "false" - exe = shutil.which(tool, path=env.get("PATH", os.defpath)) + env = allowed_env(os.environ if environ is None else environ, CLI_ENV_ALLOW, CLI_ENV_PREFIXES) + env.update(CLI_ENV_SET) + if tool == "glab": + # glab sends an environment token only to the host named by GITLAB_HOST (or its config), so name + # the same host as --hostname. Any GITLAB_HOST from the caller was dropped above. + env["GITLAB_HOST"] = host + if os.name == "nt": + env["NoDefaultCurrentDirectoryInExePath"] = "1" + exe = find_executable(tool, env.get("PATH", os.defpath)) if not exe: raise CliUnavailable(f"{tool} is not installed. Install it from {CLI_INSTALL[tool]} for exact PR data.") self.tool, self.host, self.exe, self.env = tool, host, exe, env self.hint = f"Run `{tool} auth login --hostname {host}`, or in CI set {ci_login_hint(tool, host)}." # Mode 0700 and empty: no .git or CLI config of the analysed repository or of another local user. self._cwd = tempfile.TemporaryDirectory(prefix="repo-stats-cli-") + # git (which the CLIs may run) stops looking for a repository at the temp dir, so it cannot find a + # .git that another user planted in a shared /tmp either. + self.env["GIT_CEILING_DIRECTORIES"] = os.path.dirname(self._cwd.name) def close(self) -> None: """Remove the private working directory.""" @@ -963,7 +1103,7 @@ def fetch_github(cli: Cli, owner: str, name: str, since: Optional[int], base_bra prs: list[PR] = [] seen = 0 cursor = None - while True: + for _ in range(MAX_LIST_PAGES): data = cli.graphql(GITHUB_QUERY, {"owner": owner, "name": name, "cursor": cursor}) if not isinstance(data, dict): raise ApiError("GitHub returned an unexpected response") @@ -995,7 +1135,12 @@ def fetch_github(cli: Cli, owner: str, name: str, since: Optional[int], base_bra info_page = page.get("pageInfo") or {} if stop or not info_page.get("hasNextPage"): break - cursor = info_page.get("endCursor") + nxt = info_page.get("endCursor") + if not isinstance(nxt, str) or not nxt or nxt == cursor: + raise ApiError("GitHub returned an invalid or repeating page cursor") + cursor = nxt + else: + raise ApiError(f"Stopped after {MAX_LIST_PAGES} pages of pull requests; use --since or --max-prs") if info is not None: info["seen"] = seen return prs @@ -1094,7 +1239,7 @@ def fetch_gitlab(cli: Cli, project_path: str, since: Optional[int], base_branch: base = f"projects/{urllib.parse.quote(project_path, safe='')}/merge_requests" mrs: list[dict[str, Any]] = [] page = 1 - while True: + for _ in range(MAX_LIST_PAGES): q: dict[str, Any] = {"state": "all", "scope": "all", "order_by": "updated_at", "sort": "desc", "per_page": 100, "page": page} if since: # updated_after, not created_after: an MR opened before the cutoff but merged after it still counts. @@ -1109,7 +1254,9 @@ def fetch_gitlab(cli: Cli, project_path: str, since: Optional[int], base_branch: nxt = hdrs.get("x-next-page") if not data or not nxt or (max_prs and len(mrs) >= max_prs): break - page = int(nxt) + page = next_page(nxt, page) + else: + raise ApiError(f"Stopped after {MAX_LIST_PAGES} pages of merge requests; use --since or --max-prs") if max_prs: mrs = mrs[:max_prs] if info is not None: @@ -1128,7 +1275,7 @@ def pages(endpoint: str, params: Optional[Mapping[str, str]] = None) -> Iterator nxt = hdrs.get("x-next-page") if not data or not nxt: return - page = int(nxt) + page = next_page(nxt, page) def mr_commits(iid: Any) -> List[Dict[str, Any]]: """Return every commit of one MR (GitLab lists them newest first, so all pages are needed).""" @@ -1269,7 +1416,7 @@ def local_summary(pr: PR, fp_by_sha: Dict[str, Commit]) -> Optional[Commit]: return None if len(c["parents"]) >= 2 or (pr.get("squash_sha") and pr["squash_sha"] == c["sha"]): return c - if pr["number"] is not None and re.search(rf"\(#{pr['number']}\)\s*$", c["subject"]): + if pr["number"] is not None and re.search(rf"\(#{re.escape(str(pr['number']))}\)\s*$", c["subject"]): return c return None @@ -1441,13 +1588,44 @@ def render_html(data: Dict[str, Any]) -> str: return template.replace(marker, embed_json(data), 1) +def write_output(path: str, write: Callable[[IO[str]], None]) -> None: + """Write a text output file atomically, and never through a symbolic link. + + The text goes to a new temp file in the same directory, which then replaces `path` (os.replace swaps + the directory entry and never follows a link), so a symlink planted at the output path in an untrusted + checkout cannot redirect the write. An existing symlink is refused outright. Characters that cannot be + encoded (lone surrogates from API text) are written as backslash escapes, which inside the dashboard's + JSON decode back to the same string. + """ + if os.path.islink(path): + raise ToolError(f"Refusing to write {path}: it is a symbolic link") + directory = os.path.dirname(os.path.abspath(path)) + try: + fd, tmp = tempfile.mkstemp(dir=directory, prefix="." + os.path.basename(path) + ".", suffix=".tmp") + except OSError as e: # report the output path, not the temp name + raise OSError(e.errno, e.strerror, path) from None + try: + with os.fdopen(fd, "w", encoding="utf-8", errors="backslashreplace", newline="") as f: + write(f) + umask = os.umask(0) + os.umask(umask) + os.chmod(tmp, 0o666 & ~umask) # mkstemp creates 0600; give the usual permissions of a new file + os.replace(tmp, path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(tmp) + raise + + def write_csv(path: str, records: Iterable[Record]) -> None: """Write one row per PR record to a CSV file, guarding against spreadsheet formula injection.""" cols = ["id", "title", "type", "scope", "breaking", "state", "bot", "created", "first_commit", "first_review", "merged", "additions", "deletions", "files", "commits", "risk", "risk_level", "kind", "coding", "pickup", "review", "open_to_merge", "lead", "deployed", "deploy_wait", "lead_to_deploy", "restore", "review_cycles", "changes_requested", "reviewers", "source"] - with open(path, "w", newline="", encoding="utf-8") as f: + + def write(f: IO[str]) -> None: + """Write the header and one guarded row per record to f.""" w = csv.writer(f) w.writerow(cols) for r in records: @@ -1459,6 +1637,8 @@ def write_csv(path: str, records: Iterable[Record]) -> None: row.append("" if v is None else v) w.writerow(row) + write_output(path, write) + WHEN_DATE = re.compile(r"^\d{4}(?:-\d{2}(?:-\d{2})?)?$") WHEN_DURATION = re.compile(r"^([1-9]\d*)([dwmy])$") @@ -1519,13 +1699,18 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non and run_git(repo, "rev-parse", "--is-bare-repository", check=False).strip() != "true": raise ToolError(f"{repo} is not a git repository") branch = args.branch or detect_branch(repo, args.remote) - if not run_git(repo, "rev-parse", "--verify", "-q", branch + "^{commit}", check=False).strip(): + if branch.startswith("-"): # never let a ref (possibly from a crafted repository) be read as an option + raise ToolError(f"Branch or ref '{branch}' starts with '-'; pass another --branch.") + if not run_git(repo, "rev-parse", "--verify", "-q", *revs(branch + "^{commit}"), check=False).strip(): raise ToolError(f"Branch or ref '{branch}' not found. Pass --branch.") short_branch = strip_remote_prefix(repo, branch) warnings: list[str] = [] if run_git(repo, "rev-parse", "--is-shallow-repository", check=False).strip() == "true": warnings.append("This is a shallow clone. History, lines of code over time and timings are incomplete. " "Run `git fetch --unshallow` for full results.") + partial = is_partial_clone(repo) + if partial: + log(f"warning: {PARTIAL_CLONE_HINT}") since = parse_when(args.since, "--since", end=False) until = parse_when(args.until, "--until", end=True) # exclusive: the first moment after the period if since is not None and until is not None and since >= until: @@ -1539,7 +1724,12 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non log(f"Scanning history of {branch} ...") scanner = Scanner(excludes, sensitive_re) - first_parent = scanner.scan(repo, branch) + try: + first_parent = scanner.scan(repo, branch) + except ToolError as e: + if partial: + raise ToolError(f"{e}\n{PARTIAL_CLONE_HINT}") + raise if not first_parent: raise ToolError(f"No commits found on {branch}") graph = load_graph(repo, branch) @@ -1559,7 +1749,7 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non # Decide where PR data comes from. env = os.environ if environ is None else environ - remote = run_git(repo, "remote", "get-url", args.remote, check=False).strip() + remote = run_git(repo, "remote", "get-url", "--", args.remote, check=False).strip() parsed = parse_remote(remote) if remote else None host_provider = detect_provider(parsed[0]) if parsed else None ci = ci_server(env) @@ -1764,6 +1954,8 @@ def build_parser() -> argparse.ArgumentParser: # Same policy as the template's meta tag: inline script and style only, no network access at all. CSP = ("default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; " "base-uri 'none'; form-action 'none'") +# --serve adds frame-ancestors, which only works in a header (a meta tag CSP ignores it): no framing. +SERVE_CSP = CSP + "; frame-ancestors 'none'" def serve(path: Path, port: int, open_browser: bool) -> None: @@ -1797,8 +1989,10 @@ def _send(self, head_only: bool) -> None: self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.send_header("X-Content-Type-Options", "nosniff") - self.send_header("Content-Security-Policy", CSP) + self.send_header("Content-Security-Policy", SERVE_CSP) self.send_header("Referrer-Policy", "no-referrer") + self.send_header("Cross-Origin-Resource-Policy", "same-origin") + self.send_header("Cross-Origin-Opener-Policy", "same-origin") self.end_headers() if not head_only: self.wfile.write(body) @@ -1835,9 +2029,10 @@ def main(argv: Optional[Sequence[str]] = None) -> int: try: data = collect(args) out = Path(args.out) - out.write_text(render_html(data), encoding="utf-8") + html = render_html(data) + write_output(args.out, lambda f: f.write(html)) if args.json: - Path(args.json).write_text(json.dumps(data, indent=1), encoding="utf-8") + write_output(args.json, lambda f: f.write(json.dumps(data, indent=1))) if args.csv: write_csv(args.csv, data["prs"]) except ToolError as e: diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index 5017d95..e35e067 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -2518,7 +2518,9 @@ def test_source_has_no_write_requests(self) -> None: for word in ('"POST"', '"PUT"', '"PATCH"', '"DELETE"', '"-X"', '"-F"', '"--field"', '"--input"', '"--form"'): self.assertNotIn(word, src, word) git_subcommands = set(re.findall(r'run_git\(repo, "([a-z-]+)"', src) + re.findall(r'stream_git\(repo, "([a-z-]+)"', src)) - self.assertLessEqual(git_subcommands, {"log", "rev-parse", "for-each-ref", "symbolic-ref", "remote"}, git_subcommands) + self.assertLessEqual(git_subcommands, {"log", "rev-parse", "for-each-ref", "symbolic-ref", "remote", "config"}, + git_subcommands) + self.assertEqual(re.findall(r'run_git\(repo, "config", "([^"]+)"', src), ["--get-regexp"], "git config only reads") def test_bad_hostnames_rejected(self) -> None: """--hostname must be a plain host name: no ports, schemes, paths, spaces or leading dashes.""" @@ -2564,6 +2566,7 @@ def test_every_call_is_read_only_explicit_host_and_outside_the_repo(self) -> Non # One private directory per run, and it is gone afterwards. self.assertEqual(len({c["cwd"] for c in calls}), 1) self.assertFalse(Path(calls[0]["cwd"]).exists()) + self.assertEqual(calls[0]["env"]["GIT_CEILING_DIRECTORIES"], tempfile.gettempdir()) def test_cli_working_directory_is_private_and_empty(self) -> None: """The CLI's working directory is new, empty and mode 0700, so nobody can plant a .git in it.""" @@ -2617,16 +2620,27 @@ def test_ci_server_host_is_trusted_only_when_it_matches(self) -> None: self.assertEqual(len(srv.requests), n) def test_git_never_sees_credential_variables(self) -> None: - """git, and anything it runs, gets an environment without the credential variables.""" + """git, and anything it runs, gets an allowlisted environment: no credentials, no unknown variables.""" r = fixtures.merge_workflow_repo() creds = {name: f"secret-{i}" for i, name in enumerate(rs.CREDENTIAL_VARS)} - with mock.patch.dict(os.environ, {**creds, "REPO_STATS_CANARY": "kept"}): + extra = {"REPO_STATS_CANARY": "dropped", "ACTIONS_RUNTIME_TOKEN": "secret-actions", "LC_ALL": "C", + "GIT_DIR": "/nonexistent", "GIT_WORK_TREE": "/nonexistent", "GIT_CONFIG_PARAMETERS": "'x.y'='z'"} + with mock.patch.dict(os.environ, {**creds, **extra}): out = rs.run_git(str(r.path), "-c", "alias.envdump=!env", "envdump") streamed = "".join(rs.stream_git(str(r.path), "-c", "alias.envdump=!env", "envdump")) for text in (out, streamed): - self.assertIn("REPO_STATS_CANARY=kept", text) + env = dict(line.split("=", 1) for line in text.splitlines() if "=" in line) + self.assertTrue(env.get("PATH", "").endswith(os.environ["PATH"])) # git may prepend its exec dir + self.assertEqual(env.get("LC_ALL"), "C") + self.assertEqual(env.get("GIT_NO_LAZY_FETCH"), "1") + for name in ("REPO_STATS_CANARY", "ACTIONS_RUNTIME_TOKEN", "GIT_WORK_TREE"): + self.assertNotIn(name, env) + # git exports its own -c options to the alias; the caller's injected ones must not be there. + self.assertNotIn("'x.y'", env.get("GIT_CONFIG_PARAMETERS", "")) + self.assertNotEqual(env.get("GIT_DIR"), "/nonexistent", "GIT_DIR from the caller must not reach git") for name, value in creds.items(): self.assertNotIn(value, text, name) + self.assertFalse(set(rs.CREDENTIAL_VARS) & rs.GIT_ENV_ALLOW) def test_parse_cli_response(self) -> None: """--include output splits into status, lower-cased headers and body, with CRLF or LF.""" @@ -2879,5 +2893,327 @@ def test_csv_columns(self) -> None: [("2", "1", "2"), ("", "", "")]) +# ===================================================================================================== +# I. Security hardening: outputs, environments, executables, parsing and paging +# ===================================================================================================== + +class I1_SecurityHardening(unittest.TestCase): + """Regression tests for the findings of the security review.""" + + def _cli(self, tool: str, host: str, environ: Mapping[str, str]) -> rs.Cli: + """A Cli whose private directory is removed after the test.""" + cli = rs.Cli(tool, host, environ) + self.addCleanup(cli.close) + return cli + + # -- S1: outputs are written atomically and never through a symlink + + def test_write_output_refuses_symlinks(self) -> None: + """An existing or dangling symlink at the output path is refused; its target is never touched.""" + d = tmpdir() + victim = d / "victim.txt" + victim.write_text("keep") + (d / "link.html").symlink_to(victim) + (d / "dangling.html").symlink_to(d / "created-by-attack") + for name in ("link.html", "dangling.html"): + with self.assertRaises(rs.ToolError, msg=name): + rs.write_output(str(d / name), lambda f: f.write("pwned")) + self.assertEqual(victim.read_text(), "keep") + self.assertFalse((d / "created-by-attack").exists()) + self.assertEqual(sorted(p.name for p in d.iterdir()), ["dangling.html", "link.html", "victim.txt"]) + + def test_write_output_is_atomic(self) -> None: + """A write replaces the file in one step, leaves no temp file, and a failed write keeps the old file.""" + d = tmpdir() + out = d / "o.html" + out.write_text("old") + rs.write_output(str(out), lambda f: f.write("new")) + self.assertEqual(out.read_text(), "new") + + def boom(f: Any) -> None: + """Write part of the output, then fail.""" + f.write("partial") + raise RuntimeError("boom") + + with self.assertRaises(RuntimeError): + rs.write_output(str(out), boom) + self.assertEqual(out.read_text(), "new") + self.assertEqual([p.name for p in d.iterdir()], ["o.html"], "no temp file is left behind") + + def test_cli_refuses_symlinked_outputs(self) -> None: + """-o, --json and --csv pointing at a symlink exit 1 with a clear error and leave the target alone.""" + for flag in ("-o", "--json", "--csv"): + d = tmpdir() + victim = d / "victim.txt" + victim.write_text("keep") + (d / "out.x").symlink_to(victim) + args = [merge_repo().path, "-o", d / "real.html"] if flag != "-o" else [merge_repo().path] + p = run_cli([*args, flag, d / "out.x"]) + self.assertEqual(p.returncode, 1, flag) + self.assertIn("symbolic link", p.stderr, flag) + self.assertNotIn("Traceback", p.stderr) + self.assertEqual(victim.read_text(), "keep", flag) + + # -- N5: lone surrogates in API text cannot crash a write + + def test_lone_surrogates_are_written(self) -> None: + """A lone surrogate is written as an escape: the dashboard JSON still decodes to the same string.""" + d = tmpdir() + data = {"title": "a\ud800b"} + rs.write_output(str(d / "x.html"), lambda f: f.write(rs.embed_json(data))) + self.assertEqual(json.loads((d / "x.html").read_text(encoding="utf-8")), data) + rs.write_csv(str(d / "x.csv"), [{"id": 1, "title": "t\udfffx"}]) + self.assertIn("\\udfff", (d / "x.csv").read_text(encoding="utf-8")) + + # -- S4, N9: the gh/glab environment is an allowlist + + def test_cli_environment_is_an_allowlist(self) -> None: + """Host overrides, TLS switches and unknown variables are dropped; login, CI, proxy and config stay.""" + keep = {"GITLAB_TOKEN": FAKE, "GH_TOKEN": FAKE, "GH_ENTERPRISE_TOKEN": FAKE, "CI_JOB_TOKEN": "job", + "GLAB_ENABLE_CI_AUTOLOGIN": "true", "GITLAB_CI": "true", "CI_SERVER_FQDN": "gitlab.com", + "HOME": "/home/u", "XDG_CONFIG_HOME": "/home/u/.config", "GH_CONFIG_DIR": "/c/gh", + "GLAB_CONFIG_DIR": "/c/glab", "https_proxy": "http://proxy:3128", "SSL_CERT_FILE": "/ca.pem", + "LANG": "C.UTF-8", "LC_ALL": "C", "DBUS_SESSION_BUS_ADDRESS": "unix:path=/x"} + drop = {"GITLAB_HOST": "evil.example", "GL_HOST": "evil.example", "GITLAB_URI": "evil.example", + "GITLAB_API_HOST": "evil.example", "GLAB_API_PROTOCOL": "http", "API_PROTOCOL": "http", + "GH_HOST": "evil.example", "GH_REPO": "evil/repo", "GLAB_SKIP_TLS_VERIFY": "true", + "GH_DEBUG": "api", "GLAB_DEBUG_HTTP": "true", "AWS_SECRET_ACCESS_KEY": "s", "GIT_DIR": "/x", + "GLAB_CHECK_UPDATE": "true"} + for tool, host in (("glab", "gitlab.com"), ("gh", "github.com")): + env = self._cli(tool, host, helpers.clean_env({**keep, **drop})).env + for k, v in keep.items(): + self.assertEqual(env.get(k), v, (tool, k)) + for k in drop: + if k not in ("GITLAB_HOST", "GLAB_CHECK_UPDATE"): + self.assertNotIn(k, env, (tool, k)) + self.assertEqual(env["GH_NO_UPDATE_NOTIFIER"], "1") + self.assertEqual(env["GLAB_CHECK_UPDATE"], "false") + self.assertEqual(env["GLAB_SEND_TELEMETRY"], "false") + self.assertEqual(env["GH_TELEMETRY"], "false") + self.assertEqual(self._cli("glab", "git.corp.example", helpers.clean_env(drop)).env["GITLAB_HOST"], + "git.corp.example", "glab's GITLAB_HOST is always the --hostname host") + self.assertNotIn("GITLAB_HOST", self._cli("gh", "github.com", helpers.clean_env(drop)).env) + + def test_cli_never_sees_host_overrides_end_to_end(self) -> None: + """A real run with GITLAB_API_HOST and friends set still sends glab only the trusted host.""" + r = api_repo("git@gitlab.com:grp/sub/proj.git") + log = tmpdir() / "cli.log" + evil = {"GITLAB_API_HOST": "evil.example", "GL_HOST": "evil.example", "GITLAB_URI": "evil.example"} + with ms.MockServer(ms.gitlab_handler(*gitlab_fixture(r), page_size=50)) as srv: + d, _ = collect(r, "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE, "REPO_STATS_FAKE_LOG": str(log), **evil}) + self.assertEqual(d["meta"]["mode"], "api") + calls = helpers.cli_calls(log) + self.assertTrue(calls) + for c in calls: + for k in evil: + self.assertNotIn(k, c["env"]) + self.assertEqual(c["env"]["GITLAB_HOST"], "gitlab.com") + + # -- S2: executables are found by absolute path, never in the current directory + + def test_find_executable_skips_current_and_relative_dirs(self) -> None: + """A `gh` in the current directory is never used through an empty, "." or relative PATH entry.""" + d = tmpdir() + (d / "sub").mkdir() + for p in (d / "gh", d / "sub" / "gh"): + p.write_text("#!/bin/sh\necho planted\n") + p.chmod(0o755) + old = os.getcwd() + os.chdir(d) + try: + for path in ("", ".", "sub", os.pathsep.join(["", ".", "sub", "./sub"])): + self.assertIsNone(rs.find_executable("gh", path), repr(path)) + with self.assertRaises(rs.CliUnavailable): + rs.Cli("gh", "github.com", {"PATH": os.pathsep.join([".", "sub"])}) + self.assertEqual(rs.find_executable("gh", os.pathsep.join([".", str(d / "sub")])), str(d / "sub" / "gh")) + finally: + os.chdir(old) + self.assertTrue(os.path.isabs(rs.git_cmd(".")[0])) + + # -- N1: no user info from a remote URL reaches a name or an output + + def test_parse_remote_drops_user_info(self) -> None: + """Credentials in a remote URL never end up in the host or path, also without a path.""" + cases = { + "https://user:SECRET@github.com": None, + "https://user:SECRET@github.com/": None, + "https://SECRET@github.com/acme/widgets.git": ("github.com", "acme/widgets"), + "https://u:p@ss@git.corp.example/a/b.git": ("git.corp.example", "a/b"), + "https://github.com@evil.example/o/r": ("evil.example", "o/r"), + "ssh://git@github.com:evil/o/r": None, + } + for url, want in cases.items(): + got = rs.parse_remote(url) + self.assertEqual(got, want, url) + self.assertNotIn("SECRET", repr(got), url) + + def test_token_in_pathless_remote_is_not_in_the_output(self) -> None: + """A path-less https remote with a token gives no API and no name from the remote.""" + r = fixtures.merge_workflow_repo() + add_remote(r, "https://user:SECRET-TOKEN@github.com") + d, _ = collect(r) + self.assertEqual(d["meta"]["mode"], "git") + self.assertNotIn("SECRET-TOKEN", json.dumps(d)) + + # -- N2, N3: anchored regexes, no dot segments + + def test_security_regexes_match_the_whole_string(self) -> None: + """A trailing newline, an empty label, dot segments and non-ASCII digits are all rejected.""" + for bad in ("ghe.example.com\n", "a..b", "ghe..example.com"): + self.assertIsNone(rs.HOSTNAME_RE.match(bad), repr(bad)) + self.assertIsNotNone(rs.HOSTNAME_RE.match("ghe.example.com")) + for bad in ("projects/g%2Fp/merge_requests\n", "projects/../merge_requests", "projects/./merge_requests", + "projects/../merge_requests/1/notes", "projects/g%2Fp/merge_requests/\u0661/notes"): + self.assertIsNone(rs.GITLAB_READ_ENDPOINT.match(bad), repr(bad)) + for good in ("projects/g%2Fp/merge_requests", "projects/g%2Fp/merge_requests/12/commits", "projects/...x/merge_requests"): + self.assertIsNotNone(rs.GITLAB_READ_ENDPOINT.match(good), good) + log = tmpdir() / "cli.log" + cli = self._cli("glab", "gitlab.com", helpers.clean_env({"REPO_STATS_FAKE_LOG": str(log)})) + with self.assertRaises(rs.ApiError): + cli.get("projects/../merge_requests", {}) + self.assertEqual(helpers.cli_calls(log), []) + with self.assertRaises(rs.ToolError): + collect(api_repo(), "--provider", "github", "--hostname", "ghe.example.com\n") + + # -- N4: paging is capped and validated + + def test_next_page_must_be_a_plain_increasing_number(self) -> None: + """X-Next-Page must be a plain positive integer above the current page.""" + self.assertEqual(rs.next_page("2", 1), 2) + for bad in ("-1", "+4", "1_0", "0", "1", "abc", "\u0662", "2.0", "99999999999"): + with self.assertRaises(rs.ApiError, msg=bad): + rs.next_page(bad, 1) + + def test_gitlab_repeating_next_page_stops(self) -> None: + """A server that always answers X-Next-Page: 1 fails the fetch instead of looping forever.""" + def h(req: ms.Request) -> ms.Response: + """Return one MR per page and always point back at page 1.""" + return 200, {"X-Next-Page": "1"}, [{"iid": 1, "title": "t", "state": "opened", "created_at": "2024-01-01T00:00:00Z"}] + + with ms.MockServer(h) as srv: + cli = self._cli("glab", "gitlab.com", helpers.clean_env({"REPO_STATS_FAKE_URL": srv.url, "GITLAB_TOKEN": FAKE})) + with self.assertRaises(rs.ApiError): + rs.fetch_gitlab(cli, "g/p", None, "main", True, None, False, progress=lambda m: None) + self.assertEqual(len(srv.requests), 1) + + def test_github_repeating_cursor_and_page_cap(self) -> None: + """A repeating GraphQL cursor fails the fetch, and an endless one stops at MAX_LIST_PAGES.""" + counter = [0] + + def h(repeat: bool) -> ms.Handler: + """A GraphQL handler that always has a next page, with a fixed or ever-changing cursor.""" + def inner(req: ms.Request) -> ms.Response: + """Answer with no PRs and another page.""" + counter[0] += 1 + cursor = "same" if repeat else f"c{counter[0]}" + return 200, {}, {"data": {"repository": {"pullRequests": { + "pageInfo": {"hasNextPage": True, "endCursor": cursor}, "nodes": []}}}} + return inner + + env = {"GH_TOKEN": FAKE} + with ms.MockServer(h(True)) as srv: + cli = self._cli("gh", "github.com", helpers.clean_env({**env, "REPO_STATS_FAKE_URL": srv.url})) + with self.assertRaisesRegex(rs.ApiError, "repeating"): + rs.fetch_github(cli, "o", "r", None, "main", True, None, progress=lambda m: None) + self.assertEqual(len(srv.requests), 2) + with ms.MockServer(h(False)) as srv, mock.patch.object(rs, "MAX_LIST_PAGES", 3): + cli = self._cli("gh", "github.com", helpers.clean_env({**env, "REPO_STATS_FAKE_URL": srv.url})) + with self.assertRaisesRegex(rs.ApiError, "Stopped after 3 pages"): + rs.fetch_github(cli, "o", "r", None, "main", True, None, progress=lambda m: None) + self.assertEqual(len(srv.requests), 3) + + # -- N7: --serve headers + + def test_serve_sends_framing_and_cross_origin_headers(self) -> None: + """--serve forbids framing in the header CSP and sends same-origin CORP and COOP.""" + out = tmpdir() + proc = subprocess.Popen([sys.executable, SCRIPT, str(merge_repo().path), "-o", str(out / "o.html"), + "--serve", "0", "--no-open"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + text=True, env=helpers.clean_env()) + try: + url = None + for line in proc.stderr: # pyright: ignore[reportOptionalIterable] + m = re.search(r"Serving (\S+)", line) + if m: + url = m.group(1) + break + self.assertIsNotNone(url) + status, _, headers = E2_Serve()._get(url) # pyright: ignore[reportArgumentType] + self.assertEqual(status, 200) + self.assertIn("frame-ancestors 'none'", headers["Content-Security-Policy"]) + self.assertIn("default-src 'none'", headers["Content-Security-Policy"]) + self.assertEqual(headers["Cross-Origin-Resource-Policy"], "same-origin") + self.assertEqual(headers["Cross-Origin-Opener-Policy"], "same-origin") + finally: + proc.send_signal(signal.SIGINT) + proc.wait(timeout=10) + if proc.stderr: + proc.stderr.close() + + # -- S5, S6: git hardening and partial clones + + def test_git_argv_is_hardened(self) -> None: + """Every git call disables fsmonitor and fetching; the numstat log disables textconv and ext diff.""" + argv = rs.git_cmd("/r", "log") + for opt in ("core.fsmonitor=false", "protocol.allow=never"): + self.assertEqual(argv[argv.index(opt) - 1], "-c", opt) + src = (ROOT / "repo_stats.py").read_text() + m = re.search(r'stream_git\(repo, "log", "--first-parent", "-m", "--numstat".*?\)', src, re.S) + self.assertIsNotNone(m) + self.assertIn('"--no-textconv"', m.group(0)) # pyright: ignore[reportOptionalMemberAccess] + self.assertIn('"--no-ext-diff"', m.group(0)) # pyright: ignore[reportOptionalMemberAccess] + + def test_partial_clone_warns_and_never_fetches(self) -> None: + """A blobless clone is detected; the run warns, fetches nothing, and fails with a clear hint.""" + src = merge_repo().path + dest = tmpdir() / "partial" + subprocess.run(["git", "clone", "-q", "--filter=blob:none", "--upload-pack", + "git -c uploadpack.allowFilter=true upload-pack", f"file://{src}", str(dest)], + check=True, capture_output=True) + + def missing() -> int: + """Count objects the partial clone does not have.""" + out = git_out(dest, "rev-list", "--objects", "--missing=print", "--all") + return sum(1 for line in out.splitlines() if line.startswith("?")) + + before = missing() + self.assertGreater(before, 0) + self.assertTrue(rs.is_partial_clone(str(dest))) + self.assertFalse(rs.is_partial_clone(str(src))) + p = run_cli([dest, "-o", tmpdir() / "o.html"]) + self.assertEqual(p.returncode, 1, p.stderr) + self.assertIn("warning: This is a partial clone", p.stderr) + self.assertIn("Clone without a filter", p.stderr) + self.assertNotIn("Traceback", p.stderr) + self.assertEqual(missing(), before, "no missing object may be fetched") + + # -- N6, N11: refs and PR numbers are never options or regex syntax + + def test_refs_starting_with_dash_are_refused(self) -> None: + """A branch that looks like an option is refused before git sees it; no file is created.""" + d = tmpdir() + p = run_cli([merge_repo().path, "-o", d / "o.html", "--branch=--output=pwned.txt"], cwd=d) + self.assertEqual(p.returncode, 1) + self.assertIn("starts with '-'", p.stderr) + self.assertFalse((d / "pwned.txt").exists()) + + def test_end_of_options_depends_on_git_version(self) -> None: + """--end-of-options is used from git 2.30 (rev-parse support) and left out before.""" + with mock.patch.object(rs, "_git_version", (2, 30)): + self.assertEqual(rs.revs("main"), ["--end-of-options", "main"]) + with mock.patch.object(rs, "_git_version", (2, 29)): + self.assertEqual(rs.revs("main"), ["main"]) + self.assertGreaterEqual(rs.git_version(), (2, 0)) + # And the real git accepts the argv repo-stats builds. + out = rs.run_git(str(merge_repo().path), "rev-parse", "--verify", "-q", *rs.revs("main^{commit}")) + self.assertRegex(out.strip(), r"^[0-9a-f]{40}$") + + def test_pr_number_is_escaped_in_regex(self) -> None: + """A PR number is matched literally in a squash subject, never as a regex.""" + c = {"sha": "abc", "parents": ["p"], "subject": "fix: thing (#11)"} + self.assertIsNone(rs.local_summary({"number": "1+", "sha": "abc"}, {"abc": c})) # as a regex, 1+ matches 11 + self.assertIs(rs.local_summary({"number": 11, "sha": "abc"}, {"abc": c}), c) + + if __name__ == "__main__": unittest.main()