"""Pim as a Poppy 1.0 Personal Agent: the identity and the headers it needs to talk to a Company. What the Personal Agent Protocol asks of a client, in the order a request needs it: - an **agent identity** (spec 4.1): a `client_id` that is the HTTPS URL of a client metadata document, a `jwks_uri` on the same domain with the public keys that sign client assertions and delegations, `token_endpoint_auth_method: private_key_jwt`; - **delegated keys** (spec 5.2, "Delegated keys"): Session JWTs are never signed with the keys in `jwks_uri`; a key there signs a short-lived *delegation* (`typ: poppy-delegation+jwt`, `exp` at most 24 hours after `iat`, `cnf.jwk` the delegated public key, no User, Agent or Company named in it), and every Session JWT carries that delegation in its `poppy_dlg` header; each delegated key signs for one User ID at one Company only; - a **Session JWT per request** (spec 5.2): `typ: poppy-session+jwt`, `alg: ES256`, `kid` the delegated key's RFC 7638 thumbprint; claims `iss` (client_id), `aud` (the Company's identifier), `sid`, `sub` (the User ID), `htm`, `htu`, `iat`, `jti`, and `ath` only when an access token is sent; - the **declaration headers** sent with it (spec 3.4): `Poppy-Version: 1.0` and `Poppy-Extensions`, an RFC 9651 List of Strings, identical on every request of a Session; - a **client assertion** at the token endpoint (spec 4.1, RFC 7523): `iss` = `sub` = client_id, `aud` exactly the issuer, `iat`, `exp` at most five minutes later, a unique `jti`; - an **approval** for the Operations extension (version 3, section 6): `Poppy-Approval`, an RFC 9651 Dictionary with `operation_id`, `revision`, `approver`, and optionally `approved_at`, `input_type` (user approvals only) and `reference`. Written with `cryptography` only. No upstream-compatible Python library exists (the PyPI package `poppy` is an optics toolkit; the protocol's kit ships a Node validator and JSON schemas, not a client), so this file is the signer, kept small and checked against the kit's schemas in `tests/test_poppy.py`. The demo imports it; the engine (`forgetproof`) does not depend on it. Everything personal here is fictional. User IDs are random per scenario and Company, never derived from a person's name, email or phone (spec 5.1). """ from __future__ import annotations import base64 import hashlib import json import secrets import threading import time from pathlib import Path from urllib.parse import urlsplit from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature PROTOCOL_VERSION = "1.0" AGENT_NAME = "Pim (this demo)" DELEGATION_SECONDS = 60 * 60 # within the 24-hour bound of spec 5.2; renewed a few minutes before it ends ASSERTION_SECONDS = 120 # within the five-minute bound of spec 4.1 CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" # --- small JOSE helpers (base64url, JWK, compact JWS with ES256) -------------------------------------------------- def b64url(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") def unb64url(text: str) -> bytes: return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) def _json_bytes(obj) -> bytes: return json.dumps(obj, separators=(",", ":"), sort_keys=False, ensure_ascii=False).encode("utf-8") def ec_public_jwk(key: ec.EllipticCurvePublicKey) -> dict: """A P-256 public key as a JWK (RFC 7518 section 6.2.1), members in the order RFC 7638 needs.""" nums = key.public_numbers() return {"kty": "EC", "crv": "P-256", "x": b64url(nums.x.to_bytes(32, "big")), "y": b64url(nums.y.to_bytes(32, "big"))} def thumbprint(jwk: dict) -> str: """RFC 7638: SHA-256 over the required members in lexicographic order, no whitespace, base64url.""" if jwk.get("kty") == "EC": core = {"crv": jwk["crv"], "kty": "EC", "x": jwk["x"], "y": jwk["y"]} elif jwk.get("kty") == "RSA": core = {"e": jwk["e"], "kty": "RSA", "n": jwk["n"]} else: raise ValueError("thumbprint: unsupported key type") return b64url(hashlib.sha256(json.dumps(core, separators=(",", ":"), sort_keys=True).encode()).digest()) def sign_es256(key: ec.EllipticCurvePrivateKey, header: dict, payload: dict) -> str: """Compact JWS, ES256: the signature is the raw r||s (64 bytes), not DER (RFC 7518 section 3.4).""" signing_input = b64url(_json_bytes(header)) + "." + b64url(_json_bytes(payload)) der = key.sign(signing_input.encode("ascii"), ec.ECDSA(hashes.SHA256())) r, s = decode_dss_signature(der) return signing_input + "." + b64url(r.to_bytes(32, "big") + s.to_bytes(32, "big")) def new_id(nbytes: int = 18) -> str: """An unguessable id of at least 128 bits in the URL-safe base64 alphabet (spec 8.2; the kit asks for 22+ characters).""" return secrets.token_urlsafe(nbytes) def load_or_create_key(path: Path) -> ec.EllipticCurvePrivateKey: """A P-256 private key in PEM at `path`, created with owner-only permissions when missing.""" path = Path(path) if path.exists(): key = serialization.load_pem_private_key(path.read_bytes(), password=None) if not isinstance(key, ec.EllipticCurvePrivateKey): raise ValueError(f"{path} is not an EC private key") return key key = ec.generate_private_key(ec.SECP256R1()) path.parent.mkdir(parents=True, exist_ok=True) pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) try: import os fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "wb") as f: f.write(pem) except FileExistsError: return load_or_create_key(path) return key # --- the Personal Agent ---------------------------------------------------------------------------------------- def extensions_header(declared: dict[str, str]) -> str: """`Poppy-Extensions`: an RFC 9651 List of Strings, each with the version in the `v` parameter (spec 3.4).""" return ", ".join(f'"{name}";v="{version}"' for name, version in declared.items()) def approval_header(approval: dict) -> str: """`Poppy-Approval`: an RFC 9651 Dictionary (Operations 6, APIs). Strings quoted, `approved_at` an Integer.""" parts = [] for k in ("operation_id", "revision", "approver", "approved_at", "input_type", "reference"): v = approval.get(k) if v is None: continue if k == "approved_at": parts.append(f"{k}={int(v)}") else: parts.append(f'{k}="{v}"') return ", ".join(parts) class Agent: """One Personal Agent: a long-lived P-256 key for client assertions and delegations, and the documents a Company fetches at its `client_id` (spec 4.1). The origin is given per call because Pim learns its public origin from the environment, and tests use a made-up one.""" def __init__(self, key: ec.EllipticCurvePrivateKey, name: str = AGENT_NAME): self.key = key self.name = name self.public_jwk = ec_public_jwk(key.public_key()) self.kid = thumbprint(self.public_jwk) self._lock = threading.Lock() self._delegates: dict[tuple[str, str], Delegate] = {} @classmethod def generate(cls, name: str = AGENT_NAME) -> Agent: return cls(ec.generate_private_key(ec.SECP256R1()), name) @classmethod def from_file(cls, path: Path, name: str = AGENT_NAME) -> Agent: return cls(load_or_create_key(path), name) @staticmethod def client_id(origin: str) -> str: return origin.rstrip("/") + "/poppy/agent.json" @staticmethod def jwks_uri(origin: str) -> str: return origin.rstrip("/") + "/poppy/jwks.json" def metadata(self, origin: str) -> dict: """The client metadata document (CIMD draft; spec 4.1). `redirect_uris` is empty: this agent starts no Direct Sign-In, the demo's sign-in is a labelled fixture at the Company.""" return {"client_id": self.client_id(origin), "client_name": self.name, "jwks_uri": self.jwks_uri(origin), "redirect_uris": [], "token_endpoint_auth_method": "private_key_jwt"} def jwks(self) -> dict: return {"keys": [{**self.public_jwk, "kid": self.kid, "use": "sig", "alg": "ES256"}]} def client_assertion(self, origin: str, issuer: str, now: int | None = None) -> str: """RFC 7523 client assertion for the Company's token endpoint: `aud` is the issuer, exactly, never an endpoint URL.""" now = int(now or time.time()) cid = self.client_id(origin) return sign_es256(self.key, {"alg": "ES256", "typ": "JWT", "kid": self.kid}, {"iss": cid, "sub": cid, "aud": issuer, "iat": now, "exp": now + ASSERTION_SECONDS, "jti": new_id()}) def delegate(self, origin: str, identifier: str, user_id: str) -> Delegate: """The delegated key for one User ID at one Company (spec 5.2: one key per User ID, so Companies can't match a person across Companies by its thumbprint). Renewed before its delegation expires.""" with self._lock: d = self._delegates.get((identifier, user_id)) if d is None or d.expires_at - time.time() < 300: d = Delegate(self, origin) self._delegates[(identifier, user_id)] = d return d def session(self, origin: str, identifier: str, user_id: str, *, sid: str | None = None, extensions: dict[str, str] | None = None, version: str = PROTOCOL_VERSION) -> Session: return Session(self, origin, identifier, user_id, sid or new_id(), extensions or {}, version) class Delegate: """A delegated P-256 key and the delegation that vouches for it (spec 5.2).""" def __init__(self, agent: Agent, origin: str, lifetime: int = DELEGATION_SECONDS, now: int | None = None): self.key = ec.generate_private_key(ec.SECP256R1()) self.jwk = ec_public_jwk(self.key.public_key()) self.kid = thumbprint(self.jwk) now = int(now or time.time()) self.issued_at, self.expires_at = now, now + lifetime self.compact = sign_es256(agent.key, {"alg": "ES256", "typ": "poppy-delegation+jwt", "kid": agent.kid}, {"iss": agent.client_id(origin), "cnf": {"jwk": self.jwk}, "iat": now, "exp": now + lifetime, "jti": new_id()}) class Session: """One Session with one Company for one User ID (spec 5): a random `sid`, and the same `Poppy-Version` and `Poppy-Extensions` on every request (spec 3.4). `headers()` signs a fresh Session JWT for one request.""" def __init__(self, agent: Agent, origin: str, identifier: str, user_id: str, sid: str, extensions: dict[str, str], version: str): self.agent, self.origin, self.identifier, self.user_id, self.sid = agent, origin, identifier, user_id, sid self.extensions, self.version = dict(extensions), version def session_jwt(self, method: str, url: str, access_token: str | None = None, *, now: int | None = None, agent_id: str | None = None) -> str: d = self.agent.delegate(self.origin, self.identifier, self.user_id) parts = urlsplit(url) htu = f"{parts.scheme}://{parts.netloc}{parts.path}" # no query, no fragment (RFC 9449 section 4.2) claims = {"iss": self.agent.client_id(self.origin), "aud": self.identifier, "sid": self.sid, "sub": self.user_id, "htm": method.upper(), "htu": htu, "iat": int(now or time.time()), "jti": new_id()} if agent_id: claims["agent_id"] = agent_id if access_token: claims["ath"] = b64url(hashlib.sha256(access_token.encode("ascii")).digest()) return sign_es256(d.key, {"typ": "poppy-session+jwt", "alg": "ES256", "kid": d.kid, "poppy_dlg": d.compact}, claims) def headers(self, method: str, url: str, access_token: str | None = None, *, approval: dict | None = None) -> dict[str, str]: h = {"poppy-session": self.session_jwt(method, url, access_token), "poppy-version": self.version} if self.extensions: h["poppy-extensions"] = extensions_header(self.extensions) if access_token: h["authorization"] = f"Bearer {access_token}" if approval: h["poppy-approval"] = approval_header(approval) return h