"""Prepare and scan the Git-aware input set for Gitleaks.""" from __future__ import annotations import argparse import contextlib import errno import json import os import shutil import stat import subprocess import sys import tempfile from pathlib import Path class ScanError(Exception): """Raised when the scanner cannot build or validate its inputs.""" def git_inputs(root: Path) -> list[str]: result = subprocess.run( [ "git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard", ], check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) if result.returncode != 0: raise ScanError("Git could not enumerate current secret-scan inputs.") return sorted( {os.fsdecode(value) for value in result.stdout.split(b"\0") if value}, key=os.fsencode, ) def _parts(path: str) -> tuple[str, ...]: parts = tuple(path.split("/")) if not path or path.startswith("/") or any(part in ("", ".", "..") for part in parts): raise ScanError("Git returned an unsafe input path.") return parts def _open_regular_file(root_fd: int, parts: tuple[str, ...]) -> int | None: if ( not hasattr(os, "O_NOFOLLOW") or not hasattr(os, "O_DIRECTORY") or not hasattr(os, "O_NONBLOCK") or os.open not in os.supports_dir_fd ): raise ScanError("Safe no-follow file access is unavailable on this platform.") directory_fd = os.dup(root_fd) try: for part in parts[:-1]: next_fd = os.open( part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory_fd, ) os.close(directory_fd) directory_fd = next_fd try: file_fd = os.open( parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory_fd, ) except OSError as error: if error.errno in (errno.ENOENT, errno.ENOTDIR, errno.ELOOP): return None raise if not stat.S_ISREG(os.fstat(file_fd).st_mode): os.close(file_fd) return None return file_fd except OSError as error: if error.errno in (errno.ENOENT, errno.ENOTDIR, errno.ELOOP): return None raise ScanError("A current secret-scan input could not be opened safely.") from error finally: os.close(directory_fd) def copy_git_inputs(root: Path, destination: Path) -> int: root = root.resolve(strict=True) destination_info = os.lstat(destination) if not stat.S_ISDIR(destination_info.st_mode) or destination_info.st_mode & 0o077: raise ScanError("The temporary scan directory must be a private directory.") root_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) copied = 0 try: for path in git_inputs(root): parts = _parts(path) source_fd = _open_regular_file(root_fd, parts) if source_fd is None: # Deleted tracked files and symlinks are not current file inputs. continue target = destination.joinpath(*parts) target_fd: int | None = None target_created = False try: target.parent.mkdir(mode=0o700, parents=True, exist_ok=True) target_fd = os.open( target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, ) target_created = True with os.fdopen(source_fd, "rb") as source: source_fd = -1 with os.fdopen(target_fd, "wb") as output: target_fd = None os.fchmod(output.fileno(), 0o600) shutil.copyfileobj(source, output, length=1024 * 1024) copied += 1 except OSError as error: if target_created: with contextlib.suppress(OSError): target.unlink() raise ScanError( "A current secret-scan input could not be copied safely." ) from error finally: if source_fd >= 0: os.close(source_fd) if target_fd is not None: os.close(target_fd) finally: os.close(root_fd) return copied def validate_report(path: Path) -> bool: try: with path.open("r", encoding="utf-8") as report_file: report = json.load(report_file) except (OSError, UnicodeError, json.JSONDecodeError): print(f"Gitleaks report is missing or invalid: {path}", file=sys.stderr) return False if not isinstance(report, list) or any( not isinstance(item, dict) or not isinstance(item.get("RuleID"), str) or not isinstance(item.get("File"), str) for item in report ): print(f"Gitleaks report has an invalid structure: {path}", file=sys.stderr) return False if report: print(f"Gitleaks report contains findings: {path}", file=sys.stderr) return False return True def _is_full_git_checkout(root: Path) -> bool: if not (root / ".git").exists(): print("Secret history scanning requires a Git checkout.", file=sys.stderr) return False repository_root = subprocess.run( ["git", "-C", str(root), "rev-parse", "--show-toplevel"], check=False, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, ) shallow = subprocess.run( ["git", "-C", str(root), "rev-parse", "--is-shallow-repository"], check=False, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, ) if ( repository_root.returncode != 0 or Path(repository_root.stdout.strip()).resolve() != root or shallow.returncode != 0 or shallow.stdout.strip() != "false" ): print("Secret history scanning requires a full repository-root checkout.", file=sys.stderr) return False return True def run_scan(root: Path, scanner: str, config: Path, reports: Path) -> int: root = root.resolve(strict=True) config = config.resolve(strict=True) reports = reports.resolve() reports.mkdir(mode=0o700, parents=True, exist_ok=True) files_report = reports / "gitleaks-files.json" history_report = reports / "gitleaks-history.json" version_report = reports / "gitleaks-version.txt" for report in (files_report, history_report, version_report): report.unlink(missing_ok=True) if os.sep in scanner or (os.altsep and os.altsep in scanner): scanner = str(Path(scanner).resolve()) else: scanner = shutil.which(scanner) or scanner if not _is_full_git_checkout(root): return 2 status = 0 old_umask = os.umask(0o077) try: with version_report.open("w", encoding="utf-8") as version_file: version = subprocess.run( [scanner, "version"], check=False, stdout=version_file, ) if version.returncode != 0: status = 1 try: with tempfile.TemporaryDirectory( prefix="gitleaks-scan-", dir=os.environ.get("TMPDIR") ) as scan_root: scan_path = Path(scan_root) os.chmod(scan_path, 0o700) copy_git_inputs(root, scan_path) current = subprocess.run( [ scanner, "dir", "--config", str(config), "--redact=100", "--no-banner", "--ignore-gitleaks-allow", "--report-format", "json", "--report-path", str(files_report), ".", ], cwd=scan_path, check=False, ) if current.returncode != 0: status = 1 history = subprocess.run( [ scanner, "git", "--config", str(config), "--redact=100", "--no-banner", "--ignore-gitleaks-allow", "--log-opts=--all", "--report-format", "json", "--report-path", str(history_report), str(root), ], cwd=root, check=False, ) if history.returncode != 0: status = 1 except (OSError, ScanError) as error: print(f"Gitleaks could not prepare current inputs: {error}", file=sys.stderr) return 1 finally: os.umask(old_umask) for report in (files_report, history_report): if not validate_report(report): status = 1 return status def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, required=True) parser.add_argument("--scanner", required=True) parser.add_argument("--config", type=Path, required=True) parser.add_argument("--reports", type=Path, required=True) args = parser.parse_args() try: return run_scan(args.root, args.scanner, args.config, args.reports) except (OSError, ScanError) as error: print(f"Gitleaks check failed: {error}", file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main())