Skip to content

fix(repo-stats): follow-ups from #3 (GHES login, private CLI dir, pinned CI, 404 probe) - #5

Merged
g-husam merged 1 commit into
mainfrom
repo-stats-pr3-followups
Oct 28, 2026
Merged

g-husam merged 1 commit into
mainfrom
repo-stats-pr3-followups

Conversation

@g-husam

@g-husam g-husam commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

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

 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)

 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

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 feat(repo-stats)!: read PR data through gh/glab and never handle a token #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 feat(repo-stats): count review cycles per PR and show them on the dashboard #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.

…, 404 probe

- Name GH_ENTERPRISE_TOKEN in the login hint and docs for GitHub Enterprise Server hosts.
- Run gh/glab from a new private temp dir (0700) instead of the shared system temp dir.
- Pin husam-e/scripts to a commit SHA in the Actions and GitLab CI examples.
- A 404 on the probed MR's commits no longer turns off commit lookups for every MR.
- Tests: GHES hint, glab without a login, private cwd, 404 probe; the missing-gh test no longer
  runs a real gh; retry tests patch rs._backoff instead of time.sleep (flaky with subprocess).
@g-husam
g-husam force-pushed the repo-stats-pr3-followups branch from b3b5151 to 9be99e3 Compare October 28, 2026 19:56
@g-husam
g-husam merged commit 786e7e6 into main Oct 28, 2026
@g-husam
g-husam deleted the repo-stats-pr3-followups branch October 28, 2026 20:07
g-husam added a commit that referenced this pull request Oct 28, 2026
Security hardening for repo-stats, from the security review of
`repo-stats/` (findings S1–S6 and nits N1–N11). Rebased on `main` with
#5, #6 and #7. Where #5 already covered something, this PR builds on it
and doesn't redo it.

### Findings

| ID | Status | What changed | Tests |
|----|--------|--------------|-------|
| S1 outputs follow symlinks | done | New `write_output()`: `-o`,
`--json` and `--csv` go to a `mkstemp` file in the same directory, then
`os.replace` moves it into place. An existing symlink (live or dangling)
at the output path is refused with a clear error. The new file gets the
usual umask permissions. The CI examples write outside the analysed
checkout: `$RUNNER_TEMP` on GitHub; on GitLab, a directory the job
itself creates, because GitLab only collects artifacts from inside the
project dir. | `I1.test_write_output_refuses_symlinks`,
`test_write_output_is_atomic`, `test_cli_refuses_symlinked_outputs` |
| S2 Windows cwd lookup | done | New `find_executable()` resolves git,
gh and glab to absolute paths and skips empty, `.` and relative `PATH`
entries, so it never uses `shutil.which`, which on Windows with Python
before 3.12 searches the cwd first. On Windows, child processes also get
`NoDefaultCurrentDirectoryInExePath=1`. git still runs with `-C <abs
repo>`. A separate safe cwd for git was **not** added: with an absolute
exe path and `-C`, it adds nothing. |
`I1.test_find_executable_skips_current_and_relative_dirs` |
| S3 CI docs | partly covered by #5 | #5 already pins the tool
checkout/fetch to a commit SHA. This PR adds `persist-credentials:
false` on both `actions/checkout` steps, checks the analysed repo out
into `repo/` so the cwd and outputs are not inside it, and pins the
GitLab image as `tag@sha256:<digest>` with how to look the digest up
(`docker buildx imagetools inspect` / `crane digest`). It also notes
that the actions themselves can be SHA-pinned. I used placeholders, not
a real digest: I could not check the current image digest from here. |
docs |
| S4 CLI env host overrides | done | The gh/glab env is built from an
allowlist (`CLI_ENV_ALLOW` + `CI_SERVER_*`, `XDG_*`,
`REPO_STATS_FAKE_*`). It keeps tokens, CI autologin, config, keyring
(`DBUS_SESSION_BUS_ADDRESS`), proxy, TLS CA/client-cert, locale and
Windows essentials. It drops `GH_HOST`, `GH_REPO`, `GITLAB_HOST`,
`GL_HOST`, `GITLAB_URI`, `GITLAB_API_HOST`,
`GLAB_API_PROTOCOL`/`API_PROTOCOL`, `GLAB_SKIP_TLS_VERIFY` and debug
switches. I checked this list against `gh help environment` (gh 2.103)
and the [glab env var
docs](https://docs.gitlab.com/cli/configuration/#environment-variables).
Current glab docs say an env token goes only to the host in
`GITLAB_HOST`/config, so `GITLAB_HOST` is now set to the `--hostname`
host for glab. That keeps self-managed GitLab with `GITLAB_TOKEN`
working. `REPO_STATS_FAKE_*` is allowed only so the test suite's fake
CLIs still get their mock URL and log path (there is a comment saying
so); real CLIs ignore it. | `I1.test_cli_environment_is_an_allowlist`,
`test_cli_never_sees_host_overrides_end_to_end`; existing G1/G2 tests
unchanged |
| S5 git env / README claim | done | git's env is an allowlist
(`GIT_ENV_ALLOW`: PATH, HOME, user, locale, temp, Windows essentials,
`XDG_CONFIG_HOME`, `GIT_CONFIG_GLOBAL/SYSTEM/NOSYSTEM`). git runs with
`-c core.fsmonitor=false`, and the numstat log adds `--no-textconv
--no-ext-diff`. The README now says that stripping credentials prevents
accidental leaks but is not a boundary against code running as you, and
recommends read-only, short-lived tokens. |
`G1.test_git_never_sees_credential_variables` (rewritten for the
allowlist), `I1.test_git_argv_is_hardened` |
| S6 partial clones | done | git runs with `GIT_NO_LAZY_FETCH=1` (git
2.44+) and also `-c protocol.allow=never` (blocks the lazy fetch on
older git). `is_partial_clone()` checks `extensions.partialClone` /
`remote.*.promisor` with `git config --get-regexp`, a read-only call
(the read-only test and README list now include it). A partial clone
prints a warning, and if missing objects make the scan fail, the error
explains why. | `I1.test_partial_clone_warns_and_never_fetches` (a real
blobless clone; checks that no object was fetched) |
| N1 userinfo in remote | done | `parse_remote` never reads a URL with a
scheme as scp-style, and drops everything up to the last `@` before the
host. `https://user:TOKEN@github.com` (no path) now gives `None`. |
`I1.test_parse_remote_drops_user_info`,
`test_token_in_pathless_remote_is_not_in_the_output` |
| N2 `$` anchors | done | `HOSTNAME_RE` and `GITLAB_READ_ENDPOINT` use
`\Z`. `HOSTNAME_RE` rejects `..`, and the endpoint takes ASCII `[0-9]`
only. | `I1.test_security_regexes_match_the_whole_string` |
| N3 dot segments | done | `GITLAB_READ_ENDPOINT` rejects `projects/./…`
and `projects/../…`. | same |
| N4 pagination | done | `MAX_LIST_PAGES` (2000) caps the top-level
GitHub and GitLab loops. `next_page()` requires a plain positive number
above the current page (also used in the per-MR `pages()`). A GraphQL
cursor that is missing or repeats raises an error. |
`I1.test_next_page_must_be_a_plain_increasing_number`,
`test_gitlab_repeating_next_page_stops`,
`test_github_repeating_cursor_and_page_cap` |
| N5 lone surrogates | done | Outputs are written with
`errors="backslashreplace"`. Inside the dashboard JSON this decodes back
to the same string; `--json` already used `ensure_ascii`. |
`I1.test_lone_surrogates_are_written` |
| N6 option-like refs | done | A branch/ref that starts with `-` is
refused (works on any git version). Revisions also follow
`--end-of-options` on git ≥ 2.30, the first version where `rev-parse`
accepts it (`log` has accepted it since 2.24); older git skips it.
`remote get-url` gets `--`. |
`I1.test_refs_starting_with_dash_are_refused`,
`test_end_of_options_depends_on_git_version` |
| N7 `--serve` headers | done | The header CSP adds `frame-ancestors
'none'`, plus `Cross-Origin-Resource-Policy: same-origin` and
`Cross-Origin-Opener-Policy: same-origin`. The meta CSP in the template
is unchanged (`frame-ancestors` does not work there). |
`I1.test_serve_sends_framing_and_cross_origin_headers` |
| N8 CLI cwd | covered by #5, plus one addition | #5 already runs the
CLIs from a private 0700 `TemporaryDirectory`. This PR only adds
`GIT_CEILING_DIRECTORIES=<temp dir>`, so git, if a CLI runs it, cannot
find a `.git` planted one level up in a shared `/tmp`. |
`G1.test_every_call_is_read_only_explicit_host_and_outside_the_repo`
(one extra assertion) |
| N9 update notifiers | done | The CLIs get `GH_NO_UPDATE_NOTIFIER=1`,
`GH_PROMPT_DISABLED=1`, `GH_TELEMETRY=false` (documented in gh 2.103),
`GLAB_CHECK_UPDATE=false`, `GLAB_NO_PROMPT=true`, and
`GLAB_SEND_TELEMETRY=false` as before. |
`I1.test_cli_environment_is_an_allowlist` |
| N10 inherited `GIT_*` | done | Covered by the git and CLI allowlists
(`GIT_DIR`, `GIT_WORK_TREE`, `GIT_CONFIG_PARAMETERS`, … are dropped). |
`G1.test_git_never_sees_credential_variables` |
| N11 regex from PR number | done | `re.escape(str(pr["number"]))`. |
`I1.test_pr_number_is_escaped_in_regex` |

### Not done / notes
- S2: "refuse an executable found inside the analysed repo" is not
implemented. With relative and `.` entries skipped, that would only
matter if the user's own `PATH` named an absolute directory inside the
repo.
- S1: only the last path component is protected. If `-o some/dir/file`
is used and `some/dir` is a symlink inside an untrusted checkout, the
write still follows it. The CI examples avoid this by writing outside
the checkout.
- glab's documented `GLAB_CHECK_UPDATE` env override is set to `false`.
I could not run a real glab here to confirm it disables the check; at
worst the setting has no effect.

### Testing
- `python3 -m unittest -v test_repo_stats`: 242 tests, OK (no
ResourceWarning). The 3 tests that failed on the old base for
environment reasons now pass: #5 and #6 fixed them.
- `python3 -m unittest -v test_ui`: 40 tests, OK.
- The Python 3.8 grammar test (`E3_Python38Syntax`) passes.
- Ruff from CI (`--select E9,F`) could not be installed locally (the
package index needs auth), so CI on this PR runs it.
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.

1 participant