#!/usr/bin/env python3 """attestras.py: single-file ATTESTRAS client. Python 3.9+, standard library only. export ATTESTRAS_URL=https://... ATTESTRAS_SOURCE=my-first-source export ATTESTRAS_KEY_ID=ak_... ATTESTRAS_SECRET=atsec_... python3 attestras.py demo # creates one receipt and prints a verify link python3 attestras.py check PG_ID # fetches YOUR stored record and recomputes its hash locally As a library: from attestras import Attestras a = Attestras(url, source=..., key_id=..., secret=...) receipt = a.attest(artifact_uri=..., artifact_sha256=..., actor="agent-run-1", assertion="agent emitted report") a.verify(receipt["proof_id"], receipt["proof_hash"]) A retry with the same request_id returns the original receipt, so it is safe to retry on timeouts. Never put the secret in client-side code. """ import hashlib import hmac import json import os import sys import time import urllib.error import urllib.request import uuid SIGNATURE_VERSION = "pg-hmac-sha256-v1" class AttestrasError(Exception): def __init__(self, status, body): super().__init__("HTTP %s: %s" % (status, body)) self.status, self.body = status, body def _frame(value): return len(value).to_bytes(4, "big") + value def sign(secret, *, timestamp, request_id, source, key_id, body): fields = (SIGNATURE_VERSION.encode(), timestamp.encode(), request_id.encode(), source.encode(), key_id.encode(), body) preimage = b"PGSIG\x01" + b"".join(_frame(f) for f in fields) return hmac.new(secret.encode(), preimage, hashlib.sha256).hexdigest() class Attestras: def __init__(self, base_url, *, source, key_id, secret, timeout=10): self.base_url, self.source, self.key_id, self.secret, self.timeout = base_url.rstrip("/"), source, key_id, secret, timeout def attest(self, *, artifact_uri, artifact_sha256, actor, assertion, request_id=None): body = json.dumps( {"artifact": {"uri": artifact_uri, "file_hash": artifact_sha256}, "actor": {"external_ref": actor}, "claim": {"schema": "pg.claim.v1", "assertion": assertion}}, separators=(",", ":"), ensure_ascii=False, ).encode("utf-8") ts, rid = str(int(time.time())), request_id or uuid.uuid4().hex headers = { "Content-Type": "application/json", "X-Timestamp": ts, "X-Request-ID": rid, "X-Source-System": self.source, "X-Key-ID": self.key_id, "X-Signature-Version": SIGNATURE_VERSION, "X-Signature": sign(self.secret, timestamp=ts, request_id=rid, source=self.source, key_id=self.key_id, body=body), } return self._send("/v1/proofs", body, headers, raise_on_error=True) def verify(self, proof_id, proof_hash): body = json.dumps({"proof_id": proof_id, "proof_hash": proof_hash}, separators=(",", ":")).encode() return self._send("/v1/verify", body, {"Content-Type": "application/json"}, raise_on_error=False) def export(self, proof_id): """Fetch your own stored record (signed request; only the owning key may read it).""" body = json.dumps({"proof_id": proof_id}, separators=(",", ":")).encode() ts, rid = str(int(time.time())), uuid.uuid4().hex headers = { "Content-Type": "application/json", "X-Timestamp": ts, "X-Request-ID": rid, "X-Source-System": self.source, "X-Key-ID": self.key_id, "X-Signature-Version": SIGNATURE_VERSION, "X-Signature": sign(self.secret, timestamp=ts, request_id=rid, source=self.source, key_id=self.key_id, body=body), } return self._send("/v1/records", body, headers, raise_on_error=True) def share_url(self, receipt): return "%s/verify#%s.%s" % (self.base_url, receipt["proof_id"], receipt["proof_hash"]) def _send(self, path, body, headers, raise_on_error): req = urllib.request.Request(self.base_url + path, data=body, method="POST", headers=headers) try: with urllib.request.urlopen(req, timeout=self.timeout) as r: return json.loads(r.read()) except urllib.error.HTTPError as exc: payload = exc.read().decode("utf-8", "replace") if raise_on_error: raise AttestrasError(exc.code, payload) from None return json.loads(payload) def canonical_hash(record): """Receipt hash of a record: SHA-256 of canonical JSON (sorted keys, no spaces, UTF-8). No floats.""" canon = json.dumps(record, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") return hashlib.sha256(canon).hexdigest() def _client(): try: return Attestras(os.environ["ATTESTRAS_URL"], source=os.environ["ATTESTRAS_SOURCE"], key_id=os.environ["ATTESTRAS_KEY_ID"], secret=os.environ["ATTESTRAS_SECRET"]) except KeyError as missing: sys.exit("Set %s (see your ATTESTRAS account page)." % missing.args[0]) def main(argv): if len(argv) >= 2 and argv[1] == "demo": a = _client() stamp = str(int(time.time())) report = ("attestras demo report " + stamp).encode() receipt = a.attest( artifact_uri="https://example.com/attestras-demo/%s.json" % stamp, artifact_sha256=hashlib.sha256(report).hexdigest(), actor="demo-run-" + stamp, assertion="demo run produced a report", ) print(json.dumps(receipt, indent=2)) print("\nVerify it in your browser (no account needed):\n " + a.share_url(receipt)) return 0 if len(argv) == 4 and argv[1] == "verify": print(json.dumps(_client().verify(argv[2], argv[3]), indent=2)) return 0 if len(argv) == 3 and argv[1] == "check": got = _client().export(argv[2]) mine = canonical_hash(got["record"]) print(json.dumps(got["record"], indent=2, sort_keys=True)) print("\nreceipt hash from server: " + got["proof_hash"]) print("recomputed here: " + mine) print("MATCH" if mine == got["proof_hash"] else "MISMATCH") return 0 if mine == got["proof_hash"] else 1 print("usage: python3 attestras.py demo | verify PROOF_ID PROOF_HASH | check PROOF_ID") return 2 if __name__ == "__main__": sys.exit(main(sys.argv))