From 7e95db0e560ddd9b142b3619973d62efc762b7e2 Mon Sep 17 00:00:00 2001 From: husam-e <2340614+husam-e@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:51:07 -0400 Subject: [PATCH 01/10] docs(repo-stats): plan to replace API tokens with gh/glab CLIs --- repo-stats/docs/plan-cli-auth.adoc | 345 +++++++++++++++++++++++++++++ 1 file changed, 345 insertions(+) create mode 100644 repo-stats/docs/plan-cli-auth.adoc diff --git a/repo-stats/docs/plan-cli-auth.adoc b/repo-stats/docs/plan-cli-auth.adoc new file mode 100644 index 0000000..34a5144 --- /dev/null +++ b/repo-stats/docs/plan-cli-auth.adoc @@ -0,0 +1,345 @@ += Plan: replace API tokens with the `gh` and `glab` CLIs +:toc: macro + +Base branch: `claude/zealous-johnson-rfqa12` (commit `6c2e7a1`). +Status: proposal. No code is changed on this branch yet. + +toc::[] + +== Summary + +repo-stats can stop handling tokens completely. +It can call `gh api` and `glab api` as subprocesses and never read, hold, send or print a credential. +The tokens still exist, but `gh` and `glab` own them, in the OS keychain locally and in the CI runner's environment in CI. + +This removes a whole class of bugs from the tool, and it is a real improvement for local use. +In CI the improvement is smaller, because the token still sits in an environment variable there. +One caveat matters for the design: neither CLI is safe if you point it at an arbitrary host (see <>). +So repo-stats must keep its host allowlist and must always pass `--hostname` itself. + +== Goals + +* repo-stats never reads, stores, sends, logs or names the value of a credential. +* Locally, a user who has run `gh auth login` or `glab auth login` once runs the tool with no extra setup. +* Git-only mode still needs nothing but Python and git. +* CI needs one documented environment line or one login step, and nothing more. +* No credential can reach a host the user did not choose, whatever the repository's remote says. + +[[verified]] +== Verified CLI behaviour + +These results come from gh 2.103.2 and glab 1.124.0, tested against a local listener that logs request headers. +The plan depends on them. + +[cols="1,3"] +|=== +| Behaviour | Consequence for repo-stats + +| `gh` sends `GH_TOKEN` and `GITHUB_TOKEN` only to `github.com` and `*.ghe.com`. +| A crafted remote cannot leak a github.com token. + +| `gh` sends `GH_ENTERPRISE_TOKEN` to *any* host passed with `--hostname`. +| repo-stats must not take the hostname from an untrusted remote. + +| `glab` sends `GITLAB_TOKEN` to *any* host passed with `--hostname`, including a host it never logged in to. +| Same rule: the hostname must come from the allowlist or from an explicit flag. + +| Without `--hostname`, `glab api` uses the host of the git repository in its *working directory*. With a crafted remote it sent `GITLAB_TOKEN` there, and also sent a telemetry call (`usage_data/track_event`) to that host with the token attached. +| Always pass `--hostname`. Run the CLI from a neutral directory, never from the analysed repo. Set `GLAB_SEND_TELEMETRY=false`. + +| An explicit `--hostname gitlab.com` was respected, even with the crafted repo as the working directory. +| The fix above is enough. + +| `-F key=@path` (both CLIs) reads a local file and sends its contents. `-F` also expands `{owner}`/`:fullpath` placeholders from the current repository. +| Pass every value with `-f` (raw string), never `-F`. + +| `gh` exits 4 when not authenticated and prints `gh auth login` advice. API errors exit 1, print `gh: (HTTP )` to stderr, and print the JSON body to stdout. `glab` does the same with exit 1. +| Exit codes and stderr are enough to map errors to clear messages. + +| `glab` with `GLAB_ENABLE_CI_AUTOLOGIN=true` in GitLab CI authenticates every command, `glab api` included, with `CI_JOB_TOKEN` (checked in glab's source, `internal/config/config_mapping.go`). +| GitLab CI can run on the short-lived job token instead of a long-lived PAT. The current code cannot do this, because it sends `PRIVATE-TOKEN` and the job token needs `JOB-TOKEN`. + +| The GitLab job token can call `GET /projects/:id/merge_requests` and `GET .../merge_requests/:iid/notes`, but *not* `.../merge_requests/:iid/commits`, and it cannot call GraphQL. +| Keep GitLab on REST. Degrade gracefully when the commits endpoint is refused. +|=== + +== Is it more secure? + +=== What gets better + +* *No credential code in repo-stats.* + `resolve_token`, `http_json`, the redirect guard, the proxy bypass, the insecure-URL check and the token error messages all go, about 150 lines. + Each of these existed only to stop the tool leaking a token, and each was a place a bug could hide. + The tests for them (`B3_Tokens`, the loopback-proxy tests) were needed for the same reason. +* *No token in the shell.* + The README now suggests `GITLAB_TOKEN=glpat-... python3 ...`, which writes the token into shell history. + It also suggests `GITHUB_TOKEN=$(gh auth token) ...`, which puts it in the environment of every process the tool starts, every `git` call included. + With `gh auth login` or `glab auth login`, the token stays in the OS keychain and is read only by the CLI, only for the request. +* *No pasted PATs.* + Both CLIs support browser and device-code OAuth, so users never copy a token at all. + `gh` can also use expiring, auto-refreshed tokens (`--expiring`). +* *GitLab CI can use the job token.* + It is valid only while the job runs and is masked in logs, so a long-lived token in a CI variable becomes optional. +* *TLS, proxies, redirects and enterprise CAs are handled by the vendors' maintained HTTP stacks.* + repo-stats no longer handles them itself. + +=== What does not get better, or gets worse + +* *The token still exists.* + Any process running as the same user can run `gh auth token`. + A malicious or compromised copy of repo-stats could do this, so the change protects against accidental leaks, not against a hostile tool. + The same was true before. +* *Broader default scopes.* + `gh auth login` asks for at least `repo`, `read:org` and `gist`, and `repo` gives write access to every private repository. + `glab`'s OAuth login asks for `api` and `write_repository`. + A user who carefully made a read-only, fine-grained token loses least privilege by switching to the default login. + See <> for how to keep it. +* *CI is mostly unchanged.* + The CLI still reads the token from an environment variable, and that variable is still visible to every process in the step that sets it. + The gain in CI is less credential code, plus the GitLab job token. +* *New dependency.* + API mode now trusts the `gh` or `glab` binary and its update channel, a larger supply chain than the Python standard library. + Git-only mode is unaffected. +* *Unsafe CLI defaults (see <>).* + These are why the host allowlist cannot be removed. + +Verdict: the change is worth making. +It removes every token from repo-stats and from users' shell habits, and enables job-token auth in GitLab CI. +The remaining risks are explained in <>. + +== Design + +=== User-facing changes + +[cols="1,3"] +|=== +| Removed | `--token-env`, `--api-url`, and reading `GITHUB_TOKEN`, `GH_TOKEN`, `GITLAB_TOKEN` and `GITLAB_PRIVATE_TOKEN`. +| Added | `--hostname HOST`: the GitHub Enterprise or self-managed GitLab host. It is passed to the CLI as `--hostname`. +| Unchanged | `--provider`, `--source auto/git/api`, and every other flag. +|=== + +Behaviour of `--source auto` (the default): + +. Find the provider and host (next section). If neither is found, use git mode and show a warning. +. If the CLI is not on `PATH`, use git mode and warn: "Install gh (https://cli.github.com) for exact PR data." +. Call the API. If the CLI says it is not authenticated (gh exit 4, or HTTP 401), use git mode and warn: "Run `gh auth login`" (or the glab equivalent, or set the CI variable). + +With `--source api`, each of these is an error instead of a fallback. + +There is no "is the user logged in?" pre-check. +`gh auth status` makes its own network call and is not needed, because the first real request answers the same question. + +=== Host selection (keeps the current trust model) + +* The remote host is `github.com` or `gitlab.com`: use it, and pass `--hostname github.com` or `--hostname gitlab.com`. +* Any other remote host: API mode needs `--provider` plus `--hostname`, given by the user. + Never derive the host from the remote, because `GH_ENTERPRISE_TOKEN`, `GITLAB_TOKEN` and `CI_JOB_TOKEN` would go to it. +* Optional convenience for self-managed CI: trust the remote host when it equals `CI_SERVER_FQDN` (with `GITLAB_CI=true`), or the host of `GITHUB_SERVER_URL` (with `GITHUB_ACTIONS=true`). + The runner sets these variables, and anyone who can change them already controls the job. + +=== One subprocess helper + +The new `run_cli(tool, host, args)` replaces `http_json`. It: + +* resolves the binary once with `shutil.which` and runs it from its absolute path, with `shell=False` and an argv list. +* sets `cwd` to a fresh temporary directory, so neither CLI can read the analysed repository's remotes or placeholders. +* always puts `--hostname ` in argv. +* passes only `-f key=value` (raw strings), never `-F`, `--input`, `--form` or placeholders. + The GraphQL query is a constant, and REST paths are built from `urllib.parse.quote(..., safe="")` components. +* copies `os.environ` and adds `GH_PROMPT_DISABLED=1`, `GH_NO_UPDATE_NOTIFIER=1`, `GLAB_SEND_TELEMETRY=false`, `GLAB_CHECK_UPDATE=false` and `NO_COLOR=1`. + It removes `GH_DEBUG`, `DEBUG`, `GLAB_DEBUG` and `GLAB_DEBUG_HTTP`, so stderr (which the tool may quote in errors) cannot contain request dumps. + It never reads or sets a token variable. +* uses a timeout per call. It retries with backoff when stderr ends in `(HTTP 429)` or `(HTTP 5xx)`, keeping today's backoff policy. +* maps errors to messages: exit 4 or HTTP 401 → "not logged in; run `gh auth login` / `glab auth login`, or set `GH_TOKEN` / use `GLAB_ENABLE_CI_AUTOLOGIN` in CI"; 403 → no access or rate limit; 404 → not found or no access. + It quotes at most the CLI's one-line stderr summary, never stdout. +* parses stdout as JSON. A GraphQL `errors` array is reported as today. + +=== GitHub + +The query is the existing `GITHUB_QUERY`, unchanged. +The tool keeps its own pagination loop, so it can still stop early on `--since` and `--max-prs`. + +[source] +---- +gh api graphql --hostname github.com -f query= -f owner= -f name= [-f cursor=] +---- + +`gh` sends GraphQL to `/api/graphql` on Enterprise hosts by itself, so `--api-url` has no equivalent. + +=== GitLab + +The tool stays on REST, because the job token cannot call GraphQL. +Each call passes `--method GET`, so `-f` fields become query parameters and nothing goes into the URL by hand. + +[source] +---- +glab api --hostname gitlab.com --method GET projects//merge_requests -f state=all -f scope=all -f order_by=updated_at -f sort=desc -f per_page=100 -f page= [-f updated_after=...] [-f target_branch=...] +glab api --hostname gitlab.com --method GET projects//merge_requests//commits -f per_page=100 +glab api --hostname gitlab.com --method GET projects//merge_requests//notes -f sort=asc -f order_by=created_at -f per_page=100 +---- + +* Pagination: stop when a page has fewer than `per_page` items, instead of reading `X-Next-Page`. This avoids parsing headers out of `--include` output. +* The per-MR detail calls keep the existing 8-worker thread pool, now spawning one process per call. +* If `.../commits` returns 403 or 404 (the job-token case), stop calling it. + Take `first_commit` and `commits` from the local merge-commit graph where one exists (`claims`), add `"first_commit"` to `inferred`, and add one dashboard warning. + Squash-merged MRs then have no coding time, and the warning says so. + +=== Git subprocesses + +`git_cmd` and `stream_git` pass an environment with credential variables removed: `GH_TOKEN`, `GITHUB_TOKEN`, `GH_ENTERPRISE_TOKEN`, `GITHUB_ENTERPRISE_TOKEN`, `GITLAB_TOKEN`, `GITLAB_ACCESS_TOKEN`, `GITLAB_PRIVATE_TOKEN`, `OAUTH_TOKEN` and `CI_JOB_TOKEN`. +The tool removes them by name and never reads their values. +Git needs none of them, so a malicious hook, filter or `textconv` driver in an untrusted repository cannot read them through git. + +=== Code removed from `repo_stats.py` + +`_SameHostRedirect`, `_OPENER`, `_DIRECT_OPENER`, `_is_loopback`, `http_json`, `resolve_token`, `--token-env`, `--api-url`, the token-name log line, and the `urllib.request`, `urllib.error`, `http.client`, `email.utils` and `socket` imports where nothing else uses them. +`_retry_after` goes too, because the CLIs do not expose `Retry-After` without `--include`. +A fixed backoff replaces it. + +== Implementation steps + +. Add `run_cli` and the error mapping, with unit tests that use fake CLIs (next step). +. Add fake `gh` and `glab` executables to the tests. + These are small Python scripts placed first on `PATH`. + Each one records its argv, cwd and environment to a JSON log, then answers by calling the existing `mock_servers.github_handler` and `gitlab_handler` functions with a request dict built from argv. + The fixtures stay as they are, and the tests stay stdlib-only and offline. + A Windows variant of the scripts is not needed for CI on Linux and macOS. +. Port `fetch_github` to `run_cli`. Port the `B1_GitHub` tests. +. Port `fetch_gitlab` to `run_cli`, including the job-token fallback for commits. Port the `B2_GitLab` tests. +. Replace the host and token logic in `collect()` with the host-selection rules above, and add `--hostname`. + Remove `--token-env` and `--api-url`. + Since the tool is at 0.1.0, make them hard errors that explain the new flag rather than keeping aliases. +. Strip credential variables from git subprocess environments. +. Replace `B3_Tokens` with tests that assert: +** every CLI call has `--hostname`, uses no `-F`, `--input`, `--form` or placeholder syntax, and runs from a cwd outside the repository. +** a remote such as `github.evil.example` or `gitlab.evil.example` with no `--hostname` never starts a CLI. +** `GLAB_SEND_TELEMETRY=false` is set, and the debug variables are removed. +** git child processes see none of the credential variables (a fake `git` wrapper on `PATH` can record the environment). +** a missing CLI, gh exit 4, and HTTP 401/403/404 each give the right fallback (auto) or error (api). +** a refused `.../commits` call in GitLab degrades with one warning. +. Delete the loopback-proxy and redirect tests, which covered code that no longer exists. +. Add an opt-in live smoke test, skipped unless `REPO_STATS_LIVE=1`, that runs real `gh` against a small public repository. +. Update the README (Quick start, "Where the data comes from", Security), the `--help` epilog, and the template's "Run with an API token" hint, which becomes "Install and log in to gh or glab". + +[[usage]] +== How users will run it + +=== Locally + +[source,sh] +---- +# one-time, if not already done +gh auth login # or: glab auth login +# every run, with no tokens and no env vars +python3 repo-stats/repo_stats.py /path/to/repo --serve + +# GitHub Enterprise / self-managed GitLab +gh auth login --hostname ghe.example.com +python3 repo-stats/repo_stats.py /path/to/repo --provider github --hostname ghe.example.com +---- + +If neither CLI is installed, the tool still works in git-only mode and says so on the dashboard. + +=== GitHub Actions + +`gh` is preinstalled on GitHub-hosted runners. It needs the workflow token passed in explicitly. + +[source,yaml] +---- +permissions: + contents: read + pull-requests: read +jobs: + stats: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # full history and tags + - uses: actions/checkout@v4 + with: + repository: husam-e/scripts + path: tools + - run: python3 tools/repo-stats/repo_stats.py . -o repo-stats.html + env: + GH_TOKEN: ${{ github.token }} # read by gh only, never by repo-stats + - uses: actions/upload-artifact@v4 + with: + name: repo-stats + path: repo-stats.html +---- + +`github.token` is created for the job and expires when it ends. +`permissions:` limits it to read access. +Set `GH_TOKEN` on this step only, not at job level, so other steps never see it. +To analyse a different private repository, use a GitHub App installation token (for example from `actions/create-github-app-token`), not a PAT. + +=== GitLab CI + +[source,yaml] +---- +repo-stats: + image: registry.gitlab.com/gitlab-org/cli:v1.124.0 # Alpine with glab and git; pin a version + variables: + GIT_DEPTH: 0 # full history + GLAB_ENABLE_CI_AUTOLOGIN: "true" # glab authenticates with CI_JOB_TOKEN + script: + - apk add --no-cache python3 + - git clone --depth 1 https://github.com/husam-e/scripts.git /tmp/tools + - python3 /tmp/tools/repo-stats/repo_stats.py . -o repo-stats.html + artifacts: + paths: [repo-stats.html] +---- + +The job token can list MRs and read their notes, but not their commits, so squash-merged MRs have no coding time. +For full data, store a project access token with only the `read_api` scope and a short expiry as a masked, protected CI/CD variable. +Name it `GITLAB_TOKEN`, and glab will prefer it over the job token. +On self-managed GitLab, add `--provider gitlab --hostname $CI_SERVER_FQDN` (or rely on the optional `CI_SERVER_FQDN` rule above). + +=== A remote job (cron VM, Kubernetes CronJob, Jenkins, and so on) + +Provide the token to the CLI's process only, from your secret store, for the duration of the run: + +[source,sh] +---- +# Kubernetes: mount the secret as an env var on the container +# Jenkins: withCredentials([string(credentialsId: 'gh-read', variable: 'GH_TOKEN')]) { sh '...' } +# systemd: LoadCredential=gh-token:/etc/creds/gh-token, then in the unit's script: +GH_TOKEN="$(cat "$CREDENTIALS_DIRECTORY/gh-token")" python3 repo_stats.py /srv/repo -o /srv/out/stats.html +---- + +Use one of these, from best to worst: + +. A *GitHub App* installation token, minted for each run (it expires within an hour), with read-only Pull requests and Contents permissions on only the repositories it needs. + For GitLab, use a project or group access token with `read_api`, a short expiry and rotation. +. A *fine-grained* PAT with read-only Pull requests and Contents on only the target repositories, with an expiry. +. Avoid `gh auth login` and `glab auth login` on headless servers. + With no OS keyring, both CLIs fall back to writing the token in plain text (`~/.config/gh/hosts.yml`, `~/.config/glab-cli/config.yml`). + If you must use them, run the job as a dedicated user and check that the file has mode 600. + +The repository clone needs only read access to git. +Use a deploy key or the same short-lived token through a credential helper, not a token embedded in the remote URL. + +[[least-privilege]] +== Keeping least privilege on a laptop + +`gh auth login` cannot request fewer scopes than `repo`, `read:org` and `gist`. +To use a read-only token without putting it in your shell: + +* GitHub: create a fine-grained, read-only PAT, then run `gh auth login --with-token < file` and delete the file. + `gh` stores the token in the keychain. + The gh help warns that fine-grained tokens can confuse some *other* gh commands, so a separate gh account or config dir (`GH_CONFIG_DIR`) keeps your main login untouched. +* GitLab: create a PAT with only the `read_api` scope, then run `glab auth login --stdin < file`. glab stores it in the keyring when one is available. + +[[gaps]] +== Remaining security gaps + +. *Same-user access.* Anything running as you can ask `gh` or `glab` for the token. Moving to the CLIs does not change this. +. *Scope.* Default CLI logins are read-write across all of your repositories. Mitigate as in <>. +. *Host trust depends on repo-stats.* Both CLIs send environment tokens to whatever host they are given, and glab follows the working directory's remote. The allowlist, the explicit `--hostname` and the neutral `cwd` are what prevent leaks, and the tests must pin all three. +. *A wrong but explicit `--hostname` is trusted.* A user who passes `--hostname evil.example` with `GH_ENTERPRISE_TOKEN` or `GITLAB_TOKEN` set will send it there. This is the same as `--api-url` today. Documentation is the only defence. +. *CI environment exposure.* In CI the token is an environment variable, readable by every process in that step. Scope it to the one step, use the job's own short-lived token, and do not run untrusted code in the same step. +. *Plain-text fallback.* On headless machines with no keyring, `gh` and `glab` write tokens to plain-text config files. In GitLab CI, glab always stores to the config file, not the keyring. +. *Supply chain.* API mode trusts the `gh` or `glab` binary on `PATH`. On Windows, Python can find an executable in the current directory before `PATH`. Running from a neutral `cwd` with an absolute path from `shutil.which` reduces this, but whether `which` itself checks the current directory depends on the Python version and the `NoDefaultCurrentDirectoryInExePath` setting, so it does not remove the risk. +. *Untrusted repositories.* `git` itself can run commands configured in a repository's `.git/config` (for example a `textconv` driver). Removing credential variables from git's environment limits the damage, but analysing a repository you do not trust is still risky. This is unchanged, and unrelated to tokens. +. *Output data.* The HTML, JSON and CSV contain PR titles, branch names and timings, but no credentials. `--no-titles` remains the tool for sharing. From a4811e3690501f79978375eb8928cef31e5f77de Mon Sep 17 00:00:00 2001 From: husam-e <2340614+husam-e@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:36:28 -0400 Subject: [PATCH 02/10] docs(repo-stats): fix read-only token advice; gh keychain entries are not per config dir --- repo-stats/docs/plan-cli-auth.adoc | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/repo-stats/docs/plan-cli-auth.adoc b/repo-stats/docs/plan-cli-auth.adoc index 34a5144..6dfe2ca 100644 --- a/repo-stats/docs/plan-cli-auth.adoc +++ b/repo-stats/docs/plan-cli-auth.adoc @@ -324,12 +324,25 @@ Use a deploy key or the same short-lived token through a credential helper, not == Keeping least privilege on a laptop `gh auth login` cannot request fewer scopes than `repo`, `read:org` and `gist`. -To use a read-only token without putting it in your shell: +To use a read-only token, keep it in the OS keychain under its own name and give it to the CLI for one command only. +The value then never appears in shell history, in a file, or in the shell's environment. -* GitHub: create a fine-grained, read-only PAT, then run `gh auth login --with-token < file` and delete the file. - `gh` stores the token in the keychain. - The gh help warns that fine-grained tokens can confuse some *other* gh commands, so a separate gh account or config dir (`GH_CONFIG_DIR`) keeps your main login untouched. -* GitLab: create a PAT with only the `read_api` scope, then run `glab auth login --stdin < file`. glab stores it in the keyring when one is available. +[source,sh] +---- +# macOS: store once (-w last makes it prompt), then use per run +security add-generic-password -a "$USER" -s repo-stats-github -w +GH_TOKEN="$(security find-generic-password -a "$USER" -s repo-stats-github -w)" python3 repo_stats.py /path/to/repo + +# Linux (libsecret): store once (prompts), then use per run +secret-tool store --label="repo-stats GitHub read-only" service repo-stats host github.com +GH_TOKEN="$(secret-tool lookup service repo-stats host github.com)" python3 repo_stats.py /path/to/repo +---- + +For GitLab, store a `read_api` token the same way and set `GITLAB_TOKEN` instead. + +Do not load the read-only token with `gh auth login --with-token`. +gh names its keychain entries by host and username only (`gh:github.com`, checked in gh's source, `internal/config/config.go`). +A token for the same account replaces the main login's token, even under a separate `GH_CONFIG_DIR`. [[gaps]] == Remaining security gaps From a9b3c24a242aaa4cea210ca2eb6fe105f3efd19a Mon Sep 17 00:00:00 2001 From: claude Date: Tue, 27 Oct 2026 00:44:11 +0000 Subject: [PATCH 03/10] feat(repo-stats)!: read PR data through gh/glab and never handle a token API data now comes from `gh api` (GitHub GraphQL) and `glab api` (GitLab REST), which use their own login: the OS keychain, GH_TOKEN/GITLAB_TOKEN, or the GitLab CI job token. repo_stats.py no longer reads, holds or sends a credential. - Remove http_json, the redirect guard, the loopback proxy bypass and resolve_token. A Cli class runs every request and refuses anything outside a read-only allowlist: GraphQL queries (no mutations) for gh, and GET on the MR list, commits and notes endpoints for glab. - Keep the host allowlist. gh sends GH_ENTERPRISE_TOKEN and glab sends GITLAB_TOKEN to whatever host they are given, and glab without --hostname follows the working directory's remote. So the host is github.com/gitlab.com from the remote or the new --hostname flag, it is always passed as --hostname, and the CLI runs from an empty temp dir with telemetry, prompts, update checks and debug dumps off. - In GitLab CI, a remote on CI_SERVER_HOST is trusted without --hostname. When the login cannot read MR commits (a job token), one probe stops further lookups and first-commit times come from local merge commits, marked as inferred. - git runs without credential variables in its environment. - --api-url and --token-env are replaced by --hostname; using them fails with a message that names the replacement. Tests: fake gh/glab (tests/fake_cli) forward each call to the existing mock servers, find tokens like the real CLIs and reject disallowed flags; clean_env() always puts them first on PATH. New tests cover the allowlist, --hostname, the temp working directory, the CLI environment, lookalike hosts, CI host trust, the job-token fallback and git's environment. The HTTP redirect and proxy tests are removed with that code. Checked end to end with real gh 2.103.2 and glab 1.124.0. BREAKING CHANGE: --api-url and --token-env are removed, and GITHUB_TOKEN/GITLAB_TOKEN are no longer read by repo_stats.py. Install and log in to gh or glab (or set GH_TOKEN/GITLAB_TOKEN for the CLI), and use --provider with --hostname for self-hosted servers. --- repo-stats/repo_stats.py | 480 ++++++++++++++++---------- repo-stats/template.html | 2 +- repo-stats/tests/fake_cli/_fake.py | 148 ++++++++ repo-stats/tests/fake_cli/gh | 9 + repo-stats/tests/fake_cli/glab | 9 + repo-stats/tests/helpers.py | 44 ++- repo-stats/tests/test_repo_stats.py | 505 ++++++++++++++++++---------- repo-stats/tests/test_ui.py | 2 +- 8 files changed, 845 insertions(+), 354 deletions(-) create mode 100644 repo-stats/tests/fake_cli/_fake.py create mode 100755 repo-stats/tests/fake_cli/gh create mode 100755 repo-stats/tests/fake_cli/glab diff --git a/repo-stats/repo_stats.py b/repo-stats/repo_stats.py index b73b4eb..bdbc1ce 100644 --- a/repo-stats/repo_stats.py +++ b/repo-stats/repo_stats.py @@ -5,6 +5,9 @@ one self-contained HTML file with lines of code over time, PR/MR throughput, size, type, risk and cycle-time statistics, and DORA metrics. +API data comes from the `gh` (GitHub) or `glab` (GitLab) CLI, which uses its own login. +repo-stats never reads, stores or sends a credential, and only ever sends read requests. + Python 3.8+, standard library only. Run `repo_stats.py --help` for usage. """ from __future__ import annotations @@ -15,25 +18,20 @@ import csv import datetime as dt import email.utils -import http.client import http.server -import ipaddress import json import os import re +import shutil import subprocess -import socket import sys import tempfile import threading import time -import urllib.error import urllib.parse -import urllib.request import webbrowser -from email.message import Message from pathlib import Path -from typing import IO, Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Set, Tuple, TypedDict, cast +from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Set, Tuple, TypedDict, cast __version__ = "0.1.0" @@ -217,6 +215,18 @@ 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. +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") + + +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} + + 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] @@ -225,7 +235,7 @@ def git_cmd(repo: str, *args: str) -> List[str]: def run_git(repo: str, *args: str, check: bool = True) -> str: """Run git and return its stdout; with check, raise ToolError on a non-zero exit.""" p = subprocess.run(git_cmd(repo, *args), capture_output=True, text=True, - encoding="utf-8", errors="replace") + encoding="utf-8", errors="replace", env=git_env()) if check and p.returncode != 0: raise ToolError(f"git {' '.join(args[:3])} failed: {p.stderr.strip() or p.stdout.strip()}") return p.stdout @@ -236,7 +246,7 @@ def stream_git(repo: str, *args: str) -> Iterator[str]: # stderr goes to a temp file: a PIPE nobody reads can fill up and deadlock git. with tempfile.TemporaryFile() as err: p = subprocess.Popen(git_cmd(repo, *args), stdout=subprocess.PIPE, stderr=err, - text=True, encoding="utf-8", errors="replace") + text=True, encoding="utf-8", errors="replace", env=git_env()) assert p.stdout is not None with p.stdout: for line in p.stdout: @@ -292,8 +302,8 @@ def parse_remote(url: str) -> Optional[Tuple[str, str]]: def detect_provider(host: str) -> Optional[str]: """Return "github" or "gitlab" for the public hosts only, else None. - Anything else needs --provider and --api-url, so a crafted remote URL (github.evil.example) can never - receive a token. + Anything else needs --provider and --hostname, so a crafted remote URL (github.evil.example) can never + make gh or glab send a credential to its host. """ return TRUSTED_HOSTS.get(host) @@ -694,40 +704,48 @@ def infer_prs_from_git(first_parent: List[Commit], graph: Graph, default_branch: # --------------------------------------------------------------------------- -# HTTP + API clients +# GitHub and GitLab APIs, through the gh and glab CLIs # --------------------------------------------------------------------------- +# +# repo-stats never reads, holds or sends a credential. Every API request is a read-only `gh api` or +# `glab api` call, and the CLI finds its own login: the OS keychain, GH_TOKEN / GITLAB_TOKEN, or the +# GitLab CI job token. Two CLI behaviours shape this code: both send an environment token to whatever +# --hostname they are given, and glab without --hostname follows the remote of the git repository in its +# working directory. So the host always comes from the allowlist or an explicit flag, it is always passed +# as --hostname, and the CLI always runs from an empty temporary directory. class ApiError(ToolError): - """A failed or unexpected GitHub/GitLab API call.""" - + """A failed or unexpected GitHub/GitLab API call. `status` is the HTTP status, when there was one.""" -class _SameHostRedirect(urllib.request.HTTPRedirectHandler): - """Never follow a redirect to another host or to plain http, so tokens cannot leak.""" + def __init__(self, msg: str, status: Optional[int] = None) -> None: + """Store the message and the HTTP status.""" + super().__init__(msg) + self.status = status - def redirect_request(self, req: urllib.request.Request, fp: IO[bytes], code: int, msg: str, - headers: http.client.HTTPMessage, newurl: str) -> Optional[urllib.request.Request]: - """Follow the redirect only if it stays on the same host and on https (or loopback http).""" - old, new = urllib.parse.urlparse(req.full_url), urllib.parse.urlparse(newurl) - if new.netloc != old.netloc: - raise ApiError(f"Refusing cross-host redirect to {new.netloc}") - loopback_http = old.scheme == "http" and _is_loopback(old.hostname or "") - if new.scheme != "https" and not (loopback_http and new.scheme == "http"): - raise ApiError(f"Refusing redirect to insecure URL {new.scheme}://{new.netloc}") - return super().redirect_request(req, fp, code, msg, headers, newurl) +class CliUnavailable(ApiError): + """gh or glab is not installed or not logged in: a reason to use git mode, not an API failure.""" -_OPENER = urllib.request.build_opener(_SameHostRedirect) -_DIRECT_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), _SameHostRedirect) - -def _is_loopback(host: str) -> bool: - """Return True for "localhost" or a loopback IP address.""" - if host == "localhost": - return True - try: - return ipaddress.ip_address(host).is_loopback - except ValueError: - return False +CLI_FOR = {"github": "gh", "gitlab": "glab"} +CLI_HELP = { # tool -> (install page, what to set in CI) + "gh": ("https://cli.github.com", "GH_TOKEN"), + "glab": ("https://gitlab.com/gitlab-org/cli", "GLAB_ENABLE_CI_AUTOLOGIN=true or GITLAB_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") +# No prompts, update checks, banners, pager or colour. glab's telemetry is off because it sends its own +# request, with the credential, to the API host. +CLI_QUIET_ENV = {"GH_PROMPT_DISABLED": "1", "GH_NO_UPDATE_NOTIFIER": "1", "GH_NO_EXTENSION_UPDATE_NOTIFIER": "1", + "GLAB_NO_PROMPT": "1", "GLAB_CHECK_UPDATE": "false", "GLAB_SHOW_WHATS_NEW": "false", + "GLAB_SEND_TELEMETRY": "false", "NO_COLOR": "1", "CLICOLOR": "0", "GH_PAGER": "cat", "PAGER": "cat"} +CLI_TIMEOUT = 120 +HOSTNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$") +# 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))?$") def _retry_after(value: Optional[str], default: int) -> int: @@ -748,57 +766,137 @@ def _retry_after(value: Optional[str], default: int) -> int: return min(wait, 60) if wait > 0 else default -def http_json(url: str, headers: Dict[str, str], body: Any = None, retries: int = 4) -> Tuple[Any, Message]: - """Send a GET (or a JSON POST when body is given) and return (parsed JSON, response headers). +def parse_cli_response(out: bytes) -> Tuple[Optional[int], Dict[str, str], bytes]: + """Split `gh api --include` / `glab api --include` output into (status, headers, body). - Retries rate limits, 5xx and transient network errors with backoff; raises ApiError otherwise. + Header names are lower-cased. The status is None when the output has no HTTP status line, which means + the CLI never got a response (not logged in, DNS failure, refused connection). """ - parsed = urllib.parse.urlparse(url) - if parsed.scheme != "https" and not _is_loopback(parsed.hostname or ""): - raise ApiError(f"Refusing to send credentials over insecure URL {parsed.scheme}://{parsed.netloc}") - data = json.dumps(body).encode() if body is not None else None - hdrs = dict(headers) - hdrs.setdefault("User-Agent", f"repo-stats/{__version__}") - if data is not None: - hdrs["Content-Type"] = "application/json" - delay = 2 - for attempt in range(retries + 1): - req = urllib.request.Request(url, data=data, headers=hdrs) - try: - opener = _DIRECT_OPENER if _is_loopback(parsed.hostname or "") else _OPENER - with opener.open(req, timeout=60) as resp: - raw = resp.read() - hdrs_out = resp.headers - except urllib.error.HTTPError as e: - if e.code in (429, 500, 502, 503, 504) and attempt < retries: - time.sleep(_retry_after(e.headers.get("Retry-After") if e.headers else None, delay)) - delay *= 2 - continue - if e.code == 401: - raise ApiError("API rejected the token (401). Check that it is valid and has read access.") - if e.code == 403: - raise ApiError("API returned 403: the token lacks access or the rate limit is exhausted.") - if e.code == 404: - raise ApiError("API returned 404: repository not found, or the token cannot see it.") - raise ApiError(f"API request failed with HTTP {e.code}") - except urllib.error.URLError as e: - # A refused connection or an unknown host will not fix itself: fail fast. - if attempt < retries and not isinstance(e.reason, (ConnectionRefusedError, socket.gaierror)): - time.sleep(delay) - delay *= 2 - continue - raise ApiError(f"Could not reach the API: {e.reason}") - except (OSError, http.client.HTTPException) as e: # timeouts, resets, truncated responses - if attempt < retries: - time.sleep(delay) + m = re.match(rb"HTTP/[0-9.]+ (\d{3})", out) + if not m: + return None, {}, out + sep = re.search(rb"\n\r?\n", out) + head, body = (out[:sep.start()], out[sep.end():]) if sep else (out, b"") + headers: dict[str, str] = {} + for line in head.decode("latin-1").splitlines()[1:]: + name, colon, value = line.partition(":") + if colon: + headers[name.strip().lower()] = value.strip() + return int(m.group(1)), headers, body + + +class Cli: + """Read-only access to one GitHub or GitLab host through `gh api` or `glab api`. + + Use as a context manager. Every request passes the read-only allowlist and --hostname, runs from an + empty temporary directory, and gets no debug or telemetry switches. + """ + + def __init__(self, tool: str, host: str, environ: Optional[Mapping[str, str]] = None, retries: int = 4) -> None: + """Find the CLI on PATH and prepare its environment. + + Raises: + CliUnavailable: the CLI is not installed. + ApiError: the hostname is not a plain host name. + """ + if tool not in CLI_HELP: + raise ApiError(f"Unknown CLI {tool!r}") + if not HOSTNAME_RE.match(host): + raise ApiError(f"Invalid hostname {host!r}") + env = dict(os.environ if environ is None else environ) + exe = shutil.which(tool, path=env.get("PATH", os.defpath)) + if not exe: + raise CliUnavailable(f"{tool} is not installed. Install it from {CLI_HELP[tool][0]} for exact PR data.") + for name in CLI_DEBUG_VARS: + env.pop(name, None) + env.update(CLI_QUIET_ENV) + self.tool, self.host, self.exe, self.env, self.retries = tool, host, exe, env, retries + self._dir = tempfile.TemporaryDirectory(prefix="repo-stats-cli-") + + def __enter__(self) -> Cli: + """Return self.""" + return self + + def __exit__(self, *exc: object) -> None: + """Remove the temporary working directory.""" + self._dir.cleanup() + + def graphql(self, query: str, variables: Mapping[str, Optional[str]]) -> Any: + """Send a read-only GraphQL query with string variables (None values are left out); return the JSON.""" + if self.tool != "gh" or not READ_ONLY_GRAPHQL.match(query) or WRITE_GRAPHQL.search(query): + raise ApiError("Refusing to send a GraphQL request that is not a read-only query") + args = ["api", "graphql", "--hostname", self.host, "--include", "-f", f"query={query}"] + for name, value in variables.items(): + if value is not None: + args += ["-f", f"{name}={value}"] + return self._run(args)[0] + + def get(self, endpoint: str, params: Mapping[str, Any]) -> Tuple[Any, Dict[str, str]]: + """GET an allowlisted GitLab endpoint with query parameters; return (JSON, lower-cased headers).""" + if self.tool != "glab" or not GITLAB_READ_ENDPOINT.match(endpoint): + raise ApiError(f"Refusing a request outside the read-only allowlist: {endpoint}") + args = ["api", "--hostname", self.host, "--method", "GET", "--include", endpoint] + for name, value in params.items(): + args += ["-f", f"{name}={value}"] + return self._run(args) + + def _login_hint(self) -> str: + """How to give the CLI a login, locally and in CI.""" + return f"Run `{self.tool} auth login --hostname {self.host}`, or in CI set {CLI_HELP[self.tool][1]}." + + def _run(self, args: List[str]) -> Tuple[Any, Dict[str, str]]: + """Run the CLI, retrying rate limits, 5xx and timeouts with backoff; return (JSON, headers).""" + delay = 2 + for attempt in range(self.retries + 1): + try: + p = subprocess.run([self.exe, *args], cwd=self._dir.name, env=self.env, stdin=subprocess.DEVNULL, + capture_output=True, timeout=CLI_TIMEOUT) + except subprocess.TimeoutExpired: + if attempt < self.retries: + time.sleep(delay) + delay *= 2 + continue + raise ApiError(f"{self.tool} api timed out after {CLI_TIMEOUT}s") + except OSError as e: + raise CliUnavailable(f"Could not run {self.tool}: {e.strerror or e}") + status, headers, body = parse_cli_response(p.stdout) + err = next((ln.strip() for ln in p.stderr.decode("utf-8", "replace").splitlines() if ln.strip()), "")[:300] + if status is None: + if p.returncode == 4 or "auth login" in err: + raise CliUnavailable(f"{self.tool} is not logged in to {self.host}. {self._login_hint()}") + # No HTTP response at all (DNS, refused connection, TLS): retrying will not fix it. + raise ApiError(f"Could not reach the API through {self.tool}: {err or f'exit status {p.returncode}'}") + if status in (429, 500, 502, 503, 504) and attempt < self.retries: + time.sleep(_retry_after(headers.get("retry-after"), delay)) delay *= 2 continue - raise ApiError(f"Could not reach the API: {e.__class__.__name__}") - try: - return json.loads(raw.decode("utf-8")), hdrs_out - except ValueError: - raise ApiError("API returned a response that is not JSON (a proxy or login page?)") - raise ApiError("API request failed") + if status == 401: + raise ApiError(f"API returned 401: {self.tool}'s login was rejected. {self._login_hint()}", 401) + if status == 403: + raise ApiError(f"API returned 403: {self.tool}'s login lacks access, or the rate limit is exhausted.", 403) + if status == 404: + raise ApiError(f"API returned 404: repository not found, or {self.tool}'s login cannot see it.", 404) + if not 200 <= status < 300: + raise ApiError(f"API request failed with HTTP {status}", status) + try: + return json.loads(body.decode("utf-8")), headers + except ValueError: + raise ApiError("API returned a response that is not JSON (a proxy or login page?)", status) + raise ApiError("API request failed") + + +def ci_server(environ: Mapping[str, str]) -> Optional[Tuple[str, str]]: + """Return (provider, host) of the CI server running this job, from variables the runner sets, or None. + + Whoever can change these variables already controls the job, so a remote on this host is trusted. + """ + if environ.get("GITLAB_CI") == "true" and environ.get("CI_SERVER_HOST"): + return "gitlab", environ["CI_SERVER_HOST"].lower() + if environ.get("GITHUB_ACTIONS") == "true" and environ.get("GITHUB_SERVER_URL"): + host = urllib.parse.urlparse(environ["GITHUB_SERVER_URL"]).hostname + if host: + return "github", host.lower() + return None def parse_iso(s: Optional[str]) -> Optional[int]: @@ -831,23 +929,20 @@ def parse_iso(s: Optional[str]) -> Optional[int]: """ -def fetch_github(owner: str, name: str, token: str, api_url: str, since: Optional[int], base_branch: str, +def fetch_github(cli: Cli, owner: str, name: str, since: Optional[int], base_branch: str, all_bases: bool, max_prs: Optional[int], progress: Callable[[str], None] = log, info: Optional[Dict[str, int]] = None) -> List[PR]: - """Fetch pull requests from the GitHub GraphQL API, newest-updated first. + """Fetch pull requests from the GitHub GraphQL API through `gh api`, newest-updated first. A PR merged after `since` was updated after it too, so paging stops at the first PR whose last activity is older than `since`; collect() then filters by merge (or open) time. `info`, if given, receives the number of PRs seen before the base-branch filter under "seen". """ - endpoint = api_url.rstrip("/") + "/graphql" - headers = {"Authorization": f"Bearer {token}"} prs: list[PR] = [] seen = 0 cursor = None while True: - data, _ = http_json(endpoint, headers, {"query": GITHUB_QUERY, - "variables": {"owner": owner, "name": name, "cursor": cursor}}) + data = cli.graphql(GITHUB_QUERY, {"owner": owner, "name": name, "cursor": cursor}) if not isinstance(data, dict): raise ApiError("GitHub returned an unexpected response") if data.get("errors"): @@ -855,7 +950,7 @@ def fetch_github(owner: str, name: str, token: str, api_url: str, since: Optiona raise ApiError(f"GitHub GraphQL error: {msg}") repo_node = (data.get("data") or {}).get("repository") if not repo_node: - raise ApiError("GitHub returned no repository: not found, or the token cannot see it.") + raise ApiError("GitHub returned no repository: not found, or gh's login cannot see it.") page = repo_node.get("pullRequests") if not isinstance(page, dict) or not isinstance(page.get("nodes"), list): raise ApiError("GitHub returned an unexpected pullRequests shape") @@ -925,16 +1020,18 @@ def github_pr(n: Dict[str, Any]) -> PR: } -def fetch_gitlab(project_path: str, token: str, api_url: str, since: Optional[int], base_branch: str, +def fetch_gitlab(cli: Cli, project_path: str, since: Optional[int], base_branch: str, all_bases: bool, max_prs: Optional[int], want_reviews: bool, progress: Callable[[str], None] = log, info: Optional[Dict[str, int]] = None) -> List[PR]: - """Fetch merge requests from the GitLab REST API, with per-MR commit and (optionally) review times. + """Fetch merge requests from the GitLab REST API through `glab api`, with per-MR commit and review times. + + REST, not GraphQL, because a GitLab CI job token cannot call GraphQL. A job token can list MRs and + their notes but not their commits; when the commits endpoint is refused, commit lookups stop and the + PRs are marked "commits_refused" so build_records can use local merge commits instead. - `info`, if given, receives the number of MRs fetched under "seen". + `info`, if given, receives "seen" (MRs fetched), "detail_errors" and "commits_refused" (0 or 1). """ - project = urllib.parse.quote(project_path, safe="") - base = f"{api_url.rstrip('/')}/projects/{project}" - headers = {"PRIVATE-TOKEN": token} + base = f"projects/{urllib.parse.quote(project_path, safe='')}/merge_requests" mrs: list[dict[str, Any]] = [] page = 1 while True: @@ -944,12 +1041,12 @@ def fetch_gitlab(project_path: str, token: str, api_url: str, since: Optional[in q["updated_after"] = dt.datetime.fromtimestamp(since, dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if not all_bases: q["target_branch"] = base_branch - data, hdrs = http_json(f"{base}/merge_requests?{urllib.parse.urlencode(q)}", headers) + data, hdrs = cli.get(base, q) if not isinstance(data, list): raise ApiError("GitLab returned an unexpected response for merge_requests") mrs.extend(m for m in data if isinstance(m, dict)) progress(f" fetched {len(mrs)} merge requests") - nxt = hdrs.get("X-Next-Page") + nxt = hdrs.get("x-next-page") if not data or not nxt or (max_prs and len(mrs) >= max_prs): break page = int(nxt) @@ -958,22 +1055,36 @@ def fetch_gitlab(project_path: str, token: str, api_url: str, since: Optional[in if info is not None: info["seen"] = len(mrs) - def pages(path: str) -> Iterator[Dict[str, Any]]: + def pages(endpoint: str, params: Optional[Mapping[str, str]] = None) -> Iterator[Dict[str, Any]]: """Yield every item of a paginated GitLab list endpoint, following X-Next-Page (at most 50 pages).""" - sep = "&" if "?" in path else "?" page = 1 for _ in range(50): - data, hdrs = http_json(f"{base}{path}{sep}per_page=100&page={page}", headers) + data, hdrs = cli.get(endpoint, {**(params or {}), "per_page": 100, "page": page}) if not isinstance(data, list): - raise ApiError(f"GitLab returned an unexpected response for {path.split('?')[0]}") + raise ApiError(f"GitLab returned an unexpected response for {endpoint.rsplit('/', 1)[-1]}") for item in data: if isinstance(item, dict): yield item - nxt = hdrs.get("X-Next-Page") + nxt = hdrs.get("x-next-page") if not data or not nxt: return page = int(nxt) + 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).""" + return list(pages(f"{base}/{int(iid)}/commits")) + + # One probe decides whether this login can read MR commits at all (a CI job token cannot). + commits_refused = False + probe: Optional[List[Dict[str, Any]]] = None + if mrs: + try: + probe = mr_commits(mrs[0]["iid"]) + except ApiError as e: + commits_refused = e.status in (401, 403, 404) + except (ValueError, KeyError, TypeError, AttributeError): + pass + def details(mr: Dict[str, Any]) -> Dict[str, Any]: """Fetch first commit time, commit count and first review time for one MR. @@ -982,20 +1093,20 @@ def details(mr: Dict[str, Any]) -> Dict[str, Any]: """ out: dict[str, Any] = {"first_commit": None, "commits": None, "first_review": None} iid = mr["iid"] - try: - # GitLab lists MR commits newest first, so every page is needed to find the first commit. - commits = list(pages(f"/merge_requests/{iid}/commits")) - times = [parse_iso(c.get("authored_date") or c.get("created_at")) for c in commits] - times = [t for t in times if t] - out["first_commit"] = min(times) if times else None - out["commits"] = len(commits) - except (ApiError, ValueError, KeyError, TypeError, AttributeError) as e: - out["commits_error"] = str(e) + if not commits_refused: + try: + commits = probe if (probe is not None and mr is mrs[0]) else mr_commits(iid) + times = [parse_iso(c.get("authored_date") or c.get("created_at")) for c in commits] + times = [t for t in times if t] + out["first_commit"] = min(times) if times else None + out["commits"] = len(commits) + except (ApiError, ValueError, KeyError, TypeError, AttributeError) as e: + out["commits_error"] = str(e) if want_reviews: try: me = (mr.get("author") or {}).get("username") merged_at = parse_iso(mr.get("merged_at")) - for note in pages(f"/merge_requests/{iid}/notes?sort=asc&order_by=created_at"): + for note in pages(f"{base}/{int(iid)}/notes", {"sort": "asc", "order_by": "created_at"}): a = note.get("author") or {} if note.get("system") or a.get("username") == me or _is_bot(a.get("username"), "Bot" if a.get("bot") else None): continue @@ -1012,6 +1123,7 @@ def details(mr: Dict[str, Any]) -> Dict[str, Any]: extra = list(pool.map(details, mrs)) if info is not None: info["detail_errors"] = sum(1 for ex in extra if "commits_error" in ex or "review_error" in ex) + info["commits_refused"] = int(commits_refused) result: list[PR] = [] for mr, ex in zip(mrs, extra): review_known = want_reviews and "review_error" not in ex @@ -1029,7 +1141,7 @@ def details(mr: Dict[str, Any]) -> Dict[str, Any]: "labels": mr.get("labels") or [], "reviewed": (ex["first_review"] is not None) if (state == "merged" and review_known) else None, "source": "api", "inferred": ["ready"] + ([] if review_known else ["first_review"]), - "squash_sha": mr.get("squash_commit_sha"), "local": None, + "squash_sha": mr.get("squash_commit_sha"), "local": None, "commits_refused": commits_refused, }) return result @@ -1106,13 +1218,14 @@ def build_records(prs: List[PR], ctx: Dict[str, Any]) -> List[Record]: Args: prs: raw PRs; API PRs may be filled in (size, branch_shas) from the local commit. - ctx: failure_re, failure_title_start, bot_re, fp_by_sha, claimed, claims, redact and reverts, - as built by collect(). + ctx: failure_re, failure_title_start, bot_re, fp_by_sha, claimed, claims, redact, reverts and + (optionally) graph, as built by collect(). """ failure_re = ctx["failure_re"] fp_by_sha = ctx["fp_by_sha"] claimed = ctx["claimed"] claims = ctx.get("claims") or {} + graph: Graph = ctx.get("graph") or {} records: list[Record] = [] sha_to_pr: dict[str, Record] = {} for pr in prs: @@ -1123,6 +1236,13 @@ def build_records(prs: List[PR], ctx: Dict[str, Any]) -> List[Record]: if len(c["parents"]) >= 2 and not pr.get("branch_shas"): # merge-commit workflow: the branch commits (e.g. a revert) resolve time to restore pr["branch_shas"] = claims.get(c["sha"], []) + local_first = False + if pr.get("commits_refused") and pr["first_commit"] is None and c is not None and len(c["parents"]) >= 2: + # The API login cannot read MR commits (a GitLab CI job token): use the merged branch's commits. + branch = [graph[s] for s in claims.get(c["sha"], []) if s in graph and len(graph[s][0]) < 2] + if branch: + pr["first_commit"], pr["commits"] = min(b[1] for b in branch), len(branch) + local_first = True t, scope, breaking, tsrc = classify_type(pr["title"] or "", pr.get("branch"), pr.get("labels")) kind = None if t == "revert" or REVERT_TITLE.match(pr["title"] or ""): @@ -1171,14 +1291,16 @@ def span(a: Optional[int], b: Optional[int]) -> Optional[int]: if rec["review"] is not None: rec["inferred"].append("review") rec["lead"] = span(pr["first_commit"], merged) - if rec["lead"] is not None and pr["source"] != "api": + if rec["lead"] is not None and (pr["source"] != "api" or local_first): rec["inferred"].append("lead") + if local_first and rec["coding"] is not None: + rec["inferred"].append("coding") deploy = claimed.get(pr.get("sha") or "") rec["deployed"] = deploy[0] if deploy and merged is not None else None rec["release"] = deploy[1] if deploy and merged is not None else None rec["deploy_wait"] = span(merged, rec["deployed"]) rec["lead_to_deploy"] = span(pr["first_commit"], rec["deployed"]) - if rec["lead_to_deploy"] is not None and pr["source"] != "api": + if rec["lead_to_deploy"] is not None and (pr["source"] != "api" or local_first): rec["inferred"].append("lead_to_deploy") # built from the inferred first-commit time rec["restore"] = None rec["_sha"] = pr.get("sha") @@ -1253,15 +1375,6 @@ def write_csv(path: str, records: Iterable[Record]) -> None: w.writerow(row) -def resolve_token(env_names: Iterable[str], environ: Mapping[str, str]) -> Tuple[Optional[str], Optional[str]]: - """Return (token, variable name) from the first non-empty variable in `environ`, or (None, None).""" - for name in env_names: - v = environ.get(name) - if v: - return v.strip(), name - return None, None - - def parse_date(s: Optional[str]) -> Optional[int]: """Parse a YYYY-MM-DD date as UTC midnight in Unix seconds; empty gives None.""" if not s: @@ -1277,11 +1390,20 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non Args: args: Parsed command line. - environ: Environment to read API tokens from; defaults to os.environ. + environ: Environment for the gh/glab subprocesses (PATH, their own login variables, CI variables); + defaults to os.environ. repo-stats never reads a credential from it. Returns: {"meta": ..., "prs": [record, ...], "loc": build_loc_series(...), "deploys": [...]}. """ + if getattr(args, "api_url", None): + raise ToolError("--api-url was removed: repo-stats now calls the gh or glab CLI. For GitHub Enterprise or " + "self-managed GitLab, pass --provider and --hostname HOST.") + if getattr(args, "token_env", None): + raise ToolError("--token-env was removed: gh and glab find their own login. Run `gh auth login` or " + "`glab auth login`, or set GH_TOKEN / GITLAB_TOKEN for the run.") + if args.hostname is not None and not HOSTNAME_RE.match(args.hostname): + raise ToolError(f"Invalid --hostname {args.hostname!r}: give a host name such as ghe.example.com.") repo = os.path.abspath(args.repo) if run_git(repo, "rev-parse", "--is-inside-work-tree", check=False).strip() != "true" \ and run_git(repo, "rev-parse", "--is-bare-repository", check=False).strip() != "true": @@ -1324,60 +1446,69 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non claims = claim_branch_commits(first_parent, graph) # 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() parsed = parse_remote(remote) if remote else None host_provider = detect_provider(parsed[0]) if parsed else None - provider = args.provider or host_provider - untrusted = None - if parsed and provider and provider != host_provider and not args.api_url: - # Never derive an API host from an arbitrary remote: a token would go to whoever controls it. - untrusted = (f"Remote host {parsed[0]} is not github.com or gitlab.com; pass --provider and --api-url " - "to use its API.") - elif parsed and not provider and parsed[0] not in TRUSTED_HOSTS: - untrusted = (f"Remote host {parsed[0]} is not github.com or gitlab.com; pass --provider and --api-url " - "to use its API.") - token_envs = [args.token_env] if args.token_env else ( - ["GITHUB_TOKEN", "GH_TOKEN"] if provider == "github" else - ["GITLAB_TOKEN", "GITLAB_PRIVATE_TOKEN"] if provider == "gitlab" else []) - token, token_name = resolve_token(token_envs, os.environ if environ is None else environ) + ci = ci_server(env) + if parsed and not host_provider and ci and parsed[0] == ci[1]: + host_provider = ci[0] # the CI server running this job, e.g. self-managed GitLab CI + hostname = args.hostname.lower() if args.hostname else None + provider = args.provider or (detect_provider(hostname) if hostname else None) or host_provider + api_host: Optional[str] = None + no_api = None + if hostname: + api_host = hostname # chosen explicitly by the user + if not provider: + no_api = f"--hostname {hostname} needs --provider github or --provider gitlab." + elif parsed and provider and provider == host_provider: + api_host = parsed[0] + elif parsed and (provider or parsed[0] not in TRUSTED_HOSTS): + # Never take the API host from an arbitrary remote: gh and glab send environment tokens to any host. + no_api = (f"Remote host {parsed[0]} is not github.com or gitlab.com; pass --provider and --hostname " + "to use its API.") source = args.source api_prs: Optional[List[PR]] = None + info: dict[str, int] = {} if source in ("auto", "api"): - if not parsed or not provider or untrusted: - msg = "No GitHub or GitLab remote was detected (use --remote, or --provider with --api-url)." - if untrusted: - msg += " " + untrusted + if not parsed or not provider or not api_host or no_api: + msg = "No GitHub or GitLab remote was detected (use --remote, or --provider with --hostname)." + if no_api: + msg += " " + no_api if source == "api": raise ToolError(msg) warnings.append(msg + " PRs are inferred from git history.") - elif not token: - msg = (f"No API token found (looked for {', '.join(token_envs) or 'a token variable'}).") - if source == "api": - raise ToolError(msg) - warnings.append(msg + " Using PRs inferred from git history. Set a token for exact open, review and merge times.") else: - host, path = parsed - info: dict[str, int] = {} + tool = CLI_FOR[provider] + path = parsed[1] try: - log(f"Fetching pull requests from {provider} API (token from ${token_name}) ...") - if provider == "github": - if "/" not in path: - raise ApiError(f"Cannot read owner/name from the remote path '{path}'") - owner, name = path.split("/", 1) - api_url = args.api_url or "https://api.github.com" - api_prs = fetch_github(owner, name, token, api_url, since, short_branch, args.all_bases, args.max_prs, - info=info) - else: - api_url = args.api_url or "https://gitlab.com/api/v4" - api_prs = fetch_gitlab(path, token, api_url, since, short_branch, args.all_bases, args.max_prs, - not args.no_reviews, info=info) + with Cli(tool, api_host, env) as cli: + log(f"Fetching pull requests from {api_host} with `{tool} api` ...") + if provider == "github": + if "/" not in path: + raise ApiError(f"Cannot read owner/name from the remote path '{path}'") + owner, name = path.split("/", 1) + api_prs = fetch_github(cli, owner, name, since, short_branch, args.all_bases, args.max_prs, + info=info) + else: + api_prs = fetch_gitlab(cli, path, since, short_branch, args.all_bases, args.max_prs, + not args.no_reviews, info=info) + except CliUnavailable as e: + if source == "api": + raise + warnings.append(f"{e} PRs are inferred from git history.") + api_prs = None except (ApiError, ValueError, KeyError, TypeError, AttributeError, IndexError, OSError) as e: detail = str(e) if isinstance(e, ApiError) else f"unexpected response or I/O error: {e.__class__.__name__}: {e}" if source == "api": raise ApiError(f"API fetch failed: {detail}") warnings.append(f"API fetch failed ({detail}). Using PRs inferred from git history instead.") api_prs = None + if info.get("commits_refused"): + warnings.append("The GitLab login cannot read merge request commits (a CI job token cannot). " + "First-commit times come from local merge commits where there is one, and are " + "empty for squash-merged MRs. Use a read_api token for exact values.") if info.get("detail_errors"): warnings.append(f"{info['detail_errors']} merge request(s) had commit or review lookups fail. " "Their coding time, lead time and review status are left empty, not guessed.") @@ -1398,8 +1529,8 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non mode = "git" if not prs: warnings.append("No pull requests could be inferred from git history. This usually means rebase or " - "fast-forward merges with no PR number in the commit message. Use the API (set a token) " - "or --commits-as-prs.") + "fast-forward merges with no PR number in the commit message. Use the API (install and " + "log in to gh or glab) or --commits-as-prs.") if deploys == [] and args.deploy_source == "tags": warnings.append("No release tags matched, so deployment frequency and lead time to deploy are empty. " "Adjust --tag-pattern or use --deploy-source merges.") @@ -1414,7 +1545,7 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non records = build_records(prs, { "failure_re": failure_re, "failure_title_start": args.failure_pattern is None, "bot_re": bot_re, "fp_by_sha": fp_by_sha, "claimed": claimed, "claims": claims, - "redact": args.no_titles, "reverts": load_reverts(repo, branch), + "redact": args.no_titles, "reverts": load_reverts(repo, branch), "graph": graph, }) if args.exclude_bots: records = [r for r in records if not r["bot"]] @@ -1472,8 +1603,9 @@ def build_parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser( prog="repo_stats.py", description="Generate a self-contained HTML dashboard of code statistics for a git repository.", - epilog="Environment: GITHUB_TOKEN / GH_TOKEN or GITLAB_TOKEN / GITLAB_PRIVATE_TOKEN enable exact PR data. " - "Tokens are read from the environment only and are never written to the output.", + epilog="Exact PR data comes from the gh (GitHub) or glab (GitLab) CLI, using its own login " + "(gh auth login / glab auth login, or GH_TOKEN / GITLAB_TOKEN in CI). repo-stats never reads a " + "token and only sends read requests. Without the CLI, PRs are inferred from git history.", ) p.add_argument("repo", nargs="?", default=".", help="path to a local git checkout (default: .)") p.add_argument("-o", "--out", default="repo-stats.html", help="output HTML file (default: repo-stats.html)") @@ -1486,10 +1618,12 @@ def build_parser() -> argparse.ArgumentParser: p.add_argument("--until", metavar="YYYY-MM-DD", help="only include PRs merged (or opened) on or before this UTC date (inclusive)") g = p.add_argument_group("PR data source") g.add_argument("--source", choices=["auto", "git", "api"], default="auto", - help="auto uses the API when a token is available, otherwise infers PRs from git (default: auto)") + help="auto uses the API through gh/glab when available, otherwise infers PRs from git (default: auto)") g.add_argument("--provider", choices=["github", "gitlab"], help="hosting provider (default: detected from the remote)") - g.add_argument("--api-url", help="API base URL for self-hosted servers, e.g. https://host/api/v4 (GitLab) or https://host/api (GitHub Enterprise)") - g.add_argument("--token-env", metavar="NAME", help="environment variable that holds the API token") + g.add_argument("--hostname", metavar="HOST", help="GitHub Enterprise or self-managed GitLab host to query with gh/glab " + "(use with --provider). The default is github.com or gitlab.com, taken from the remote") + g.add_argument("--api-url", help=argparse.SUPPRESS) # removed: explains --hostname + g.add_argument("--token-env", help=argparse.SUPPRESS) # removed: gh/glab find their own login g.add_argument("--no-reviews", action="store_true", help="GitLab: skip per-MR review lookups (faster, fewer API calls)") g.add_argument("--all-bases", action="store_true", help="include PRs that target branches other than the analysed one") g.add_argument("--max-prs", type=positive_int, metavar="N", help="stop after N PRs (newest first)") diff --git a/repo-stats/template.html b/repo-stats/template.html index fa8c7f0..955954e 100644 --- a/repo-stats/template.html +++ b/repo-stats/template.html @@ -1037,7 +1037,7 @@

Repository stats

const api = META.mode === "api"; const box = h("div", { class: "banner" + (api ? " ok" : "") }, h("strong", null, api ? `Exact PR data from the ${META.provider} API.` : "PR data is inferred from git history."), - " ", api ? "Open, review and merge times are real." : "Open and review times are missing, first-commit times are approximate, and PRs that left no trace in git are absent. Run with an API token for accurate results."); + " ", api ? "Open, review and merge times are real." : "Open and review times are missing, first-commit times are approximate, and PRs that left no trace in git are absent. Install and log in to gh or glab for accurate results."); if (META.warnings.length) box.append(h("ul", null, META.warnings.map((w) => h("li", null, w)))); b.append(box); } diff --git a/repo-stats/tests/fake_cli/_fake.py b/repo-stats/tests/fake_cli/_fake.py new file mode 100644 index 0000000..8d899f9 --- /dev/null +++ b/repo-stats/tests/fake_cli/_fake.py @@ -0,0 +1,148 @@ +"""Fake `gh` and `glab` for the tests. Stdlib only. + +Each call turns one `gh api` / `glab api` invocation into one HTTP request to the mock server named by +REPO_STATS_FAKE_URL, and prints the answer the way the real CLI does with --include: status line, headers, +blank line, body. The exit status is 0 for 2xx and 1 otherwise; `gh` exits 4 when it has no token. + +Only the arguments repo-stats is allowed to use are accepted, so a test fails if the code ever sends +anything else (-F, --input, --form, another method, a missing --hostname). When REPO_STATS_FAKE_LOG is set, +every call appends {"tool", "argv", "cwd", "env"} to it as one JSON line. + +Credentials are found as the real CLIs find them: gh reads GH_TOKEN, then GITHUB_TOKEN, for github.com +and *.ghe.com, and GH_ENTERPRISE_TOKEN / GITHUB_ENTERPRISE_TOKEN for any other host; glab reads +GITLAB_TOKEN, GITLAB_ACCESS_TOKEN or OAUTH_TOKEN, and with GLAB_ENABLE_CI_AUTOLOGIN=true in GitLab CI +(GITLAB_CI=true) it sends CI_JOB_TOKEN as JOB-TOKEN. + +`glab token create ...` (used only by run.sh --store) prints REPO_STATS_FAKE_NEW_TOKEN and exits 0 when +that variable is set, and fails like a GitLab.com Free project otherwise. +""" +from __future__ import annotations + +import json +import os +import sys +import urllib.error +import urllib.parse +import urllib.request +from typing import Dict, List, Optional, Tuple + +_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + +class Usage(Exception): + """An argument the real repo-stats must never pass.""" + + +def _parse(tool: str, argv: List[str]) -> Tuple[str, Optional[str], Dict[str, str]]: + """Return (endpoint, hostname, -f fields) or raise Usage for anything outside the allowed set.""" + if not argv or argv[0] != "api": + raise Usage(f"only `{tool} api` is allowed, got {argv[:1]}") + endpoint = None + hostname = None + method = None + include = False + fields: Dict[str, str] = {} + it = iter(argv[1:]) + for a in it: + if a == "--hostname": + hostname = next(it) + elif a == "--include": + include = True + elif a == "--method" and tool == "glab": + method = next(it) + elif a == "-f": + key, eq, value = next(it).partition("=") + if not eq: + raise Usage("-f needs key=value") + fields[key] = value + elif a.startswith("-"): + raise Usage(f"flag not allowed: {a}") + elif endpoint is None: + endpoint = a + else: + raise Usage(f"unexpected argument {a}") + if endpoint is None or not hostname or not include: + raise Usage("endpoint, --hostname and --include are required") + if tool == "gh" and endpoint != "graphql": + raise Usage("gh may only call graphql") + if tool == "glab" and method != "GET": + raise Usage("glab must use --method GET") + return endpoint, hostname, fields + + +def _log(tool: str, argv: List[str]) -> None: + """Append this call to REPO_STATS_FAKE_LOG, if set.""" + path = os.environ.get("REPO_STATS_FAKE_LOG") + if path: + with open(path, "a", encoding="utf-8") as f: + f.write(json.dumps({"tool": tool, "argv": argv, "cwd": os.getcwd(), "env": dict(os.environ)}) + "\n") + + +def _first(*names: str) -> Optional[str]: + """Return the first non-empty environment variable among names.""" + return next((os.environ[n] for n in names if os.environ.get(n)), None) + + +def main(tool: str, argv: List[str]) -> int: + """Run one fake CLI call and return its exit status.""" + _log(tool, argv) + if tool == "glab" and argv[:2] == ["token", "create"]: + new = os.environ.get("REPO_STATS_FAKE_NEW_TOKEN") + if new: + print(new) + return 0 + print("glab: 403 Forbidden (HTTP 403)", file=sys.stderr) + return 1 + try: + endpoint, host, fields = _parse(tool, argv) + except (Usage, StopIteration) as e: + print(f"{tool}: usage error: {e}", file=sys.stderr) + return 2 + headers = {"User-Agent": f"fake-{tool}"} + if tool == "gh": + public = host == "github.com" or bool(host and host.endswith(".ghe.com")) + token = _first("GH_TOKEN", "GITHUB_TOKEN") if public else _first("GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN") + if not token: + print("To get started with GitHub CLI, please run: gh auth login", file=sys.stderr) + return 4 + headers["Authorization"] = f"Bearer {token}" + query = fields.pop("query", "") + data: Optional[bytes] = json.dumps({"query": query, "variables": fields}).encode() + headers["Content-Type"] = "application/json" + path = "/graphql" + else: + token = _first("GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN") + if token: + headers["PRIVATE-TOKEN"] = token + elif (os.environ.get("GLAB_ENABLE_CI_AUTOLOGIN") == "true" and os.environ.get("GITLAB_CI") == "true" + and os.environ.get("CI_JOB_TOKEN")): + headers["JOB-TOKEN"] = os.environ["CI_JOB_TOKEN"] + data = None + path = "/api/v4/" + endpoint + ("?" + urllib.parse.urlencode(fields) if fields else "") + base = os.environ.get("REPO_STATS_FAKE_URL") + if not base: + print(f"{tool}: no mock server (REPO_STATS_FAKE_URL is not set)", file=sys.stderr) + return 1 + req = urllib.request.Request(base.rstrip("/") + path, data=data, headers=headers) + try: + resp = _OPENER.open(req, timeout=30) + status, reason, hdrs, body = resp.status, resp.reason, resp.headers, resp.read() + except urllib.error.HTTPError as e: + status, reason, hdrs, body = e.code, e.reason, e.headers, e.read() + except (urllib.error.URLError, OSError) as e: + print(f"error connecting to {base}: {getattr(e, 'reason', e)}", file=sys.stderr) + return 1 + out = sys.stdout.buffer + out.write(f"HTTP/1.1 {status} {reason}\r\n".encode()) + for k, v in hdrs.items(): + out.write(f"{k}: {v}\r\n".encode()) + out.write(b"\r\n" + body) + out.flush() + if 200 <= status < 300: + return 0 + try: + msg = json.loads(body).get("message", "") + except (ValueError, AttributeError): + msg = "" + print(f"{tool}: {msg} (HTTP {status})", file=sys.stderr) + return 1 diff --git a/repo-stats/tests/fake_cli/gh b/repo-stats/tests/fake_cli/gh new file mode 100755 index 0000000..02be813 --- /dev/null +++ b/repo-stats/tests/fake_cli/gh @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +"""Fake `gh` for the repo-stats tests: see _fake.py.""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _fake # noqa: E402 + +sys.exit(_fake.main("gh", sys.argv[1:])) diff --git a/repo-stats/tests/fake_cli/glab b/repo-stats/tests/fake_cli/glab new file mode 100755 index 0000000..55b7582 --- /dev/null +++ b/repo-stats/tests/fake_cli/glab @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +"""Fake `glab` for the repo-stats tests: see _fake.py.""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import _fake # noqa: E402 + +sys.exit(_fake.main("glab", sys.argv[1:])) diff --git a/repo-stats/tests/helpers.py b/repo-stats/tests/helpers.py index 1729d93..cb9522d 100644 --- a/repo-stats/tests/helpers.py +++ b/repo-stats/tests/helpers.py @@ -20,34 +20,66 @@ import repo_stats as rs # noqa: E402 SCRIPT = str(ROOT / "repo_stats.py") -TOKEN_VARS = ("GITHUB_TOKEN", "GH_TOKEN", "GITLAB_TOKEN", "GITLAB_PRIVATE_TOKEN") CACHE = Path(tempfile.gettempdir()) / "repostats-test-cache" +# Fake gh and glab (see fake_cli/_fake.py). clean_env() puts them first on PATH, so no test can reach a +# real CLI, a real login or the network. +FAKE_CLI_DIR = HERE / "fake_cli" +# Credentials, CI markers and fake-CLI settings from the developer's shell never leak into a test. +STRIP_VARS = rs.CREDENTIAL_VARS + ("GITLAB_CI", "GITHUB_ACTIONS", "CI_SERVER_HOST", "GITHUB_SERVER_URL", + "GLAB_ENABLE_CI_AUTOLOGIN", "GH_HOST", "GITLAB_HOST", "GH_CONFIG_DIR", + "GLAB_CONFIG_DIR", "REPO_STATS_FAKE_URL", "REPO_STATS_FAKE_LOG") +# Test-only pseudo-option for run_cli() and collect(): `--fake-api URL` is removed from the argv and points +# the fake gh/glab at the mock server at URL. +FAKE_API = "--fake-api" def clean_env(extra: Mapping[str, str] | None = None) -> dict[str, str]: - """Return a copy of os.environ without API tokens, plus `extra`.""" - env = {k: v for k, v in os.environ.items() if k not in TOKEN_VARS} + """Return os.environ without credentials or CI markers, with the fake CLIs first on PATH, plus `extra`.""" + env = {k: v for k, v in os.environ.items() if k not in STRIP_VARS} + env["PATH"] = os.pathsep.join([str(FAKE_CLI_DIR), env.get("PATH", os.defpath)]) env.update(extra or {}) return env +def _split_fake_api(args: Iterable[object], env: Mapping[str, str] | None) -> tuple[list[str], dict[str, str]]: + """Remove `--fake-api URL` from args and return (args, env with REPO_STATS_FAKE_URL set).""" + out: list[str] = [] + env = dict(env or {}) + it = iter(map(str, args)) + for a in it: + if a == FAKE_API: + env["REPO_STATS_FAKE_URL"] = next(it) + else: + out.append(a) + return out, env + + def run_cli(args: Iterable[object], env: Mapping[str, str] | None = None, timeout: float = 120, cwd: str | Path | None = None) -> subprocess.CompletedProcess[str]: - """Run the CLI as a subprocess with real tokens stripped. Returns CompletedProcess.""" - return subprocess.run([sys.executable, SCRIPT, *map(str, args)], capture_output=True, text=True, + """Run the CLI as a subprocess with real credentials stripped. Returns CompletedProcess.""" + argv, env = _split_fake_api(args, env) + return subprocess.run([sys.executable, SCRIPT, *argv], capture_output=True, text=True, env=clean_env(env), timeout=timeout, cwd=cwd) def collect(repo: fixtures.Repo | str | Path, *extra: str, env: Mapping[str, str] | None = None) -> tuple[dict[str, Any], str]: """In-process collect() with stderr swallowed. Returns (data, stderr_text).""" path = getattr(repo, "path", repo) - args = rs.build_parser().parse_args([str(path), *extra]) + argv, env = _split_fake_api(extra, env) + args = rs.build_parser().parse_args([str(path), *argv]) buf = io.StringIO() with contextlib.redirect_stderr(buf): data = rs.collect(args, environ=clean_env(env)) return data, buf.getvalue() +def cli_calls(log: str | Path) -> list[dict[str, Any]]: + """Read the fake CLI call log written through REPO_STATS_FAKE_LOG.""" + import json + p = Path(log) + return [json.loads(line) for line in p.read_text().splitlines()] if p.exists() else [] + + def by_number(data: Mapping[str, Any]) -> dict[int, dict[str, Any]]: """Index a collect() result's PRs by PR number.""" return {p["number"]: p for p in data["prs"]} diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index 99761fa..0424ba6 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -1,10 +1,12 @@ """Python-side tests for repo_stats.py (plan sections A, B, C and the non-browser parts of E). Run: python3 -m unittest discover -s tests -v -Stdlib only. Deterministic. No real network: API tests use 127.0.0.1 mock servers and fake tokens. +Stdlib only. Deterministic. No real network: API tests run fake gh/glab CLIs (tests/fake_cli) that +forward to 127.0.0.1 mock servers, with fake tokens. """ from __future__ import annotations +import argparse import ast import contextlib import csv @@ -936,7 +938,7 @@ def setUpClass(cls) -> None: cls.r = api_repo() cls.nodes = github_nodes(cls.r) cls.srv = ms.MockServer(ms.github_handler(desc_nodes(cls.nodes), page_size=3, expect_token=FAKE)).start() - cls.data, cls.err = collect(cls.r, "--api-url", cls.srv.url, env={"GITHUB_TOKEN": FAKE}) + cls.data, cls.err = collect(cls.r, "--fake-api", cls.srv.url, env={"GITHUB_TOKEN": FAKE}) cls.prs = by_number(cls.data) @classmethod @@ -949,7 +951,7 @@ def test_mode_and_pagination(self) -> None: self.assertEqual(self.data["meta"]["mode"], "api") self.assertEqual(self.data["meta"]["provider"], "github") self.assertEqual(len(self.srv.requests), 4) # 10 nodes / 3 per page - cursors = [json.loads(q["body"])["variables"]["cursor"] for q in self.srv.requests] + cursors = [json.loads(q["body"])["variables"].get("cursor") for q in self.srv.requests] self.assertEqual(cursors, [None, "3", "6", "9"]) def test_base_branch_filter(self) -> None: @@ -960,7 +962,7 @@ def test_base_branch_filter(self) -> None: def test_all_bases(self) -> None: """--all-bases keeps PRs into other base branches.""" with ms.MockServer(ms.github_handler(desc_nodes(self.nodes), page_size=3)) as srv: - d, _ = collect(self.r, "--api-url", srv.url, "--all-bases", env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, "--all-bases", env={"GITHUB_TOKEN": FAKE}) self.assertIn(8, by_number(d)) def test_states(self) -> None: @@ -1033,7 +1035,7 @@ def test_since_stops_early(self) -> None: """--since stops paging once PRs are older than the cutoff.""" day = time.strftime("%Y-%m-%d", time.gmtime(BASE + 4 * DAY)) with ms.MockServer(ms.github_handler(desc_nodes(self.nodes), page_size=3)) as srv: - d, _ = collect(self.r, "--api-url", srv.url, "--since", day, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, "--since", day, env={"GITHUB_TOKEN": FAKE}) n_requests = len(srv.requests) self.assertLess(n_requests, 4, "pagination must stop once PRs older than --since are seen") self.assertTrue(all(p["number"] >= 4 for p in d["prs"])) @@ -1041,7 +1043,7 @@ def test_since_stops_early(self) -> None: def test_max_prs(self) -> None: """--max-prs stops paging once enough PRs are fetched.""" with ms.MockServer(ms.github_handler(desc_nodes(self.nodes), page_size=3)) as srv: - d, _ = collect(self.r, "--api-url", srv.url, "--max-prs", "4", env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, "--max-prs", "4", env={"GITHUB_TOKEN": FAKE}) self.assertEqual(len(srv.requests), 2) self.assertEqual(len(d["prs"]), 4) @@ -1056,43 +1058,44 @@ def test_auth_header_and_no_token_in_url(self) -> None: def test_graphql_errors_fall_back(self) -> None: """GraphQL errors fall back to git mode with a warning.""" with ms.MockServer(lambda req: (200, {}, {"errors": [{"message": "Could not resolve to a Repository"}]})) as srv: - d, _ = collect(self.r, "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "git") self.assertTrue(any("Could not resolve" in w for w in d["meta"]["warnings"])) def test_repository_null_falls_back(self) -> None: """A null repository in the response falls back to git mode.""" with ms.MockServer(lambda req: (200, {}, {"data": {"repository": None}})) as srv: - d, _ = collect(self.r, "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "git") - def test_missing_token_falls_back_with_warning(self) -> None: - """Without a token, auto mode uses git and warns.""" - d, _ = collect(self.r, "--api-url", self.srv.url) + def test_not_logged_in_falls_back_with_warning(self) -> None: + """When gh has no login, auto mode uses git and says how to log in.""" + n = len(self.srv.requests) + d, _ = collect(self.r, "--fake-api", self.srv.url) self.assertEqual(d["meta"]["mode"], "git") - self.assertTrue(any("No API token" in w for w in d["meta"]["warnings"])) + self.assertEqual(len(self.srv.requests), n) + self.assertTrue(any("not logged in" in w and "gh auth login --hostname github.com" in w + for w in d["meta"]["warnings"]), d["meta"]["warnings"]) def test_source_git_never_calls_api(self) -> None: """--source git never contacts the API.""" n = len(self.srv.requests) - d, _ = collect(self.r, "--api-url", self.srv.url, "--source", "git", env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", self.srv.url, "--source", "git", env={"GITHUB_TOKEN": FAKE}) self.assertEqual(len(self.srv.requests), n) self.assertEqual(d["meta"]["mode"], "git") - def test_token_env_option(self) -> None: - """--token-env reads the token from the named variable.""" - seen = [] - - def h(req: ms.Request) -> ms.Response: - """Record the Authorization header, then answer as the GitHub mock.""" - seen.append(req["headers"].get("authorization")) - return ms.github_handler(desc_nodes(self.nodes), page_size=50)(req) - - with ms.MockServer(h) as srv: - d, _ = collect(self.r, "--api-url", srv.url, "--token-env", "MY_CUSTOM_TOK", - env={"MY_CUSTOM_TOK": "custom-tok-1", "GITHUB_TOKEN": "should-not-be-used"}) - self.assertEqual(d["meta"]["mode"], "api") - self.assertEqual(set(seen), {"Bearer custom-tok-1"}) + def test_removed_flags_explain_the_replacement(self) -> None: + """--api-url and --token-env fail with a message that names the replacement.""" + with self.assertRaises(rs.ToolError) as cm: + collect(self.r, "--api-url", "https://api.github.com", env={"GITHUB_TOKEN": FAKE}) + self.assertIn("--hostname", str(cm.exception)) + with self.assertRaises(rs.ToolError) as cm: + collect(self.r, "--token-env", "MY_TOKEN", env={"MY_TOKEN": FAKE}) + self.assertIn("gh auth login", str(cm.exception)) + p = run_cli([self.r.path, "-o", tmpdir() / "o.html", "--api-url", "https://x.example/api"]) + self.assertEqual(p.returncode, 1) + self.assertIn("--api-url was removed", p.stderr) + self.assertNotIn("Traceback", p.stderr) def gitlab_fixture(r: Repo) -> tuple[list[dict[str, Any]], dict[int, list[dict[str, Any]]], @@ -1128,7 +1131,7 @@ def setUpClass(cls) -> None: cls.r = api_repo("git@gitlab.com:grp/sub/proj.git") cls.mrs, cls.commits, cls.notes = gitlab_fixture(cls.r) cls.srv = ms.MockServer(ms.gitlab_handler(cls.mrs, cls.commits, cls.notes, page_size=2)).start() - cls.data, _ = collect(cls.r, "--api-url", cls.srv.url + "/api/v4", env={"GITLAB_TOKEN": FAKE}) + cls.data, _ = collect(cls.r, "--fake-api", cls.srv.url, env={"GITLAB_TOKEN": FAKE}) cls.prs = by_number(cls.data) @classmethod @@ -1181,7 +1184,7 @@ def test_inferred_only_ready(self) -> None: def test_no_reviews_flag(self) -> None: """--no-reviews skips the notes requests and review metrics.""" with ms.MockServer(ms.gitlab_handler(self.mrs, self.commits, self.notes, page_size=2)) as srv: - d, _ = collect(self.r, "--api-url", srv.url + "/api/v4", "--no-reviews", env={"GITLAB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, "--no-reviews", env={"GITLAB_TOKEN": FAKE}) self.assertFalse([q for q in srv.requests if q["path"].endswith("/notes")]) p = by_number(d)[1] self.assertIsNone(p["first_review"]) @@ -1194,7 +1197,7 @@ def test_since_sends_updated_after(self) -> None: """--since is sent as updated_after, not created_after.""" # updated_after (not created_after): an MR opened before --since but merged after it must still be fetched. with ms.MockServer(ms.gitlab_handler(self.mrs, self.commits, self.notes, page_size=50)) as srv: - collect(self.r, "--api-url", srv.url + "/api/v4", "--since", "2022-02-05", env={"GITLAB_TOKEN": FAKE}) + collect(self.r, "--fake-api", srv.url, "--since", "2022-02-05", env={"GITLAB_TOKEN": FAKE}) q = [q for q in srv.requests if q["path"].endswith("/merge_requests")][0] self.assertEqual(q["query"]["updated_after"], ["2022-02-05T00:00:00Z"]) self.assertNotIn("created_after", q["query"]) @@ -1202,7 +1205,7 @@ def test_since_sends_updated_after(self) -> None: def test_all_bases_drops_target_filter(self) -> None: """--all-bases drops the target_branch filter.""" with ms.MockServer(ms.gitlab_handler(self.mrs, self.commits, self.notes, page_size=50)) as srv: - collect(self.r, "--api-url", srv.url + "/api/v4", "--all-bases", env={"GITLAB_TOKEN": FAKE}) + collect(self.r, "--fake-api", srv.url, "--all-bases", env={"GITLAB_TOKEN": FAKE}) q = [q for q in srv.requests if q["path"].endswith("/merge_requests")][0] self.assertNotIn("target_branch", q["query"]) @@ -1215,20 +1218,20 @@ def h(req: ms.Request) -> ms.Response: return ms.gitlab_handler(self.mrs, self.commits, self.notes, page_size=50)(req) with mock.patch.object(rs.time, "sleep", lambda s: None), ms.MockServer(h) as srv: - d, _ = collect(self.r, "--api-url", srv.url + "/api/v4", env={"GITLAB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "api") -class B3_Tokens(unittest.TestCase): - """Token handling in the CLI.""" +class B3_CliLogin(unittest.TestCase): + """repo-stats never handles a credential: gh and glab use their own login, and nothing leaks.""" def _run(self, remote: str, provider_env: str, handler: ms.Handler, extra: Sequence[str] = ()) -> tuple[subprocess.CompletedProcess[str], Path, list[ms.Request]]: - """Run the CLI with all three outputs against a mock API and a fake token. + """Run the CLI with all three outputs against a mock API, with a fake token for the fake CLI. Args: remote: Origin URL for the test repo. - provider_env: Environment variable that carries the token. + provider_env: Environment variable the fake gh/glab reads its token from. handler: Mock API handler. extra: Extra CLI arguments. @@ -1238,9 +1241,8 @@ def _run(self, remote: str, provider_env: str, handler: ms.Handler, r = api_repo(remote) out = tmpdir() with ms.MockServer(handler) as srv: - api = srv.url + ("/api/v4" if provider_env == "GITLAB_TOKEN" else "") - p = run_cli([r.path, "-o", out / "o.html", "--json", out / "o.json", "--csv", out / "o.csv", "--api-url", api, *extra], - env={provider_env: FAKE}) + p = run_cli([r.path, "-o", out / "o.html", "--json", out / "o.json", "--csv", out / "o.csv", + "--fake-api", srv.url, *extra], env={provider_env: FAKE}) reqs = list(srv.requests) return p, out, reqs @@ -1252,19 +1254,18 @@ def _assert_no_leak(self, p: subprocess.CompletedProcess[str], out: Path) -> Non self.assertNotIn(FAKE, p.stderr) self.assertNotIn(FAKE, p.stdout) - def test_github_cli_no_leak_and_header(self) -> None: - """GitHub CLI runs send a bearer token and leak it nowhere.""" + def test_github_cli_no_leak(self) -> None: + """A run through gh (logged in via GITHUB_TOKEN) gets API data and leaks the token nowhere.""" nodes = github_nodes(fixtures.merge_workflow_repo()) p, out, reqs = self._run("https://github.com/acme/widgets.git", "GITHUB_TOKEN", ms.github_handler(desc_nodes(nodes), page_size=50, expect_token=FAKE)) self._assert_no_leak(p, out) self.assertIn("source: api", p.stderr) + self.assertIn("with `gh api`", p.stderr) self.assertTrue(reqs) - for q in reqs: - self.assertEqual(q["headers"]["authorization"], f"Bearer {FAKE}") - def test_gitlab_cli_no_leak_and_header(self) -> None: - """GitLab CLI runs send PRIVATE-TOKEN and leak it nowhere.""" + def test_gitlab_cli_no_leak(self) -> None: + """A run through glab (logged in via GITLAB_TOKEN) gets API data and leaks the token nowhere.""" mrs, commits, notes = gitlab_fixture(fixtures.merge_workflow_repo()) p, out, reqs = self._run("https://gitlab.com/grp/proj.git", "GITLAB_TOKEN", ms.gitlab_handler(mrs, commits, notes, page_size=50)) self._assert_no_leak(p, out) @@ -1277,82 +1278,76 @@ def test_credentials_embedded_in_remote_not_leaked(self) -> None: nodes = github_nodes(fixtures.merge_workflow_repo()) r = api_repo("https://octo:EMBEDDEDSECRET99@github.com/acme/widgets.git") out = tmpdir() + log = tmpdir() / "cli.log" with ms.MockServer(ms.github_handler(desc_nodes(nodes), page_size=50)) as srv: - p = run_cli([r.path, "-o", out / "o.html", "--json", out / "o.json", "--api-url", srv.url], env={"GITHUB_TOKEN": FAKE}) + p = run_cli([r.path, "-o", out / "o.html", "--json", out / "o.json", "--fake-api", srv.url], + env={"GITHUB_TOKEN": FAKE, "REPO_STATS_FAKE_LOG": str(log)}) for q in srv.requests: self.assertNotIn("EMBEDDEDSECRET99", json.dumps(q["headers"]) + q["raw_path"]) self.assertEqual(p.returncode, 0, p.stderr) for f in ("o.html", "o.json"): self.assertNotIn("EMBEDDEDSECRET99", (out / f).read_text()) self.assertNotIn("EMBEDDEDSECRET99", p.stderr) + self.assertNotIn("EMBEDDEDSECRET99", json.dumps([c["argv"] for c in helpers.cli_calls(log)])) def test_token_on_api_failure_not_in_stderr(self) -> None: """A failed API run does not print the token.""" r = api_repo() with ms.MockServer(lambda req: (401, {}, {"message": "Bad credentials"})) as srv: - p = run_cli([r.path, "-o", tmpdir() / "o.html", "--api-url", srv.url, "--source", "api"], env={"GITHUB_TOKEN": FAKE}) + p = run_cli([r.path, "-o", tmpdir() / "o.html", "--fake-api", srv.url, "--source", "api"], env={"GITHUB_TOKEN": FAKE}) self.assertNotEqual(p.returncode, 0) + self.assertIn("gh auth login", p.stderr) self.assertNotIn(FAKE, p.stderr + p.stdout) - def test_no_token_means_no_request(self) -> None: - """Without a token no API request is made.""" + def test_not_logged_in_means_no_request(self) -> None: + """When gh has no login, no API request is made and the run falls back to git.""" r = api_repo() with ms.MockServer(lambda req: (200, {}, {})) as srv: - p = run_cli([r.path, "-o", tmpdir() / "o.html", "--api-url", srv.url]) + p = run_cli([r.path, "-o", tmpdir() / "o.html", "--fake-api", srv.url]) self.assertEqual(srv.requests, []) self.assertEqual(p.returncode, 0) - self.assertIn("No API token", p.stderr) + self.assertIn("not logged in", p.stderr) - def test_source_api_without_token_is_error(self) -> None: - """--source api without a token exits 1 with a clean error.""" + def test_source_api_not_logged_in_is_error(self) -> None: + """--source api without a gh login exits 1 with the login command, no traceback.""" r = api_repo() p = run_cli([r.path, "-o", tmpdir() / "o.html", "--source", "api"]) self.assertEqual(p.returncode, 1) - self.assertIn("No API token", p.stderr) + self.assertIn("gh auth login --hostname github.com", p.stderr) self.assertNotIn("Traceback", p.stderr) - def test_token_env_cli(self) -> None: - """--token-env works from the CLI and the token is not leaked.""" - nodes = github_nodes(fixtures.merge_workflow_repo()) - r = api_repo() - out = tmpdir() - with ms.MockServer(ms.github_handler(desc_nodes(nodes), page_size=50, expect_token="viaenv-777")) as srv: - p = run_cli([r.path, "-o", out / "o.html", "--api-url", srv.url, "--token-env", "CUSTOM_ENV_TOKEN"], - env={"CUSTOM_ENV_TOKEN": "viaenv-777"}) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("source: api", p.stderr) - self.assertNotIn("viaenv-777", (out / "o.html").read_text() + p.stderr) - - def test_loopback_api_never_uses_proxy(self) -> None: - """Requests to a loopback --api-url bypass http_proxy even when NO_PROXY does not exempt it.""" - nodes = github_nodes(fixtures.merge_workflow_repo()) + def test_missing_cli_falls_back_or_errors(self) -> None: + """Without gh installed, auto mode uses git and says where to get it; --source api is an error.""" r = api_repo() - with ms.MockServer(ms.github_handler(desc_nodes(nodes), page_size=50, expect_token=FAKE)) as srv, \ - ms.MockServer(lambda req: (502, {}, {"message": "proxy"})) as proxy: - env = {"GITHUB_TOKEN": FAKE, "http_proxy": proxy.url, "HTTP_PROXY": proxy.url, "NO_PROXY": "", "no_proxy": ""} - p = run_cli([r.path, "-o", tmpdir() / "o.html", "--provider", "github", "--api-url", srv.url, - "--source", "api"], env=env) - reqs, proxied = list(srv.requests), list(proxy.requests) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertTrue(reqs) - for q in reqs: - self.assertEqual(q["headers"]["authorization"], f"Bearer {FAKE}") - self.assertEqual(proxied, []) + empty = tmpdir() # a PATH with no gh on it (git still runs from the real PATH) + d, _ = collect(r, env={"PATH": str(empty), "GITHUB_TOKEN": FAKE}) + self.assertEqual(d["meta"]["mode"], "git") + self.assertTrue(any("gh is not installed" in w and "cli.github.com" in w for w in d["meta"]["warnings"])) + with self.assertRaises(rs.CliUnavailable): + collect(r, "--source", "api", env={"PATH": str(empty)}) - def test_collect_uses_given_environ(self) -> None: - """collect() reads tokens from its environ argument, not from os.environ.""" + def test_collect_passes_given_environ_to_the_cli(self) -> None: + """collect() runs gh with its environ argument, not os.environ.""" nodes = github_nodes(fixtures.merge_workflow_repo()) r = api_repo() with ms.MockServer(ms.github_handler(desc_nodes(nodes), page_size=50)) as srv: - args = rs.build_parser().parse_args([str(r.path), "--provider", "github", "--api-url", srv.url]) + args = rs.build_parser().parse_args([str(r.path)]) + env = helpers.clean_env({"GITHUB_TOKEN": "from-param", "REPO_STATS_FAKE_URL": srv.url}) with mock.patch.dict(os.environ, {"GITHUB_TOKEN": "from-os-environ"}), \ contextlib.redirect_stderr(io.StringIO()): - d = rs.collect(args, environ={"GITHUB_TOKEN": "from-param"}) + d = rs.collect(args, environ=env) auths = [q["headers"].get("authorization") for q in srv.requests] self.assertEqual(d["meta"]["mode"], "api") - self.assertTrue(auths) self.assertEqual(set(auths), {"Bearer from-param"}) - self.assertNotIn("from-os-environ", json.dumps([q["headers"] for q in srv.requests])) + + def test_repo_stats_never_reads_a_credential(self) -> None: + """The source never looks up a credential variable's value; it only removes the names for git.""" + src = (ROOT / "repo_stats.py").read_text() + for name in rs.CREDENTIAL_VARS: + for pat in (rf"environ(?:\.get)?\(\s*[\"']{name}", rf"environ\[\s*[\"']{name}", rf"getenv\(\s*[\"']{name}"): + self.assertIsNone(re.search(pat, src), (name, pat)) + self.assertNotIn("Authorization", src) + self.assertNotIn("PRIVATE-TOKEN", src) class B4_Failures(unittest.TestCase): @@ -1371,7 +1366,7 @@ def test_auto_falls_back_for_4xx(self) -> None: """Auto mode falls back to git on 401, 403 and 404 with a warning.""" for status, needle in ((401, "401"), (403, "403"), (404, "404")): with self._srv(status) as srv: - d, _ = collect(self.r, "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "git", status) self.assertEqual(len(d["prs"]), 5) self.assertTrue(any("API fetch failed" in w and needle in w for w in d["meta"]["warnings"]), (status, d["meta"]["warnings"])) @@ -1380,7 +1375,7 @@ def test_api_source_errors_for_4xx_cli(self) -> None: """--source api exits 1 with the status code on 4xx errors.""" for status in (401, 403, 404): with self._srv(status) as srv: - p = run_cli([self.r.path, "-o", tmpdir() / "o.html", "--api-url", srv.url, "--source", "api"], env={"GITHUB_TOKEN": FAKE}) + p = run_cli([self.r.path, "-o", tmpdir() / "o.html", "--fake-api", srv.url, "--source", "api"], env={"GITHUB_TOKEN": FAKE}) self.assertEqual(p.returncode, 1, status) self.assertIn(f"{status}", p.stderr) self.assertIn("error:", p.stderr) @@ -1390,7 +1385,7 @@ def test_500_retries_then_falls_back(self) -> None: """Server errors are retried with exponential back-off, then fall back.""" sleeps = [] with mock.patch.object(rs.time, "sleep", sleeps.append), self._srv(500) as srv: - d, _ = collect(self.r, "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(len(srv.requests), 5) self.assertEqual(sleeps, [2, 4, 8, 16]) self.assertEqual(d["meta"]["mode"], "git") @@ -1399,7 +1394,7 @@ def test_500_with_source_api_raises(self) -> None: """--source api raises ToolError after repeated 500s.""" with mock.patch.object(rs.time, "sleep", lambda s: None), self._srv(500) as srv: with self.assertRaises(rs.ToolError) as cm: - collect(self.r, "--api-url", srv.url, "--source", "api", env={"GITHUB_TOKEN": FAKE}) + collect(self.r, "--fake-api", srv.url, "--source", "api", env={"GITHUB_TOKEN": FAKE}) self.assertIn("500", str(cm.exception)) def test_connection_refused(self) -> None: @@ -1410,11 +1405,11 @@ def test_connection_refused(self) -> None: s.close() sleeps = [] with mock.patch.object(rs.time, "sleep", sleeps.append): - d, _ = collect(self.r, "--api-url", f"http://127.0.0.1:{port}", env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", f"http://127.0.0.1:{port}", env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "git") self.assertTrue(any("Could not reach" in w for w in d["meta"]["warnings"])) with self.assertRaises(rs.ToolError): - collect(self.r, "--api-url", f"http://127.0.0.1:{port}", "--source", "api", env={"GITHUB_TOKEN": FAKE}) + collect(self.r, "--fake-api", f"http://127.0.0.1:{port}", "--source", "api", env={"GITHUB_TOKEN": FAKE}) # UX: a dead host should not make the user wait this long before the git fallback kicks in. self.assertLessEqual(sum(sleeps) / 2, 10, f"waited {sum(sleeps) / 2}s of back-off before giving up on a refused connection") @@ -1433,7 +1428,7 @@ def h(req: ms.Request) -> ms.Response: sleeps = [] with mock.patch.object(rs.time, "sleep", sleeps.append), ms.MockServer(h) as srv: - d, _ = collect(self.r, "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(sleeps, [3]) self.assertEqual(d["meta"]["mode"], "api") @@ -1451,7 +1446,7 @@ def h(req: ms.Request) -> ms.Response: return inner(req) with mock.patch.object(rs.time, "sleep", lambda s: None), ms.MockServer(h) as srv: - d, _ = collect(self.r, "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "api") def test_non_json_200_falls_back(self) -> None: @@ -1460,14 +1455,14 @@ def test_non_json_200_falls_back(self) -> None: An HTML page (captive portal, proxy error) with status 200 must be a clean fallback, not a traceback. """ with ms.MockServer(lambda req: (200, {"Content-Type": "text/html"}, "proxy login")) as srv: - d, _ = collect(self.r, "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(self.r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "git") self.assertTrue(any("API fetch failed" in w for w in d["meta"]["warnings"])) def test_non_json_200_cli_clean_error(self) -> None: """A non-JSON 200 with --source api exits 1 without a traceback.""" with ms.MockServer(lambda req: (200, {}, "nope")) as srv: - p = run_cli([self.r.path, "-o", tmpdir() / "o.html", "--api-url", srv.url, "--source", "api"], env={"GITHUB_TOKEN": FAKE}) + p = run_cli([self.r.path, "-o", tmpdir() / "o.html", "--fake-api", srv.url, "--source", "api"], env={"GITHUB_TOKEN": FAKE}) self.assertEqual(p.returncode, 1) self.assertNotIn("Traceback", p.stderr) @@ -1484,65 +1479,6 @@ def test_no_remote_auto_and_api(self) -> None: class B5_Safety(unittest.TestCase): """HTTP safety rules and remote URL parsing.""" - def test_refuses_plain_http_non_loopback(self) -> None: - """Plain HTTP to non-loopback hosts is refused.""" - for url in ("http://example.com/graphql", "http://10.1.2.3/x", "http://localhost.evil.test/x", "http://127.0.0.1.evil.test/x"): - with self.assertRaises(rs.ApiError, msg=url): - rs.http_json(url, {"Authorization": "Bearer x"}) - - def test_allows_loopback_http(self) -> None: - """Plain HTTP to 127.0.0.1 and localhost is allowed.""" - with ms.MockServer(lambda req: (200, {}, {"ok": True})) as srv: - self.assertEqual(rs.http_json(srv.url + "/x", {})[0], {"ok": True}) - self.assertEqual(rs.http_json(f"http://localhost:{srv.port}/x", {})[0], {"ok": True}) - - def test_cross_host_redirect_refused(self) -> None: - """Redirects to another port are refused before the token is sent.""" - with ms.MockServer(lambda req: (200, {}, {"leak": True})) as other: - def h(req: ms.Request) -> ms.Response: - """Redirect every request to the other server.""" - return 302, {"Location": f"{other.url}/steal"}, {} - - with ms.MockServer(h) as srv: - with self.assertRaises(rs.ApiError): - rs.http_json(srv.url + "/x", {"Authorization": f"Bearer {FAKE}"}) - self.assertEqual(other.requests, [], "token must not reach the redirect target") - - def test_cross_hostname_redirect_refused(self) -> None: - """Redirects from 127.0.0.1 to localhost are refused.""" - with ms.MockServer(lambda req: (200, {}, {"leak": True})) as srv_b: - pass - with ms.MockServer(lambda req: (200, {}, {"ok": 1})) as srv: - def h(req: ms.Request) -> ms.Response: - """Redirect every request to the second server, addressed as localhost.""" - return 302, {"Location": f"http://localhost:{srv.port}/x"}, {} - - with ms.MockServer(h) as a: - with self.assertRaises(rs.ApiError): - rs.http_json(a.url + "/x", {"Authorization": "Bearer t"}) - self.assertEqual(srv.requests, []) - - def test_same_host_redirect_followed(self) -> None: - """Same-host redirects are followed and keep the Authorization header.""" - def h(req: ms.Request) -> ms.Response: - """Redirect /a to /b on the same server; /b echoes the Authorization header.""" - if req["path"] == "/a": - return 302, {"Location": f"http://127.0.0.1:{req['port']}/b"}, {} - return 200, {}, {"final": req["headers"].get("authorization")} - - with ms.MockServer(h) as srv: - self.assertEqual(rs.http_json(srv.url + "/a", {"Authorization": "Bearer t"})[0], {"final": "Bearer t"}) - - def test_https_to_http_downgrade_redirect_refused(self) -> None: - """An https-to-http redirect on the same host is refused. - - Same host but https -> http would send the Authorization header in clear text. - """ - handler = rs._SameHostRedirect() - req = urllib.request.Request("https://api.example.com/graphql", headers={"Authorization": f"Bearer {FAKE}"}) - with self.assertRaises(rs.ApiError): - handler.redirect_request(req, None, 302, "Found", {}, "http://api.example.com/graphql") # pyright: ignore[reportArgumentType] - def test_parse_remote_styles(self) -> None: """parse_remote() handles HTTPS, SSH, scp-style and credentialed URLs.""" cases = { @@ -1573,7 +1509,7 @@ def test_token_not_sent_to_lookalike_hosts(self) -> None: """Lookalike hosts are not auto-detected as GitHub or GitLab. Only github.com and gitlab.com may be auto-detected; any other host (github.evil.com, *gitlab*) - needs an explicit --provider/--api-url, otherwise a crafted remote URL receives the token. + needs an explicit --provider/--hostname, because gh and glab send environment tokens to any host. """ for host in ("github.evil.com", "github.evil.example", "gitlab.evil.com", "notgitlab.example", "my-gitlab.corp.example", "github.com.evil.example"): @@ -1588,18 +1524,24 @@ def test_lookalike_remote_gets_no_request(self) -> None: d, _ = collect(r, env={"GITHUB_TOKEN": FAKE}) # must not even try https://github.evil.com/api self.assertEqual(d["meta"]["mode"], "git") - def test_provider_and_api_url_override(self) -> None: - """--provider and --api-url enable a self-hosted GitLab.""" + def test_provider_and_hostname_override(self) -> None: + """--provider and --hostname enable a self-hosted GitLab, and glab gets exactly that host.""" r = fixtures.merge_workflow_repo() add_remote(r, "git@git.corp.example:team/app.git") d, _ = collect(r, env={"GITLAB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "git") self.assertTrue(any("No GitHub or GitLab remote" in w for w in d["meta"]["warnings"])) mrs, commits, notes = gitlab_fixture(r) + log = tmpdir() / "cli.log" with ms.MockServer(ms.gitlab_handler(mrs, commits, notes, page_size=50)) as srv: - d, _ = collect(r, "--provider", "gitlab", "--api-url", srv.url + "/api/v4", env={"GITLAB_TOKEN": FAKE}) + d, _ = collect(r, "--provider", "gitlab", "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE}) + self.assertEqual(d["meta"]["mode"], "git", "--provider alone must not trust the remote's host") + d, _ = collect(r, "--provider", "gitlab", "--hostname", "Git.Corp.Example", "--fake-api", srv.url, + env={"GITLAB_TOKEN": FAKE, "REPO_STATS_FAKE_LOG": str(log)}) self.assertTrue(any("team%2Fapp" in q["raw_path"] for q in srv.requests)) self.assertEqual(d["meta"]["mode"], "api") + hosts = {c["argv"][c["argv"].index("--hostname") + 1] for c in helpers.cli_calls(log)} + self.assertEqual(hosts, {"git.corp.example"}) self.assertEqual(d["meta"]["name"], "app") def test_remote_option(self) -> None: @@ -1608,7 +1550,7 @@ def test_remote_option(self) -> None: add_remote(r, "https://github.com/acme/widgets.git", "upstream") nodes = desc_nodes(github_nodes(r)) with ms.MockServer(ms.github_handler(nodes, page_size=50)) as srv: - d, _ = collect(r, "--remote", "upstream", "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(r, "--remote", "upstream", "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) body = json.loads(srv.requests[0]["body"]) self.assertEqual(body["variables"]["owner"], "acme") self.assertEqual(body["variables"]["name"], "widgets") @@ -1643,8 +1585,8 @@ def test_auto_mode_falls_back_on_any_exception(self) -> None: """Auto mode falls back to git on any client exception.""" r = api_repo() for exc in (ValueError("bad json"), TimeoutError("read timed out"), KeyError("data"), OSError("reset")): - with mock.patch.object(rs, "http_json", side_effect=exc): - d, _ = collect(r, "--api-url", "http://127.0.0.1:1", env={"GITHUB_TOKEN": FAKE}) + with mock.patch.object(rs.Cli, "_run", side_effect=exc): + d, _ = collect(r, "--fake-api", "http://127.0.0.1:1", env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "git", repr(exc)) self.assertTrue(any("API fetch failed" in w for w in d["meta"]["warnings"])) @@ -1658,7 +1600,7 @@ def test_since_keeps_prs_opened_before_but_merged_after_cutoff(self) -> None: since_day = time.strftime("%Y-%m-%d", time.gmtime(BASE + 5 * DAY)) nodes = [new, old, older] # created DESC with ms.MockServer(ms.github_handler(nodes, page_size=1)) as srv: - d, _ = collect(r, "--api-url", srv.url, "--since", since_day, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(r, "--fake-api", srv.url, "--since", since_day, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(sorted(p["number"] for p in d["prs"]), [20, 21]) def test_branch_with_non_origin_remote_prefix_still_matches_api_base(self) -> None: @@ -1667,7 +1609,7 @@ def test_branch_with_non_origin_remote_prefix_still_matches_api_base(self) -> No r.git("update-ref", "refs/remotes/upstream/main", "HEAD") nodes = desc_nodes(github_nodes(r)) with ms.MockServer(ms.github_handler(nodes, page_size=50)) as srv: - d, _ = collect(r, "--branch", "upstream/main", "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(r, "--branch", "upstream/main", "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "api") self.assertGreater(len(d["prs"]), 0, "base-branch filter compared 'upstream/main' with 'main' and dropped every PR") @@ -1679,7 +1621,7 @@ def test_remote_option_with_default_branch_of_that_remote(self) -> None: r.git("symbolic-ref", "refs/remotes/upstream/HEAD", "refs/remotes/upstream/main") nodes = desc_nodes(github_nodes(r)) with ms.MockServer(ms.github_handler(nodes, page_size=50)) as srv: - d, _ = collect(r, "--remote", "upstream", "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(r, "--remote", "upstream", "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) self.assertEqual(d["meta"]["mode"], "api") self.assertGreater(len(d["prs"]), 0, "zero PRs with --remote upstream and no warning") @@ -1688,7 +1630,7 @@ def test_zero_api_prs_after_base_filter_warns(self) -> None: r = api_repo() nodes = [ms.gh_node(1, "feat: x", BASE, merged=BASE + 100, base="some-other-branch")] with ms.MockServer(ms.github_handler(nodes, page_size=50)) as srv: - d, _ = collect(r, "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + d, _ = collect(r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) if not d["prs"]: self.assertTrue(d["meta"]["warnings"], "API returned PRs but all were filtered out by base branch, silently") @@ -1916,6 +1858,8 @@ def test_help_lists_all_flags(self) -> None: p = run_cli(["--help"]) self.assertEqual(p.returncode, 0) for action in rs.build_parser()._actions: + if action.help == argparse.SUPPRESS: # removed flags kept only to explain their replacement + continue for opt in action.option_strings: self.assertIn(opt, p.stdout, opt) @@ -2242,9 +2186,6 @@ def test_generated_html_has_no_remote_resource_loads(self) -> None: self.assertIsNone(self.RESOURCE.search(html)) -if __name__ == "__main__": - unittest.main() - # ===================================================================================================== # F. Regression tests for review findings @@ -2295,9 +2236,10 @@ class F2_GitLabDetailErrors(unittest.TestCase): def _fetch(self, handler: ms.Handler) -> tuple[list[dict[str, Any]], dict[str, int]]: """Run fetch_gitlab against `handler` and return (raw PRs, info).""" info: dict[str, int] = {} - with mock.patch.object(rs.time, "sleep", lambda s: None), ms.MockServer(handler) as srv: - prs = rs.fetch_gitlab("g/p", FAKE, srv.url + "/api/v4", None, "main", False, None, True, - progress=lambda m: None, info=info) + env = helpers.clean_env({"GITLAB_TOKEN": FAKE}) + with mock.patch.object(rs.time, "sleep", lambda s: None), ms.MockServer(handler) as srv, \ + rs.Cli("glab", "gitlab.com", {**env, "REPO_STATS_FAKE_URL": srv.url}) as cli: + prs = rs.fetch_gitlab(cli, "g/p", None, "main", False, None, True, progress=lambda m: None, info=info) return prs, info def test_notes_failure_is_not_unreviewed(self) -> None: @@ -2329,7 +2271,7 @@ def h(req: ms.Request) -> ms.Response: return (500, {}, {"message": "boom"}) if req["path"].endswith("/notes") else base(req) with mock.patch.object(rs.time, "sleep", lambda s: None), ms.MockServer(h) as srv: - d, _ = collect(r, "--api-url", srv.url + "/api/v4", env={"GITLAB_TOKEN": FAKE}) + d, _ = collect(r, "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE}) self.assertTrue(any("lookups fail" in w for w in d["meta"]["warnings"])) self.assertTrue(all(p["reviewed"] is None for p in d["prs"])) @@ -2445,3 +2387,220 @@ def test_csv_guard_covers_leading_whitespace(self) -> None: with open(path, newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f)) self.assertEqual([r["title"] for r in rows], ["' =HYPERLINK(\"http://x\")", " ", "fix: ok"]) + + +# ===================================================================================================== +# G. gh / glab: read-only requests, host trust and no credential handling +# ===================================================================================================== + +class G1_ReadOnlyCli(unittest.TestCase): + """Every API request is a read-only gh/glab call to an explicit host, from outside the repository.""" + + def _cli(self, tool: str, url: str = "http://127.0.0.1:1", **extra: str) -> rs.Cli: + """A Cli for `tool` that uses the fake CLIs and the mock server at `url`.""" + return rs.Cli(tool, "github.com" if tool == "gh" else "gitlab.com", + helpers.clean_env({"REPO_STATS_FAKE_URL": url, **extra})) + + def test_graphql_refuses_mutations(self) -> None: + """Mutations, subscriptions and anything that is not a query are refused before gh runs.""" + log = tmpdir() / "cli.log" + with self._cli("gh", REPO_STATS_FAKE_LOG=str(log)) as cli: + for q in ("mutation { addStar(input:{starrableId:\"x\"}) { clientMutationId } }", + "query { a } mutation { b }", "subscription { x }", "{ viewer { login } }", ""): + with self.assertRaises(rs.ApiError, msg=q): + cli.graphql(q, {}) + self.assertEqual(helpers.cli_calls(log), [], "no gh process may start for a refused request") + + def test_gitlab_refuses_endpoints_outside_the_allowlist(self) -> None: + """Only the three merge request list endpoints can be requested, and only with GET.""" + log = tmpdir() / "cli.log" + with self._cli("glab", REPO_STATS_FAKE_LOG=str(log)) as cli: + for ep in ("projects/g%2Fp/merge_requests/1/approve", "projects/g%2Fp/merge_requests/1/merge", + "projects/g%2Fp", "user", "projects/g/p/merge_requests", "projects/g%2Fp/merge_requests/1", + "projects/g%2Fp/merge_requests?x=1", "graphql", "/projects/g%2Fp/merge_requests"): + with self.assertRaises(rs.ApiError, msg=ep): + cli.get(ep, {}) + with self.assertRaises(rs.ApiError): # gh cannot be used for GitLab requests, nor glab for GraphQL + cli.graphql(rs.GITHUB_QUERY, {}) + with self._cli("gh") as cli: + with self.assertRaises(rs.ApiError): + cli.get("projects/g%2Fp/merge_requests", {}) + self.assertEqual(helpers.cli_calls(log), []) + + def test_source_has_no_write_requests(self) -> None: + """The source sends no mutation and names no write method.""" + src = (ROOT / "repo_stats.py").read_text() + self.assertTrue(rs.READ_ONLY_GRAPHQL.match(rs.GITHUB_QUERY)) + self.assertIsNone(rs.WRITE_GRAPHQL.search(rs.GITHUB_QUERY)) + 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) + + def test_bad_hostnames_rejected(self) -> None: + """--hostname must be a plain host name: no ports, schemes, paths, spaces or leading dashes.""" + r = api_repo() + for bad in ("-x", "--hostname=evil", "evil.example:8443", "https://evil.example", "a b", "evil.example/x", ""): + with self.assertRaises((rs.ToolError, SystemExit), msg=bad): + collect(r, "--provider", "github", "--hostname", bad, env={"GITHUB_TOKEN": FAKE}) + with self.assertRaises(rs.ApiError): + rs.Cli("gh", "evil example", helpers.clean_env()) + + def test_hostname_needs_provider_for_unknown_hosts(self) -> None: + """--hostname for a host that is not github.com/gitlab.com needs --provider.""" + r = api_repo("git@git.corp.example:team/app.git") + d, _ = collect(r, "--hostname", "git.corp.example", env={"GITLAB_TOKEN": FAKE}) + self.assertEqual(d["meta"]["mode"], "git") + self.assertTrue(any("needs --provider" in w for w in d["meta"]["warnings"])) + + def test_every_call_is_read_only_explicit_host_and_outside_the_repo(self) -> None: + """Each gh/glab call has --hostname and --include, no write flags, and runs from an empty temp dir.""" + for remote, provider_env, handler_for in ( + ("https://github.com/acme/widgets.git", "GITHUB_TOKEN", + lambda r: ms.github_handler(desc_nodes(github_nodes(r)), page_size=3)), + ("git@gitlab.com:grp/sub/proj.git", "GITLAB_TOKEN", + lambda r: ms.gitlab_handler(*gitlab_fixture(r), page_size=2))): + r = api_repo(remote) + log = tmpdir() / "cli.log" + with ms.MockServer(handler_for(r)) as srv: + d, _ = collect(r, "--fake-api", srv.url, env={provider_env: FAKE, "REPO_STATS_FAKE_LOG": str(log)}) + self.assertEqual(d["meta"]["mode"], "api", remote) + calls = helpers.cli_calls(log) + self.assertGreater(len(calls), 1) + cwds = set() + for c in calls: + argv = c["argv"] + self.assertEqual(argv[0], "api") + self.assertIn(argv[argv.index("--hostname") + 1], ("github.com", "gitlab.com")) + self.assertIn("--include", argv) + if c["tool"] == "glab": + self.assertEqual(argv[argv.index("--method") + 1], "GET") + else: + self.assertEqual(argv[1], "graphql") + query = next(a for a in argv if a.startswith("query="))[len("query="):] + self.assertTrue(rs.READ_ONLY_GRAPHQL.match(query)) + cwd = Path(c["cwd"]).resolve() + self.assertFalse(str(cwd).startswith(str(Path(r.path).resolve())), cwd) + cwds.add(cwd) + for cwd in cwds: + self.assertFalse(cwd.exists(), "the temporary working directory is removed afterwards") + + def test_cli_environment_is_quiet_and_has_no_debug_switches(self) -> None: + """The CLIs run with telemetry, prompts and update checks off, and without request-dumping debug flags.""" + r = api_repo("git@gitlab.com:grp/sub/proj.git") + log = tmpdir() / "cli.log" + noisy = {"GH_DEBUG": "api", "DEBUG": "1", "GLAB_DEBUG": "true", "GLAB_DEBUG_HTTP": "true"} + with ms.MockServer(ms.gitlab_handler(*gitlab_fixture(r), page_size=50)) as srv: + collect(r, "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE, "REPO_STATS_FAKE_LOG": str(log), **noisy}) + calls = helpers.cli_calls(log) + self.assertTrue(calls) + for c in calls: + for k, v in rs.CLI_QUIET_ENV.items(): + self.assertEqual(c["env"].get(k), v, k) + for k in noisy: + self.assertNotIn(k, c["env"]) + self.assertEqual(c["env"].get("GITLAB_TOKEN"), FAKE, "the CLI keeps its own login variables") + + def test_lookalike_remote_never_starts_a_cli(self) -> None: + """A lookalike or unknown remote host starts no gh/glab process at all.""" + for url in ("https://github.evil.com/acme/widgets.git", "git@gitlab.evil.example:a/b.git", + "https://github.com.evil.example/a/b.git"): + r = fixtures.merge_workflow_repo() + add_remote(r, url) + log = tmpdir() / "cli.log" + d, _ = collect(r, env={"GITHUB_TOKEN": FAKE, "GITLAB_TOKEN": FAKE, "REPO_STATS_FAKE_LOG": str(log)}) + self.assertEqual(d["meta"]["mode"], "git", url) + self.assertEqual(helpers.cli_calls(log), [], url) + + def test_ci_server_host_is_trusted_only_when_it_matches(self) -> None: + """In GitLab CI, a remote on CI_SERVER_HOST uses glab without --hostname; any other host does not.""" + r = api_repo("https://git.corp.example/grp/proj.git") + mrs, commits, notes = gitlab_fixture(r) + ci = {"GITLAB_CI": "true", "GITLAB_TOKEN": FAKE} + with ms.MockServer(ms.gitlab_handler(mrs, commits, notes, page_size=50)) as srv: + d, _ = collect(r, "--fake-api", srv.url, env={**ci, "CI_SERVER_HOST": "git.corp.example"}) + self.assertEqual(d["meta"]["mode"], "api") + self.assertEqual(d["meta"]["provider"], "gitlab") + n = len(srv.requests) + d, _ = collect(r, "--fake-api", srv.url, env={**ci, "CI_SERVER_HOST": "other.example"}) + self.assertEqual(d["meta"]["mode"], "git") + d, _ = collect(r, "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE, "CI_SERVER_HOST": "git.corp.example"}) + self.assertEqual(d["meta"]["mode"], "git", "CI_SERVER_HOST counts only inside GitLab CI") + 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.""" + 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"}): + 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) + for name, value in creds.items(): + self.assertNotIn(value, text, name) + + def test_parse_cli_response(self) -> None: + """--include output splits into status, lower-cased headers and body, with CRLF or LF.""" + st, h, body = rs.parse_cli_response(b"HTTP/2.0 200 OK\r\nX-Next-Page: 2\r\nLink: ; rel=next\r\n\r\n[1, 2]") + self.assertEqual((st, h["x-next-page"], h["link"], json.loads(body)), (200, "2", "; rel=next", [1, 2])) + st, h, body = rs.parse_cli_response(b"HTTP/1.1 404 Not Found\nContent-Type: application/json\n\n{\"message\": \"x\"}") + self.assertEqual((st, h["content-type"], body), (404, "application/json", b'{"message": "x"}')) + self.assertEqual(rs.parse_cli_response(b"HTTP/2.0 204 No Content\r\n\r\n")[::2], (204, b"")) + self.assertEqual(rs.parse_cli_response(b"error connecting to api.github.com")[0], None) + self.assertEqual(rs.parse_cli_response(b"")[0], None) + + +class G2_GitLabJobToken(unittest.TestCase): + """A login that cannot read MR commits (a GitLab CI job token) degrades to local commits, once.""" + + def test_refused_commits_use_local_merge_commits(self) -> None: + """One refused probe stops all commit lookups; merge-commit MRs get first-commit times from git.""" + r = api_repo("git@gitlab.com:grp/sub/proj.git") + mrs, commits, notes = gitlab_fixture(r) + inner = ms.gitlab_handler(mrs, commits, notes, page_size=50) + + def h(req: ms.Request) -> ms.Response: + """Refuse every commits request with 403, as GitLab does for a job token; serve the rest.""" + if req["path"].endswith("/commits"): + return 403, {}, {"message": "403 Forbidden"} + return inner(req) + + with ms.MockServer(h) as srv: + d, _ = collect(r, "--fake-api", srv.url, env={"GITLAB_TOKEN": FAKE}) + commit_calls = [q for q in srv.requests if q["path"].endswith("/commits")] + self.assertEqual(d["meta"]["mode"], "api") + self.assertEqual(len(commit_calls), 1, "after one refusal, no more commit lookups") + self.assertTrue(any("cannot read merge request commits" in w for w in d["meta"]["warnings"])) + self.assertFalse(any("lookups fail" in w for w in d["meta"]["warnings"])) + p1 = by_number(d)[1] # merged with a local merge commit: first commit comes from the branch + self.assertIsNotNone(p1["first_commit"]) + self.assertLessEqual(p1["first_commit"], p1["merged"]) + self.assertIn("lead", p1["inferred"]) + self.assertIn("coding", p1["inferred"]) + self.assertTrue(p1["reviewed"]) # notes still work with a job token + self.assertIsNone(by_number(d)[4]["first_commit"]) # open, no local commit: stays unknown + + def test_job_token_autologin_reaches_the_api(self) -> None: + """With GLAB_ENABLE_CI_AUTOLOGIN in GitLab CI, glab authenticates with CI_JOB_TOKEN by itself.""" + r = api_repo("git@gitlab.com:grp/sub/proj.git") + mrs, commits, notes = gitlab_fixture(r) + inner = ms.gitlab_handler(mrs, commits, notes, page_size=50) + seen = [] + + def h(req: ms.Request) -> ms.Response: + """Accept JOB-TOKEN like GitLab does; refuse commits, which a job token cannot read.""" + seen.append(req["headers"].get("job-token")) + if req["path"].endswith("/commits"): + return 403, {}, {"message": "403 Forbidden"} + return inner({**req, "headers": {**req["headers"], "private-token": req["headers"].get("job-token")}}) + + env = {"GITLAB_CI": "true", "GLAB_ENABLE_CI_AUTOLOGIN": "true", "CI_JOB_TOKEN": "job-tok-123"} + with ms.MockServer(h) as srv: + d, _ = collect(r, "--fake-api", srv.url, env=env) + self.assertEqual(d["meta"]["mode"], "api") + self.assertEqual(set(seen), {"job-tok-123"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/repo-stats/tests/test_ui.py b/repo-stats/tests/test_ui.py index a09449e..2b10666 100644 --- a/repo-stats/tests/test_ui.py +++ b/repo-stats/tests/test_ui.py @@ -262,7 +262,7 @@ def build_api_data() -> dict[str, Any]: nodes.append(node) nodes.sort(key=lambda n: n["createdAt"], reverse=True) with ms.MockServer(ms.github_handler(nodes, page_size=40)) as srv: - data, _ = collect(work, "--api-url", srv.url, env={"GITHUB_TOKEN": FAKE}) + data, _ = collect(work, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) return data From 410e28d7f1de3ce1b44edb34669787e9a653d05c Mon Sep 17 00:00:00 2001 From: claude Date: Tue, 27 Oct 2026 00:44:11 +0000 Subject: [PATCH 04/10] feat(repo-stats): add run.sh to keep a read-only token in the OS keychain `run.sh --store github` opens GitHub's fine-grained token page with read-only Contents and Pull requests (30 days) filled in, for the remote's owner, and saves the pasted token. `run.sh --store gitlab --project grp/proj` asks glab for a read_api Reporter project token and falls back to the personal token page with only read_api selected. `run.sh [options]` then hands the saved token to gh/glab (GH_TOKEN, GH_ENTERPRISE_TOKEN for that --hostname, or GITLAB_TOKEN) for that run only; without one, gh/glab use their own login. `--forget` deletes it. The token is read at a hidden prompt and reaches the keychain on stdin through shell builtins, so it never appears in shell history, a file, or any process's arguments. Uses the macOS Keychain or secret-tool on Linux. Tests use a fake secret-tool and skip on macOS. --- repo-stats/run.sh | 223 ++++++++++++++++++++++++++++ repo-stats/tests/test_repo_stats.py | 132 ++++++++++++++++ 2 files changed, 355 insertions(+) create mode 100755 repo-stats/run.sh diff --git a/repo-stats/run.sh b/repo-stats/run.sh new file mode 100755 index 0000000..b575511 --- /dev/null +++ b/repo-stats/run.sh @@ -0,0 +1,223 @@ +#!/bin/sh +# repo-stats with a read-only API token kept in the OS keychain. +# +# run.sh --store github|gitlab [--hostname HOST] [--project GROUP/PROJECT] [--owner OWNER] +# Get a read-only token and save it in the keychain. On GitHub this opens the token page with +# read-only permissions filled in; you paste the token at a hidden prompt. On GitLab with --project, +# it first tries `glab token create` (read_api, 30 days), then falls back to the token page. +# run.sh --forget github|gitlab [--hostname HOST] +# Delete the saved token. +# run.sh [repo_stats.py options] +# Run repo-stats. A saved token is given to gh/glab for this run only, as GH_TOKEN, +# GH_ENTERPRISE_TOKEN or GITLAB_TOKEN. Without one, gh/glab use their own login. +# +# The token is never echoed, never passed as a command argument (where `ps` could see it) and never +# written to shell history or a file. repo_stats.py itself never reads it: only gh/glab do, and +# repo_stats.py removes it from the environment of the git commands it runs. +# +# Keychains: macOS Keychain (`security`) or the Linux Secret Service (`secret-tool`, from libsecret-tools). +set -eu + +here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +service=repo-stats +tok= + +die() { printf 'run.sh: %s\n' "$*" >&2; exit 1; } +note() { printf '%s\n' "$*" >&2; } + +keychain() { + if [ "$(uname -s)" = Darwin ] && command -v security >/dev/null 2>&1; then echo macos + elif command -v secret-tool >/dev/null 2>&1; then echo secret-tool + else echo none + fi +} + +check_host() { + case $1 in + ''|-*|*[!A-Za-z0-9.-]*) die "invalid host name '$1'" ;; + esac +} + +lookup() { # print the saved token for host $1, or nothing + case $(keychain) in + macos) security find-generic-password -a "$1" -s "$service" -w 2>/dev/null || true ;; + secret-tool) secret-tool lookup service "$service" host "$1" 2>/dev/null || true ;; + esac +} + +save() { # save $tok for host $1 + [ -n "$tok" ] || die "no token given" + case $tok in + *[!A-Za-z0-9_.-]*) tok=; die "that does not look like a token (unexpected characters); nothing saved" ;; + esac + case $(keychain) in + macos) + # `security -i` reads the command from stdin, so the token is not in any process's arguments. + printf 'add-generic-password -U -a "%s" -s "%s" -l "%s" -w "%s"\n' "$1" "$service" "repo-stats $1" "$tok" \ + | security -i >/dev/null ;; + secret-tool) + printf '%s' "$tok" | secret-tool store --label="repo-stats $1 (read-only)" service "$service" host "$1" ;; + *) tok=; die "no supported keychain found. Install secret-tool (libsecret-tools) or use 'gh auth login' / 'glab auth login'." ;; + esac + tok= +} + +forget() { + case $(keychain) in + macos) security delete-generic-password -a "$1" -s "$service" >/dev/null 2>&1 || true ;; + secret-tool) secret-tool clear service "$service" host "$1" 2>/dev/null || true ;; + esac +} + +read_secret() { # read a line into $tok without echoing it + if [ -t 0 ]; then + printf '%s' "$1" >&2 + trap 'stty echo 2>/dev/null' EXIT INT TERM + stty -echo + IFS= read -r tok || true + stty echo + trap - EXIT INT TERM + printf '\n' >&2 + else + IFS= read -r tok || true + fi +} + +open_url() { # open $1 in a browser when run from a terminal; always print it + note " $1" + [ -t 1 ] || return 0 + case $(uname -s) in + Darwin) open "$1" 2>/dev/null || true ;; + *) if command -v xdg-open >/dev/null 2>&1; then xdg-open "$1" >/dev/null 2>&1 || true; fi ;; + esac +} + +remote_owner() { # best effort: the owner/group of origin when it is on host $1 + url=$(git remote get-url origin 2>/dev/null) || return 0 + printf '%s\n' "$url" | sed -n -E "s#^([a-z+]+://)?([^@/]+@)?$1[:/]([^/]+)/.*#\\3#p" | head -n 1 +} + +store() { + provider=$1; shift + host='' project='' owner='' + while [ $# -gt 0 ]; do + case $1 in + --hostname) host=${2:-}; shift 2 ;; + --hostname=*) host=${1#*=}; shift ;; + --project) project=${2:-}; shift 2 ;; + --project=*) project=${1#*=}; shift ;; + --owner) owner=${2:-}; shift 2 ;; + --owner=*) owner=${1#*=}; shift ;; + *) die "unknown option for --store: $1" ;; + esac + done + case $provider in + github) host=${host:-github.com} ;; + gitlab) host=${host:-gitlab.com} ;; + *) die "--store needs github or gitlab" ;; + esac + check_host "$host" + [ "$(keychain)" != none ] || die "no supported keychain found. Install secret-tool (libsecret-tools) or use 'gh auth login' / 'glab auth login'." + + if [ "$provider" = gitlab ] && [ -n "$project" ] && command -v glab >/dev/null 2>&1; then + note "Creating a read-only project access token for $project with glab (read_api, Reporter, 30 days) ..." + tok=$(cd "${TMPDIR:-/tmp}" && GLAB_SEND_TELEMETRY=false GLAB_NO_PROMPT=1 GLAB_CHECK_UPDATE=false \ + glab token create --repo "https://$host/$project" --access-level reporter --scope read_api \ + --duration 30d --description "Read-only token for repo-stats" "repo-stats-$(date +%Y%m%d%H%M%S)") || tok= + if [ -n "$tok" ]; then + save "$host" + note "Saved. Run: $0 /path/to/repo" + return 0 + fi + note "glab could not create a project access token (on GitLab.com they need Premium or Ultimate and the" + note "Maintainer role). Create a personal token instead:" + fi + + if [ "$provider" = github ]; then + owner=${owner:-$(remote_owner "$host")} + url="https://$host/settings/personal-access-tokens/new?name=repo-stats+read-only&description=Read-only+token+for+repo-stats&expires_in=30&contents=read&pull_requests=read" + [ -z "$owner" ] || url="$url&target_name=$owner" + note "1. Open this page (it fills in a read-only token: Contents and Pull requests, read; 30 days):" + open_url "$url" + note "2. Under Repository access, choose 'Only select repositories' and pick the repositories to analyse." + note "3. Click 'Generate token' and copy it." + else + note "1. Open this page (it fills in a token with only the read_api scope):" + open_url "https://$host/-/user_settings/personal_access_tokens?name=repo-stats+read-only&scopes=read_api" + note "2. Set an expiry date, click 'Create token' and copy it." + fi + read_secret "Paste the token (it will not be shown): " + save "$host" + note "Saved in the keychain for $host. Run: $0 /path/to/repo" +} + +case ${1:-} in + --store) + shift + [ $# -gt 0 ] || die "--store needs github or gitlab" + store "$@" + exit 0 ;; + --forget) + shift + case ${1:-} in + github) host=github.com ;; + gitlab) host=gitlab.com ;; + *) die "--forget needs github or gitlab" ;; + esac + shift + case ${1:-} in + --hostname) host=${2:-} ;; + --hostname=*) host=${1#*=} ;; + esac + check_host "$host" + forget "$host" + note "Removed the saved token for $host (if there was one)." + exit 0 ;; +esac + +# Run repo-stats. Find --hostname/--provider among its options to pick the saved token, if any. +hostname='' provider='' prev='' +for a in "$@"; do + case $prev in + --hostname) hostname=$a ;; + --provider) provider=$a ;; + esac + case $a in + --hostname=*) hostname=${a#*=} ;; + --provider=*) provider=${a#*=} ;; + esac + prev=$a +done +hostname=$(printf '%s' "$hostname" | tr '[:upper:]' '[:lower:]') + +if [ "$(keychain)" != none ]; then + if [ -n "$hostname" ]; then + check_host "$hostname" + case $hostname in + github.com) provider=${provider:-github} ;; + gitlab.com) provider=${provider:-gitlab} ;; + esac + t=$(lookup "$hostname") + if [ -n "$t" ]; then + case $provider in + github) + # gh sends GH_TOKEN only to github.com and GH_ENTERPRISE_TOKEN to other hosts; repo-stats passes + # this same host to gh as --hostname. + if [ "$hostname" = github.com ]; then GH_TOKEN=$t; export GH_TOKEN + else GH_ENTERPRISE_TOKEN=$t; export GH_ENTERPRISE_TOKEN; fi + note "Using the read-only token for $hostname from the keychain." ;; + gitlab) + GITLAB_TOKEN=$t; export GITLAB_TOKEN + note "Using the read-only token for $hostname from the keychain." ;; + esac + fi + else + t=$(lookup github.com) + if [ -n "$t" ]; then GH_TOKEN=$t; export GH_TOKEN; note "Using the read-only github.com token from the keychain."; fi + t=$(lookup gitlab.com) + if [ -n "$t" ]; then GITLAB_TOKEN=$t; export GITLAB_TOKEN; note "Using the read-only gitlab.com token from the keychain."; fi + fi + t= +fi + +exec "${PYTHON:-python3}" "$here/repo_stats.py" "$@" diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index 0424ba6..5a5892b 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -2602,5 +2602,137 @@ def h(req: ms.Request) -> ms.Response: self.assertEqual(set(seen), {"job-tok-123"}) +FAKE_SECRET_TOOL = r'''#!/bin/sh +# Fake secret-tool: one file per host in $FAKE_KEYRING; logs its arguments to argv.log. +printf '%s\n' "$*" >> "$FAKE_KEYRING/argv.log" +cmd=$1; shift +host='' +while [ $# -gt 0 ]; do + case $1 in host) host=$2; shift 2 ;; *) shift ;; esac +done +case $cmd in + store) cat > "$FAKE_KEYRING/$host" ;; + lookup) if [ -f "$FAKE_KEYRING/$host" ]; then cat "$FAKE_KEYRING/$host"; fi ;; + clear) rm -f "$FAKE_KEYRING/$host" ;; +esac +''' + + +@unittest.skipIf(sys.platform == "darwin", "run.sh would use the real macOS Keychain") +class H1_RunScript(unittest.TestCase): + """run.sh keeps a read-only token in the keychain and hands it to gh/glab for one run only.""" + + def setUp(self) -> None: + """A fake secret-tool on PATH, backed by a temporary directory.""" + self.ring = tmpdir() + bin_dir = tmpdir() + tool = bin_dir / "secret-tool" + tool.write_text(FAKE_SECRET_TOOL) + tool.chmod(0o755) + self.env = helpers.clean_env({"FAKE_KEYRING": str(self.ring)}) + self.env["PATH"] = os.pathsep.join([str(bin_dir), self.env["PATH"]]) + + def sh(self, args: Sequence[object], stdin: str = "", cwd: str | Path | None = None, + extra: Mapping[str, str] | None = None) -> subprocess.CompletedProcess[str]: + """Run run.sh with the fake keychain and fake CLIs.""" + return subprocess.run(["sh", str(ROOT / "run.sh"), *map(str, args)], input=stdin, capture_output=True, + text=True, cwd=cwd, env={**self.env, **(extra or {})}, timeout=120) + + def argv_log(self) -> str: + """Everything passed to secret-tool as arguments.""" + p = self.ring / "argv.log" + return p.read_text() if p.exists() else "" + + def test_store_github_reads_stdin_and_never_puts_the_token_in_argv(self) -> None: + """--store github prints a read-only token link for the remote's owner and saves the pasted token.""" + r = api_repo() + p = self.sh(["--store", "github"], stdin=FAKE + "\n", cwd=r.path) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual((self.ring / "github.com").read_text(), FAKE) + self.assertNotIn(FAKE, self.argv_log()) + self.assertNotIn(FAKE, p.stdout + p.stderr) + url = next(w for w in p.stderr.split() if w.startswith("https://github.com/settings/personal-access-tokens/new?")) + q = urllib.parse.parse_qs(urllib.parse.urlparse(url).query) + self.assertEqual((q["contents"], q["pull_requests"], q["target_name"], q["expires_in"]), + (["read"], ["read"], ["acme"], ["30"])) + self.assertNotIn("write", url) + + def test_store_rejects_text_that_is_not_a_token(self) -> None: + """Pasting something with spaces or quotes saves nothing.""" + p = self.sh(["--store", "github"], stdin='not "a" token\n') + self.assertNotEqual(p.returncode, 0) + self.assertFalse((self.ring / "github.com").exists()) + + def test_run_hands_the_saved_token_to_gh_for_one_run(self) -> None: + """A saved github.com token reaches gh as GH_TOKEN; it is in no output and not in git's environment.""" + r = api_repo() + (self.ring / "github.com").write_text(FAKE) + out = tmpdir() + log = tmpdir() / "cli.log" + with ms.MockServer(ms.github_handler(desc_nodes(github_nodes(r)), page_size=50, expect_token=FAKE)) as srv: + p = self.sh([r.path, "-o", out / "o.html", "--json", out / "o.json"], + extra={"REPO_STATS_FAKE_URL": srv.url, "REPO_STATS_FAKE_LOG": str(log)}) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("Using the read-only github.com token from the keychain", p.stderr) + self.assertEqual(json.loads((out / "o.json").read_text())["meta"]["mode"], "api") + self.assertNotIn(FAKE, (out / "o.html").read_text() + (out / "o.json").read_text() + p.stdout + p.stderr) + self.assertEqual({c["env"].get("GH_TOKEN") for c in helpers.cli_calls(log)}, {FAKE}) + + def test_enterprise_host_gets_the_enterprise_variable(self) -> None: + """For --hostname ghe.example.com the token goes to gh as GH_ENTERPRISE_TOKEN, for that host only.""" + r = api_repo("git@ghe.example.com:acme/widgets.git") + (self.ring / "ghe.example.com").write_text(FAKE) + (self.ring / "github.com").write_text("other-token-should-not-be-used") + log = tmpdir() / "cli.log" + with ms.MockServer(ms.github_handler(desc_nodes(github_nodes(r)), page_size=50, expect_token=FAKE)) as srv: + p = self.sh([r.path, "-o", tmpdir() / "o.html", "--provider", "github", "--hostname", "GHE.example.com", + "--source", "api"], extra={"REPO_STATS_FAKE_URL": srv.url, "REPO_STATS_FAKE_LOG": str(log)}) + self.assertEqual(p.returncode, 0, p.stderr) + calls = helpers.cli_calls(log) + self.assertTrue(calls) + for c in calls: + self.assertEqual(c["env"].get("GH_ENTERPRISE_TOKEN"), FAKE) + self.assertNotIn("GH_TOKEN", c["env"]) + self.assertEqual(c["argv"][c["argv"].index("--hostname") + 1], "ghe.example.com") + + def test_without_a_saved_token_the_cli_login_is_used(self) -> None: + """With nothing saved, run.sh sets no token and gh uses its own login.""" + r = api_repo() + with ms.MockServer(ms.github_handler(desc_nodes(github_nodes(r)), page_size=50, expect_token="own-login")) as srv: + p = self.sh([r.path, "-o", tmpdir() / "o.html", "--source", "api"], + extra={"REPO_STATS_FAKE_URL": srv.url, "GH_TOKEN": "own-login"}) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertNotIn("from the keychain", p.stderr) + + def test_forget(self) -> None: + """--forget deletes the saved token.""" + (self.ring / "gitlab.com").write_text(FAKE) + p = self.sh(["--forget", "gitlab"]) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertFalse((self.ring / "gitlab.com").exists()) + + def test_store_gitlab_creates_a_read_api_project_token_with_glab(self) -> None: + """--store gitlab --project asks glab for a read_api Reporter token and saves it without echoing it.""" + log = tmpdir() / "cli.log" + p = self.sh(["--store", "gitlab", "--project", "grp/proj"], + extra={"REPO_STATS_FAKE_NEW_TOKEN": "glpat-New_Token.01", "REPO_STATS_FAKE_LOG": str(log)}) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual((self.ring / "gitlab.com").read_text(), "glpat-New_Token.01") + self.assertNotIn("glpat-New_Token.01", self.argv_log() + p.stdout + p.stderr) + argv = helpers.cli_calls(log)[0]["argv"] + self.assertEqual(argv[:2], ["token", "create"]) + for flag, value in (("--scope", "read_api"), ("--access-level", "reporter"), ("--duration", "30d"), + ("--repo", "https://gitlab.com/grp/proj")): + self.assertEqual(argv[argv.index(flag) + 1], value, flag) + + def test_store_gitlab_falls_back_to_the_token_page(self) -> None: + """When glab cannot create a project token, the read_api token page is offered instead.""" + p = self.sh(["--store", "gitlab", "--project", "grp/proj"], stdin="glpat-pasted\n") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("could not create a project access token", p.stderr) + self.assertIn("personal_access_tokens?name=repo-stats+read-only&scopes=read_api", p.stderr) + self.assertEqual((self.ring / "gitlab.com").read_text(), "glpat-pasted") + + if __name__ == "__main__": unittest.main() From 7aecb134759f30cf9cd623747c9de4098083709b Mon Sep 17 00:00:00 2001 From: claude Date: Tue, 27 Oct 2026 00:44:11 +0000 Subject: [PATCH 05/10] docs(repo-stats): document gh/glab logins, read-only tokens and CI use README: quick start without tokens; a "Logging in" section for local use, run.sh, GitHub Actions, GitLab CI and scheduled jobs; and a Security section on the read-only allowlist, host trust and what remains. The plan records how the implementation differs from it. --- repo-stats/README.adoc | 163 ++++++++++++++++++++++++----- repo-stats/docs/plan-cli-auth.adoc | 14 ++- 2 files changed, 150 insertions(+), 27 deletions(-) diff --git a/repo-stats/README.adoc b/repo-stats/README.adoc index 2931856..bcefd4f 100644 --- a/repo-stats/README.adoc +++ b/repo-stats/README.adoc @@ -19,7 +19,8 @@ image::docs/dashboard-dark.png[Dashboard overview in dark theme: KPIs, lines of .PR size section in the light theme image::docs/dashboard-light.png[PR size statistics, histogram, cumulative frequency and size buckets in light theme] -The tool is one Python file plus one HTML template. It needs Python 3.8 or newer and git, and nothing else. +The tool is one Python file plus one HTML template. It needs Python 3.8 or newer and git. +For exact PR data it also uses the GitHub CLI (`gh`) or the GitLab CLI (`glab`), with the login you already have. The output is a single HTML file. It works offline, and you can mail it, attach it or host it anywhere. == Quick start @@ -27,19 +28,14 @@ The output is a single HTML file. It works offline, and you can mail it, attach [source,sh] ---- # from a clone of this repository -python3 repo-stats/repo_stats.py /path/to/your/repo -o stats.html -open stats.html # or xdg-open on Linux +python3 repo-stats/repo_stats.py /path/to/your/repo --serve # builds the dashboard and opens it -# exact PR data from GitHub (recommended) -GITHUB_TOKEN=$(gh auth token) python3 repo-stats/repo_stats.py /path/to/repo - -# exact MR data from GitLab -GITLAB_TOKEN=glpat-... python3 repo-stats/repo_stats.py /path/to/repo - -# serve it locally and open a browser -python3 repo-stats/repo_stats.py /path/to/repo --serve +# exact PR data: log in to gh or glab once (skip this if you already use them) +gh auth login # or: glab auth login +python3 repo-stats/repo_stats.py /path/to/repo -o stats.html ---- +No tokens or environment variables are needed: repo-stats asks `gh` or `glab` for the data, and they use their own login. Run `repo_stats.py --help` for every flag. == Where the data comes from @@ -47,15 +43,13 @@ Run `repo_stats.py --help` for every flag. Git has no record of pull requests. The tool has two sources and says on the dashboard which one it used. API (recommended):: -With a token, the tool reads PRs from the GitHub GraphQL API or the GitLab REST API. +When the remote is on `github.com` or `gitlab.com` and `gh` or `glab` is installed and logged in, the tool reads PRs from the GitHub GraphQL API or the GitLab REST API through `gh api` or `glab api`. Open, ready-for-review, first review and merge times are then exact. -Tokens are read from the environment only (`GITHUB_TOKEN`, `GH_TOKEN`, `GITLAB_TOKEN`, `GITLAB_PRIVATE_TOKEN`, or the variable named by `--token-env`). -They are never written to any output. -A token is sent automatically only to `github.com` and `gitlab.com`. -For GitHub Enterprise or self-hosted GitLab, pass `--provider` and `--api-url`. +For GitHub Enterprise or self-managed GitLab, pass `--provider` and `--hostname HOST`. +If the CLI is missing or not logged in, the tool says how to fix it and uses git instead (or exits, with `--source api`). Git only (fallback):: -Without a token, PRs are inferred from history. +Without the API, PRs are inferred from history. A PR is a merge commit on the branch, or a squash commit whose subject ends in `(#123)` or whose body names a merge request. GitHub, GitLab and Bitbucket message formats are recognised. Open and review times do not exist in git, so those metrics are empty. @@ -65,15 +59,132 @@ 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. +== Logging in + +repo-stats never reads, stores or sends a token. `gh` and `glab` find their own login, in this order: an environment variable (`GH_TOKEN`, `GITLAB_TOKEN`), then the login saved by `gh auth login` or `glab auth login` (in the OS keychain where there is one). + +=== On your machine + +`gh auth login` and `glab auth login` are the simplest choice. +Their tokens can write to your repositories, though repo-stats only ever reads (see <>). +To give repo-stats a token that cannot write, keep a read-only token in the OS keychain with `run.sh`: + +[source,sh] +---- +repo-stats/run.sh --store github # opens GitHub's token page with read-only permissions filled in +repo-stats/run.sh --store gitlab --project grp/proj # glab creates a read_api project token, or opens the token page +repo-stats/run.sh /path/to/repo --serve # every run: same options as repo_stats.py +repo-stats/run.sh --forget github # delete the saved token +---- + +On GitHub, choose "Only select repositories" on the token page and pick the repositories to analyse. +GitLab.com project tokens need Premium or Ultimate and the Maintainer role; otherwise `run.sh` opens the personal token page with only `read_api` selected. +You paste the token at a hidden prompt. It is never shown, never passed as a command argument and never written to shell history or a file. +Each run hands it to `gh` or `glab` for that run only, and repo-stats removes it from the environment of the git commands it runs. +`run.sh` uses the macOS Keychain or, on Linux, the Secret Service (`secret-tool`, package `libsecret-tools`). +Do not load a read-only token with `gh auth login --with-token`: gh keeps one keychain entry per host and account, so it would replace your normal login. + +=== GitHub Actions + +`gh` is installed on GitHub-hosted runners. Give the step the job's own token, limited to read access: + +[source,yaml] +---- +permissions: + contents: read + pull-requests: read +jobs: + stats: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # full history and tags + - uses: actions/checkout@v4 + with: + repository: husam-e/scripts + path: tools + - run: python3 tools/repo-stats/repo_stats.py . -o 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 +---- + +Set `GH_TOKEN` on this step only, so other steps never see it. +To analyse another private repository, use a GitHub App installation token (for example from `actions/create-github-app-token`), not a personal token. + +=== GitLab CI + +[source,yaml] +---- +repo-stats: + image: registry.gitlab.com/gitlab-org/cli:v1.124.0 # glab and git; pin a version + variables: + GIT_DEPTH: 0 # full history + GLAB_ENABLE_CI_AUTOLOGIN: "true" # glab signs in with the job's CI_JOB_TOKEN + script: + - apk add --no-cache python3 + - git clone --depth 1 https://github.com/husam-e/scripts.git /tmp/tools + - python3 /tmp/tools/repo-stats/repo_stats.py . -o repo-stats.html + artifacts: + paths: [repo-stats.html] +---- + +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`. +The job token is not strictly read-only (GitLab also lets it create releases and deployments), so prefer a `read_api` token where that matters. +On self-managed GitLab, a remote on the job's own server (`CI_SERVER_HOST`) is used without `--hostname`. + +=== Scheduled or remote jobs + +Give the token to the run only, from your secret store, and prefer short-lived, read-only tokens: a GitHub App installation token, or a fine-grained token with read-only Contents and Pull requests; on GitLab, a `read_api` project or group token with an expiry. + +[source,sh] +---- +# systemd: LoadCredential=gh-token:/etc/creds/gh-token, then in the service's script: +GH_TOKEN="$(cat "$CREDENTIALS_DIRECTORY/gh-token")" python3 repo_stats.py /srv/repo -o /srv/out/stats.html +# Jenkins: withCredentials([string(credentialsId: 'gh-read', variable: 'GH_TOKEN')]) { sh '...' } +# Kubernetes: mount the secret as an environment variable of the container +---- + +Avoid `gh auth login` and `glab auth login` on servers: with no keychain, they save the token in a plain-text file. + +[[read-only]] == Security -Tokens are read from the environment only and are never written to any output. -A token is sent automatically only to `github.com` and `gitlab.com`. -API requests to `127.0.0.1`, `::1` or `localhost` never go through a proxy. -`--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. -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". +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`). +* 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. + +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 an empty temporary directory, so `glab` cannot pick up a host from the analysed repository. glab telemetry, update checks, prompts 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. +* 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. +* 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". + +What remains: + +* Any program running as you can ask `gh` or `glab` for its token. Read-only, short-lived tokens limit what a leaked or misused token can do. +* A wrong `--hostname` is trusted: an environment token for that CLI goes to it. +* In CI, the token is readable by every process in the step that sets it. +* Analysing a repository you do not trust still runs git on it. == Heuristics @@ -131,6 +242,8 @@ The Elite, High, Medium and Low bands use rounded thresholds from published DORA | `--json FILE`, `--csv FILE` | Export the raw data. | `--all-bases` | Include PRs that target other branches. | `--max-prs N` | Stop after N PRs. Useful on very large repositories. +| `--provider`, `--hostname HOST` | Use GitHub Enterprise or self-managed GitLab. +| `--source git` | Never call the API. |=== The dashboard filters by date range, PR type and bots, and switches between day, week and month. @@ -144,5 +257,5 @@ Every chart has a Table view with the numbers behind it. cd repo-stats && python3 -m unittest discover -s tests -v ---- -The tests build synthetic repositories and run the API clients against local mock servers. +The tests build synthetic repositories and run the API code through fake `gh` and `glab` commands (`tests/fake_cli`) that answer from local mock servers. No test reaches the network or a real login. The browser tests use Playwright with Chromium, and skip when either is missing. diff --git a/repo-stats/docs/plan-cli-auth.adoc b/repo-stats/docs/plan-cli-auth.adoc index 6dfe2ca..6e21c17 100644 --- a/repo-stats/docs/plan-cli-auth.adoc +++ b/repo-stats/docs/plan-cli-auth.adoc @@ -1,8 +1,18 @@ = Plan: replace API tokens with the `gh` and `glab` CLIs :toc: macro -Base branch: `claude/zealous-johnson-rfqa12` (commit `6c2e7a1`). -Status: proposal. No code is changed on this branch yet. +Base branch: `claude/zealous-johnson-rfqa12` (rebased on commit `e0fb5b5`). +Status: implemented on this branch. The README's "Logging in" and "Security" sections are the user-facing description. + +== As implemented: differences from this plan + +* *Errors come from the HTTP status, not from stderr.* Every call passes `--include`, so the CLI prints the status line and headers before the body. That gives the status code, `Retry-After` (so `_retry_after` stayed) and GitLab's `X-Next-Page`. +* *GitLab paging still follows `X-Next-Page`*, read from the `--include` headers, instead of stopping on a short page. The per-MR commit and note paging added in `31a6c9e` is kept. +* *The job-token check is one probe.* Before the per-MR lookups, one commits request decides whether the login can read MR commits. On 401/403/404, no more commits are requested, PRs are marked `commits_refused`, and `build_records` takes the first commit from the local merge commit's branch, marking `coding`, `lead` and `lead_to_deploy` as inferred. +* *The fake CLIs forward to the existing mock servers.* `tests/fake_cli/gh` and `glab` turn each call into one HTTP request to the mock server, find tokens the way the real CLIs do, and reject any flag outside the allowlist. `helpers.clean_env()` always puts them first on `PATH`, so no test can reach a real CLI or login. +* *`--api-url` and `--token-env` still parse* (hidden from `--help`) so that using them fails with a message naming the replacement. +* *`run.sh` was added* for read-only tokens kept in the OS keychain (see the README). +* *The read-only allowlist and `--hostname` validation* are enforced in `Cli`, and the G1/G2/H1 tests pin them. toc::[] From 244104e9696889c4d9e3df0bda502bf049c12644 Mon Sep 17 00:00:00 2001 From: claude Date: Tue, 27 Oct 2026 02:23:11 +0000 Subject: [PATCH 06/10] test(repo-stats): check the fallback warning when gh is missing Run the CLI with no gh on PATH and assert it prints "warning: gh is not installed", says PRs are inferred from git history, and ends with "source: git". The existing test only checked the warning in-process. --- repo-stats/tests/test_repo_stats.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index 5a5892b..47bbab6 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -1326,6 +1326,17 @@ def test_missing_cli_falls_back_or_errors(self) -> None: with self.assertRaises(rs.CliUnavailable): collect(r, "--source", "api", env={"PATH": str(empty)}) + def test_missing_cli_warns_on_the_command_line(self) -> None: + """Without gh on PATH, the run prints a warning, uses local git history and says so.""" + r = api_repo() + empty = tmpdir() + git_dir = Path(subprocess.run(["sh", "-c", "command -v git"], capture_output=True, text=True).stdout.strip()).parent + p = run_cli([r.path, "-o", tmpdir() / "o.html"], env={"PATH": os.pathsep.join([str(empty), str(git_dir)])}) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("warning: gh is not installed", p.stderr) + self.assertIn("PRs are inferred from git history", p.stderr) + self.assertIn("source: git", p.stderr) + def test_collect_passes_given_environ_to_the_cli(self) -> None: """collect() runs gh with its environ argument, not os.environ.""" nodes = github_nodes(fixtures.merge_workflow_repo()) From 3d09681300245c21aab026bd472bc31c3b8780ea Mon Sep 17 00:00:00 2001 From: claude Date: Tue, 27 Oct 2026 02:23:11 +0000 Subject: [PATCH 07/10] feat(repo-stats): accept months, years and durations for --since/--until --since and --until now take a UTC date (2025-01-15), month (2025-01) or year (2025), or a duration back from now (90d, 6w, 6m, 1y). --until covers the whole day, month or year it names, so `--since 2025-01 --until 2025-07` is January through July, and `--since 1y` is the last year. Months are calendar months, clamped to the month's last day. A window whose start is not before its end is an error. --- repo-stats/README.adoc | 6 ++- repo-stats/repo_stats.py | 64 ++++++++++++++++++++++------- repo-stats/tests/test_repo_stats.py | 47 ++++++++++++++++++++- 3 files changed, 101 insertions(+), 16 deletions(-) diff --git a/repo-stats/README.adoc b/repo-stats/README.adoc index bcefd4f..416ee5f 100644 --- a/repo-stats/README.adoc +++ b/repo-stats/README.adoc @@ -33,6 +33,10 @@ python3 repo-stats/repo_stats.py /path/to/your/repo --serve # builds the das # exact PR data: log in to gh or glab once (skip this if you already use them) gh auth login # or: glab auth login python3 repo-stats/repo_stats.py /path/to/repo -o stats.html + +# a time window: January to July 2025, or the last year +python3 repo-stats/repo_stats.py /path/to/repo --since 2025-01 --until 2025-07 +python3 repo-stats/repo_stats.py /path/to/repo --since 1y ---- No tokens or environment variables are needed: repo-stats asks `gh` or `glab` for the data, and they use their own login. @@ -236,7 +240,7 @@ The Elite, High, Medium and Low bands use rounded thresholds from published DORA [cols="1,3"] |=== | `--branch REF` | Branch to analyse. The default is the remote's default branch. -| `--since / --until YYYY-MM-DD` | Limit the PR window. Lines of code still use full history. +| `--since / --until WHEN` | Limit the PR window. WHEN is a UTC date (`2025-01-15`), month (`2025-01`) or year (`2025`), or a duration back from now (`90d`, `6w`, `6m`, `1y`). `--until` includes the whole day, month or year it names. Lines of code still use full history. | `--exclude-bots` | Drop PRs from bots (Dependabot, Renovate, `[bot]` accounts). | `--no-titles` | Replace PR titles and scopes with numbers before sharing the file. | `--json FILE`, `--csv FILE` | Export the raw data. diff --git a/repo-stats/repo_stats.py b/repo-stats/repo_stats.py index bdbc1ce..8fcb5d3 100644 --- a/repo-stats/repo_stats.py +++ b/repo-stats/repo_stats.py @@ -13,6 +13,7 @@ from __future__ import annotations import argparse +import calendar import collections import concurrent.futures import csv @@ -1375,14 +1376,45 @@ def write_csv(path: str, records: Iterable[Record]) -> None: w.writerow(row) -def parse_date(s: Optional[str]) -> Optional[int]: - """Parse a YYYY-MM-DD date as UTC midnight in Unix seconds; empty gives None.""" - if not s: +WHEN_DATE = re.compile(r"^\d{4}(?:-\d{2}(?:-\d{2})?)?$") +WHEN_DURATION = re.compile(r"^([1-9]\d*)([dwmy])$") + + +def add_months(t: dt.datetime, n: int) -> dt.datetime: + """Return t moved by n calendar months, clamping the day (Mar 31 - 1 month = Feb 28/29).""" + y, m = divmod(t.year * 12 + t.month - 1 + n, 12) + return t.replace(year=y, month=m + 1, day=min(t.day, calendar.monthrange(y, m + 1)[1])) + + +def parse_when(value: Optional[str], flag: str, end: bool, now: Optional[dt.datetime] = None) -> Optional[int]: + """Parse a --since/--until value into Unix seconds; None or "" gives None. + + YYYY-MM-DD, YYYY-MM and YYYY name a UTC day, month or year. The result is its first moment, or with + `end` the first moment after it, so `--until 2025-07` includes all of July. A duration (90d, 6w, 6m, 1y) + counts back from now. + """ + if not value: return None - try: - return int(dt.datetime.strptime(s, "%Y-%m-%d").replace(tzinfo=dt.timezone.utc).timestamp()) - except ValueError: - raise ToolError(f"Invalid date '{s}'. Use YYYY-MM-DD.") + v = value.strip().lower() + now = now or dt.datetime.now(dt.timezone.utc) + m = WHEN_DURATION.match(v) + if m: + n, unit = int(m.group(1)), m.group(2) + if unit in "dw": + return int((now - dt.timedelta(days=n * (7 if unit == "w" else 1))).timestamp()) + return int(add_months(now, -n * (12 if unit == "y" else 1)).timestamp()) + if WHEN_DATE.match(v): + fmt = {4: "%Y", 7: "%Y-%m", 10: "%Y-%m-%d"}[len(v)] + try: + t = dt.datetime.strptime(v, fmt).replace(tzinfo=dt.timezone.utc) + except ValueError: + pass + else: + if end: + t = t + dt.timedelta(days=1) if len(v) == 10 else add_months(t, 1 if len(v) == 7 else 12) + return int(t.timestamp()) + raise ToolError(f"Invalid date '{value}' for {flag}. Use YYYY-MM-DD, YYYY-MM, YYYY (UTC), " + "or a duration back from now such as 90d, 6w, 6m or 1y.") def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = None) -> Dict[str, Any]: @@ -1416,8 +1448,10 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non 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.") - since = parse_date(args.since) - until = parse_date(args.until) + 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: + raise ToolError(f"--since {args.since} is not before --until {args.until}.") excludes = [] if args.no_default_excludes else list(DEFAULT_EXCLUDES) excludes += args.exclude or [] @@ -1537,8 +1571,8 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non if since: prs = [p for p in prs if (p["merged"] or p["created"] or 0) >= since] - if until: # --until is inclusive of that whole UTC day - prs = [p for p in prs if (p["merged"] or p["created"] or 0) < until + 86400] + if until: + prs = [p for p in prs if (p["merged"] or p["created"] or 0) < until] if args.max_prs and mode == "git": prs = prs[-args.max_prs:] @@ -1554,7 +1588,7 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non if since: deploys = [d for d in deploys if d["t"] >= since] if until: - deploys = [d for d in deploys if d["t"] < until + 86400] + deploys = [d for d in deploys if d["t"] < until] # Mark deploy as failure-related when it contains a revert/hotfix PR. fail_releases = {r["release"] for r in records if r["kind"] and r["release"]} for d in deploys: @@ -1614,8 +1648,10 @@ def build_parser() -> argparse.ArgumentParser: p.add_argument("--title", help="name shown in the dashboard (default: repository name)") p.add_argument("--branch", help="branch to analyse (default: the remote's default branch)") p.add_argument("--remote", default="origin", help="remote used to find the hosting provider (default: origin)") - p.add_argument("--since", metavar="YYYY-MM-DD", help="only include PRs merged (or opened, if unmerged) on or after this UTC date") - p.add_argument("--until", metavar="YYYY-MM-DD", help="only include PRs merged (or opened) on or before this UTC date (inclusive)") + p.add_argument("--since", metavar="WHEN", help="only include PRs merged (or opened, if unmerged) from WHEN: a UTC date " + "(2025-01-15), month (2025-01) or year (2025), or a duration back from now (90d, 6w, 6m, 1y)") + p.add_argument("--until", metavar="WHEN", help="only include PRs merged (or opened) up to the end of WHEN, same formats " + "(--until 2025-07 includes all of July)") g = p.add_argument_group("PR data source") g.add_argument("--source", choices=["auto", "git", "api"], default="auto", help="auto uses the API through gh/glab when available, otherwise infers PRs from git (default: auto)") diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index 47bbab6..98c6de3 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -544,6 +544,51 @@ def test_until_is_inclusive_of_that_day_only(self) -> None: d, _ = collect(r, "--until", "2022-01-06") self.assertEqual(len(d["prs"]), 1) + def test_month_and_year_windows(self) -> None: + """YYYY-MM and YYYY cover whole UTC months and years: --until includes the last second, not the next.""" + r = Repo() + r.commit("chore: init", {"a.py": lines(2)}) + for n, when in ((1, T0 + 30 * DAY + DAY - 1), # 2022-01-31T23:59:59Z + (2, T0 + 31 * DAY), # 2022-02-01T00:00:00Z + (3, T0 + 365 * DAY - 1), # 2022-12-31T23:59:59Z + (4, T0 + 365 * DAY)): # 2023-01-01T00:00:00Z + r.clock = when + r.squash_pr(n, f"feat: pr {n}", {f"f{n}.py": lines(2)}) + nums = lambda *a: [p["number"] for p in collect(r, *a)[0]["prs"]] # noqa: E731 + self.assertEqual(nums("--until", "2022-01"), [1]) + self.assertEqual(nums("--since", "2022-02"), [2, 3, 4]) + self.assertEqual(nums("--since", "2022-02", "--until", "2022-12"), [2, 3]) + self.assertEqual(nums("--since", "2022", "--until", "2022"), [1, 2, 3]) + self.assertEqual(nums("--since", "2023"), [4]) + self.assertEqual(nums("--since", "2022-01-31", "--until", "2022-02-01"), [1, 2]) + + def test_durations_count_back_from_now(self) -> None: + """90d, 6w, 6m and 1y count back from now in UTC; months clamp to the month's last day.""" + now = rs.dt.datetime(2025, 3, 31, 12, tzinfo=rs.dt.timezone.utc) + iso = lambda v: rs.dt.datetime.fromtimestamp(rs.parse_when(v, "--since", False, now), rs.dt.timezone.utc).isoformat() # noqa: E731 + self.assertEqual(iso("1y"), "2024-03-31T12:00:00+00:00") + self.assertEqual(iso("1m"), "2025-02-28T12:00:00+00:00") + self.assertEqual(iso("13m"), "2024-02-29T12:00:00+00:00") + self.assertEqual(iso("6w"), "2025-02-17T12:00:00+00:00") + self.assertEqual(iso("90d"), "2024-12-31T12:00:00+00:00") + self.assertEqual(iso("1Y"), iso("12m")) + self.assertEqual(rs.parse_when("2024-02", "--until", True, now), rs.parse_when("2024-03", "--since", False, now)) + + def test_relative_window_in_a_run(self) -> None: + """--since 1y drops PRs from 2022; a long enough duration keeps them all; --until 1d keeps them too.""" + d, _ = collect(merge_repo(), "--since", "1y") + self.assertEqual(d["prs"], []) + self.assertEqual(d["deploys"], []) + d, _ = collect(merge_repo(), "--since", "100y", "--until", "1d") + self.assertEqual([p["number"] for p in d["prs"]], [1, 2, 3, 4, 5]) + + def test_since_must_be_before_until(self) -> None: + """An empty or reversed window is an error, not an empty dashboard.""" + for since, until in (("2025-07", "2025-01"), ("2025-03-01", "2025-02-28"), ("2025-08", "2025-07")): + with self.assertRaises(rs.ToolError, msg=(since, until)): + collect(merge_repo(), "--since", since, "--until", until) + collect(merge_repo(), "--since", "2025-07", "--until", "2025-07") # one whole month is fine + def test_since_excludes_earlier_day(self) -> None: """--since drops PRs merged the day before.""" r = Repo() @@ -1894,7 +1939,7 @@ def test_invalid_dates(self) -> None: """Invalid dates exit 1 with a clear error.""" r = merge_repo().path for flag in ("--since", "--until"): - for bad in ("2022-13-45", "yesterday", "2022/01/01"): + for bad in ("2022-13-45", "yesterday", "2022/01/01", "2022-1-5", "0d", "1q", "22", "2022-02-30"): p = run_cli([r, "-o", tmpdir() / "o.html", flag, bad]) self.assertEqual(p.returncode, 1, (flag, bad)) self.assertIn("Invalid date", p.stderr) From 08bccac892f3289cf950dd5880c93580b628a1a5 Mon Sep 17 00:00:00 2001 From: claude Date: Tue, 27 Oct 2026 02:23:11 +0000 Subject: [PATCH 08/10] refactor(repo-stats)!: drop the --api-url/--token-env compatibility errors Keep the script simple: the removed flags are no longer parsed at all, so argparse rejects them like any unknown option. --- repo-stats/docs/plan-cli-auth.adoc | 3 +-- repo-stats/repo_stats.py | 8 -------- repo-stats/tests/test_repo_stats.py | 16 ---------------- 3 files changed, 1 insertion(+), 26 deletions(-) diff --git a/repo-stats/docs/plan-cli-auth.adoc b/repo-stats/docs/plan-cli-auth.adoc index 6e21c17..d755044 100644 --- a/repo-stats/docs/plan-cli-auth.adoc +++ b/repo-stats/docs/plan-cli-auth.adoc @@ -10,7 +10,7 @@ Status: implemented on this branch. The README's "Logging in" and "Security" sec * *GitLab paging still follows `X-Next-Page`*, read from the `--include` headers, instead of stopping on a short page. The per-MR commit and note paging added in `31a6c9e` is kept. * *The job-token check is one probe.* Before the per-MR lookups, one commits request decides whether the login can read MR commits. On 401/403/404, no more commits are requested, PRs are marked `commits_refused`, and `build_records` takes the first commit from the local merge commit's branch, marking `coding`, `lead` and `lead_to_deploy` as inferred. * *The fake CLIs forward to the existing mock servers.* `tests/fake_cli/gh` and `glab` turn each call into one HTTP request to the mock server, find tokens the way the real CLIs do, and reject any flag outside the allowlist. `helpers.clean_env()` always puts them first on `PATH`, so no test can reach a real CLI or login. -* *`--api-url` and `--token-env` still parse* (hidden from `--help`) so that using them fails with a message naming the replacement. +* *`--api-url` and `--token-env` are removed outright*, with no compatibility handling. * *`run.sh` was added* for read-only tokens kept in the OS keychain (see the README). * *The read-only allowlist and `--hostname` validation* are enforced in `Cli`, and the G1/G2/H1 tests pin them. @@ -218,7 +218,6 @@ A fixed backoff replaces it. . Port `fetch_gitlab` to `run_cli`, including the job-token fallback for commits. Port the `B2_GitLab` tests. . Replace the host and token logic in `collect()` with the host-selection rules above, and add `--hostname`. Remove `--token-env` and `--api-url`. - Since the tool is at 0.1.0, make them hard errors that explain the new flag rather than keeping aliases. . Strip credential variables from git subprocess environments. . Replace `B3_Tokens` with tests that assert: ** every CLI call has `--hostname`, uses no `-F`, `--input`, `--form` or placeholder syntax, and runs from a cwd outside the repository. diff --git a/repo-stats/repo_stats.py b/repo-stats/repo_stats.py index 8fcb5d3..d7ece59 100644 --- a/repo-stats/repo_stats.py +++ b/repo-stats/repo_stats.py @@ -1428,12 +1428,6 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non Returns: {"meta": ..., "prs": [record, ...], "loc": build_loc_series(...), "deploys": [...]}. """ - if getattr(args, "api_url", None): - raise ToolError("--api-url was removed: repo-stats now calls the gh or glab CLI. For GitHub Enterprise or " - "self-managed GitLab, pass --provider and --hostname HOST.") - if getattr(args, "token_env", None): - raise ToolError("--token-env was removed: gh and glab find their own login. Run `gh auth login` or " - "`glab auth login`, or set GH_TOKEN / GITLAB_TOKEN for the run.") if args.hostname is not None and not HOSTNAME_RE.match(args.hostname): raise ToolError(f"Invalid --hostname {args.hostname!r}: give a host name such as ghe.example.com.") repo = os.path.abspath(args.repo) @@ -1658,8 +1652,6 @@ def build_parser() -> argparse.ArgumentParser: g.add_argument("--provider", choices=["github", "gitlab"], help="hosting provider (default: detected from the remote)") g.add_argument("--hostname", metavar="HOST", help="GitHub Enterprise or self-managed GitLab host to query with gh/glab " "(use with --provider). The default is github.com or gitlab.com, taken from the remote") - g.add_argument("--api-url", help=argparse.SUPPRESS) # removed: explains --hostname - g.add_argument("--token-env", help=argparse.SUPPRESS) # removed: gh/glab find their own login g.add_argument("--no-reviews", action="store_true", help="GitLab: skip per-MR review lookups (faster, fewer API calls)") g.add_argument("--all-bases", action="store_true", help="include PRs that target branches other than the analysed one") g.add_argument("--max-prs", type=positive_int, metavar="N", help="stop after N PRs (newest first)") diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index 98c6de3..a637c8a 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -6,7 +6,6 @@ """ from __future__ import annotations -import argparse import ast import contextlib import csv @@ -1129,19 +1128,6 @@ def test_source_git_never_calls_api(self) -> None: self.assertEqual(len(self.srv.requests), n) self.assertEqual(d["meta"]["mode"], "git") - def test_removed_flags_explain_the_replacement(self) -> None: - """--api-url and --token-env fail with a message that names the replacement.""" - with self.assertRaises(rs.ToolError) as cm: - collect(self.r, "--api-url", "https://api.github.com", env={"GITHUB_TOKEN": FAKE}) - self.assertIn("--hostname", str(cm.exception)) - with self.assertRaises(rs.ToolError) as cm: - collect(self.r, "--token-env", "MY_TOKEN", env={"MY_TOKEN": FAKE}) - self.assertIn("gh auth login", str(cm.exception)) - p = run_cli([self.r.path, "-o", tmpdir() / "o.html", "--api-url", "https://x.example/api"]) - self.assertEqual(p.returncode, 1) - self.assertIn("--api-url was removed", p.stderr) - self.assertNotIn("Traceback", p.stderr) - def gitlab_fixture(r: Repo) -> tuple[list[dict[str, Any]], dict[int, list[dict[str, Any]]], dict[int, list[dict[str, Any]]]]: @@ -1914,8 +1900,6 @@ def test_help_lists_all_flags(self) -> None: p = run_cli(["--help"]) self.assertEqual(p.returncode, 0) for action in rs.build_parser()._actions: - if action.help == argparse.SUPPRESS: # removed flags kept only to explain their replacement - continue for opt in action.option_strings: self.assertIn(opt, p.stdout, opt) From 78a4a79d1505ce61da3d7e9cb6b8ff4048cb7d7f Mon Sep 17 00:00:00 2001 From: claude Date: Tue, 27 Oct 2026 02:29:15 +0000 Subject: [PATCH 09/10] refactor(repo-stats): remove run.sh; document the --since/--until values run.sh was more than the tool needs: repo-stats already works from an existing gh/glab login or, without one, from local git history with a warning. Remove the script, its tests and the fake `glab token create`. README: a "Time window" section lists every accepted --since/--until value (UTC day, month, year, or Nd/Nw/Nm/Ny back from now) with examples, and "On your machine" now says to use the existing CLI login, with a one-line way to run with a read-only token instead. --- repo-stats/README.adoc | 52 +++++-- repo-stats/docs/plan-cli-auth.adoc | 3 +- repo-stats/run.sh | 223 ---------------------------- repo-stats/tests/fake_cli/_fake.py | 10 -- repo-stats/tests/test_repo_stats.py | 132 ---------------- 5 files changed, 39 insertions(+), 381 deletions(-) delete mode 100755 repo-stats/run.sh diff --git a/repo-stats/README.adoc b/repo-stats/README.adoc index 416ee5f..a0da477 100644 --- a/repo-stats/README.adoc +++ b/repo-stats/README.adoc @@ -34,7 +34,7 @@ python3 repo-stats/repo_stats.py /path/to/your/repo --serve # builds the das gh auth login # or: glab auth login python3 repo-stats/repo_stats.py /path/to/repo -o stats.html -# a time window: January to July 2025, or the last year +# only PRs from January to July 2025, or from the last year (see "Time window") python3 repo-stats/repo_stats.py /path/to/repo --since 2025-01 --until 2025-07 python3 repo-stats/repo_stats.py /path/to/repo --since 1y ---- @@ -63,29 +63,53 @@ 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. +== Time window + +`--since` and `--until` limit the PRs (by merge time, or open time if unmerged) and the releases on the dashboard. +Lines of code over time always use the full history. +Both options are optional, and you can use either one alone. + +[cols="1,2,2"] +|=== +| Value | Meaning for `--since` | Meaning for `--until` + +| `YYYY-MM-DD`, e.g. `2025-01-15` | from the start of that day | to the end of that day +| `YYYY-MM`, e.g. `2025-07` | from the first day of that month | to the end of that month +| `YYYY`, e.g. `2025` | from 1 January | to the end of 31 December +| `Nd`, `Nw`, `Nm`, `Ny`, e.g. `90d`, `6w`, `6m`, `1y` | from N days, weeks, months or years ago | up to N days, weeks, months or years ago +|=== + +* Dates are in UTC. Write them in full, with leading zeros: `2025-01-05`, not `2025-1-5`. +* `N` is a whole number of at least 1. Months and years are calendar months back from now: one month before 31 March is 28 (or 29) February. +* `--since` must be before `--until`, otherwise the run stops with an error. + +[source,sh] +---- +--since 2025-01 --until 2025-07 # 1 January to 31 July 2025 +--since 2025 --until 2025 # all of 2025 +--since 2025-03-15 --until 2025-03-31 # second half of March 2025 +--since 1y # the last 12 months +--since 90d # the last 90 days +--since 2y --until 1y # the year before last +---- + == Logging in repo-stats never reads, stores or sends a token. `gh` and `glab` find their own login, in this order: an environment variable (`GH_TOKEN`, `GITLAB_TOKEN`), then the login saved by `gh auth login` or `glab auth login` (in the OS keychain where there is one). === On your machine -`gh auth login` and `glab auth login` are the simplest choice. -Their tokens can write to your repositories, though repo-stats only ever reads (see <>). -To give repo-stats a token that cannot write, keep a read-only token in the OS keychain with `run.sh`: +Use the login you already have, or run `gh auth login` / `glab auth login` once. Nothing else is needed. +If neither CLI is installed or logged in, repo-stats prints a warning and uses local git history instead. + +Those logins can write to your repositories, though repo-stats only ever reads (see <>). +To run with a read-only token instead (a GitHub fine-grained token with read-only Contents and Pull requests, or a GitLab token with only `read_api`), give it to the CLI for one run, for example from a password manager, so it never appears in shell history: [source,sh] ---- -repo-stats/run.sh --store github # opens GitHub's token page with read-only permissions filled in -repo-stats/run.sh --store gitlab --project grp/proj # glab creates a read_api project token, or opens the token page -repo-stats/run.sh /path/to/repo --serve # every run: same options as repo_stats.py -repo-stats/run.sh --forget github # delete the saved token +GH_TOKEN="$(op read op://Private/gh-readonly/token)" python3 repo-stats/repo_stats.py /path/to/repo ---- -On GitHub, choose "Only select repositories" on the token page and pick the repositories to analyse. -GitLab.com project tokens need Premium or Ultimate and the Maintainer role; otherwise `run.sh` opens the personal token page with only `read_api` selected. -You paste the token at a hidden prompt. It is never shown, never passed as a command argument and never written to shell history or a file. -Each run hands it to `gh` or `glab` for that run only, and repo-stats removes it from the environment of the git commands it runs. -`run.sh` uses the macOS Keychain or, on Linux, the Secret Service (`secret-tool`, package `libsecret-tools`). Do not load a read-only token with `gh auth login --with-token`: gh keeps one keychain entry per host and account, so it would replace your normal login. === GitHub Actions @@ -240,7 +264,7 @@ The Elite, High, Medium and Low bands use rounded thresholds from published DORA [cols="1,3"] |=== | `--branch REF` | Branch to analyse. The default is the remote's default branch. -| `--since / --until WHEN` | Limit the PR window. WHEN is a UTC date (`2025-01-15`), month (`2025-01`) or year (`2025`), or a duration back from now (`90d`, `6w`, `6m`, `1y`). `--until` includes the whole day, month or year it names. Lines of code still use full history. +| `--since / --until WHEN` | Limit the PR window: a UTC date, month or year (`2025-01-15`, `2025-01`, `2025`) or a duration back from now (`90d`, `6w`, `6m`, `1y`). See <