Files
aigc-home/docs/hel-892/batch179-target-snapshots/audit.py
T

374 lines
15 KiB
Python

"""Offline receipt/provenance comparison only. Never run the supplied collector."""
import ast
import csv
import datetime as dt
import hashlib
import json
import re
import zipfile
import zlib
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
INCOMING = HERE / "incoming"
CORE_REPO = "https://github.com/Comfy-Org/ComfyUI"
AUX_REPO = "https://github.com/Fannovel16/comfyui_controlnet_aux"
EXPECTED_ROOTS = ["/media/ComfyUI", "/media/ComfyUI_cu130/ComfyUI"]
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def now():
return dt.datetime.now(dt.timezone.utc).isoformat()
def write(name, value):
with (HERE / name).open("x", encoding="utf-8") as stream:
json.dump(value, stream, ensure_ascii=False, indent=2)
stream.write("\n")
def load(path):
return json.loads(Path(path).read_text())
def utc(value):
result = dt.datetime.fromisoformat(value)
assert result.utcoffset() == dt.timedelta(0)
return result
def collector_constants():
# Parse only literal scope constants; do not import/compile/execute the script.
tree = ast.parse((INCOMING / "collect_installed.py").read_text())
result = {}
for node in tree.body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in ("CORE", "AUX", "roots"):
result[target.id] = ast.literal_eval(node.value)
assert result["roots"] == EXPECTED_ROOTS
assert len(result["CORE"]) == 7 and len(result["AUX"]) == 10
return result
def receive():
archive = INCOMING / "target179-access.zip"
manifest = load(INCOMING / "manifest.json")
with zipfile.ZipFile(archive) as package:
assert package.testzip() is None and len(package.namelist()) == 6
assert len(set(package.namelist())) == 6
for info in package.infolist():
assert not info.filename.startswith("/") and ".." not in Path(info.filename).parts
assert package.read(info) == (INCOMING / info.filename).read_bytes()
assert {r["file"] for r in manifest["files"]} == {
"collect_installed.py",
"ssh-snapshot.stdout.json",
"ssh-snapshot.stderr.txt",
"collection-receipt.json",
"access-findings.md",
}
for row in manifest["files"]:
raw = (INCOMING / row["file"]).read_bytes()
assert len(raw) == row["bytes"] and sha(raw) == row["sha256"]
receipt = load(INCOMING / "collection-receipt.json")
for key, filename in (
("script_sha256", "collect_installed.py"),
("stdout_sha256", "ssh-snapshot.stdout.json"),
("stderr_sha256", "ssh-snapshot.stderr.txt"),
):
assert receipt[key] == sha((INCOMING / filename).read_bytes())
assert receipt["exit_code"] == 0
snapshot = load(INCOMING / "ssh-snapshot.stdout.json")
assert utc(receipt["started_at_utc"]) <= utc(snapshot["started_at_utc"])
assert utc(snapshot["completed_at_utc"]) <= utc(receipt["completed_at_utc"])
return snapshot, dict(
attachment_id="01a19f3c-dd3d-704e-b9e3-2e123d018ea5",
archive_bytes=archive.stat().st_size,
archive_sha256=sha(archive.read_bytes()),
crc_sha_checked=True,
original_receipt=receipt,
local_rechecked_at_utc=now(),
collector_executed_this_run=False,
)
def validate_snapshot(snapshot):
constants = collector_constants()
assert snapshot["target"] == "192.168.200.12" and snapshot["ssh_user"] == "root"
assert len(snapshot["installations"]) == 2
for index, item in enumerate(snapshot["installations"]):
root = EXPECTED_ROOTS[index]
for kind in ("core", "aux"):
record = item[kind]
expected = root if kind == "core" else root + "/custom_nodes/comfyui_controlnet_aux"
assert record["path"] == record["canonical_path"] == expected
assert record["allowlist"] == constants[kind.upper()]
assert [f["relative_path"] for f in record["files"]] == record["allowlist"]
assert (
utc(snapshot["started_at_utc"])
<= utc(record["recorded_at_utc"])
<= utc(record["completed_at_utc"])
<= utc(snapshot["completed_at_utc"])
)
query = record["git_head_query"]
assert query["command"] == ["rev-parse", "--verify", "HEAD"]
if record.get("head"):
assert query["exit_code"] == 0 and query["stdout"] == record["head"]
assert re.fullmatch("[a-f0-9]{40}", record["head"])
else:
assert query["exit_code"] != 0
for file in record["files"]:
assert (
utc(record["recorded_at_utc"])
<= utc(file["recorded_at_utc"])
<= utc(record["completed_at_utc"])
)
if file["state"] != "read":
continue
assert type(file["bytes"]) is int and 0 <= file["bytes"] <= 4 * 1024 * 1024
assert re.fullmatch("[a-f0-9]{64}", file["sha256"])
assert re.fullmatch("[a-f0-9]{40}", file["git_blob_sha1"])
assert file["unchanged_during_read"] is True
if record.get("head"):
q = file["head_object_query"]
assert q["command"] == [
"rev-parse",
"--verify",
"HEAD:" + file["relative_path"],
]
agrees = q["exit_code"] == 0 and q["stdout"] == file["git_blob_sha1"]
assert file["matches_head_blob"] is agrees
else:
assert "matches_head_blob" not in file and "head_object_query" not in file
return constants
def references():
rows = []
prior177 = ROOT / "docs/hel-892/batch177-controlnet-provenance"
prior178 = ROOT / "docs/hel-892/batch178-aio-protocol"
for filename in ("engine-sources.json", "direct-sources.json"):
for i, proof in enumerate(load(prior178 / filename)):
raw = (prior178 / proof["file"]).read_bytes()
assert sha(raw) == proof["sha256"] and proof["repository"] == CORE_REPO
blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()
assert blob == proof["git_blob_sha1"]
rows.append(
dict(
kind="core",
version=proof["version"],
repository=CORE_REPO,
commit=proof["commit"],
path=proof["path"],
sha256=sha(raw),
bytes=len(raw),
git_blob_sha1=blob,
original_acquired_at=proof["retrieved_at"],
proof_pointer=f"docs/hel-892/batch178-aio-protocol/{filename}#/{i}",
raw_path=str((prior178 / proof["file"]).relative_to(ROOT)),
)
)
for i, proof in enumerate(load(prior177 / "core-bindings.json")):
raw = (ROOT / proof["retained_path"]).read_bytes()
blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()
assert sha(raw) == proof["sha256"] and blob == proof["git_blob_sha1"]
old_sources = load(ROOT / "docs/hel-892/serialization-evidence/sources.json")["sources"]
own = [
s
for s in old_sources
if s.get("repository") == CORE_REPO
and s["commit"] == proof["commit"]
and s["file"] == proof["path"]
and s["sha256"] == proof["sha256"]
]
times = [s["retrieved_at"] for s in own if s.get("retrieved_at")]
rows.append(
dict(
kind="core",
version=proof["version"],
repository=CORE_REPO,
commit=proof["commit"],
path=proof["path"],
sha256=sha(raw),
bytes=len(raw),
git_blob_sha1=blob,
original_acquired_at=min(times, key=utc) if times else None,
proof_pointer=f"docs/hel-892/batch177-controlnet-provenance/core-bindings.json#/{i}",
raw_path=proof["retained_path"],
)
)
binding = load(prior177 / "network/registry-version.body")
assert binding["node_id"] == "comfyui_controlnet_aux" and binding["version"] == "1.1.5"
directory = load(prior177 / "release-directory.json")
assert binding["downloadUrl"] == directory["artifact_url"]
needed = set(collector_constants()["AUX"])
for i, proof in enumerate(load(prior177 / "release-member-proofs.json")):
if proof["name"] not in needed:
continue
raw = (prior177 / proof["file"]).read_bytes()
entry = next(e for e in directory["entries"] if e["name"] == proof["name"])
assert len(raw) == proof["bytes"] == entry["bytes"]
assert zlib.crc32(raw) & 0xFFFFFFFF == proof["crc32"] == entry["crc32"]
assert sha(raw) == proof["sha256"]
blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()
rows.append(
dict(
kind="aux",
version="1.1.5",
repository=AUX_REPO,
commit=None,
artifact_url=binding["downloadUrl"],
path=proof["name"],
bytes=len(raw),
sha256=sha(raw),
git_blob_sha1=blob,
crc32=proof["crc32"],
original_acquired_at=proof["retrieved_at"],
proof_pointer=f"docs/hel-892/batch177-controlnet-provenance/release-member-proofs.json#/{i}",
raw_path=str((prior177 / proof["file"]).relative_to(ROOT)),
)
)
assert sum(r["kind"] == "aux" for r in rows) == 10
return rows
def compare(file, kind, ref):
assert kind == ref["kind"] and file["relative_path"] == ref["path"]
if file["state"] != "read":
return "snapshot_unavailable"
return (
"match"
if (file["bytes"], file["sha256"], file["git_blob_sha1"])
== (ref["bytes"], ref["sha256"], ref["git_blob_sha1"])
else "different"
)
def matrix(snapshot, refs):
rows = []
for index, item in enumerate(snapshot["installations"]):
for kind in ("core", "aux"):
install = item[kind]
for file in install["files"]:
candidates = []
for version in ("0.21.1", "0.17.0") if kind == "core" else ("1.1.5",):
matched_path = [
r
for r in refs
if r["kind"] == kind
and r["version"] == version
and r["path"] == file["relative_path"]
]
assert len(matched_path) <= 1
candidates.append(
dict(
version=version,
status="no_exact_reference"
if not matched_path
else compare(file, kind, matched_path[0]),
reference=matched_path[0] if matched_path else None,
)
)
state = (
"snapshot_unavailable"
if file["state"] != "read"
else "match"
if any(c["status"] == "match" for c in candidates)
else "different"
if any(c["reference"] for c in candidates)
else "no_exact_reference"
)
rows.append(
dict(
installation_id=f"install-{index + 1}",
installation_root=item["core"]["path"],
kind=kind,
actual_source_path=install["path"] + "/" + file["relative_path"],
snapshot_pointer=f"/installations/{index}/{kind}/files/{install['files'].index(file)}",
original_sample=file,
original_install_head=install.get("head"),
original_head_query=install["git_head_query"],
head_binds_working_file=file.get("matches_head_blob"),
candidates=candidates,
comparison=state,
loaded_source_binding="unknown",
target_text_received=False,
protocol_178_reusable=False,
limitation=(
"digest-only snapshot; no target bytes recomputed or engine executed"
),
)
)
return rows
def main():
snapshot, receipt = receive()
validate_snapshot(snapshot)
refs = references()
rows = matrix(snapshot, refs)
write("receipt-check.json", receipt)
write("reference-catalog.json", refs)
write("installation-matrix.json", rows)
with (HERE / "installation-matrix.csv").open("x", encoding="utf-8", newline="") as stream:
writer = csv.DictWriter(stream, list(rows[0]), lineterminator="\n")
writer.writeheader()
for row in rows:
writer.writerow({k: json.dumps(v, ensure_ascii=False) for k, v in row.items()})
summary = []
for index, item in enumerate(snapshot["installations"]):
own = [r for r in rows if r["installation_id"] == f"install-{index + 1}"]
summary.append(
dict(
installation_id=f"install-{index + 1}",
root=item["core"]["path"],
core_head=item["core"].get("head"),
core_head_matches=sum(
bool(r["head_binds_working_file"]) for r in own if r["kind"] == "core"
),
comparisons={
k: {
s: sum(r["kind"] == k and r["comparison"] == s for r in own)
for s in (
"match",
"different",
"no_exact_reference",
"snapshot_unavailable",
)
}
for k in ("core", "aux")
},
aux_independent_git_commit=None,
protocol_178_reusable=False,
loaded_installation="unknown",
)
)
write(
"summary.json",
dict(
installations=summary,
rows=len(rows),
unique_digest_pairs=len(
{
(r["original_sample"].get("bytes"), r["original_sample"].get("sha256"))
for r in rows
}
),
comparison_scope="34 snapshot entries, not 34 unique source texts",
new_target_requests=0,
target_source_texts_received=0,
original_snapshot_utc=snapshot["started_at_utc"],
local_analysis_utc=now(),
),
)
print(json.dumps(load(HERE / "summary.json"), ensure_ascii=False))
if __name__ == "__main__":
main()