"""The reference Company's HTTP surface: Poppy discovery (poppy.json and the two OAuth metadata documents), the synthetic issuer's token and revocation endpoints, the ForgetMe v1 routes, the Company's own small API (what an agent uses when it shares an address, what the courier reads), and the labelled fixture routes the demo uses to create synthetic accounts. Starlette, pure ASGI otherwise; its own process and origin. python -m company # http://localhost:8090 COMPANY_DATA=/data/company # where the key and the SQLite files live COMPANY_ORIGIN=https://company.… # the public origin for absolute URLs and the Company's identifier; else RAILWAY_PUBLIC_DOMAIN; else the request's host COMPANY_DEV_CLIENTS=1 # accept http:// and loopback client_ids (a Pim on localhost): development and tests only Every route under /forget-me/v1 except the index, and every /api route, is a Poppy resource (spec 5, 7): it verifies the Session header, the declaration headers and the access token before it reads a body, and the body never says who. """ from __future__ import annotations import contextlib import json import os import sys import time from collections import deque from pathlib import Path from urllib.parse import parse_qs from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.routing import Route from forgetproof import __version__, forgetme if __package__: from . import poppy from .core import ENDPOINT_PATH, FORGET_ME_SCOPE, Caller, Company, ContractError else: # pragma: no cover - `python company/app.py` sys.path.insert(0, str(Path(__file__).parent)) import poppy # type: ignore from core import ENDPOINT_PATH, FORGET_ME_SCOPE, Caller, Company, ContractError # type: ignore HERE = Path(__file__).parent DATA = Path(os.environ.get("COMPANY_DATA") or HERE / "data") # Pim opens one synthetic account per scenario, all from the site's address: the per-visitor limit must sit above the # site's own scenario rate; the live-account cap (COMPANY_MAX_ACCOUNTS) and the TTL bound what anyone can create. PER_IP = int(os.environ.get("COMPANY_ACCOUNTS_PER_IP", "40")) WINDOW = 600 READ_SCOPES = (FORGET_ME_SCOPE["item"], FORGET_ME_SCOPE["account"]) # either reads an operation the account owns NO_STORE = {"cache-control": "no-store"} company = Company(DATA) _per_ip: dict[str, deque] = {} def origin_of(request: Request) -> str: env = os.environ.get("COMPANY_ORIGIN") if env: return env.rstrip("/") dom = os.environ.get("RAILWAY_PUBLIC_DOMAIN") if dom: return f"https://{dom}" proto = request.headers.get("x-forwarded-proto", request.url.scheme) host = request.headers.get("x-forwarded-host", request.headers.get("host", request.url.netloc)) return f"{proto}://{host}" def _error(e: ContractError | poppy.PoppyError) -> Response: headers = {**NO_STORE} if isinstance(e, poppy.PoppyError): headers.update(e.headers) body = e.body() if e.code else {"error_description": e.description, **e.extra} # a 401 challenge has no error code (spec 7) else: body = e.body() if "retry_after" in e.extra: headers["retry-after"] = str(e.extra["retry_after"]) return JSONResponse(body, status_code=e.status, headers=headers) def _credential(request: Request) -> str | None: auth = request.headers.get("authorization", "") return auth[7:].strip() if auth.startswith("Bearer ") and auth[7:].strip() else None def _caller(request: Request, *, scopes: tuple[str, ...] | None) -> Caller: """The Poppy checks every resource makes before it believes a request (spec 5.3, 3.4, 7), in this order: the Session header (identity: the agent and its User ID), the declaration headers (version, extensions), the access token (the account and its scopes, issued to that same agent), the Session record (continuity), then the scopes the route needs: no token is a 401 challenge naming them, too little is `insufficient_scope`.""" origin = origin_of(request) token = _credential(request) claims = company.verifier(origin).verify(request.headers, request.method, origin + request.url.path, token) neg = poppy.negotiate(request.headers) if not neg.compatible: raise poppy.PoppyError(400, "version_unsupported", f"Poppy-Version is missing or not compatible with {poppy.PROTOCOL_VERSION}, the version this Company serves (spec 3.4)") account, tscopes = None, () if token: account, client_id, tscopes = company.authenticate_token(token) if client_id != claims.client_id: raise poppy.PoppyError(401, "invalid_token", "the access token was issued to another client than the Session JWT's iss (spec 5.3)", headers={"www-authenticate": 'Bearer error="invalid_token", error_description="issued to another client"'}) company.touch_session(claims, neg, account) if scopes is not None: if not token: raise poppy.PoppyError(401, "", f"this route needs the account: an access token with scope {scopes[0]} (spec 7)", headers={"www-authenticate": f'Bearer scope="{scopes[0]}"'}) if not any(s in tscopes for s in scopes): raise poppy.PoppyError(403, "insufficient_scope", f"the access token lacks the scope this route needs: {scopes[0]}", headers={"www-authenticate": f'Bearer error="insufficient_scope", scope="{scopes[0]}"'}, scope=scopes[0]) return Caller(claims.client_id, claims.client_name, claims.sid, claims.sub, claims.agent_id, account, tuple(tscopes), neg) async def _json(request: Request) -> dict: raw = await request.body() if len(raw) > forgetme.MAX_BODY_BYTES: raise ContractError(413, "too_large", f"the body exceeds {forgetme.MAX_BODY_BYTES} bytes") try: body = json.loads(raw or b"{}") except ValueError: raise ContractError(400, "bad_request", "the body isn't JSON") from None if not isinstance(body, dict): raise ContractError(400, "bad_request", "the body must be a JSON object") return body def _ok(body, status: int = 200) -> Response: return JSONResponse(body, status_code=status, headers=NO_STORE) # --- discovery (public, no Session header: spec 3, 3.2) -------------------------------------------------------------- async def home(request: Request) -> Response: o = origin_of(request) return HTMLResponse(f""" Bay Parcel · reference Company for ForgetMe v1

Bay Parcel

The reference Company for ForgetMe v1. A fictional courier that holds the delivery addresses a personal agent shared with it, and serves the ForgetMe v1 wire contract on this origin with its own key and its own stores, as a Poppy 1.0 Company: Session header verified, account access by OAuth, destructive execution only through the Operations extension (version 3) with the person's approval of the exact terms. ForgetMe · powered by ForgetProof. A third-party extension proposal targeting Poppy 1.0; not approved, adopted or reviewed by anyone.

Every account here is a synthetic fixture the demo creates for its fictional user and removes after a while. Its issuer is synthetic too: it signs nobody in; the fixture mints the refresh token a sign-in would have produced, for the one personal agent named, and the rest is the protocol. Origin as this Company sees it: {o}.

""") async def health(request: Request) -> Response: return JSONResponse({"ok": True, "service": "forgetme-company", "version": __version__, "accounts": company.live_accounts()}) PUBLIC_HEADERS = {"cache-control": "public, max-age=300", "access-control-allow-origin": "*"} # tenant-neutral: any page may read the keys async def poppy_json(request: Request) -> Response: return JSONResponse(company.poppy(origin_of(request)), headers=PUBLIC_HEADERS) async def protected_resource(request: Request) -> Response: return JSONResponse(company.protected_resource(origin_of(request)), headers=PUBLIC_HEADERS) async def authorization_server(request: Request) -> Response: return JSONResponse(company.authorization_server(origin_of(request)), headers=PUBLIC_HEADERS) async def openapi(request: Request) -> Response: return JSONResponse(company.openapi(origin_of(request)), headers=PUBLIC_HEADERS) async def index(request: Request) -> Response: return JSONResponse(company.index(origin_of(request)), headers=PUBLIC_HEADERS) async def unsupported_version(request: Request) -> Response: return _error(ContractError(404, "unsupported_version", "this Company serves ForgetMe version 1 only", supported=["1"])) # --- the synthetic issuer: token and revocation endpoints (spec 4.4, 4.6; no Session header here) ----------------------- async def _form(request: Request) -> dict[str, str]: raw = await request.body() if len(raw) > 64 * 1024: raise poppy.PoppyError(400, "invalid_request", "the form is too large") return {k: v[-1] for k, v in parse_qs(raw.decode("utf-8", "replace"), keep_blank_values=True).items()} def _client_of(form: dict, origin: str) -> str: if form.get("client_assertion_type") != poppy.CLIENT_ASSERTION_TYPE or not form.get("client_assertion"): raise poppy.PoppyError(400, "invalid_client", "authenticate with private_key_jwt: client_assertion_type and a client_assertion (spec 4.1)") client_id = company.verifier(origin).verify_client_assertion(form["client_assertion"]) if form.get("client_id") and form["client_id"] != client_id: raise poppy.PoppyError(400, "invalid_client", "client_id does not match the assertion") return client_id async def oauth_token(request: Request) -> Response: try: origin = origin_of(request) form = await _form(request) if form.get("grant_type") != "refresh_token": raise poppy.PoppyError(400, "unsupported_grant_type", "this issuer accepts grant_type=refresh_token only: it signs nobody in (the demo's fixture issues " "the refresh token a sign-in would have produced)") client_id = _client_of(form, origin) return _ok(company.refresh_grant(client_id, form.get("refresh_token", ""), form.get("scope") or None, form.get("resource"), origin)) except poppy.PoppyError as e: return _error(e) async def oauth_revoke(request: Request) -> Response: try: origin = origin_of(request) form = await _form(request) client_id = _client_of(form, origin) company.revoke_refresh_token(client_id, form.get("token", "")) return _ok({}) except poppy.PoppyError as e: return _error(e) # --- the contract (Poppy resources) -------------------------------------------------------------------------------- async def preview(request: Request) -> Response: try: caller = _caller(request, scopes=READ_SCOPES) return _ok(company.preview(caller.account, caller.scopes, await _json(request))) except (ContractError, poppy.PoppyError) as e: return _error(e) async def submit(request: Request) -> Response: try: caller = _caller(request, scopes=READ_SCOPES) approval = poppy.parse_approval(request.headers.get("poppy-approval")) code, body = await company.submit(caller, await _json(request), approval, origin_of(request)) return _ok(body, code) except (ContractError, poppy.PoppyError) as e: return _error(e) async def operation(request: Request) -> Response: try: caller = _caller(request, scopes=READ_SCOPES) return _ok(company.status(caller.account, request.path_params["id"], origin_of(request))) except (ContractError, poppy.PoppyError) as e: return _error(e) async def evidence(request: Request) -> Response: try: caller = _caller(request, scopes=READ_SCOPES) return _ok(company.evidence(caller.account, request.path_params["id"], origin_of(request))) except (ContractError, poppy.PoppyError) as e: return _error(e) # --- the Company's own API (Poppy resources, scope addresses) -------------------------------------------------------- async def api_addresses(request: Request) -> Response: try: caller = _caller(request, scopes=("addresses",)) account = caller.account if request.method == "GET": return _ok({"account": account, "addresses": company.addresses(account), "deliveries": company.deliveries(account)}) body = await _json(request) rec = company.add_address(account, body.get("line"), body.get("label", "Delivery address")) rec["forget_me"] = {"reference": rec["reference"], "endpoint": company.endpoint(origin_of(request))} return _ok(rec, 201) except (ContractError, poppy.PoppyError) as e: return _error(e) async def api_deliveries(request: Request) -> Response: try: caller = _caller(request, scopes=("addresses",)) body = await _json(request) if not isinstance(body.get("address"), int): raise ContractError(400, "bad_request", "address must be the id of one of your addresses") parcel = body.get("parcel") or f"BP-{int(time.time()) % 9000 + 1000}" if not isinstance(parcel, str) or len(parcel) > 32: raise ContractError(400, "bad_request", "parcel must be a short string") return _ok(company.add_delivery(caller.account, body["address"], parcel), 201) except (ContractError, poppy.PoppyError) as e: return _error(e) async def api_lookup(request: Request) -> Response: try: caller = _caller(request, scopes=("addresses",)) found = company.lookup(caller.account) return _ok({"account": caller.account, "found": found, "note": "the address the courier would deliver to right now: the first it holds that is not withdrawn"}) except (ContractError, poppy.PoppyError) as e: return _error(e) async def api_restore(request: Request) -> Response: try: caller = _caller(request, scopes=("addresses",)) return _ok(company.restore_address(caller.account, int(request.path_params["id"]))) except (ContractError, poppy.PoppyError) as e: return _error(e) # --- fixtures (labelled; not protocol endpoints, so no Session header) ------------------------------------------------ def _ip(request: Request) -> str: fwd = request.headers.get("x-forwarded-for", "") return fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "?") async def fixture_accounts(request: Request) -> Response: q = _per_ip.setdefault(_ip(request), deque()) cutoff = time.time() - WINDOW while q and q[0] < cutoff: q.popleft() if len(q) >= PER_IP: return _error(ContractError(429, "rate_limited", f"{PER_IP} synthetic accounts every ten minutes per visitor", retry_after=60)) q.append(time.time()) try: body = await _json(request) addresses = body.get("addresses", []) if not isinstance(addresses, list) or len(addresses) > 4 or any(not isinstance(a, dict) for a in addresses): raise ContractError(400, "bad_request", "addresses must be a list of up to four {label, line} objects") busy = body.get("records_busy_seconds", 0) if not isinstance(busy, (int, float)) or not 0 <= busy <= 120: raise ContractError(400, "bad_request", "records_busy_seconds must be between 0 and 120") origin = origin_of(request) out = company.create_account(body.get("name", "Fixture account"), scopes=tuple(body.get("scopes", ["item", "account"])), scenario=str(body.get("scenario", ""))[:64] or None, records_busy_seconds=busy, addresses=addresses, deliveries=min(int(body.get("deliveries", 0)), 5), archive_copy=bool(body.get("archive_copy", False)), neighbour=bool(body.get("neighbour", True)), client_id=body.get("client_id")) out["endpoint"] = company.endpoint(origin) if "grant" in out: out["grant"]["token_endpoint"] = company.authorization_server(origin)["token_endpoint"] out["grant"]["issuer"] = company.identifier(origin) return _ok(out, 201) except ContractError as e: return _error(e) async def fixture_revoke(request: Request) -> Response: """Sign the account out: what a closed account, a disconnected agent or a revoked grant looks like to a queued step. Takes the access token; revokes every refresh token of its account and the access tokens under them.""" token = _credential(request) try: if not token: raise poppy.PoppyError(401, "invalid_token", "send the access token to sign its account out", headers={"www-authenticate": "Bearer"}) account, _, _ = company.authenticate_token(token) return _ok({"revoked": company.sign_out(account) > 0}) except poppy.PoppyError as e: return _error(e) def create_app() -> Starlette: routes = [ Route("/", home), Route("/health", health), Route("/.well-known/poppy.json", poppy_json), Route("/.well-known/oauth-protected-resource", protected_resource), Route("/.well-known/oauth-authorization-server", authorization_server), Route("/openapi.json", openapi), Route("/oauth/token", oauth_token, methods=["POST"]), Route("/oauth/revoke", oauth_revoke, methods=["POST"]), Route(ENDPOINT_PATH, index), Route(f"{ENDPOINT_PATH}/preview", preview, methods=["POST"]), Route(f"{ENDPOINT_PATH}/submit", submit, methods=["POST"]), Route(f"{ENDPOINT_PATH}/operations/{{id}}", operation), Route(f"{ENDPOINT_PATH}/operations/{{id}}/evidence", evidence), Route("/forget-me/v{n:int}/{path:path}", unsupported_version, methods=["GET", "POST"]), Route("/forget-me/v{n:int}", unsupported_version, methods=["GET", "POST"]), Route("/api/addresses", api_addresses, methods=["GET", "POST"]), Route("/api/addresses/{id:int}/restore", api_restore, methods=["POST"]), Route("/api/deliveries", api_deliveries, methods=["POST"]), Route("/api/lookup", api_lookup), Route("/fixture/accounts", fixture_accounts, methods=["POST"]), Route("/fixture/revoke", fixture_revoke, methods=["POST"]), ] return Starlette(routes=routes, middleware=[Middleware(SecurityHeaders)], lifespan=lifespan) @contextlib.asynccontextmanager async def lifespan(app): import asyncio await asyncio.to_thread(company.reconcile) # a restart mid-operation: scan again, never erase again yield class SecurityHeaders: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): if scope["type"] != "http": return await self.app(scope, receive, send) async def send_with_headers(message): if message["type"] == "http.response.start": headers = dict(message.get("headers", [])) for k, v in ((b"x-content-type-options", b"nosniff"), (b"referrer-policy", b"strict-origin-when-cross-origin"), (b"x-frame-options", b"DENY")): headers.setdefault(k, v) message = {**message, "headers": list(headers.items())} await send(message) await self.app(scope, receive, send_with_headers) app = create_app()