Skip to content

feat(repo-stats)!: read PR data through gh/glab and never handle a token - #3

Merged
g-husam merged 10 commits into
mainfrom
claude/repo-stats-cli-auth
Oct 28, 2026
Merged

g-husam merged 10 commits into
mainfrom
claude/repo-stats-cli-auth

Conversation

@husam-e

@husam-e husam-e commented Oct 27, 2026 •

Copy link
Copy Markdown
Owner

repo-stats stops handling API tokens. PR data comes from gh api / glab api, which use their own login (keychain, a token variable, or the GitLab CI job token). If the CLI is missing or not logged in, repo-stats warns and infers PRs from local git history. --since / --until also accept months, years and relative durations.

How a request flows

sequenceDiagram
    participant RS as repo_stats.py
    participant W as Cli wrapper
    participant CLI as gh / glab
    participant API as GitHub / GitLab
    RS->>RS: pick the API host (see Host rules)
    RS->>W: graphql(query) or get(endpoint)
    W->>W: allowlist, GraphQL query only or GET on 3 MR endpoints
    W->>CLI: api --hostname HOST --include, from the temp dir, debug and glab telemetry off
    CLI->>API: request with the CLI's own login
    API-->>CLI: status, headers, JSON
    CLI-->>W: --include output
    W->>W: retry 429, 5xx and timeouts with backoff
    W-->>RS: JSON and headers
    Note over RS,W: no CLI, no login, or an API error → warning, PRs from git history (--source api exits instead)
Loading

Host rules

The CLIs send environment tokens to any --hostname they get, so the host is never taken from an arbitrary remote:

api_host
  --hostname HOST                        → HOST   (provider from --provider, the host, or the remote)
  remote on github.com / gitlab.com      → that host
  remote on this CI job's server         → that host   (GitLab CI: CI_SERVER_HOST, Actions: GITHUB_SERVER_URL)
  any other remote                       → no API call, warning, git history

What changed

 collect
-  parse_date(--since/--until)                    # YYYY-MM-DD only
+  parse_when(--since/--until)                    # day, month, year, or 90d / 6w / 6m / 1y
-  resolve_token(GITHUB_TOKEN, GITLAB_TOKEN, --token-env)
-  fetch_github / fetch_gitlab(token, api_url) → http_json   # urllib, redirect guard, proxy bypass
+  api_host = host rules above
+  cli = Cli(tool, api_host)
+  fetch_github(cli) → cli.graphql               # read-only queries only
+  fetch_gitlab(cli) → cli.get                   # GET only, one probe detects refused MR commits
   build_records
+    first-commit time from local merge commits when MR commits are refused
 run_git / stream_git
+  env without credential variables              # hooks and filters in the repo cannot read them
repo-stats/
├── repo_stats.py          # Cli class, host rules, time windows; HTTP client and token lookup removed
├── README.adoc            # time window values; logging in (local, Actions, GitLab CI, scheduled jobs); security
├── template.html          # banner: "log in to gh or glab" instead of "set a token"
└── tests/
    ├── fake_cli/          # fake gh/glab → existing mock servers; reject disallowed flags
    ├── helpers.py         # fake CLIs first on PATH, credentials and CI variables stripped
    └── test_repo_stats.py # read-only allowlist, host rules, job token, time windows

Time window

Value --since --until
2025-01-15 / 2025-07 / 2025 start of that UTC day / month / year end of that day / month / year
90d, 6w, 6m, 1y that long ago up to that long ago

--since 2025-01 --until 2025-07 is January–July 2025. --since 1y is the last year. --since must be before --until.

Breaking

  • --api-url and --token-env are removed (use --provider + --hostname).
  • repo_stats.py reads no token. The CLIs read their own:
    • gh: GH_TOKEN / GITHUB_TOKEN for github.com and *.ghe.com; GH_ENTERPRISE_TOKEN / GITHUB_ENTERPRISE_TOKEN for GitHub Enterprise Server.
    • glab: GITLAB_TOKEN / GITLAB_ACCESS_TOKEN / OAUTH_TOKEN, or CI_JOB_TOKEN with GLAB_ENABLE_CI_AUTOLOGIN=true.
  • No longer picked up: GITLAB_PRIVATE_TOKEN, and GITHUB_TOKEN for GitHub Enterprise Server (it used to work with --api-url). Those setups now fall back to git history with a warning.

Testing

  • 240 tests pass, including the Playwright UI tests; the API tests also pass on Python 3.8.
  • End to end with real gh 2.103.2 (this repo) and glab 1.124.0 (gitlab-org/cli), both with personal logins.
  • Not run on Windows. repo_stats.py has no POSIX-only code, but the test suite does (fake CLIs, sh).

Still open

  • Any process running as the user can run gh auth token, and default gh/glab logins can write. A read-only token given as GH_TOKEN/GITLAB_TOKEN limits the damage.
  • An explicit but wrong --hostname is trusted.
  • In CI, the token is visible to every process in the step that sets it.

Follow-up PR (after merge)

  • GitHub Enterprise Server: the CI hint in CLI_HELP and the README Actions example say GH_TOKEN, but gh needs GH_ENTERPRISE_TOKEN there, so the run falls back to git history.
  • The CLI runs from the shared system temp dir; use a private mkdtemp() dir instead.
  • The README CI examples run this repo's code unpinned next to a token; pin a commit SHA.
  • The GitLab probe treats a 404 on the first MR's commits as "commits refused" for every MR.
  • glab not-logged-in detection and the job-token permissions are not tested against real GitLab.
  • The "no PRs in the selected date range" warning ignores an --until-only window.

Base automatically changed from claude/zealous-johnson-rfqa12 to main October 27, 2026 02:00
husam-e and others added 5 commits October 27, 2026 02:01
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.
…hain

`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.
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.
@husam-e
husam-e force-pushed the claude/repo-stats-cli-auth branch from 1f60e17 to 7aecb13 Compare October 27, 2026 02:01
@husam-e
husam-e marked this pull request as ready for review October 27, 2026 02:10
@husam-e
husam-e marked this pull request as draft October 27, 2026 02:20
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.
--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.
…rrors

Keep the script simple: the removed flags are no longer parsed at all,
so argparse rejects them like any unknown option.
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.
- Delete docs/plan-cli-auth.adoc; the README describes the design.
- Cli is a plain object: no context manager or per-run temporary
  directory (the CLI runs from the system temp directory; the explicit
  --hostname is what stops glab following a remote), no internal tool
  and hostname re-checks (collect() validates --hostname), no one-use
  helper.
- Of the environment changes, keep only GLAB_SEND_TELEMETRY=false (glab
  telemetry sends its own request with the credential) and removing the
  debug switches. The prompt, update-check, pager and colour variables
  were not needed: run without a terminal, both CLIs print clean
  --include output and send banners to stderr.
@husam-e
husam-e marked this pull request as ready for review October 28, 2026 01:09
@g-husam
g-husam merged commit fe4bc25 into main Oct 28, 2026
@g-husam
g-husam deleted the claude/repo-stats-cli-auth branch October 28, 2026 18:00
g-husam added a commit that referenced this pull request Oct 28, 2026
…ned CI, 404 probe) (#5)

Follow-ups from the #3 review. They fix GitHub Enterprise logins, run
the CLI from a private directory, pin the CI examples, and stop a single
404 from turning off GitLab commit lookups for every MR. The tests no
longer reach a real `gh` or depend on timing.

### What changed

```diff
 Cli(tool, host)
-  hint: "in CI set GH_TOKEN"                    # wrong for GitHub Enterprise Server
+  hint: "in CI set " + ci_login_hint(tool, host) # GH_TOKEN for github.com / *.ghe.com, else GH_ENTERPRISE_TOKEN
-  _run: cwd = tempfile.gettempdir()             # shared /tmp: another user can plant a .git
+  _run: cwd = private TemporaryDirectory        # new, empty, 0700, one per run, removed after it
+  close() / with-block
 collect
-  cli = Cli(...)
+  with Cli(...) as cli
 fetch_gitlab
-  probe refused on 401 / 403 / 404              # one missing MR turned off commits for all MRs
+  probe refused on 401 / 403                    # a 404 only affects that MR
 retries
-  time.sleep(...)
+  _backoff(...)                                 # tests patch this instead of time.sleep for everyone
```

### Docs (`README.adoc`)

```diff
 Logging in
+  NOTE: GitHub Enterprise Server uses GH_ENTERPRISE_TOKEN, not GH_TOKEN
 GitHub Actions
+  ref: <full commit SHA>                        # pin the tool: it runs next to the token
+  GHES: set GH_ENTERPRISE_TOKEN instead
 GitLab CI
-  git clone --depth 1 …scripts.git              # unpinned HEAD
+  git fetch --depth 1 …scripts.git "$REPO_STATS_SHA" && git checkout FETCH_HEAD
 Security
-  runs from the system temp directory
+  runs from a new, empty, private temp directory
```

### Tests

```text
tests/test_repo_stats.py
├── B3  login hint names GH_ENTERPRISE_TOKEN for a GHES host (and GH_TOKEN alone is not enough)
├── B3  glab with no login → anonymous 401 → git fallback naming `glab auth login`
├── B3  "gh missing" test puts only git on PATH (/usr/bin also holds a real gh, which it used to run)
├── B4/F2/…  patch rs._backoff instead of time.sleep (subprocess's own sleeps made the retry tests flaky)
├── G1  every CLI call runs in one private repo-stats-cli-* dir, mode 0700, removed after the run
├── G2  a 404 on the probed MR's commits does not stop lookups for the other MRs
└── review cycles (#4)  close the Cli the GitLab helper creates
```

### Not changed
- The review also said the "no PRs in the selected date range" warning
ignores `--until`. That was wrong: the API filters only by `--since`, so
an empty result with only `--until` means the repository has no PRs. The
message is correct as it is.
- No code left over from #3 needed deleting: no unused imports,
functions or constants were found.

### Testing
- `python3 -m unittest test_repo_stats`: 222 tests pass on Python 3.13
(rebased on main with #4), with no `ResourceWarning`. Run with
`GIT_CONFIG_GLOBAL=/dev/null`, because a global `tag.gpgSign` breaks the
fixtures' annotated tags.
- Not run: the Playwright UI tests (no node here) and Python 3.8.
`template.html` is unchanged.
- The real `glab` no-login behaviour and the job-token permissions are
still checked only against the fakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants