"""Poppy 1.0 at the reference Company: what it verifies before it believes a request. The Personal Agent Protocol puts three things on a request to a Company's API, and this module checks each one the way the spec says, with the section cited beside the check: - the **declaration headers** (spec 3.4): `Poppy-Version`, which must name a version the Company serves (same major from 1.0; missing or incompatible is `version_unsupported`, HTTP 400), and `Poppy-Extensions`, an RFC 9651 List of Strings naming the extensions the request uses, one version each; a missing or unparseable list declares no extensions, and unknown names or versions are ignored (spec 3.3); - the **Session header** (spec 5.2, 5.3): a Session JWT signed per request with a delegated key, whose delegation a key from the agent's `jwks_uri` signed; the Company fetches the client metadata at `iss` and its key set, verifies the delegation and the Session JWT in the order 5.2 gives, checks `aud`, `htm`, `htu`, `iat`, `ath`, and may refuse a reused `jti`; any failure is `invalid_session` (HTTP 400); - the **access token** (spec 4.5, section 7): issued by the Company's own issuer to the same `client_id` as the Session JWT's `iss`, carrying scopes; a missing token is a 401 challenge naming the scopes, a bad one `invalid_token`, a short one `insufficient_scope` (HTTP 403), all in `WWW-Authenticate`. Plus the client assertion at the token endpoint (spec 4.1, RFC 7523: `aud` exactly the issuer, five minutes at most, a fresh `jti`) and the `Poppy-Approval` header of the Operations extension, version 3. No upstream-compatible library exists for any of this (the PyPI `poppy` is an optics package; the protocol's kit ships a Node validator and JSON schemas), so the verifier is written here with `cryptography` only, kept small, and covered by `tests/test_poppy.py`. The storage it needs (Sessions, tokens, operations) lives in `company/core.py`; this module is stateless apart from two caches that the spec allows: verified delegations until they expire, and the `jti` values seen inside the acceptance window. """ from __future__ import annotations import base64 import hashlib import ipaddress import json import re import threading import time from dataclasses import dataclass, field from urllib.parse import urlsplit from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature PROTOCOL_VERSION = "1.0" SERVED_MAJOR = 1 SESSION_TYP = "poppy-session+jwt" DELEGATION_TYP = "poppy-delegation+jwt" DELEGATION_MAX_SECONDS = 24 * 3600 # spec 5.2 ASSERTION_MAX_SECONDS = 300 # spec 4.1 IAT_WINDOW = 60 # spec 5.3 suggests about a minute CLOCK_SKEW = 30 # the guides suggest a small skew CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" ID_CHARS = re.compile(r"^[A-Za-z0-9_-]{1,256}$") # spec 8.2: Conversation IDs, sids, operation ids METADATA_MAX_BYTES = 100 * 1024 METADATA_TTL = 300 class PoppyError(Exception): """A refusal with the upstream shape: HTTP status, `error` code, a sentence for the developer, extra members and, for access-token errors, the `WWW-Authenticate` challenge (spec 7).""" def __init__(self, status: int, code: str, description: str, *, headers: dict | None = None, **extra): super().__init__(description) self.status, self.code, self.description, self.extra = status, code, description, extra self.headers = headers or {} def body(self) -> dict: return {"error": self.code, "error_description": self.description, **self.extra} # --- RFC 9651 Structured Field Values, the subset the headers use ---------------------------------------------- # # `Poppy-Extensions` is a List of Strings with a `v` parameter; `Poppy-Approval` and `Poppy-Operation` are # Dictionaries of Strings and Integers. The parser below follows RFC 9651 section 4.2 for Lists, Dictionaries, # Items (Strings, Tokens, Integers, Decimals, Booleans, Byte Sequences), Inner Lists and Parameters; anything it # does not understand is a parse failure, which spec 3.4 says is "declares no extensions". class _SFParseError(ValueError): pass class Token(str): """An RFC 9651 Token, kept apart from a String so a bare `operations` is not mistaken for `"operations"`.""" class _SF: def __init__(self, text: str): self.s, self.i = text, 0 def peek(self) -> str: return self.s[self.i] if self.i < len(self.s) else "" def eat_sp(self) -> None: while self.peek() == " ": self.i += 1 def eat_ows(self) -> None: while self.peek() in (" ", "\t") and self.peek(): self.i += 1 def key(self) -> str: m = re.match(r"[a-z*][a-z0-9_.*-]*", self.s[self.i:]) if not m: raise _SFParseError("key") self.i += m.end() return m.group(0) def bare_item(self): c = self.peek() if c == '"': self.i += 1 out = [] while True: if self.i >= len(self.s): raise _SFParseError("unterminated string") ch = self.s[self.i] self.i += 1 if ch == "\\": nxt = self.peek() if nxt not in ('"', "\\"): raise _SFParseError("bad escape") out.append(nxt) self.i += 1 elif ch == '"': return "".join(out) elif not (0x20 <= ord(ch) <= 0x7E): raise _SFParseError("non-ascii in string") else: out.append(ch) if c == "?": self.i += 1 b = self.peek() if b not in ("0", "1"): raise _SFParseError("boolean") self.i += 1 return b == "1" if c == ":": m = re.match(r":([A-Za-z0-9+/=]*):", self.s[self.i:]) if not m: raise _SFParseError("byte sequence") self.i += m.end() return base64.b64decode(m.group(1) + "=" * (-len(m.group(1)) % 4)) if c == "-" or c.isdigit(): m = re.match(r"-?\d{1,15}(\.\d{1,3})?", self.s[self.i:]) if not m: raise _SFParseError("number") self.i += m.end() txt = m.group(0) return float(txt) if "." in txt else int(txt) if c.isalpha() or c == "*": m = re.match(r"[A-Za-z*][A-Za-z0-9:/!#$%&'*+\-.^_`|~]*", self.s[self.i:]) self.i += m.end() return Token(m.group(0)) raise _SFParseError("item") def parameters(self) -> dict: params: dict = {} while self.peek() == ";": self.i += 1 self.eat_sp() k = self.key() v: object = True if self.peek() == "=": self.i += 1 v = self.bare_item() params[k] = v return params def item_or_inner_list(self): if self.peek() == "(": self.i += 1 items = [] while True: self.eat_sp() if self.peek() == ")": self.i += 1 return items, self.parameters() if self.i >= len(self.s): raise _SFParseError("unterminated inner list") v = self.bare_item() items.append((v, self.parameters())) if self.peek() not in (" ", ")"): raise _SFParseError("inner list separator") v = self.bare_item() return v, self.parameters() def list(self) -> list: out = [] self.eat_sp() while self.i < len(self.s): out.append(self.item_or_inner_list()) self.eat_ows() if self.i >= len(self.s): return out if self.peek() != ",": raise _SFParseError("list separator") self.i += 1 self.eat_ows() if self.i >= len(self.s): raise _SFParseError("trailing comma") return out def dictionary(self) -> dict: out: dict = {} self.eat_sp() while self.i < len(self.s): k = self.key() if self.peek() == "=": self.i += 1 v = self.item_or_inner_list() else: v = (True, self.parameters()) out[k] = v # a repeated key: the last wins (RFC 9651 section 4.2.2) self.eat_ows() if self.i >= len(self.s): return out if self.peek() != ",": raise _SFParseError("dictionary separator") self.i += 1 self.eat_ows() if self.i >= len(self.s): raise _SFParseError("trailing comma") return out def parse_sf_list(value: str | None) -> list | None: """[(item, params)] or None when the field fails to parse (RFC 9651 section 4.2). Items keep their type: `str` for Strings, `Token` for Tokens, int/float/bool/bytes, or a list for an Inner List.""" if value is None: return None try: return _SF(value.strip(" \t")).list() except (_SFParseError, IndexError, AttributeError): return None def parse_sf_dictionary(value: str | None) -> dict | None: """{key: (item, params)} or None when the field fails to parse.""" if value is None: return None try: return _SF(value.strip(" \t")).dictionary() except (_SFParseError, IndexError, AttributeError): return None # --- negotiation (spec 3.3, 3.4) ------------------------------------------------------------------------------------ @dataclass class Negotiation: version: str | None # the request's Poppy-Version as sent compatible: bool # same major as the version this Company serves (from 1.0: same major) extensions: dict[str, str] = field(default_factory=dict) # name -> version, as declared; unknown ones included, the Company ignores them parsed: bool = True # False when Poppy-Extensions was present but failed to parse (then `extensions` is empty) def uses(self, name: str, version: str) -> bool: return self.extensions.get(name) == version def key(self) -> str: """A normalized form, to compare declarations across a Session (spec 3.4: identical on every request).""" return json.dumps({"v": self.version, "x": sorted(self.extensions.items())}, separators=(",", ":")) def negotiate(headers, served_major: int = SERVED_MAJOR) -> Negotiation: """Read `Poppy-Version` and `Poppy-Extensions` from a request's headers (spec 3.4). Does not raise: the caller answers `version_unsupported` when `compatible` is false on an endpoint that verifies the Session.""" version = headers.get("poppy-version") compatible = False if isinstance(version, str) and re.fullmatch(r"\d+\.\d+", version.strip()): compatible = int(version.strip().split(".")[0]) == served_major raw = headers.get("poppy-extensions") parsed = parse_sf_list(raw) declared: dict[str, str] = {} if parsed is None: return Negotiation(version, compatible, {}, parsed=raw is None) for item, params in parsed: # each member is a String naming an extension, with the version as a String in `v`; anything else is ignored if isinstance(item, str) and not isinstance(item, Token) and isinstance(params.get("v"), str) and not isinstance(params.get("v"), Token): declared.setdefault(item, params["v"]) # one version of each: the first declaration counts return Negotiation(version, compatible, declared) # --- JOSE: JWK to key, compact JWS verification (ES256, PS384) ----------------------------------------------------- def b64url(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") def unb64url(text: str) -> bytes: if not isinstance(text, str) or not re.fullmatch(r"[A-Za-z0-9_-]*", text): raise ValueError("not base64url") return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) def thumbprint(jwk: dict) -> str: """RFC 7638 JWK thumbprint (SHA-256, 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("unsupported key type") return b64url(hashlib.sha256(json.dumps(core, separators=(",", ":"), sort_keys=True).encode()).digest()) def public_key_from_jwk(jwk: dict): """A public key from a JWK: EC P-256 or RSA (2048 to 4096 bits). Private members are refused (RFC 7800: cnf.jwk is a public key; the guides: ignore any key embedded in a JWT except the one a verified delegation names).""" if not isinstance(jwk, dict) or any(k in jwk for k in ("d", "p", "q", "dp", "dq", "qi", "k")): raise ValueError("not a public JWK") if jwk.get("kty") == "EC": if jwk.get("crv") != "P-256": raise ValueError("EC key must be P-256") x, y = int.from_bytes(unb64url(jwk["x"]), "big"), int.from_bytes(unb64url(jwk["y"]), "big") return ec.EllipticCurvePublicNumbers(x, y, ec.SECP256R1()).public_key() if jwk.get("kty") == "RSA": n, e = int.from_bytes(unb64url(jwk["n"]), "big"), int.from_bytes(unb64url(jwk["e"]), "big") key = rsa.RSAPublicNumbers(e, n).public_key() if not 2048 <= key.key_size <= 4096: raise ValueError("RSA key must be 2048 to 4096 bits") return key raise ValueError("unsupported key type") def split_jws(compact: str) -> tuple[dict, dict, bytes, bytes]: """(header, payload, signing_input, signature) of a compact JWS; raises ValueError on anything malformed.""" if not isinstance(compact, str): raise ValueError("not a JWS") parts = compact.split(".") if len(parts) != 3: raise ValueError("a compact JWS has three parts") header, payload = json.loads(unb64url(parts[0])), json.loads(unb64url(parts[1])) if not isinstance(header, dict) or not isinstance(payload, dict): raise ValueError("header and payload must be JSON objects") return header, payload, (parts[0] + "." + parts[1]).encode("ascii"), unb64url(parts[2]) def verify_jws_signature(alg: str, key, signing_input: bytes, signature: bytes) -> None: """ES256 (raw r||s) or PS384 (RSA-PSS, SHA-384, salt the hash length). `alg: none` and HMACs never get here.""" try: if alg == "ES256": if not isinstance(key, ec.EllipticCurvePublicKey) or len(signature) != 64: raise ValueError("ES256 needs a P-256 key and a 64-byte signature") der = encode_dss_signature(int.from_bytes(signature[:32], "big"), int.from_bytes(signature[32:], "big")) key.verify(der, signing_input, ec.ECDSA(hashes.SHA256())) elif alg == "PS384": if not isinstance(key, rsa.RSAPublicKey): raise ValueError("PS384 needs an RSA key") key.verify(signature, signing_input, padding.PSS(mgf=padding.MGF1(hashes.SHA384()), salt_length=48), hashes.SHA384()) else: raise ValueError(f"algorithm {alg!r} is not accepted") except InvalidSignature: raise ValueError("the signature does not verify") from None # --- the agent's documents: client metadata and keys, fetched under the address rules (spec 3, 4.1) ------------------ def _host_is_private(host: str) -> bool: h = host.lower().strip("[]") if h == "localhost" or h.endswith(".localhost"): return True try: ip = ipaddress.ip_address(h) except ValueError: return False return ip.is_loopback or ip.is_private or ip.is_link_local or ip.is_unspecified def check_url(url: str, *, dev: bool, what: str) -> None: """Spec 3: every URL the protocol exchanges is HTTPS; neither party connects to a loopback, private or link-local address for a URL the other gave it, unless configured to on purpose (`dev`).""" parts = urlsplit(url) if parts.scheme != "https" and not (dev and parts.scheme == "http"): raise PoppyError(400, "invalid_session", f"{what} must be an https URL") if not parts.hostname: raise PoppyError(400, "invalid_session", f"{what} has no host") if _host_is_private(parts.hostname) and not dev: raise PoppyError(400, "invalid_session", f"{what} points at a loopback, private or link-local address; this Company connects there only when configured to (COMPANY_DEV_CLIENTS=1)") class ClientDirectory: """Fetches and caches a Personal Agent's client metadata document and key set (spec 4.1, 5.3 step 1; the guides, "Fetching metadata safely"): no redirects, a size limit, a timeout, no credentials, HTTPS and public addresses unless `dev` allows loopback for local development. `transport` is for tests (an `httpx.MockTransport`).""" def __init__(self, *, dev: bool = False, transport=None, ttl: int = METADATA_TTL): self.dev, self.transport, self.ttl = dev, transport, ttl self._cache: dict[str, tuple[float, dict]] = {} self._lock = threading.Lock() def fetch_json(self, url: str, what: str) -> dict: check_url(url, dev=self.dev, what=what) with self._lock: hit = self._cache.get(url) if hit and hit[0] > time.time(): return hit[1] import httpx # the site extra; the Company runs with it try: with httpx.Client(transport=self.transport, follow_redirects=False, timeout=5.0, headers={"accept": "application/json", "user-agent": "forgetproof-company/0.2 (Poppy 1.0 resource)"}) as c: r = c.get(url) except httpx.HTTPError as e: raise PoppyError(400, "invalid_session", f"{what} could not be fetched: {type(e).__name__}") from None if r.status_code != 200: raise PoppyError(400, "invalid_session", f"{what} answered HTTP {r.status_code} (redirects are not followed)") if len(r.content) > METADATA_MAX_BYTES: raise PoppyError(400, "invalid_session", f"{what} is larger than {METADATA_MAX_BYTES} bytes") try: doc = r.json() except ValueError: raise PoppyError(400, "invalid_session", f"{what} is not JSON") from None if not isinstance(doc, dict): raise PoppyError(400, "invalid_session", f"{what} is not a JSON object") with self._lock: self._cache[url] = (time.time() + self.ttl, doc) return doc def client(self, client_id: str) -> tuple[dict, list[dict]]: """(metadata, keys) for a client_id: the document's client_id must equal the URL it was fetched from, and jwks_uri must be on the same domain (spec 4.1).""" meta = self.fetch_json(client_id, "the client metadata document at iss") if meta.get("client_id") != client_id: raise PoppyError(400, "invalid_session", "the client metadata document's client_id is not the URL it was fetched from") if meta.get("token_endpoint_auth_method") != "private_key_jwt": raise PoppyError(400, "invalid_session", "the client metadata document must declare private_key_jwt") jwks_uri = meta.get("jwks_uri") if not isinstance(jwks_uri, str) or urlsplit(jwks_uri).netloc.lower() != urlsplit(client_id).netloc.lower(): raise PoppyError(400, "invalid_session", "jwks_uri must be an https URL on the same domain as client_id") jwks = self.fetch_json(jwks_uri, "the key set at jwks_uri") keys = [k for k in jwks.get("keys", []) if isinstance(k, dict)] if isinstance(jwks.get("keys"), list) else [] if not keys: raise PoppyError(400, "invalid_session", "the key set at jwks_uri has no keys") return meta, keys def key(self, client_id: str, kid: str) -> dict: _, keys = self.client(client_id) for k in keys: if k.get("kid") == kid: return k raise PoppyError(400, "invalid_session", "no key in the agent's jwks_uri has the kid the token names") def forget(self, url: str | None = None) -> None: with self._lock: if url is None: self._cache.clear() else: self._cache.pop(url, None) class ReplayCache: """`jti` values seen inside a window (spec 5.3, "Replayed JWTs": a Company MAY reject a reused jti). In memory, for this one process; the guides say to share it across servers when there are several.""" def __init__(self): self._seen: dict[str, float] = {} self._lock = threading.Lock() def seen_before(self, key: str, until: float) -> bool: now = time.time() with self._lock: for k, exp in [(k, e) for k, e in self._seen.items() if e < now]: self._seen.pop(k, None) if key in self._seen: return True self._seen[key] = until return False # --- the Session header (spec 5.2, 5.3) ------------------------------------------------------------------------------ @dataclass class SessionClaims: client_id: str sid: str sub: str agent_id: str | None client_name: str jti: str iat: int delegation_hash: str class SessionVerifier: """Verifies `Poppy-Session` for one Company identifier (its issuer). The checks, in the order of spec 5.2 (Delegated keys) and 5.3: fetch the agent's metadata and keys; verify the delegation's signature with the `jwks_uri` key its `kid` names, its typ, iss, expiry and 24-hour bound; verify the Session JWT with `cnf.jwk` and its `kid` against that key's thumbprint; then typ, aud, htm, htu, iat, and ath.""" def __init__(self, identifier: str, directory: ClientDirectory, *, window: int = IAT_WINDOW, skew: int = CLOCK_SKEW): self.identifier, self.directory, self.window, self.skew = identifier, directory, window, skew self.replays = ReplayCache() self._delegations: dict[str, tuple[dict, int, str]] = {} # sha256(compact) -> (cnf.jwk, exp, iss) self._lock = threading.Lock() def _delegation(self, compact: str, iss: str, now: int) -> tuple[dict, int]: h = hashlib.sha256(compact.encode("ascii", "replace")).hexdigest() with self._lock: hit = self._delegations.get(h) if hit and hit[1] > now and hit[2] == iss: return hit[0], hit[1] try: header, payload, signing_input, signature = split_jws(compact) except (ValueError, TypeError): raise PoppyError(400, "invalid_session", "poppy_dlg is not a compact JWS") from None if header.get("typ") != DELEGATION_TYP: raise PoppyError(400, "invalid_session", f"the delegation's typ must be {DELEGATION_TYP}") alg = header.get("alg") if alg not in ("ES256", "PS384"): raise PoppyError(400, "invalid_session", "the delegation must be signed with ES256 or PS384") kid = header.get("kid") if not isinstance(kid, str) or not kid: raise PoppyError(400, "invalid_session", "the delegation names no kid") jwk = self.directory.key(iss, kid) # step 1 of 5.3: the agent's documents, under the address rules try: verify_jws_signature(alg, public_key_from_jwk(jwk), signing_input, signature) except (ValueError, KeyError, TypeError) as e: raise PoppyError(400, "invalid_session", f"the delegation's signature does not verify with the key its kid names ({e})") from None if payload.get("iss") != iss: raise PoppyError(400, "invalid_session", "the delegation's iss is not the Session JWT's iss") iat, exp = payload.get("iat"), payload.get("exp") if not isinstance(iat, int) or not isinstance(exp, int) or isinstance(iat, bool) or isinstance(exp, bool): raise PoppyError(400, "invalid_session", "the delegation needs integer iat and exp") if exp <= now - self.skew: raise PoppyError(400, "invalid_session", "the delegation has expired") if exp - iat > DELEGATION_MAX_SECONDS: raise PoppyError(400, "invalid_session", "a delegation lasts at most 24 hours") if any(k in payload for k in ("sub", "aud", "agent_id")): raise PoppyError(400, "invalid_session", "a delegation names no User, Agent or Company") cnf = payload.get("cnf", {}).get("jwk") if isinstance(payload.get("cnf"), dict) else None if not isinstance(cnf, dict) or not isinstance(payload.get("jti"), str): raise PoppyError(400, "invalid_session", "the delegation needs cnf.jwk and a jti") with self._lock: self._delegations[h] = (cnf, exp, iss) return cnf, exp def verify(self, headers, method: str, url: str, access_token: str | None, *, now: int | None = None) -> SessionClaims: now = int(now or time.time()) raw = headers.get("poppy-session") if not raw: raise PoppyError(400, "invalid_session", "the request carries no Poppy-Session header, and this route uses Session claims (spec 5.3)") try: header, payload, signing_input, signature = split_jws(raw) except (ValueError, TypeError): raise PoppyError(400, "invalid_session", "Poppy-Session is not a compact JWS") from None if header.get("typ") != SESSION_TYP: raise PoppyError(400, "invalid_session", f"the Session JWT's typ must be {SESSION_TYP}") if header.get("alg") != "ES256": raise PoppyError(400, "invalid_session", "the Session JWT must be signed with ES256") iss = payload.get("iss") if not isinstance(iss, str) or not iss: raise PoppyError(400, "invalid_session", "the Session JWT names no iss (the agent's client_id)") dlg = header.get("poppy_dlg") if not isinstance(dlg, str) or not dlg: raise PoppyError(400, "invalid_session", "a Session JWT without a delegation is rejected, including one signed with a jwks_uri key (spec 5.2)") cnf, dlg_exp = self._delegation(dlg, iss, now) try: if header.get("kid") != thumbprint(cnf): raise ValueError("kid is not the thumbprint of the delegated key") verify_jws_signature("ES256", public_key_from_jwk(cnf), signing_input, signature) except (ValueError, KeyError, TypeError) as e: raise PoppyError(400, "invalid_session", f"the Session JWT does not verify with the delegated key ({e})") from None # claims (spec 5.2, 5.3 step 2) if payload.get("aud") != self.identifier: raise PoppyError(400, "invalid_session", "aud is not this Company's identifier (compared character for character)") sid, sub, jti = payload.get("sid"), payload.get("sub"), payload.get("jti") if not isinstance(sid, str) or not ID_CHARS.match(sid) or len(sid) < 16: raise PoppyError(400, "invalid_session", "sid must be a random id in the URL-safe base64 alphabet") if not isinstance(sub, str) or not sub or len(sub) > 256: raise PoppyError(400, "invalid_session", "sub (the User ID) is missing") agent_id = payload.get("agent_id") if agent_id is not None and (not isinstance(agent_id, str) or not agent_id): raise PoppyError(400, "invalid_session", "agent_id, when present, is a non-empty string") if payload.get("htm") != method.upper(): raise PoppyError(400, "invalid_session", "htm is not the request's method") p = urlsplit(url) expected_htu = f"{p.scheme.lower()}://{p.netloc.lower()}{p.path}" htu = payload.get("htu") hp = urlsplit(htu) if isinstance(htu, str) else None if not hp or hp.query or hp.fragment or f"{hp.scheme.lower()}://{hp.netloc.lower()}{hp.path}" != expected_htu: raise PoppyError(400, "invalid_session", "htu is not the request's URL (scheme, host and path, without query or fragment; RFC 9449 section 4.3)") iat = payload.get("iat") if not isinstance(iat, int) or isinstance(iat, bool) or abs(now - iat) > self.window + self.skew: raise PoppyError(400, "invalid_session", f"iat is outside the acceptance window of {self.window} seconds") if not isinstance(jti, str) or len(jti) < 16: raise PoppyError(400, "invalid_session", "jti is missing or too short to be unguessable") ath = payload.get("ath") if access_token: if ath != b64url(hashlib.sha256(access_token.encode("ascii", "replace")).digest()): raise PoppyError(400, "invalid_session", "ath does not match the access token the request carries") elif ath is not None: raise PoppyError(400, "invalid_session", "ath must be absent when the request carries no access token") if self.replays.seen_before(f"session:{jti}", now + self.window + self.skew): raise PoppyError(400, "invalid_session", "this Session JWT was presented before (jti reused)") meta, _ = self.directory.client(iss) return SessionClaims(iss, sid, sub, agent_id, str(meta.get("client_name") or iss), jti, iat, hashlib.sha256(dlg.encode("ascii", "replace")).hexdigest()) # --- client assertions at the token endpoint (spec 4.1, RFC 7523) ------------------------------------------------- def verify_client_assertion(self, compact: str, *, now: int | None = None) -> str: """Returns the client_id. Refusals are `invalid_client` (RFC 6749 section 5.2).""" now = int(now or time.time()) try: header, payload, signing_input, signature = split_jws(compact) except (ValueError, TypeError): raise PoppyError(400, "invalid_client", "client_assertion is not a compact JWS") from None alg = header.get("alg") if alg not in ("ES256", "PS384"): raise PoppyError(400, "invalid_client", "client assertions are accepted with ES256 and PS384") if header.get("typ") in (SESSION_TYP, DELEGATION_TYP): raise PoppyError(400, "invalid_client", "a Session JWT or a delegation is not a client assertion") cid = payload.get("iss") if not isinstance(cid, str) or not cid or payload.get("sub") != cid: raise PoppyError(400, "invalid_client", "a client assertion's iss and sub are both the client_id") if payload.get("aud") != self.identifier: raise PoppyError(400, "invalid_client", "aud must be this issuer, as a single string; an endpoint URL is refused (spec 4.1)") iat, exp, jti = payload.get("iat"), payload.get("exp"), payload.get("jti") if not isinstance(iat, int) or not isinstance(exp, int) or isinstance(iat, bool) or isinstance(exp, bool): raise PoppyError(400, "invalid_client", "a client assertion needs integer iat and exp") if exp - iat > ASSERTION_MAX_SECONDS: raise PoppyError(400, "invalid_client", "a client assertion lasts at most five minutes") if exp <= now - self.skew or iat > now + self.skew: raise PoppyError(400, "invalid_client", "the client assertion has expired or is not yet valid") if not isinstance(jti, str) or len(jti) < 16: raise PoppyError(400, "invalid_client", "a client assertion needs an unguessable jti") kid = header.get("kid") if not isinstance(kid, str): raise PoppyError(400, "invalid_client", "the client assertion names no kid") try: check_url(cid, dev=self.directory.dev, what="client_id") jwk = self.directory.key(cid, kid) verify_jws_signature(alg, public_key_from_jwk(jwk), signing_input, signature) except PoppyError as e: raise PoppyError(400, "invalid_client", e.description) from None except (ValueError, KeyError, TypeError) as e: raise PoppyError(400, "invalid_client", f"the client assertion's signature does not verify ({e})") from None if self.replays.seen_before(f"assertion:{cid}:{jti}", exp + self.skew): raise PoppyError(400, "invalid_client", "this client assertion was presented before (jti reused)") return cid # --- the Operations extension, version 3: the approval header ------------------------------------------------------- def parse_approval(value: str | None) -> dict | None: """`Poppy-Approval` (Operations 6, APIs): a Dictionary with operation_id, revision, approver, input_type and reference as Strings and approved_at as an Integer. Unknown members are ignored. None when absent; a header that is present but unusable is `invalid_request` (HTTP 400), the code Operations 4 uses for an unusable reference, so the agent sees its mistake instead of an approval_required loop.""" if value is None: return None d = parse_sf_dictionary(value) if d is None: raise PoppyError(400, "invalid_request", "Poppy-Approval is not an RFC 9651 Dictionary") out: dict = {} for k in ("operation_id", "revision", "approver", "input_type", "reference"): if k in d: v = d[k][0] if not isinstance(v, str) or isinstance(v, Token): raise PoppyError(400, "invalid_request", f"Poppy-Approval member {k} must be a String") out[k] = v if "approved_at" in d: v = d["approved_at"][0] if not isinstance(v, int) or isinstance(v, bool): raise PoppyError(400, "invalid_request", "Poppy-Approval member approved_at must be an Integer (Unix seconds)") out["approved_at"] = v for k in ("operation_id", "revision", "approver"): if k not in out: raise PoppyError(400, "invalid_request", f"Poppy-Approval needs {k}") if out["approver"] not in ("user", "agent"): raise PoppyError(400, "invalid_request", "approver is user or agent") if out["approver"] == "agent": out.pop("input_type", None) # a Company ignores input_type with agent (Operations 6) for k in ("operation_id", "revision", "reference"): if k in out and not ID_CHARS.match(out[k]): raise PoppyError(400, "invalid_request", f"Poppy-Approval member {k} has characters outside the URL-safe base64 alphabet") return out