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)
+1 -1
View File
@@ -10,7 +10,7 @@ import sys
from urllib.parse import unquote, urlsplit
SKIP = {".git", "bin", "obj", ".artifacts", "node_modules"}
SKIP = {".git", "bin", "obj", ".artifacts", "artifacts", "node_modules"}
IDENTIFIER = re.compile(r"\b[RD][0-9]+\b")
LINK = re.compile(r"!?\[[^\]\n]*\]\((<[^>\n]+>|[^()\s]*(?:\([^()\s]*\)[^()\s]*)*)(?:\s+[\"'][^\n]*?[\"'])?\)")
REFERENCE = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]+>|\S+)")
+1 -1
View File
@@ -69,7 +69,7 @@ class DocumentationCheck(unittest.TestCase):
self.assertEqual(["notes.md:4: missing anchor: #hidden"], check(self.root))
def test_excluded_trees(self):
for directory in (".git", "bin", "obj", ".artifacts", "node_modules"):
for directory in (".git", "bin", "obj", ".artifacts", "artifacts", "node_modules"):
self.write(f"{directory}/notes.md", "R99 [Gone](gone.md)\n")
self.write("nested/.git", "gitdir: elsewhere\n")
self.write("nested/notes.md", "R99\n")
+2
View File
@@ -51,6 +51,8 @@ def main():
else:
shutil.copy2(file, target)
shutil.copytree(root / 'src' / 'FinalToken.StreamDeck' / 'plugin', plugin, dirs_exist_ok=True)
shutil.copy2(root / 'LICENSE', output / 'LICENSE')
shutil.copy2(root / 'LICENSE', plugin / 'LICENSE')
manifest_path = plugin / 'manifest.json'
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
manifest['Version'] = plugin_version
+14
View File
@@ -0,0 +1,14 @@
"""Shared publication/deployment policy for local runtime files; never read their contents."""
from pathlib import PurePosixPath
PRIVATE_NAMES = {"server.json", "worker.json", "server.env", "worker.env", "transport-keys.json", "dashboard-key", "worker-key",
"auth.json", ".credentials.json", "snapshot.json", "fleet.json", "history.json", "history.state.json",
"history.journal.jsonl", "usage.json", "profile.json", "settings.json", "id_rsa", "id_ecdsa", "id_ed25519"}
def is_private_path(path):
p = PurePosixPath(str(path).replace("\\", "/").lower())
return (p.name in PRIVATE_NAMES or p.name == ".env" or p.name.startswith(".env.") and p.name != ".env.example"
or p.suffix in (".env", ".key", ".pem", ".pfx", ".p12")
or any(part in (".claude", ".codex", ".ssh", ".aws", ".azure") for part in p.parts)
or len(p.parts) > 1 and p.parts[0] in ("data", "state", "logs", "runs", "history"))
+98
View File
@@ -0,0 +1,98 @@
"""Publication guard tests use synthetic values and read-only Git ignore queries."""
import subprocess
import tempfile
from pathlib import Path
import unittest
from unittest.mock import patch
import check_public
class PublicCheckTests(unittest.TestCase):
def test_private_names_are_reported_without_reading_them(self):
for path in ("server.json", "deploy/worker.env", "profiles/.codex/auth.json", "fleet.json", "private.pem", ".env.production"):
with self.subTest(path=path):
self.assertTrue(check_public.sensitive_path(path))
def test_source_and_placeholder_examples_are_allowed(self):
for path in ("server.example.json", "src/FinalToken.Core/HistoryStore.cs", "docs/web-dashboard.md", ".env.example", "LICENSE"):
self.assertFalse(check_public.sensitive_path(path))
def test_matching_values_never_appear_in_findings(self):
synthetic = "sk-" + "ant-" + "x" * 32
findings = check_public.inspect("synthetic.txt", ("header\n" + synthetic).encode())
self.assertEqual(1, len(findings))
self.assertEqual(2, findings[0].line)
self.assertEqual("provider token", findings[0].kind)
self.assertNotIn(synthetic, repr(findings))
def test_private_key_and_url_credentials_are_detected(self):
key = b"-----BEGIN " + b"PRIVATE KEY-----"
url = b"https://" + b"fixture:[email protected]/repo.git"
self.assertEqual({"private key", "credential in URL"}, {f.kind for f in check_public.inspect("fixture", key + b"\n" + url)})
def test_binary_input_is_not_treated_as_source(self):
self.assertEqual([], check_public.inspect("image.png", b"\0" + b"sk-" + b"ant-" + b"x" * 32))
def test_staged_secret_is_found_even_when_working_copy_is_clean(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "source.txt").write_text("clean working copy")
staged = ("sk-" + "proj-" + "x" * 32).encode()
oid = "a" * 40
def fake_git(where, *args, data=None):
if args[0] == "ls-files" and "--stage" in args:
return f"100644 {oid} 0\tsource.txt\0".encode()
if args[0] == "ls-files":
return b"source.txt\0"
if args[:2] == ("cat-file", "-s"):
return str(len(staged)).encode()
if args[:2] == ("cat-file", "blob"):
return staged
self.fail("Unexpected Git read")
with patch.object(check_public, "git", side_effect=fake_git):
findings, _, _ = check_public.working_tree(root)
self.assertTrue(any(f.path.startswith("index:") and f.kind == "provider token" for f in findings))
def test_working_tree_symlink_is_rejected_before_resolving_its_target(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
with patch.object(check_public, "git", return_value=b"link.cs\0"), \
patch.object(check_public, "index", return_value=([], 0, [])), \
patch.object(Path, "is_symlink", return_value=True), patch.object(Path, "read_bytes", side_effect=AssertionError("must not read")):
findings, _, _ = check_public.working_tree(root)
self.assertEqual("symlink/outside source tree", findings[0].kind)
def test_historical_private_name_is_detected_when_same_blob_had_a_public_name(self):
oid = "c" * 40
def fake_git(root, *args, data=None):
if args[0] == "rev-list":
return b"first\nsecond\n"
name = "examples/example.json" if args[-1] == "first" else "auth.json"
return f"100644 blob {oid}\t{name}\0".encode()
with patch.object(check_public, "git", side_effect=fake_git):
paths = check_public.historical_private_paths(Path("unused"))
self.assertEqual({oid: {"auth.json"}}, paths)
def test_staged_private_file_is_reported_without_opening_its_blob(self):
def fake_git(root, *args, data=None):
self.assertEqual("ls-files", args[0])
return ("100644 " + "a" * 40 + " 0\tserver.env\0").encode()
with patch.object(check_public, "git", side_effect=fake_git):
findings, count, _ = check_public.index(Path("unused"))
self.assertEqual(0, count)
self.assertEqual("index:server.env", findings[0].path)
def test_git_ignores_live_runtime_data_but_keeps_examples(self):
paths = ["server.json", "deploy/worker.json", "server.env", ".env.production", "transport-keys.json", "fleet.json",
"snapshot.json", "history.journal.jsonl", "profiles/.codex/auth.json", "private.key", "logs/session.log"]
result = subprocess.run(["git", "check-ignore", "-z", "--stdin"], cwd=check_public.ROOT,
input=("\0".join(paths) + "\0").encode(), capture_output=True, check=True)
self.assertEqual(set(paths), set(result.stdout.decode().strip("\0").split("\0")))
examples = subprocess.run(["git", "check-ignore", "-z", "--stdin"], cwd=check_public.ROOT,
input=b".env.example\0server.example.json\0LICENSE\0", capture_output=True)
self.assertEqual(1, examples.returncode)
if __name__ == "__main__":
unittest.main()
+6
View File
@@ -7,6 +7,7 @@ import tempfile
import unittest
from unittest.mock import patch
import xml.etree.ElementTree as ET
import zipfile
import publish
@@ -28,6 +29,11 @@ class PublishTests(unittest.TestCase):
self.assertIsNotNone(version)
manifest = json.loads((output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/manifest.json').read_text(encoding='utf-8'))
self.assertEqual(version + '.0', manifest['Version'])
license_text = (Path(publish.__file__).resolve().parent.parent / 'LICENSE').read_text(encoding='utf-8')
self.assertEqual(license_text, (output / 'LICENSE').read_text(encoding='utf-8'))
self.assertEqual(license_text, (output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/LICENSE').read_text(encoding='utf-8'))
with zipfile.ZipFile(output.with_suffix('.zip')) as bundle:
self.assertEqual(license_text, bundle.read('LICENSE').decode('utf-8'))
if __name__ == '__main__':