#!/usr/bin/env python3 """Create an exact, secret-scanned manifest for the tracked research source.""" from __future__ import annotations import argparse import hashlib import json import os import re import stat import subprocess import tempfile from datetime import datetime, timezone from pathlib import Path from typing import Any FORMAT = "dsv4vl-private-source-manifest-v1" REMOTE_PREFIX = "source/repository" SECRET_PATTERNS = ( ("Hugging Face token", re.compile(rb"hf_[A-Za-z0-9]{20,}")), ("private key", re.compile(rb"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----")), ("AWS access key", re.compile(rb"AKIA[0-9A-Z]{16}")), ) def now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def sha256_bytes(value: bytes) -> str: return hashlib.sha256(value).hexdigest() def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def git(repo: Path, *args: str) -> bytes: return subprocess.check_output(["git", "-C", str(repo), *args]) def tracked_paths(repo: Path) -> list[Path]: values = git(repo, "ls-files", "-z").split(b"\0") paths = [Path(os.fsdecode(value)) for value in values if value] if not paths or len(paths) != len(set(paths)): raise ValueError("tracked source inventory is empty or contains duplicates") return sorted(paths, key=lambda value: value.as_posix()) def scan_for_secrets(relative: Path, data: bytes) -> None: for label, pattern in SECRET_PATTERNS: if pattern.search(data): raise ValueError(f"refusing tracked {label} in {relative.as_posix()}") def build_manifest(repo: Path) -> dict[str, Any]: repo = repo.expanduser().resolve() if not (repo / ".git").exists(): raise ValueError(f"not a Git repository: {repo}") dirty = git(repo, "status", "--porcelain=v1", "--untracked-files=all") if dirty: raise ValueError("source repository must be clean before it is manifested") commit = git(repo, "rev-parse", "HEAD").decode().strip() tree = git(repo, "rev-parse", "HEAD^{tree}").decode().strip() files: list[dict[str, Any]] = [] for relative in tracked_paths(repo): if relative.is_absolute() or ".." in relative.parts: raise ValueError(f"unsafe tracked path: {relative}") path = repo / relative mode = path.lstat().st_mode if not stat.S_ISREG(mode): raise ValueError(f"tracked source is not a regular file: {relative}") data = path.read_bytes() scan_for_secrets(relative, data) files.append( { "path": relative.as_posix(), "bytes": len(data), "sha256": sha256_bytes(data), "executable": bool(mode & stat.S_IXUSR), } ) inventory_sha256 = sha256_bytes( json.dumps( files, sort_keys=True, separators=(",", ":"), ensure_ascii=False ).encode() ) return { "format": FORMAT, "status": "PASS", "created_at": now(), "git_commit": commit, "git_tree": tree, "remote_prefix": REMOTE_PREFIX, "file_count": len(files), "total_bytes": sum(int(item["bytes"]) for item in files), "inventory_sha256": inventory_sha256, "files": files, } def write_json_atomic(path: Path, payload: dict[str, Any]) -> None: path = path.expanduser().resolve() path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile( "w", dir=path.parent, prefix=f".{path.name}.", delete=False ) as handle: json.dump(payload, handle, indent=2, sort_keys=True) handle.write("\n") temporary = Path(handle.name) temporary.replace(path) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--repo", type=Path, default=Path.cwd()) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() manifest = build_manifest(args.repo) write_json_atomic(args.output, manifest) print( "DSV4VL_PRIVATE_SOURCE_MANIFEST=PASS " f"commit={manifest['git_commit']} files={manifest['file_count']} " f"bytes={manifest['total_bytes']} inventory_sha256={manifest['inventory_sha256']}" ) if __name__ == "__main__": main()