Enforce a 25 MiB Git blob size limit in GitHub Actions and pre-commit (#2985) Add `.github/workflows/check-file-sizes.yml` and `.github/scripts/check_file_sizes.py` to reject Git blobs larger than 25 MiB (`26,214,400` bytes) in `HEAD` or across commits in the pull request or push commit range due to limitations of an internal clone of this repository. Also extend `.githooks/pre-commit` to enforce the same staged blob size limit locally, and add unit tests in `.github/scripts/check_file_sizes_test.py`. context: b/580911465
diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 8ef4ade..0774a99 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit
@@ -13,26 +13,29 @@ COMBINED_REGEX="($GITHUB_TOKEN_REGEX|$BUILDKITE_TOKEN_REGEX)" SECRETS_FOUND=0 +OVERSIZED_FOUND=0 +MAX_BYTES="${MAX_FILE_SIZE_BYTES:-$((25 * 1024 * 1024))}" -# Get a list of all files that are staged for commit (Added, Copied, or Modified) -# We ignore deleted files because you can't add a token by deleting a file. -STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM) - -if [ -z "$STAGED_FILES" ]; then - exit 0 -fi - -# Inspect each staged file -for file in $STAGED_FILES; do +# Inspect each staged file (Added, Copied, or Modified), NUL-delimited so paths +# with spaces are handled safely. Deleted files are ignored. +while IFS= read -r -d '' file; do # 1. git diff --cached: Outputs the diff of the staged changes # 2. grep '^+': Only look at newly added lines # 3. grep -v '^+++': Ignore the diff file headers # 4. grep -q -E: Check quietly against the regex - if git diff --cached "$file" | grep '^+' | grep -v '^+++' | grep -E -q "$COMBINED_REGEX"; then - echo " ❌ $file" >&2 + if git diff --cached -- "$file" | grep '^+' | grep -v '^+++' | grep -E -q "$COMBINED_REGEX"; then + echo " ❌ $file (contains token pattern)" >&2 SECRETS_FOUND=1 fi -done + + if [ "$(git cat-file -t ":$file" 2>/dev/null)" = "blob" ]; then + blob_size=$(git cat-file -s ":$file") + if [ "$blob_size" -gt "$MAX_BYTES" ]; then + echo " ❌ $file ($blob_size bytes > $MAX_BYTES bytes)" >&2 + OVERSIZED_FOUND=1 + fi + fi +done < <(git diff --cached --name-only -z --diff-filter=ACM) if [ $SECRETS_FOUND -eq 1 ]; then echo "" >&2 @@ -48,4 +51,16 @@ exit 1 fi +if [ $OVERSIZED_FOUND -eq 1 ]; then + echo "" >&2 + echo "========================================================================" >&2 + echo "🚨 ERROR: Commit rejected! File(s) above exceed the $MAX_BYTES-byte limit" >&2 + echo "due to limitations of an internal clone of this repository." >&2 + echo "" >&2 + echo "Store large binaries or archives externally (for example, in GCS)" >&2 + echo "instead of committing them to Git." >&2 + echo "========================================================================" >&2 + exit 1 +fi + exit 0
diff --git a/.github/scripts/check_file_sizes.py b/.github/scripts/check_file_sizes.py new file mode 100755 index 0000000..30c30eb --- /dev/null +++ b/.github/scripts/check_file_sizes.py
@@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +# +# Copyright 2026 The Bazel Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Checks that repository Git blobs do not exceed the 25 MiB size limit.""" + +import argparse +import os +from pathlib import Path +import subprocess +import sys + +BYTES_PER_MIB = 1024 * 1024 +MAX_FILE_SIZE_BYTES = 25 * BYTES_PER_MIB +DEFAULT_REPO_DIR = str(Path(__file__).resolve().parents[2]) + + +def _run_git(repo_dir, args, input_text=None, check=True): + return subprocess.run( + ["git", "-C", repo_dir, "-c", "core.quotePath=false", *args], + input=input_text, + check=check, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + encoding="utf-8", + errors="surrogateescape", + ) + + +def find_oversized_blobs(repo_dir, base_ref="origin/master", max_bytes=MAX_FILE_SIZE_BYTES): + """Returns sorted (path, size_bytes) pairs exceeding max_bytes.""" + head_check = _run_git(repo_dir, ["rev-parse", "--verify", "HEAD"], check=False) + if head_check.returncode != 0: + return [] + + oversized = {} + + ls_tree = _run_git(repo_dir, ["ls-tree", "-r", "-l", "-z", "HEAD"]) + for entry in ls_tree.stdout.split("\0"): + if not entry or "\t" not in entry: + continue + meta, path = entry.split("\t", 1) + parts = meta.split() + if len(parts) < 4: + continue + obj_type, size_str = parts[1], parts[3] + if obj_type != "blob" or size_str == "-": + continue + size = int(size_str) + if size > max_bytes: + oversized[path] = max(oversized.get(path, 0), size) + + if base_ref: + merge_base = _run_git(repo_dir, ["merge-base", base_ref, "HEAD"], check=False) + if merge_base.returncode == 0: + base_sha = merge_base.stdout.strip() + rev_list = _run_git(repo_dir, ["rev-list", "--objects", f"{base_sha}..HEAD"]) + if rev_list.stdout: + cat_file = _run_git( + repo_dir, + ["cat-file", "--batch-check=%(objecttype) %(objectsize) %(rest)"], + input_text=rev_list.stdout, + ) + for line in cat_file.stdout.splitlines(): + parts = line.split(" ", 2) + if len(parts) < 2 or parts[0] != "blob": + continue + size = int(parts[1]) + if size > max_bytes: + path = parts[2] if len(parts) > 2 and parts[2] else "<unnamed blob>" + oversized[path] = max(oversized.get(path, 0), size) + + return sorted(oversized.items()) + + +def _resolve_default_base_ref(repo_dir): + gh_base = os.environ.get("GITHUB_BASE_REF", "").strip() + if gh_base: + remote_ref = f"origin/{gh_base}" + verify = _run_git( + repo_dir, + ["rev-parse", "--verify", "--quiet", f"refs/remotes/{remote_ref}"], + check=False, + ) + if verify.returncode == 0: + return remote_ref + fetch = _run_git(repo_dir, ["fetch", "--no-tags", "origin", gh_base], check=False) + if fetch.returncode == 0: + return "FETCH_HEAD" + return remote_ref + return "origin/master" + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--repo-dir", + default=DEFAULT_REPO_DIR, + help="Path to the Git repository root.", + ) + parser.add_argument( + "--base-ref", + default=None, + help="Base Git ref used to inspect blobs across commits in base..HEAD.", + ) + parser.add_argument( + "--max-bytes", + type=int, + default=MAX_FILE_SIZE_BYTES, + help="Maximum allowed blob size in bytes.", + ) + args = parser.parse_args(argv) + base_ref = ( + args.base_ref if args.base_ref is not None else _resolve_default_base_ref(args.repo_dir) + ) + + oversized = find_oversized_blobs( + args.repo_dir, base_ref=base_ref, max_bytes=args.max_bytes + ) + if not oversized: + return 0 + + limit_mib = args.max_bytes / BYTES_PER_MIB + print( + f"ERROR: File(s) exceed the {limit_mib:g} MiB ({args.max_bytes:,} bytes) limit " + "due to limitations of an internal clone of this repository:", + file=sys.stderr, + ) + for path, size in oversized: + size_mib = size / BYTES_PER_MIB + print(f" - {path}: {size_mib:.2f} MiB ({size:,} bytes)", file=sys.stderr) + print( + "Store large binaries or archives externally (for example, in GCS) " + "instead of committing them to Git.", + file=sys.stderr, + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main())
diff --git a/.github/scripts/check_file_sizes_test.py b/.github/scripts/check_file_sizes_test.py new file mode 100755 index 0000000..db519ca --- /dev/null +++ b/.github/scripts/check_file_sizes_test.py
@@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +# +# Copyright 2026 The Bazel Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Unit tests for .github/scripts/check_file_sizes.py and .githooks/pre-commit.""" + +import contextlib +from contextlib import redirect_stderr +import io +import os +import shutil +import stat +import subprocess +import tempfile +import unittest +from unittest import mock + +import check_file_sizes + + +class CheckFileSizesTest(unittest.TestCase): + """Tests for .github/scripts/check_file_sizes.py and .githooks/pre-commit.""" + + @contextlib.contextmanager + def _temp_repo_dir(self): + repo_dir = tempfile.mkdtemp() + try: + yield repo_dir + finally: + def _handle_readonly(func, path, _exc_info): + os.chmod(path, stat.S_IWRITE) + func(path) + + shutil.rmtree(repo_dir, onerror=_handle_readonly) + + def _git(self, repo_dir, *args): + subprocess.run( + [ + "git", + "-C", + repo_dir, + "-c", + "user.name=Test User", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + *args, + ], + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + def _write_file(self, repo_dir, rel_path, size_bytes, fill_byte=b"x"): + full_path = os.path.join(repo_dir, rel_path) + os.makedirs(os.path.dirname(full_path), exist_ok=True) + with open(full_path, "wb") as f: + f.write(fill_byte * size_bytes) + + def test_default_limit_and_repo_dir(self): + self.assertEqual(check_file_sizes.BYTES_PER_MIB, 1024 * 1024) + self.assertEqual(check_file_sizes.MAX_FILE_SIZE_BYTES, 25 * 1024 * 1024) + self.assertTrue( + os.path.isfile( + os.path.join(check_file_sizes.DEFAULT_REPO_DIR, ".githooks", "pre-commit") + ) + ) + + def test_allows_blobs_at_or_below_limit_and_rejects_above_limit(self): + one_mib = 1024 * 1024 + with self._temp_repo_dir() as repo_dir: + self._git(repo_dir, "init") + self._git(repo_dir, "checkout", "-B", "master") + self._write_file(repo_dir, "exact_limit.bin", one_mib, fill_byte=b"\0") + self._git(repo_dir, "add", "exact_limit.bin") + self._git(repo_dir, "commit", "-m", "Add file at limit") + + self.assertEqual( + check_file_sizes.find_oversized_blobs( + repo_dir, base_ref="origin/master", max_bytes=one_mib + ), + [], + ) + + self._write_file( + repo_dir, "dir with spaces/over limit.bin", one_mib + 1, fill_byte=b"\0" + ) + self._git(repo_dir, "add", "dir with spaces/over limit.bin") + self._git(repo_dir, "commit", "-m", "Add oversized file") + + oversized = check_file_sizes.find_oversized_blobs( + repo_dir, base_ref="origin/master", max_bytes=one_mib + ) + self.assertEqual(oversized, [("dir with spaces/over limit.bin", one_mib + 1)]) + + exit_code, stderr_text = self._run_cli( + repo_dir, max_bytes=one_mib, base_ref="origin/master" + ) + self.assertEqual(exit_code, 1) + self.assertIn("exceed the 1 MiB (1,048,576 bytes) limit", stderr_text) + self.assertIn( + "dir with spaces/over limit.bin: 1.00 MiB (1,048,577 bytes)", stderr_text + ) + self.assertIn("internal clone of this repository", stderr_text) + + def test_catches_oversized_blob_added_then_deleted_in_commit_range(self): + with self._temp_repo_dir() as repo_dir: + self._git(repo_dir, "init") + self._git(repo_dir, "checkout", "-B", "master") + self._write_file(repo_dir, "small.txt", 32) + self._git(repo_dir, "add", "small.txt") + self._git(repo_dir, "commit", "-m", "Initial commit") + self._git(repo_dir, "update-ref", "refs/remotes/origin/master", "HEAD") + + self._git(repo_dir, "checkout", "-b", "feature") + self._write_file(repo_dir, "transient_archive.tar", 2048) + self._git(repo_dir, "add", "transient_archive.tar") + self._git(repo_dir, "commit", "-m", "Add large archive") + + self._git(repo_dir, "rm", "transient_archive.tar") + self._git(repo_dir, "commit", "-m", "Delete large archive") + + oversized = check_file_sizes.find_oversized_blobs( + repo_dir, base_ref="origin/master", max_bytes=1000 + ) + self.assertEqual(oversized, [("transient_archive.tar", 2048)]) + + def test_fetches_github_base_ref_when_missing_locally(self): + with self._temp_repo_dir() as origin_dir, self._temp_repo_dir() as clone_dir: + self._git(origin_dir, "init", "--bare") + self._git(clone_dir, "init") + self._git(clone_dir, "checkout", "-B", "master") + self._git(clone_dir, "remote", "add", "origin", origin_dir) + self._write_file(clone_dir, "small.txt", 32) + self._git(clone_dir, "add", "small.txt") + self._git(clone_dir, "commit", "-m", "Initial commit") + self._git(clone_dir, "push", "origin", "master") + self._git(clone_dir, "update-ref", "-d", "refs/remotes/origin/master") + + self._git(clone_dir, "checkout", "-b", "pr-branch") + self._write_file(clone_dir, "temp_bundle.bin", 2048) + self._git(clone_dir, "add", "temp_bundle.bin") + self._git(clone_dir, "commit", "-m", "Add oversized file") + self._git(clone_dir, "rm", "temp_bundle.bin") + self._git(clone_dir, "commit", "-m", "Remove oversized file") + + with mock.patch.dict(os.environ, {"GITHUB_BASE_REF": "master"}): + exit_code, stderr_text = self._run_cli(clone_dir, max_bytes=1000) + self.assertEqual(exit_code, 1) + self.assertIn("temp_bundle.bin", stderr_text) + + @unittest.skipIf(os.name == "nt", "Bash pre-commit hook test runs on POSIX") + def test_pre_commit_hook_enforces_staged_blob_size_limit(self): + hook_path = os.path.join( + check_file_sizes.DEFAULT_REPO_DIR, ".githooks", "pre-commit" + ) + default_limit = 25 * 1024 * 1024 + with self._temp_repo_dir() as repo_dir: + self._git(repo_dir, "init") + self._git(repo_dir, "checkout", "-B", "master") + self._write_file(repo_dir, "exact_25mib.bin", default_limit, fill_byte=b"\0") + self._git(repo_dir, "add", "exact_25mib.bin") + + env = os.environ.copy() + env.pop("MAX_FILE_SIZE_BYTES", None) + ok_proc = subprocess.run( + ["bash", hook_path], + cwd=repo_dir, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + self.assertEqual(ok_proc.returncode, 0, msg=ok_proc.stderr) + + self._write_file( + repo_dir, "sub dir/too_big.bin", default_limit + 1, fill_byte=b"\0" + ) + self._git(repo_dir, "add", "sub dir/too_big.bin") + bad_proc = subprocess.run( + ["bash", hook_path], + cwd=repo_dir, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + self.assertEqual(bad_proc.returncode, 1) + self.assertIn( + f"sub dir/too_big.bin ({default_limit + 1} bytes > {default_limit} bytes)", + bad_proc.stderr, + ) + self.assertIn("internal clone of this repository", bad_proc.stderr) + + def _run_cli(self, repo_dir, max_bytes, base_ref=None): + cli_args = ["--repo-dir", repo_dir, "--max-bytes", str(max_bytes)] + if base_ref is not None: + cli_args.extend(["--base-ref", base_ref]) + err = io.StringIO() + with redirect_stderr(err): + code = check_file_sizes.main(cli_args) + return code, err.getvalue() + + +if __name__ == "__main__": + unittest.main()
diff --git a/.github/workflows/check-file-sizes.yml b/.github/workflows/check-file-sizes.yml new file mode 100644 index 0000000..9a41ec5 --- /dev/null +++ b/.github/workflows/check-file-sizes.yml
@@ -0,0 +1,36 @@ +name: Check File Sizes + +on: + pull_request: + push: + branches: ["master"] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + check-file-sizes: + name: Check Git blob sizes (<= 25 MiB) + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + + - name: Run unit tests + run: python3 .github/scripts/check_file_sizes_test.py -v + + - name: Check repository blob sizes + env: + PUSH_BEFORE_SHA: ${{ github.event.before }} + run: | + if [[ "${GITHUB_EVENT_NAME}" == "push" && -n "${PUSH_BEFORE_SHA}" && "${PUSH_BEFORE_SHA}" != "0000000000000000000000000000000000000000" ]]; then + python3 .github/scripts/check_file_sizes.py --base-ref "${PUSH_BEFORE_SHA}" + else + python3 .github/scripts/check_file_sizes.py + fi