"""The public contract over real HTTP, between two processes. The reference Company and the demo site (Pim) each run as their own process on a loopback port. The client below uses only the public contract: `httpx` for HTTP, `cryptography` for Ed25519 (the receipts) and P-256 (its Poppy identity), its own canonical JSON. It never imports forgetproof, the Company or the demo. As a Poppy 1.0 Personal Agent it serves its own client metadata document from a thread, discovers the Company from `/.well-known/poppy.json` and the two OAuth metadata documents, exchanges the fixture's refresh token for an access token with a client assertion, signs a Session JWT per request, is told the exact terms of the withdrawal (403 approval_required), approves them as the person, withdraws one record, polls, fetches the evidence and verifies every portable receipt against the keys the issuer publishes; then it does the same through Pim, whose evidence carries the Company's receipts as received. """ import base64 import hashlib import json import os import secrets import socket import subprocess import sys import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path import pytest httpx = pytest.importorskip("httpx") pytest.importorskip("uvicorn") pytest.importorskip("starlette") # the two server processes run on the same interpreter and need the site extra from cryptography.hazmat.primitives import hashes # noqa: E402 from cryptography.hazmat.primitives.asymmetric import ec # noqa: E402 from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey # noqa: E402 from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature # noqa: E402 ROOT = Path(__file__).resolve().parent.parent NAMESPACE = "stellarminds.ai/forget-me" OLD = "118 Harbor Lane, Oakland CA 94607" pytestmark = pytest.mark.fix # Pim's scenario builds and rewrites a Chroma collection # --- the client: public contract only --------------------------------------------------------------------------- def canonical(obj) -> bytes: return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() def unb64(s: str) -> bytes: return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) def fingerprint(pub: str) -> str: return hashlib.sha256(unb64(pub)).hexdigest()[:32] def verify(rec: dict, published_keys: list[str]) -> None: assert rec["format"] == "forget-me-receipt/1" and rec["namespace"] == NAMESPACE and rec["version"] == "1" assert rec["public_key"] in published_keys, "signed by a key the issuer does not publish" body = {k: v for k, v in rec.items() if k != "signature"} Ed25519PublicKey.from_public_bytes(unb64(rec["public_key"])).verify(unb64(rec["signature"]), canonical(body)) blob = json.dumps(rec) assert OLD not in blob and "/" not in json.dumps(rec["coverage"]) and ".db" not in blob and "tmp" not in rec["issuer"] def b64u(b: bytes) -> str: return base64.urlsafe_b64encode(b).rstrip(b"=").decode() def jws(key, header: dict, payload: dict) -> str: """Compact JWS with ES256: the signature is raw r||s (RFC 7518 section 3.4).""" si = b64u(json.dumps(header, separators=(",", ":")).encode()) + "." + b64u(json.dumps(payload, separators=(",", ":")).encode()) r, s_ = decode_dss_signature(key.sign(si.encode(), ec.ECDSA(hashes.SHA256()))) return si + "." + b64u(r.to_bytes(32, "big") + s_.to_bytes(32, "big")) class Agent: """A Poppy 1.0 Personal Agent built from the spec alone: a P-256 key, a client metadata document and key set served by a thread, delegations (spec 5.2), a Session JWT per request, client assertions (spec 4.1), the approval header.""" def __init__(self): self.key = ec.generate_private_key(ec.SECP256R1()) self.jwk = self._jwk(self.key) self.kid = self._thumb(self.jwk) self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), self._handler()) threading.Thread(target=self.httpd.serve_forever, daemon=True).start() self.origin = f"http://127.0.0.1:{self.httpd.server_address[1]}" self.client_id = self.origin + "/agent.json" self.delegated = ec.generate_private_key(ec.SECP256R1()) now = int(time.time()) self.delegation = jws(self.key, {"alg": "ES256", "typ": "poppy-delegation+jwt", "kid": self.kid}, {"iss": self.client_id, "cnf": {"jwk": self._jwk(self.delegated)}, "iat": now, "exp": now + 3600, "jti": secrets.token_urlsafe(18)}) self.sid, self.user = secrets.token_urlsafe(18), "usr_" + secrets.token_urlsafe(12) @staticmethod def _jwk(key) -> dict: n = key.public_key().public_numbers() return {"kty": "EC", "crv": "P-256", "x": b64u(n.x.to_bytes(32, "big")), "y": b64u(n.y.to_bytes(32, "big"))} @staticmethod def _thumb(jwk: dict) -> str: return b64u(hashlib.sha256(json.dumps({"crv": jwk["crv"], "kty": "EC", "x": jwk["x"], "y": jwk["y"]}, separators=(",", ":"), sort_keys=True).encode()).digest()) def _handler(self): agent = self class H(BaseHTTPRequestHandler): def do_GET(self): docs = {"/agent.json": {"client_id": agent.client_id, "client_name": "Wire test agent", "jwks_uri": agent.origin + "/jwks.json", "redirect_uris": [], "token_endpoint_auth_method": "private_key_jwt"}, "/jwks.json": {"keys": [{**agent.jwk, "kid": agent.kid}]}} body = json.dumps(docs.get(self.path, {"error": "not_found"})).encode() self.send_response(200 if self.path in docs else 404) self.send_header("content-type", "application/json") self.send_header("content-length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *a): pass return H def assertion(self, issuer: str) -> str: now = int(time.time()) return jws(self.key, {"alg": "ES256", "typ": "JWT", "kid": self.kid}, {"iss": self.client_id, "sub": self.client_id, "aud": issuer, "iat": now, "exp": now + 120, "jti": secrets.token_urlsafe(18)}) def headers(self, identifier: str, method: str, url: str, token: str | None, approval: dict | None = None) -> dict: claims = {"iss": self.client_id, "aud": identifier, "sid": self.sid, "sub": self.user, "htm": method, "htu": url.split("?")[0], "iat": int(time.time()), "jti": secrets.token_urlsafe(18)} if token: claims["ath"] = b64u(hashlib.sha256(token.encode()).digest()) h = {"poppy-session": jws(self.delegated, {"typ": "poppy-session+jwt", "alg": "ES256", "kid": self._thumb(self._jwk(self.delegated)), "poppy_dlg": self.delegation}, claims), "poppy-version": "1.0", "poppy-extensions": '"stellarminds.ai/forget-me";v="1", "operations";v="3"'} if token: h["authorization"] = f"Bearer {token}" if approval: h["poppy-approval"] = ", ".join(f'{k}="{v}"' if k != "approved_at" else f"{k}={v}" for k, v in approval.items()) return h def discover(origin: str) -> tuple[str, dict, dict]: """poppy.json (spec 3), the ForgetMe entry, the protected resource and issuer metadata (spec 3.2), the index.""" poppy = httpx.get(origin + "/.well-known/poppy.json", timeout=10).json() assert poppy["protocol_version"].startswith("1.") and poppy["organization"]["domain"] == origin.split("://")[1] entries = poppy["extensions"][NAMESPACE] endpoint = next(e["endpoint"] for e in entries if e["version"] == "1") if endpoint.startswith("/"): endpoint = origin + endpoint assert any(e["version"] == "3" for e in poppy["extensions"]["operations"]) prm = httpx.get(origin + "/.well-known/oauth-protected-resource", timeout=10).json() assert prm["resource"] == origin issuer = prm["authorization_servers"][0] meta = httpx.get(issuer + "/.well-known/oauth-authorization-server", timeout=10).json() assert meta["issuer"] == issuer and origin in meta["protected_resources"] and "refresh_token" in meta["grant_types_supported"] index = httpx.get(endpoint, timeout=10).json() assert index["namespace"] == NAMESPACE and index["version"] == "1" and index["keys"] and index["approval"]["approver"] == "user" return endpoint.rstrip("/"), index, {"issuer": issuer, "token_endpoint": meta["token_endpoint"]} def token_for(agent: Agent, oauth: dict, refresh_token: str) -> str: r = httpx.post(oauth["token_endpoint"], data={"grant_type": "refresh_token", "refresh_token": refresh_token, "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", "client_assertion": agent.assertion(oauth["issuer"])}, timeout=10) assert r.status_code == 200, r.text return r.json()["access_token"] def withdraw(endpoint: str, agent: Agent, identifier: str, token: str, body: dict, key: str) -> tuple[dict, dict]: def H(method, url, approval=None): return agent.headers(identifier, method, url, token, approval) with httpx.Client(timeout=30) as c: pv = c.post(f"{endpoint}/preview", json=body, headers=H("POST", f"{endpoint}/preview")) assert pv.status_code == 200, pv.text preview = pv.json() terms = {**preview["terms"], "idempotency_key": key} # the Operations extension: the Company states the exact terms and performs nothing until the person approves them offered = c.post(f"{endpoint}/submit", json=terms, headers=H("POST", f"{endpoint}/submit")) assert offered.status_code == 403 and offered.json()["error"] == "approval_required", offered.text op = offered.json()["operation"] assert op["terms"]["reference"] == body.get("reference") and op["summary"] and op["expires_at"] approval = {"operation_id": op["operation_id"], "revision": op["revision"], "approver": "user", "approved_at": int(time.time()), "input_type": "tap", "reference": "apr_" + secrets.token_urlsafe(9)} sub = c.post(f"{endpoint}/submit", json=terms, headers=H("POST", f"{endpoint}/submit", approval)) assert sub.status_code == 202, sub.text again = c.post(f"{endpoint}/submit", json=terms, headers=H("POST", f"{endpoint}/submit", approval)) # the retry path: the same answer, once performed assert again.status_code == 200 and again.json()["operation"] == sub.json()["operation"] op_id = sub.json()["operation"] deadline = time.time() + 180 while True: st = c.get(f"{endpoint}/operations/{op_id}", headers=H("GET", f"{endpoint}/operations/{op_id}")).json() if st["state"] in ("done", "error") and not st["outcome"].get("outstanding"): break assert time.time() < deadline, st time.sleep(1.0) ev = c.get(f"{endpoint}/operations/{op_id}/evidence", headers=H("GET", f"{endpoint}/operations/{op_id}/evidence")).json() return st, ev # --- the two processes -------------------------------------------------------------------------------------------- def free_port() -> int: with socket.socket() as s: s.bind(("127.0.0.1", 0)) return s.getsockname()[1] def start(args: list[str], env: dict, url: str, log: Path) -> subprocess.Popen: """Output to a file, never a pipe nobody drains: a full pipe makes uvicorn's access log block the server.""" p = subprocess.Popen([sys.executable, *args], cwd=str(ROOT), env=env, stdout=log.open("w", encoding="utf-8"), stderr=subprocess.STDOUT, text=True) for _ in range(300): if p.poll() is not None: raise RuntimeError(f"{args} exited: {log.read_text(encoding='utf-8', errors='replace')[-2000:]}") try: if httpx.get(url + "/health", timeout=1).status_code == 200: return p except httpx.HTTPError: time.sleep(0.2) p.kill() raise RuntimeError(f"{args} never became healthy: {p.stdout.read()[-2000:]}") @pytest.fixture(scope="module") def servers(tmp_path_factory): tmp = tmp_path_factory.mktemp("wire") base = {**os.environ, "PYTHONPATH": os.pathsep.join(filter(None, [str(ROOT / "src"), str(ROOT), os.environ.get("PYTHONPATH", "")])), "PYTHONUNBUFFERED": "1", "ANONYMIZED_TELEMETRY": "False"} cport, pport = free_port(), free_port() company_url, pim_url = f"http://127.0.0.1:{cport}", f"http://127.0.0.1:{pport}" company = start(["-m", "company"], {**base, "COMPANY_DATA": str(tmp / "company"), "COMPANY_ORIGIN": company_url, "COMPANY_PORT": str(cport), "COMPANY_ACCOUNTS_PER_IP": "1000", "COMPANY_DEV_CLIENTS": "1"}, company_url, tmp / "company.log") try: pim = start(["-m", "demo.server"], {**base, "PORT": str(pport), "FORGETPROOF_SITE_RUNS": str(tmp / "runs"), "FORGETPROOF_HOME": str(tmp / "home"), "FORGETME_COMPANY_URL": company_url, "RUNS_PER_IP": "1000", "FORGETME_RECIPIENT_RETRY": "1", "PIM_ORIGIN": pim_url}, pim_url, tmp / "pim.log") except Exception: company.kill() raise try: yield company_url, pim_url finally: for p in (pim, company): p.kill() p.wait(timeout=10) def test_client_discovers_withdraws_polls_and_verifies_at_the_company(servers): company_url, _ = servers endpoint, index, oauth = discover(company_url) keys = [k["public_key"] for k in index["keys"]] assert all(fingerprint(k["public_key"]) == k["key_fingerprint"] for k in index["keys"]) agent = Agent() # demo-specific: a synthetic account with the record already shared, and the refresh token a sign-in would have produced acct = httpx.post(company_url + "/fixture/accounts", json={"name": "John Reyes", "addresses": [{"label": "Home", "line": OLD}], "deliveries": 1, "client_id": agent.client_id}, timeout=10).json() token = token_for(agent, oauth, acct["grant"]["refresh_token"]) # the protocol and the contract, and nothing else, from here on st, ev = withdraw(endpoint, agent, oauth["issuer"], token, {"scope": "item", "reference": acct["addresses"][0]["reference"]}, "wire-key-company-0001") assert st["approval"]["approver"] == "user" and st["approval"]["client"] == "Wire test agent" assert st["state"] == "done" and st["outcome"]["overall"] == "intentionally-retained" rows = {h["holder"]: h for h in st["outcome"]["holders"]} assert rows["records"]["outcome"] == "inspected-and-clear" and rows["invoices"]["retained_until"] assert ev["issuer"] == index["issuer"] and ev["issuer_key_url"] == endpoint assert len(ev["receipts"]) == 3 for r in ev["receipts"]: verify(r["receipt"], keys) assert r["receipt"]["issuer"] == index["issuer"] and r["receipt"]["operation"] == st["operation"] # a tampered receipt and a foreign key are rejected by the same client code bad = json.loads(json.dumps(ev["receipts"][0]["receipt"])) bad["after"]["residue"] = 7 with pytest.raises(Exception): verify(bad, keys) with pytest.raises(AssertionError): verify(ev["receipts"][0]["receipt"], ["H5HcybllX8T0JfSfNJ5AJ2jhFfqSnRj0ibEjf6_AcwM"]) # another account cannot read the operation; a stranger without a Session gets no further than invalid_session other = httpx.post(company_url + "/fixture/accounts", json={"name": "Other", "client_id": agent.client_id}, timeout=10).json() other_token = token_for(agent, oauth, other["grant"]["refresh_token"]) other_agent = Agent() other_agent.key, other_agent.kid, other_agent.jwk, other_agent.delegated, other_agent.delegation, other_agent.client_id = agent.key, agent.kid, agent.jwk, agent.delegated, agent.delegation, agent.client_id url = f"{endpoint}/operations/{st['operation']}" assert httpx.get(url, headers=other_agent.headers(oauth["issuer"], "GET", url, other_token), timeout=10).status_code == 404 assert httpx.get(url, headers={"authorization": f"Bearer {token}"}, timeout=10).json()["error"] == "invalid_session" def test_client_withdraws_through_pim_and_verifies_the_companys_receipts_as_received(servers): company_url, pim_url = servers pim_endpoint, pim_index = discover_pim(pim_url) company_endpoint, company_index, _ = discover(company_url) # demo-specific sign-in: the synthetic session for the fictional user; then Pim's own memory list started = httpx.post(pim_url + "/pim/sessions", timeout=10).json() headers = {"authorization": f"Bearer {started['credential']}"} for _ in range(600): m = httpx.get(pim_url + "/pim/memory", headers=headers, timeout=10) if m.status_code == 200: break time.sleep(0.2) old = next(i for i in m.json()["items"] if OLD in i["text"]) assert [s["party"] for s in old["shared_with"]][0] == "Bay Parcel" # the contract with httpx.Client(timeout=30, headers=headers) as c: preview = c.post(f"{pim_endpoint}/preview", json={"scope": "item", "reference": old["reference"]}).json() recipients = [e for e in preview["exceptions"] if e.get("party")] assert {e["party"].split(" (")[0] for e in recipients} == {"Bay Parcel", "Harbor Pharmacy", "Oakland Utilities"} bay = next(e for e in recipients if e["party"] == "Bay Parcel") assert bay["default"] == "delete" and bay["approval"]["protocol"] == "operations/3" and OLD in bay["approval"]["summary"] # the Company's exact terms, shown first assert all(e["default"] == "keep" for e in recipients if "simulated" in e["party"]) # selectable, not default terms = {**preview["terms"], "exceptions": {k: ("delete" if any(e["id"] == k and e.get("party") for e in recipients) else v) for k, v in preview["terms"]["exceptions"].items()}, "approvals": {bay["id"]: {"operation_id": bay["approval"]["operation_id"], "revision": bay["approval"]["revision"], "input_type": "tap"}}} st, ev = withdraw_terms(pim_endpoint, headers, terms, "wire-key-pim-0001") assert st["state"] == "done" rows = {h["holder"]: h for h in st["outcome"]["holders"]} assert rows["memory"]["outcome"] == "inspected-and-clear" and rows["notes"]["outcome"] == "intentionally-retained" assert rows["bay-parcel-records"]["outcome"] == "inspected-and-clear" and rows["bay-parcel-invoices"]["outcome"] == "intentionally-retained" assert rows["harbor-pharmacy"]["outcome"] == "unsupported" and rows["harbor-pharmacy"]["evidence"] assert rows["oakland-utilities"]["outcome"] == "unsupported" and rows["oakland-utilities"]["evidence"] is None assert all(h["action"] and h["at"] for h in st["outcome"]["holders"]) pim_keys = [k["public_key"] for k in pim_index["keys"]] company_keys = [k["public_key"] for k in company_index["keys"]] by_party = {} for r in ev["receipts"]: verify(r["receipt"], company_keys if r.get("party") == "Bay Parcel" else pim_keys) by_party.setdefault(r.get("party", "Pim"), []).append(r) assert len(by_party["Pim"]) == 4 and len(by_party["Bay Parcel"]) == 3 and len(by_party["Harbor Pharmacy (simulated)"]) == 1 assert all(r["verified_by_host"] for r in by_party["Bay Parcel"]) and all(r["issuer"] == company_index["issuer"] for r in by_party["Bay Parcel"]) assert ev["observations"][0]["holder"] == "oakland-utilities" and ev["observations"][0]["observed_by"] == pim_index["issuer"] assert OLD not in json.dumps(ev) def discover_pim(origin: str) -> tuple[str, dict]: """Pim is a host behind the button (its own cookie session), and a Personal Agent toward the Company: it publishes its client metadata document at /poppy/agent.json, not a poppy.json (it is not a Company).""" index = httpx.get(origin + "/forget-me/v1", timeout=10).json() assert index["namespace"] == NAMESPACE and index["keys"] and index["cross_provider"]["enabled"] is True assert index["cross_provider"]["poppy"]["client_id"] == origin + "/poppy/agent.json" meta = httpx.get(origin + "/poppy/agent.json", timeout=10).json() assert meta["client_id"] == origin + "/poppy/agent.json" and httpx.get(meta["jwks_uri"], timeout=10).json()["keys"][0]["kty"] == "EC" return origin + "/forget-me/v1", index def withdraw_terms(endpoint: str, headers: dict, terms: dict, key: str) -> tuple[dict, dict]: with httpx.Client(timeout=60, headers=headers) as c: sub = c.post(f"{endpoint}/submit", json={**terms, "idempotency_key": key}) assert sub.status_code == 202, sub.text op_id = sub.json()["operation"] deadline = time.time() + 240 while True: st = c.get(f"{endpoint}/operations/{op_id}").json() if st["state"] in ("done", "error") and not st["outcome"].get("outstanding"): break assert time.time() < deadline, st time.sleep(1.0) ev = c.get(f"{endpoint}/operations/{op_id}/evidence").json() return st, ev