#!/usr/bin/env python3 """Replay the local newsletter sample and print its deterministic evidence.""" import argparse import hashlib import hmac import http.client import io import json from pathlib import Path import runpy import tempfile from threading import Thread from zipfile import ZipFile SAMPLE_SHA256 = "561d8335e9924808711f6af4d69616aaeef0ba3bb9898906eb4534c1a7307d21" FIXTURE_KEY = "newsletter-replay-fixture" FIXTURE_TOKEN = "newsletter-replay-operator" def verify(condition, message): if not condition: raise RuntimeError(message) def local_request(server, method, path, data=None, headers=None): connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5) try: connection.request(method, path, data, headers or {}) response = connection.getresponse() return response.status, json.load(response) finally: connection.close() def replay(archive): with archive.open("rb") as handle: raw = handle.read(512 * 1024 + 1) digest = hashlib.sha256(raw).hexdigest() verify(len(raw) <= 512 * 1024 and digest == SAMPLE_SHA256, "Use the exact published newsletter.zip archive.") with tempfile.TemporaryDirectory() as workspace: root = Path(workspace) module_path = root / "newsletter.py" with ZipFile(io.BytesIO(raw)) as bundle: module_path.write_bytes(bundle.read("newsletter.py")) module = runpy.run_path(str(module_path)) db = str(root / "state.sqlite") event = {"event_id": "demo-1", "subscription_id": "reader-1", "email": "reader@example.test", "status": "active", "version": 1} raw_event = json.dumps(event).encode() signature = hmac.new(FIXTURE_KEY.encode(), raw_event, hashlib.sha256).hexdigest() event_headers = {"X-Event-Signature": "sha256=" + signature} issue = {"issue_id": "welcome", "subject": "First edition", "body": "Thanks for reading."} issue_headers = {"Authorization": "Bearer " + FIXTURE_TOKEN} def start(): server = module["server"](db, "127.0.0.1", 0, FIXTURE_KEY, FIXTURE_TOKEN) thread = Thread(target=server.serve_forever) thread.start() return server, thread def stop(server, thread): server.shutdown() thread.join() server.server_close() server, thread = start() try: applied = local_request(server, "POST", "/v1/billing/events", raw_event, event_headers) duplicate = local_request(server, "POST", "/v1/billing/events", raw_event, event_headers) created = local_request(server, "POST", "/v1/issues", json.dumps(issue), issue_headers) verify(applied == (200, {"outcome": "applied"}), "Synthetic subscription was not applied.") verify(duplicate == (200, {"outcome": "duplicate"}), "Replay was not recognized.") verify(created == (201, {"issue_id": "welcome", "recipient_count": 1}), "Expected one local recipient.") finally: stop(server, thread) server, thread = start() try: repeated = local_request(server, "POST", "/v1/issues", json.dumps(issue), issue_headers) conflict = local_request(server, "POST", "/v1/issues", json.dumps({**issue, "body": "Different issue body."}), issue_headers) verify(repeated == (200, created[1]), "The original issue was not recovered after restart.") verify(conflict == (409, {"error": "issue conflict"}), "Changed contents reused an existing ID.") report = module["report"](db, "reconcile") mailbox = module["report"](db, "mailbox")["messages"] verify(report["accepted_events"] == 1 and report["delivery_count"] == len(mailbox) == 1, "Replay changed the accepted event or local message count.") verify(mailbox[0]["issue_id"] == "welcome" and mailbox[0]["email"] == "reader@example.test" and mailbox[0]["subject"] == "First edition" and mailbox[0]["body"] == "Thanks for reading.", "The local message did not match the issued sample.") finally: stop(server, thread) return { "schema": "tesi-newsletter-proof/v1", "scope": "simulated_billing_and_local_mailbox", "sampleSha256": digest, "checks": [ {"id": "billing_replay", "outcome": duplicate[1]["outcome"], "acceptedEvents": report["accepted_events"]}, {"id": "issue_creation", "httpStatus": created[0], "recipientCount": created[1]["recipient_count"]}, {"id": "restart_replay", "httpStatus": repeated[0], "localMessages": len(mailbox)}, {"id": "changed_issue", "httpStatus": conflict[0]}, ], "sampleMessage": {"subject": mailbox[0]["subject"], "body": mailbox[0]["body"]}, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path, help="the published newsletter.zip") args = parser.parse_args() try: result = replay(args.archive) except (OSError, RuntimeError, ValueError) as error: parser.exit(1, f"{error}\n") print(json.dumps(result, indent=2, sort_keys=True)) if __name__ == "__main__": main()