Repository navigation
fix(repo-stats): security hardening from review - #8
Merged
Merged
Conversation
…d environments - Resolve git, gh and glab to absolute paths, skipping empty, "." and relative PATH entries (on Windows a bare name also searches the current directory). - Build git's environment from an allowlist (drops credentials, GIT_DIR, GIT_WORK_TREE, GIT_CONFIG_PARAMETERS, ...), set GIT_NO_LAZY_FETCH=1 and run git with core.fsmonitor=false and protocol.allow=never; the numstat log uses --no-textconv and --no-ext-diff. - Build the gh/glab environment from an allowlist: host and repo overrides (GH_HOST, GITLAB_HOST, GL_HOST, GITLAB_URI, GITLAB_API_HOST, ...) and TLS switches never reach the CLI; glab's GITLAB_HOST is set to the --hostname host. Turn off update checks, prompts and gh telemetry, and stop git discovery above the private CLI directory (GIT_CEILING_DIRECTORIES). - Warn on partial clones and explain the failure when objects are missing. - Refuse refs that start with "-" and pass revisions after --end-of-options on git 2.30+.
…-serve headers - parse_remote drops any user info before the host and never reads a URL with a scheme as scp-style, so a path-less https://user:TOKEN@host remote cannot put the token into the dashboard name. - HOSTNAME_RE and GITLAB_READ_ENDPOINT match the whole string (\Z, not $), reject empty host labels, "." and ".." project segments and non-ASCII digits. - Cap top-level GitHub and GitLab pagination, require X-Next-Page to be a plain number above the current page and the GraphQL cursor to change. - --serve adds frame-ancestors 'none' to the header CSP and same-origin Cross-Origin-Resource-Policy and Cross-Origin-Opener-Policy. - re.escape the PR number in the squash-subject regex.
-o, --json and --csv are written to a new temp file in the same directory and moved into place with os.replace, and an existing symlink at the output path is refused, so a symlink planted in an untrusted checkout cannot redirect the write. Characters that cannot be encoded (lone surrogates from API text) are written as backslash escapes instead of crashing the run.
…the hardening - GitHub Actions: check the analysed repository out into its own directory with persist-credentials: false, write the dashboard to $RUNNER_TEMP. - GitLab CI: pin the image by digest (with how to look it up) and write the dashboard into a directory the job creates. - Security: describe the allowlisted environments, absolute executable paths, no lazy fetch, safe output writes and --serve headers, and say plainly that stripping credentials from git's environment prevents accidental leaks but is not a boundary against code running as you.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Security hardening for repo-stats, from the security review of
repo-stats/(findings S1–S6 and nits N1–N11). Rebased onmainwith #5, #6 and #7. Where #5 already covered something, this PR builds on it and doesn't redo it.Findings
write_output():-o,--jsonand--csvgo to amkstempfile in the same directory, thenos.replacemoves 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_TEMPon 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_outputsfind_executable()resolves git, gh and glab to absolute paths and skips empty,.and relativePATHentries, so it never usesshutil.which, which on Windows with Python before 3.12 searches the cwd first. On Windows, child processes also getNoDefaultCurrentDirectoryInExePath=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_dirspersist-credentials: falseon bothactions/checkoutsteps, checks the analysed repo out intorepo/so the cwd and outputs are not inside it, and pins the GitLab image astag@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.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 dropsGH_HOST,GH_REPO,GITLAB_HOST,GL_HOST,GITLAB_URI,GITLAB_API_HOST,GLAB_API_PROTOCOL/API_PROTOCOL,GLAB_SKIP_TLS_VERIFYand debug switches. I checked this list againstgh help environment(gh 2.103) and the glab env var docs. Current glab docs say an env token goes only to the host inGITLAB_HOST/config, soGITLAB_HOSTis now set to the--hostnamehost for glab. That keeps self-managed GitLab withGITLAB_TOKENworking.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 unchangedGIT_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_hardenedGIT_NO_LAZY_FETCH=1(git 2.44+) and also-c protocol.allow=never(blocks the lazy fetch on older git).is_partial_clone()checksextensions.partialClone/remote.*.promisorwithgit 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)parse_remotenever 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 givesNone.I1.test_parse_remote_drops_user_info,test_token_in_pathless_remote_is_not_in_the_output$anchorsHOSTNAME_REandGITLAB_READ_ENDPOINTuse\Z.HOSTNAME_RErejects.., and the endpoint takes ASCII[0-9]only.I1.test_security_regexes_match_the_whole_stringGITLAB_READ_ENDPOINTrejectsprojects/./…andprojects/../….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-MRpages()). 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_caperrors="backslashreplace". Inside the dashboard JSON this decodes back to the same string;--jsonalready usedensure_ascii.I1.test_lone_surrogates_are_written-is refused (works on any git version). Revisions also follow--end-of-optionson git ≥ 2.30, the first version whererev-parseaccepts it (loghas accepted it since 2.24); older git skips it.remote get-urlgets--.I1.test_refs_starting_with_dash_are_refused,test_end_of_options_depends_on_git_version--serveheadersframe-ancestors 'none', plusCross-Origin-Resource-Policy: same-originandCross-Origin-Opener-Policy: same-origin. The meta CSP in the template is unchanged (frame-ancestorsdoes not work there).I1.test_serve_sends_framing_and_cross_origin_headersTemporaryDirectory. This PR only addsGIT_CEILING_DIRECTORIES=<temp dir>, so git, if a CLI runs it, cannot find a.gitplanted one level up in a shared/tmp.G1.test_every_call_is_read_only_explicit_host_and_outside_the_repo(one extra assertion)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, andGLAB_SEND_TELEMETRY=falseas before.I1.test_cli_environment_is_an_allowlistGIT_*GIT_DIR,GIT_WORK_TREE,GIT_CONFIG_PARAMETERS, … are dropped).G1.test_git_never_sees_credential_variablesre.escape(str(pr["number"])).I1.test_pr_number_is_escaped_in_regexNot done / notes
.entries skipped, that would only matter if the user's ownPATHnamed an absolute directory inside the repo.-o some/dir/fileis used andsome/diris a symlink inside an untrusted checkout, the write still follows it. The CI examples avoid this by writing outside the checkout.GLAB_CHECK_UPDATEenv override is set tofalse. 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: fix(repo-stats): follow-ups from #3 (GHES login, private CLI dir, pinned CI, 404 probe) #5 and ci: add GitHub Actions workflow for tests and lints #6 fixed them.python3 -m unittest -v test_ui: 40 tests, OK.E3_Python38Syntax) passes.--select E9,F) could not be installed locally (the package index needs auth), so CI on this PR runs it.