interplane.Get Omega
Read in your language

aien-receipts

Append-only AIEN verification receipts, indexed by repository and exact source commit. Read verdicts, signatures and retained logs before making a claim.

Brought by drakestapleton

branch main Branches Tags History

aien-receipts / audit / tools / stamp.py

218 lines · 10950 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Validate an org audit stamp (schema aien-audit-stamp/1).
3
4Usage:
5 stamp.py validate <stamp-dir> [--salts FILE]
6
7A stamp lives at audit/stamps/<repo-or-private-NN>/<sha>/stamp.json, next to the
8checks/ directory written by checks.py and the review reports it cites. The rules
9below are mechanical; they say what a stamp may claim, not whether a review is right.
10
11 * verdict is one of PASS, PASS-WITH-NOTES, FAIL; no stamp text says "pristine",
12 "approved", "certified" or "flawless".
13 * deterministic_checked and model_reviewed are separate lists. Every check names
14 tool, version, command and output_sha256; every review names agent role, model,
15 effort, files covered and the sha256 of its report, which must be in the stamp dir.
16 * the claimed verdict is never better than verdict_ceiling(): any open high or
17 critical finding is FAIL; any NOT_RUN item, INCOMPLETE or NOT_RUN check,
18 untriaged FLAGGED item, open finding, incomplete review, or no review at all
19 caps the verdict at PASS-WITH-NOTES.
20 * UPSTREAM-FORK subjects pin the upstream merge-base and the checks ran in fork-diff
21 mode against that same base.
22 * private subjects carry only an anonymous id (private-01 .. private-99) and a
23 salted SHA-256 commitment; with --salts, the real names must not appear anywhere.
24
25Exit 0 valid, 1 invalid (reasons on stderr), 2 usage error.
26"""
27import argparse, hashlib, json, os, re, sys
28
29SCHEMA = "aien-audit-stamp/1"
30VERDICTS = ("PASS", "PASS-WITH-NOTES", "FAIL")
31RANK = {"PASS": 0, "PASS-WITH-NOTES": 1, "FAIL": 2}
32FORBIDDEN = re.compile(r"\b(pristine|approved|certified|flawless)\b", re.I)
33SHA40 = re.compile(r"^[0-9a-f]{40}$")
34SHA64 = re.compile(r"^[0-9a-f]{64}$")
35ANON = re.compile(r"^private-\d{2}$")
36KINDS = ("FIRST-PARTY", "UPSTREAM-FORK", "ARCHIVED")
37CHECK_STATUS = ("PASS", "FLAGGED", "INCOMPLETE", "NOT_RUN")
38FINDING_STATUS = ("OPEN", "FIXED", "ACCEPTED", "FALSE-POSITIVE")
39SEVERITIES = ("critical", "high", "medium", "low", "info")
40
41
42def strings(o):
43 if isinstance(o, str):
44 yield o
45 elif isinstance(o, dict):
46 for k, v in o.items():
47 yield k
48 yield from strings(v)
49 elif isinstance(o, list):
50 for v in o:
51 yield from strings(v)
52
53
54def verdict_ceiling(st):
55 """Best verdict the stamp's own contents allow, with the reasons that capped it."""
56 reasons = []
57 findings = st.get("findings", [])
58 if any(f.get("status") == "OPEN" and f.get("severity") in ("critical", "high") for f in findings):
59 return "FAIL", ["open critical/high finding"]
60 if st.get("not_run"):
61 reasons.append("%d NOT_RUN item(s)" % len(st["not_run"]))
62 for c in st.get("deterministic_checked", {}).get("checks", []):
63 if c.get("status") in ("NOT_RUN", "INCOMPLETE"):
64 reasons.append("check %s is %s" % (c.get("check"), c.get("status")))
65 elif c.get("status") == "FLAGGED" and c.get("triaged", 0) < (c.get("count") or 0):
66 reasons.append("check %s has %d untriaged item(s)" % (c.get("check"), (c.get("count") or 0) - c.get("triaged", 0)))
67 if any(f.get("status") == "OPEN" for f in findings):
68 reasons.append("open finding(s)")
69 reviews = st.get("model_reviewed", [])
70 if not reviews:
71 reasons.append("no model review")
72 for r in reviews:
73 if not r.get("complete"):
74 reasons.append("review %s/%s incomplete (%s of %s files)" % (r.get("agent_role"), r.get("model"),
75 r.get("files_covered"), r.get("files_total")))
76 return ("PASS-WITH-NOTES" if reasons else "PASS"), reasons
77
78
79def validate(stamp_dir, salts=None):
80 errs = []
81 path = os.path.join(stamp_dir, "stamp.json")
82 try:
83 with open(path, "rb") as fh:
84 raw = fh.read()
85 st = json.loads(raw)
86 except (OSError, ValueError) as e:
87 return ["cannot read stamp.json: %s" % e]
88 if st.get("schema") != SCHEMA:
89 errs.append("schema must be %s" % SCHEMA)
90 for s in strings(st):
91 m = FORBIDDEN.search(s)
92 if m:
93 errs.append("forbidden word %r in stamp text" % m.group(0))
94 break
95 sub = st.get("subject", {})
96 commit = sub.get("commit", "")
97 if not SHA40.match(commit):
98 errs.append("subject.commit must be a full 40-hex sha")
99 if os.path.basename(os.path.normpath(stamp_dir)) != commit:
100 errs.append("stamp directory name must equal subject.commit")
101 if not SHA40.match(sub.get("tree", "")):
102 errs.append("subject.tree must be a full 40-hex sha")
103 if sub.get("kind") not in KINDS:
104 errs.append("subject.kind must be one of %s" % ", ".join(KINDS))
105 ident = os.path.basename(os.path.dirname(os.path.normpath(stamp_dir)))
106 if sub.get("visibility") == "private":
107 if "repository" in sub:
108 errs.append("private subject must not carry a repository name")
109 if not ANON.match(sub.get("anonymous_id", "")) or sub.get("anonymous_id") != ident:
110 errs.append("private subject needs anonymous_id private-NN equal to the stamp's parent directory")
111 if not SHA64.match(sub.get("name_commitment", "")):
112 errs.append("private subject needs a 64-hex name_commitment")
113 if st.get("self_reported") is not True:
114 errs.append("private stamp must set self_reported: true")
115 elif sub.get("visibility") == "public":
116 if sub.get("repository") != ident:
117 errs.append("public subject.repository must equal the stamp's parent directory")
118 if "anonymous_id" in sub or "name_commitment" in sub:
119 errs.append("public subject must not carry anonymous fields")
120 else:
121 errs.append("subject.visibility must be public or private")
122 dc = st.get("deterministic_checked", {})
123 if sub.get("kind") == "UPSTREAM-FORK":
124 up = sub.get("upstream", {})
125 if not up.get("repository") or not SHA40.match(up.get("base_sha", "")):
126 errs.append("UPSTREAM-FORK needs upstream.repository and a 40-hex upstream.base_sha")
127 elif dc.get("mode") != "fork-diff" or dc.get("fork_base") != up.get("base_sha"):
128 errs.append("UPSTREAM-FORK checks must run in fork-diff mode against upstream.base_sha")
129 checks = dc.get("checks")
130 if not isinstance(checks, list) or not checks:
131 errs.append("deterministic_checked.checks must be a non-empty list")
132 checks = []
133 for c in checks:
134 for k in ("check", "tool", "version", "command", "output_sha256", "status"):
135 if k not in c:
136 errs.append("check %s lacks %s" % (c.get("check", "?"), k))
137 if c.get("status") not in CHECK_STATUS:
138 errs.append("check %s has status %r" % (c.get("check"), c.get("status")))
139 if c.get("output_sha256") and not SHA64.match(c["output_sha256"]):
140 errs.append("check %s output_sha256 is not 64 hex" % c.get("check"))
141 f = os.path.join(stamp_dir, "checks", "%s.json" % c.get("check"))
142 if os.path.exists(f):
143 with open(f, "rb") as fh:
144 if hashlib.sha256(fh.read()).hexdigest() != c.get("output_sha256"):
145 errs.append("checks/%s.json does not match its output_sha256" % c.get("check"))
146 elif c.get("status") != "NOT_RUN":
147 errs.append("checks/%s.json missing" % c.get("check"))
148 for r in st.get("model_reviewed", []):
149 for k in ("agent_role", "model", "effort", "files_covered", "files_total", "report", "report_sha256", "complete"):
150 if k not in r:
151 errs.append("review lacks %s" % k)
152 rp = os.path.normpath(os.path.join(stamp_dir, r.get("report", "")))
153 if not rp.startswith(os.path.normpath(stamp_dir) + os.sep):
154 errs.append("review report %r is outside the stamp directory" % r.get("report"))
155 elif not os.path.exists(rp):
156 errs.append("review report %s missing" % r.get("report"))
157 else:
158 with open(rp, "rb") as fh:
159 if hashlib.sha256(fh.read()).hexdigest() != r.get("report_sha256"):
160 errs.append("review report %s does not match report_sha256" % r.get("report"))
161 if r.get("complete") and r.get("files_covered") != r.get("files_total"):
162 errs.append("review marked complete but covers %s of %s files" % (r.get("files_covered"), r.get("files_total")))
163 for f in st.get("findings", []):
164 if f.get("source") not in ("DETERMINISTIC", "MODEL"):
165 errs.append("finding %s source must be DETERMINISTIC or MODEL" % f.get("id"))
166 if f.get("status") not in FINDING_STATUS:
167 errs.append("finding %s status must be one of %s" % (f.get("id"), ", ".join(FINDING_STATUS)))
168 if f.get("severity") not in SEVERITIES:
169 errs.append("finding %s severity must be one of %s" % (f.get("id"), ", ".join(SEVERITIES)))
170 if f.get("status") == "FIXED" and not f.get("fix"):
171 errs.append("finding %s is FIXED without a fix reference" % f.get("id"))
172 for n in st.get("not_run", []):
173 if not n.get("item") or not n.get("reason"):
174 errs.append("not_run entries need item and reason")
175 v = st.get("verdict")
176 if v not in VERDICTS:
177 errs.append("verdict must be one of %s" % ", ".join(VERDICTS))
178 else:
179 ceil, why = verdict_ceiling(st)
180 if RANK[v] < RANK[ceil]:
181 errs.append("verdict %s is better than the contents allow (%s: %s)" % (v, ceil, "; ".join(why)))
182 if salts:
183 with open(salts) as fh:
184 sd = json.load(fh) # {"private-NN": {"name", "salt", "commitment"}}, kept off the shelf at mode 0600
185 low = raw.decode("utf-8", "replace").lower()
186 for e in sd.values():
187 if re.search(r"(?<![a-z0-9_.-])%s(?![a-z0-9_-])" % re.escape(e["name"].lower()), low):
188 errs.append("a private repository name appears in the stamp")
189 break
190 if sub.get("visibility") == "private":
191 ent = sd.get(sub.get("anonymous_id"))
192 if not ent or commitment(ent["salt"], ent["name"]) != sub.get("name_commitment"):
193 errs.append("name_commitment does not match the private salt record")
194 return errs
195
196
197def commitment(salt, name):
198 """sha256("<salt hex>:<repository name>"), the form used when the salts were drawn on 2026-10-26."""
199 return hashlib.sha256(f"{salt}:{name}".encode()).hexdigest()
200
201
202def main():
203 ap = argparse.ArgumentParser()
204 sp = ap.add_subparsers(dest="cmd", required=True)
205 v = sp.add_parser("validate")
206 v.add_argument("stamp_dir")
207 v.add_argument("--salts", default="")
208 a = ap.parse_args()
209 errs = validate(a.stamp_dir, a.salts or None)
210 for e in errs:
211 print("INVALID: " + e, file=sys.stderr)
212 if not errs:
213 print("VALID " + a.stamp_dir)
214 sys.exit(1 if errs else 0)
215
216
217if __name__ == "__main__":
218 main()