tools: prepare MIT source for public distribution

Ship MIT notices with published outputs and keep runtime credentials, configuration and history out of source archives. Audit working files, staged blobs and reachable history before publication.

Refs #19
This commit is contained in:
Florian Schmidt
2026-11-15 10:59:13 +01:00
parent c02829e2e1
commit cd000437a0
12 changed files with 484 additions and 2 deletions
+171
View File
@@ -0,0 +1,171 @@
"""Read-only publication check. Reports paths/pattern names, never matching secret values."""
import argparse
from dataclasses import dataclass
from pathlib import Path
import re
import subprocess
import sys
from source_policy import is_private_path as sensitive_path
ROOT = Path(__file__).resolve().parent.parent
LIMIT = 2 * 1024 * 1024
PATTERNS = (
("private key", re.compile(rb"-----BEGIN (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRIVATE KEY-----")),
("provider token", re.compile(rb"\bsk-(?:ant-|proj-|svcacct-)[A-Za-z0-9_-]{24,}")),
("Git hosting token", re.compile(rb"\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})")),
("credential in URL", re.compile(rb"https?://[^\s/:@]+:[^\s/@]+@")),
)
@dataclass(frozen=True)
class Finding:
path: str
kind: str
line: int = 0
def inspect(path, data):
if b"\0" in data[:8192]:
return []
return [Finding(path, kind, data.count(b"\n", 0, match.start()) + 1)
for kind, pattern in PATTERNS for match in pattern.finditer(data)]
def git(root, *arguments, data=None):
return subprocess.run(["git", *arguments], cwd=root, input=data, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, check=True).stdout
def working_tree(root):
names = set(git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard").decode("utf-8").split("\0")) - {""}
findings, skipped, scanned = [], [], 0
for name in sorted(names):
path = root / name
if sensitive_path(name):
findings.append(Finding(name, "local configuration/credential/runtime filename"))
elif path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
findings.append(Finding(name, "symlink/outside source tree"))
elif not path.exists():
continue # Removed tracked file; history is checked separately.
elif not path.is_file() or path.stat().st_size > LIMIT:
skipped.append(name)
else:
data = path.read_bytes()
if b"\0" in data[:8192]:
skipped.append(name)
continue
findings.extend(inspect(name, data))
scanned += 1
staged, staged_count, staged_skipped = index(root)
return findings + staged, scanned + staged_count, skipped + staged_skipped
def index(root):
"""Audit actual index blobs, not their potentially different working copies. No staging changes."""
records = git(root, "ls-files", "--stage", "-z").decode("utf-8").split("\0")
findings, skipped, scanned = [], [], 0
for record in filter(None, records):
metadata, name = record.split("\t", 1)
mode, oid, stage = metadata.split()
label = "index:" + name
if sensitive_path(name):
findings.append(Finding(label, "staged local configuration/credential/runtime filename"))
elif stage != "0" or mode not in ("100644", "100755"):
findings.append(Finding(label, "unmerged index, symlink or submodule needs review"))
elif int(git(root, "cat-file", "-s", oid)) > LIMIT:
skipped.append(label)
else:
data = git(root, "cat-file", "blob", oid)
if b"\0" in data[:8192]:
skipped.append(label)
else:
findings.extend(inspect(label, data))
scanned += 1
return findings, scanned, skipped
def historical_private_paths(root):
# rev-list --objects gives only one name hint per blob. A blob can have been
# renamed/copied under a private filename in another tree without changing its id.
private = {}
for commit in git(root, "rev-list", "--all").decode("ascii").splitlines():
for record in git(root, "ls-tree", "-r", "-z", "--full-tree", commit).decode("utf-8").split("\0"):
if not record:
continue
metadata, name = record.split("\t", 1)
if sensitive_path(name):
private.setdefault(metadata.split()[2], set()).add(name)
return private
def history(root):
private = historical_private_paths(root)
objects = {}
for entry in git(root, "rev-list", "--objects", "--all").decode("utf-8").splitlines():
oid, _, name = entry.partition(" ")
objects[oid] = name
findings, skipped, scanned = [], [], 0
metadata = git(root, "cat-file", "--batch-check", data="".join(o + "\n" for o in objects).encode()).decode("ascii")
candidates = []
for row in metadata.splitlines():
oid, kind, size = row.split()
if kind not in ("blob", "commit", "tag"):
continue
name = objects[oid] or "<" + kind + ">"
label = "history:" + oid[:12] + ":" + name
if oid in private or sensitive_path(name):
findings.extend(Finding("history:" + oid[:12] + ":" + p, "historical local configuration/credential/runtime filename")
for p in sorted(private.get(oid, {name})))
elif int(size) > LIMIT:
skipped.append(label)
else:
candidates.append((oid, label))
# One batch process avoids starting Git separately for every historical source blob.
with subprocess.Popen(["git", "cat-file", "--batch"], cwd=root, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL) as process:
for oid, label in candidates:
process.stdin.write((oid + "\n").encode())
process.stdin.flush()
header = process.stdout.readline().split()
if len(header) != 3 or header[1] not in (b"blob", b"commit", b"tag"):
raise ValueError("Unexpected Git object response")
data = process.stdout.read(int(header[2]))
if process.stdout.read(1) != b"\n":
raise ValueError("Truncated Git object response")
if b"\0" in data[:8192]:
skipped.append(label)
else:
findings.extend(inspect(label, data))
scanned += 1
process.stdin.close()
if process.wait() != 0:
raise ValueError("Git object read failed")
return findings, scanned, skipped
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--history", action="store_true", help="Also inspect reachable Git source, commit and tag text")
args = parser.parse_args(argv)
findings, count, skipped = working_tree(ROOT)
print(f"Worktree/index: {count} text versions scanned; {len(skipped)} binary/oversized versions skipped.")
if args.history:
old, count, old_skipped = history(ROOT)
findings.extend(old)
skipped.extend(old_skipped)
print(f"Reachable history: {count} text objects; {len(old_skipped)} binary/oversized objects skipped.")
print("Git author/committer identities remain unchanged; inspect them before publication.")
for item in findings:
print(f"{item.path}:{item.line}: {item.kind}")
for path in skipped:
print("Not content-scanned: " + path)
print(f"Pattern findings: {len(findings)}. This targeted check cannot prove absence of arbitrary secrets.")
return 1 if findings else 0
if __name__ == "__main__":
try:
sys.exit(main())
except (OSError, ValueError, subprocess.CalledProcessError):
print("Publication check could not complete; no source/credential values are printed.", file=sys.stderr)
sys.exit(2)