"""Bay Parcel, the reference Company: ForgetMe v1 served by a recipient on its own stack. A courier that holds the delivery addresses a personal agent shared with it, delivery summaries derived from them, invoices it must keep for a while, and a legacy export made before it tracked provenance. It speaks ForgetMe v1 (docs/extension.md) on its own origin with its own Ed25519 key and its own SQLite files, and it implements the whole lifecycle itself: references issued when a record is stored, preview, at-most-once submit, stop-retrieval-first, deletion by id, derived items rebuilt from provenance, residue erased and inspected with the engine, one restore attempt refused, portable receipts signed, a queued step that re-checks its authority, reconciliation after a restart. What it takes from ForgetProof: `forget()` and `scan()` for the erase and the inspection of its SQLite files and its export, `receipt` for the key and canonical JSON, and `forgetme` for the portable receipt and the vocabulary. It does not import `forgetproof.agent.Provider`; the contract is implemented here. Everything personal is fictional. Accounts are synthetic fixtures the demo creates per visitor and removes after a while. Who may act on an account is Poppy's job (phase 3): the Company is a Poppy 1.0 resource with its own synthetic OAuth issuer (`company/poppy.py` verifies the Session header, the declaration headers and the client assertions; this module keeps the Sessions, the refresh and access tokens, and the Operations v3 operations and approvals in `company.db`). The one fixture left is the refresh token `POST /fixture/accounts` mints for a named Personal Agent, standing in for the Direct Sign-In a fictional user cannot do; everything after it is the real protocol. """ from __future__ import annotations import asyncio import contextlib import hashlib import json import os import secrets import sqlite3 import threading from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from pathlib import Path from urllib.parse import urlsplit from forgetproof import forget as forget_mod, forgetme, receipt as receipt_mod from forgetproof.scanner import scan from forgetproof.subject import subject as make_subject if __package__: from . import poppy else: # pragma: no cover - `python company/app.py` import poppy # type: ignore NAME = "Bay Parcel" ISSUER = "Bay Parcel (reference Company)" ENDPOINT_PATH = "/forget-me/v1" ACCOUNT_TTL = int(os.environ.get("COMPANY_ACCOUNT_TTL", str(30 * 60))) MAX_ACCOUNTS = int(os.environ.get("COMPANY_MAX_ACCOUNTS", "60")) INVOICE_RETENTION_DAYS = 90 TOKEN_TTL = int(os.environ.get("COMPANY_TOKEN_TTL", "3600")) # access tokens: hours, not days (the guides) APPROVAL_TTL = int(os.environ.get("COMPANY_APPROVAL_TTL", "900")) # Operations 3: at least 15 minutes to read and decide def dev_clients() -> bool: """Accept http:// and loopback client_ids (a Pim on localhost): local development and tests only. Read when a Company is built, so a test process that starts several Companies under different settings gets each one right.""" return os.environ.get("COMPANY_DEV_CLIENTS", "") == "1" # The Company's OAuth scopes (spec 4.7: each Company defines its own). ForgetMe's two request scopes map onto the # first two; the discovery entry says so (`scopes` in the forget-me fragment), and a 401 challenge names them. SCOPES = { "forget-me:item": "Withdraw a record you shared, by the opaque reference Bay Parcel issued for it, and read the evidence", "forget-me:account": "Withdraw everything Bay Parcel holds for your account; granted separately, never implied", "addresses": "See the delivery addresses Bay Parcel holds for you, share one, and book a delivery", } SCOPE_HINTS = {"forget-me:item": {"changes": "irreversible", "personal_data": True}, "forget-me:account": {"changes": "irreversible", "personal_data": True}, "addresses": {"changes": "reversible", "personal_data": True}} FORGET_ME_SCOPE = {"item": "forget-me:item", "account": "forget-me:account"} FIXTURE_SCOPE_ALIASES = {"item": "forget-me:item", "account": "forget-me:account", "addresses": "addresses"} NEIGHBOUR = {"name": "Dana Whitfield", "label": "current tenant"} # fictional: the person now living at a shared address HOLDERS = { "records": ("Bay Parcel's address book and delivery summaries", "sqlite", "the address record, the delivery summaries derived from it, and the free pages of the database"), "invoices": ("Bay Parcel's invoices", "sqlite", "an invoice carries the delivery address and is kept 90 days under tax law"), "archive": ("Bay Parcel's legacy export", "files", "a JSONL export made before provenance tracking; inspected for the exact text only"), } COVERAGE_SCOPE = "your records and their residue; other accounts' live records are outside this statement" ARCHIVE_LIMIT = "the export predates provenance tracking: derived copies in it are found by exact text only, never deleted on a guess" def now_dt() -> datetime: return datetime.now(timezone.utc) def now() -> str: return now_dt().isoformat(timespec="seconds") def _in(seconds: float) -> str: return (now_dt() + timedelta(seconds=seconds)).isoformat(timespec="seconds") def _past(iso: str | None) -> bool: return bool(iso) and datetime.fromisoformat(iso) <= now_dt() def _day(d: datetime) -> str: return f"{d.day} {d:%B %Y}" def _hash(text: str) -> str: return hashlib.sha256(text.encode()).hexdigest() def _terms_hash(terms: dict) -> str: return _hash(json.dumps(terms, sort_keys=True, separators=(",", ":"))) class ContractError(Exception): """An error the contract documents: HTTP status, machine code, human sentence, extra fields.""" def __init__(self, status: int, code: str, description: str, **extra): super().__init__(description) self.status, self.code, self.description, self.extra = status, code, description, extra def body(self) -> dict: return {"error": self.code, "error_description": self.description, **self.extra} @dataclass class Caller: """A verified request, as the routes hand it to the Company: who (the Personal Agent and its User ID, from the verified Session header), on which account with which scopes (from the access token the Company issued to that same agent), and what the request declared (Poppy-Version, Poppy-Extensions). Nothing in here came from the body.""" client_id: str client_name: str sid: str sub: str agent_id: str | None account: str | None scopes: tuple[str, ...] negotiation: poppy.Negotiation = field(default_factory=lambda: poppy.Negotiation("1.0", True)) class Company: """One Company per process; everything durable lives under `data_dir`.""" def __init__(self, data_dir: Path | str, *, name: str = NAME, issuer: str = ISSUER): self.dir = Path(data_dir) self.dir.mkdir(parents=True, exist_ok=True) self.name, self.issuer = name, issuer self.key = receipt_mod.load_or_create_key(self.dir / "signing_key.pem") self.control = self.dir / "company.db" self.records = self.dir / "records.db" self.invoices = self.dir / "invoices.db" self.archive = self.dir / "archive.jsonl" self.receipts_dir = self.dir / "receipts" # the full engine receipts, private to the Company self.receipts_dir.mkdir(exist_ok=True) self.lock = threading.RLock() # one erase at a time on these files self._alock: asyncio.Lock | None = None # Poppy: the agents' documents are fetched under the address rules; one verifier per identifier (normally one) self.directory = poppy.ClientDirectory(dev=dev_clients()) self._verifiers: dict[str, poppy.SessionVerifier] = {} self._init_db() self.sweep() # -- storage ----------------------------------------------------------------------------------------- @contextlib.contextmanager def _conn(self, path: Path): """A connection that commits and closes: the engine rewrites these files, so nothing may hold them open.""" conn = sqlite3.connect(path, timeout=10) conn.execute("pragma secure_delete=off") # the common default; the engine erases what deletes leave conn.row_factory = sqlite3.Row try: yield conn conn.commit() finally: conn.close() def _init_db(self) -> None: with self._conn(self.control) as c: c.executescript(""" create table if not exists accounts (id text primary key, name text, created_at text, expires_at text, busy_until text, scenario text); create table if not exists refresh_tokens (hash text primary key, account text, client_id text, scopes text, issued_at text, revoked_at text); create table if not exists access_tokens (hash text primary key, account text, client_id text, scopes text, refresh_hash text, expires_at text, revoked_at text); create table if not exists sessions (client_id text, sid text, sub text, agent_id text, declaration text, account text, client_name text, started_at text, last_seen text, primary key (client_id, sid, sub)); create table if not exists poppy_ops (operation_id text, revision text, account text, client_id text, sub text, terms_hash text, terms text, summary text, expires_at text, created_at text, performed_op text, approval text, primary key (operation_id, revision)); create table if not exists refs (reference text primary key, account text, record_table text, record_id integer, issued_at text, expires_at text, withdrawn_at text, operation text); create table if not exists ops (id text primary key, account text, body text, state text, updated_at text); create table if not exists idempotency (account text, key_hash text, op text, primary key (account, key_hash)); create table if not exists tombstones (record_key text primary key, account text, withdrawn_at text, cleaned_at text, operation text); create table if not exists portable (id text primary key, op text, holder text, body text); """) with self._conn(self.records) as c: c.executescript(""" create table if not exists addresses (id integer primary key, account text, label text, line text, created_at text, withdrawn_at text); create table if not exists deliveries (id integer primary key, account text, address_id integer, parcel text, summary text, delivered_at text); create table if not exists provenance (derived_table text, derived_id integer, source_table text, source_id integer, how text, primary key (derived_table, derived_id, source_table, source_id)); """) with self._conn(self.invoices) as c: c.executescript(""" create table if not exists invoices (id integer primary key, account text, address_id integer, number text, body text, issued_at text, retain_until text); """) if not self.archive.exists(): # a legacy export: fictional lines, no provenance, never empty (an empty file is no store) self.archive.write_text("".join(json.dumps(e) + "\n" for e in [ {"exported": "2025-12-30T00:00:00+00:00", "account": None, "kind": "note", "text": "export of the 2025 delivery log; addresses were not tagged with their source records"}, {"exported": "2025-12-30T00:00:00+00:00", "account": None, "kind": "delivery", "text": "delivered to 7 Example Court, Oakland CA 94607 (legacy export, no provenance)"}, ]), encoding="utf-8") def alock(self) -> asyncio.Lock: if self._alock is None: self._alock = asyncio.Lock() return self._alock # -- discovery ----------------------------------------------------------------------------------------- def endpoint(self, origin: str) -> str: return origin.rstrip("/") + ENDPOINT_PATH @staticmethod def identifier(origin: str) -> str: """The Company's identifier (spec 3.2): its issuer, which is its own origin here (host lowercase, no trailing slash). Session JWTs and client assertions carry it as `aud`.""" p = urlsplit(origin.rstrip("/")) return f"{p.scheme.lower()}://{p.netloc.lower()}" @staticmethod def domain(origin: str) -> str: """`organization.domain` (spec 3.1): the host that serves poppy.json, with its port when that isn't 443.""" p = urlsplit(origin) host = (p.hostname or "").lower() if p.port and not (p.scheme == "https" and p.port == 443) and not (p.scheme == "http" and p.port == 80): return f"{host}:{p.port}" return host def verifier(self, origin: str) -> poppy.SessionVerifier: ident = self.identifier(origin) v = self._verifiers.get(ident) if v is None: v = self._verifiers[ident] = poppy.SessionVerifier(ident, self.directory) return v def protected_resource(self, origin: str) -> dict: """RFC 9728 metadata at /.well-known/oauth-protected-resource (spec 3.2): `resource` is exactly the domain's origin, `authorization_servers` names the issuer.""" ident = self.identifier(origin) return {"resource": ident, "authorization_servers": [ident], "scopes_supported": list(SCOPES), "bearer_methods_supported": ["header"]} def authorization_server(self, origin: str) -> dict: """RFC 8414 metadata for the issuer (spec 3.2). The issuer is synthetic and labelled: it offers no Direct or Device Sign-In (`grant_types_supported` lists `refresh_token` only), because the only account holder is fictional; the demo's fixture mints the refresh token a real sign-in would have produced, and everything after that is OAuth.""" ident = self.identifier(origin) return {"issuer": ident, "token_endpoint": f"{ident}/oauth/token", "revocation_endpoint": f"{ident}/oauth/revoke", "grant_types_supported": ["refresh_token"], "response_types_supported": [], "token_endpoint_auth_methods_supported": ["private_key_jwt"], "token_endpoint_auth_signing_alg_values_supported": ["ES256", "PS384"], "client_id_metadata_document_supported": True, "scopes_supported": list(SCOPES), "protected_resources": [ident], "fixture": {"note": "a synthetic issuer inside the demo's synthetic deployment: it signs in nobody (no authorization_code or device_code " "grant); the refresh tokens it accepts come from POST /fixture/accounts, which creates throwaway fictional " "accounts. It is not a general identity provider.", "accounts": f"{ident}/fixture/accounts"}} def openapi(self, origin: str) -> dict: """A small OpenAPI 3.1 description of the APIs poppy.json lists (spec 7), with the scopes each needs and which operations can answer approval_required (the guides, Operations).""" ident, ep = self.identifier(origin), self.endpoint(origin) bearer = {"type": "oauth2", "description": "Account access per Poppy 1.0 section 4. Every request also carries the Poppy-Session header (section 5).", "flows": {"clientCredentials": {"tokenUrl": f"{ident}/oauth/token", "scopes": SCOPES}}} def op(summary, scopes, *, approval=False): d = {"summary": summary, "security": [{"poppy": scopes}], "responses": {"200": {"description": "OK"}, "400": {"description": "invalid_session, session_ended, version_unsupported, or a ForgetMe error"}, "401": {"description": "no or invalid access token (WWW-Authenticate)"}, "403": {"description": "insufficient_scope or extension_required"}}} if approval: d["responses"]["403"]["description"] += "; approval_required with the operation, or approval_declined (Operations extension, version 3)" d["responses"]["202"] = {"description": "the approved operation, accepted"} return d return {"openapi": "3.1.0", "info": {"title": f"{self.name}: addresses, deliveries and ForgetMe v1", "version": "1"}, "servers": [{"url": ident}], "components": {"securitySchemes": {"poppy": bearer}}, "paths": {"/api/addresses": {"get": op("The addresses and deliveries held for the account", ["addresses"]), "post": op("Share an address (a reference comes back)", ["addresses"])}, "/api/deliveries": {"post": op("Book a delivery to a held address", ["addresses"])}, "/api/lookup": {"get": op("Where the courier would deliver now", ["addresses"])}, "/api/addresses/{id}/restore": {"post": op("The undo path a withdrawal must defeat", ["addresses"])}, f"{ENDPOINT_PATH}/preview": {"post": op("ForgetMe v1 preview: what a withdrawal would touch; no side effects", ["forget-me:item"])}, f"{ENDPOINT_PATH}/submit": {"post": op("ForgetMe v1 submit: destructive; performed only with an approval of its exact terms", ["forget-me:item"], approval=True)}, f"{ENDPOINT_PATH}/operations/{{id}}": {"get": op("ForgetMe v1 operation status (owner-scoped)", ["forget-me:item"])}, f"{ENDPOINT_PATH}/operations/{{id}}/evidence": {"get": op("ForgetMe v1 evidence: the portable receipts (owner-scoped)", ["forget-me:item"])}}, "x-forget-me": {"index": ep, "contract": "https://github.com/Sharathvc23/forgetproof/blob/main/docs/extension.md"}} def keys(self) -> list[dict]: pub = receipt_mod.public_key_b64(self.key) return [{"public_key": pub, "key_fingerprint": receipt_mod.fingerprint(pub)}] def poppy(self, origin: str) -> dict: """The Company's /.well-known/poppy.json per spec 3.1: protocol_version, organization (domain = the serving host), auth (the issuer is this origin; `disabled` because the Company offers Personal Agents no sign-in type, the fictional account holder cannot sign in; refresh tokens the fixture issued keep working, spec 3.2), the APIs, and `extensions`: this extension's fragment, with the scope names it needs, and `operations` version 3, which is how destructive execution is approved here (Operations 2).""" ident = self.identifier(origin) fragment = forgetme.discovery_fragment(self.endpoint(origin)) fragment["extensions"][forgetme.NAMESPACE][0]["scopes"] = dict(FORGET_ME_SCOPE) return { "protocol_version": poppy.PROTOCOL_VERSION, "organization": {"name": self.name, "domain": self.domain(origin)}, "auth": {"issuer": ident, "disabled": True, "scopes": dict(SCOPES), "scope_hints": {k: dict(v) for k, v in SCOPE_HINTS.items()}}, "apis": [{"type": "openapi", "url": f"{ident}/openapi.json", "description": "Addresses, deliveries, and ForgetMe v1 withdrawals with their evidence"}], "extensions": {**fragment["extensions"], "operations": [{"version": "3"}]}, "description": "Reference Company for ForgetMe v1: a fictional courier. Synthetic accounts only; ForgetMe is a third-party extension proposal, not approved by anyone.", } def index(self, origin: str) -> dict: ep = self.endpoint(origin) return { "namespace": forgetme.NAMESPACE, "version": forgetme.VERSION, "issuer": self.issuer, "keys": self.keys(), "routes": forgetme.routes(ep), "scopes": list(forgetme.SCOPES), "evidence_format": forgetme.RECEIPT_FORMAT, "status": forgetme.STATUS + "; this is the reference Company of the forgetproof demo, with synthetic accounts", "limits": {"max_body_bytes": forgetme.MAX_BODY_BYTES, "idempotency_key": list(forgetme.IDEMPOTENCY_KEY), "poll_interval_ms": 1000}, "well_known": {"poppy": origin.rstrip("/") + "/.well-known/poppy.json"}, "approval": {"extension": "operations", "version": "3", "approver": "user", "note": "submit is performed only with a Poppy-Approval of its exact terms, given by the person (agent approvals are declined)"}, "identity": {"protocol": "poppy", "version": poppy.PROTOCOL_VERSION, "issuer": self.identifier(origin), "oauth_scopes": dict(FORGET_ME_SCOPE)}, "fixture": {"accounts": origin.rstrip("/") + "/fixture/accounts", "note": "synthetic accounts for the demo, each with a refresh token minted for the Personal Agent the request names: a labelled " "fixture standing in for a sign-in the fictional user cannot do; not a sign-up and not an identity provider"}, } # -- accounts and credentials (fixtures) ------------------------------------------------------------------ def sweep(self) -> int: """Remove expired accounts with everything they hold. Called on start and on every account creation.""" gone = 0 with self.lock, self._conn(self.control) as c: for row in c.execute("select id from accounts where expires_at <= ?", (now(),)).fetchall(): self._remove_account(row["id"]) gone += 1 c.execute("delete from poppy_ops where performed_op is null and expires_at <= ?", (_in(-86400),)) c.execute("delete from access_tokens where expires_at <= ?", (_in(-86400),)) return gone def _remove_account(self, account: str) -> None: with self._conn(self.control) as c: for table in ("refresh_tokens", "access_tokens", "refs", "ops", "idempotency", "tombstones", "poppy_ops"): c.execute(f"delete from {table} where account = ?", (account,)) c.execute("delete from portable where op not in (select id from ops)") c.execute("delete from accounts where id = ?", (account,)) with self._conn(self.records) as c: ids = [r["id"] for r in c.execute("select id from addresses where account = ?", (account,)).fetchall()] dids = [r["id"] for r in c.execute("select id from deliveries where account = ?", (account,)).fetchall()] for i in dids: c.execute("delete from provenance where derived_table = 'deliveries' and derived_id = ?", (i,)) for i in ids: c.execute("delete from provenance where source_table = 'addresses' and source_id = ?", (i,)) c.execute("delete from deliveries where account = ?", (account,)) c.execute("delete from addresses where account = ?", (account,)) with self._conn(self.invoices) as c: c.execute("delete from invoices where account = ?", (account,)) lines = [ln for ln in self.archive.read_text(encoding="utf-8").splitlines() if ln and json.loads(ln).get("account") != account] self.archive.write_text("".join(ln + "\n" for ln in lines), encoding="utf-8") def live_accounts(self) -> int: with self._conn(self.control) as c: return c.execute("select count(*) from accounts").fetchone()[0] @staticmethod def oauth_scopes(scopes) -> tuple[str, ...]: """The fixture's `scopes` option as OAuth scopes: `item`/`account` are aliases of the forget-me scopes; `addresses` (the Company's own API) always comes along, as a real account would have it.""" out: list[str] = [] for s_ in scopes: name = FIXTURE_SCOPE_ALIASES.get(s_, s_) if name in SCOPES and name not in out: out.append(name) if "addresses" not in out: out.append("addresses") return tuple(out) def create_account(self, name: str, *, scopes=("item", "account"), scenario: str | None = None, records_busy_seconds: float = 0, addresses: list[dict] | None = None, deliveries: int = 0, archive_copy: bool = False, neighbour: bool = True, client_id: str | None = None) -> dict: """A synthetic account, optionally seeded. With `client_id`, a refresh token is minted for that Personal Agent (spec 4.4): the labelled stand-in for the Direct Sign-In a fictional user cannot do. It is usable only with that agent's own key, through the token endpoint. Returned once.""" self.sweep() if self.live_accounts() >= MAX_ACCOUNTS: raise ContractError(429, "busy", f"{MAX_ACCOUNTS} synthetic accounts are live right now; try again in a few minutes", retry_after=60) if not isinstance(name, str) or not 1 <= len(name) <= 80: raise ContractError(400, "bad_request", "name must be a short string") if client_id is not None and (not isinstance(client_id, str) or not client_id.startswith(("https://", "http://")) or len(client_id) > 512): raise ContractError(400, "bad_request", "client_id must be the HTTPS URL of a Personal Agent's client metadata document") granted = self.oauth_scopes(scopes) account = "acct_" + secrets.token_hex(6) with self.lock, self._conn(self.control) as c: c.execute("insert into accounts values (?,?,?,?,?,?)", (account, name, now(), _in(ACCOUNT_TTL), _in(records_busy_seconds) if records_busy_seconds else None, scenario)) out = {"account": account, "name": name, "scopes": list(granted), "expires_at": _in(ACCOUNT_TTL), "label": "synthetic account issued by the reference Company for the demo; not a sign-up", "addresses": []} if client_id: out["grant"] = {"refresh_token": self.issue_refresh_token(account, client_id, granted), "client_id": client_id, "scope": " ".join(granted), "token_type_hint": "refresh_token", "label": "a refresh token minted by the demo's synthetic issuer for this Personal Agent, as if the fictional user had completed " "Direct Sign-In and approved these scopes; a labelled fixture, usable only with that agent's key (private_key_jwt)"} for a in addresses or []: rec = self.add_address(account, a.get("line", ""), a.get("label", "Delivery address")) for i in range(int(deliveries)): self.add_delivery(account, rec["id"], f"BP-{secrets.randbelow(9000) + 1000}") if archive_copy: self._append_archive({"exported": "2025-12-30T00:00:00+00:00", "account": account, "kind": "delivery", "text": f"delivered to {a.get('line', '')} (legacy export, no provenance)"}) if neighbour: # the person who lives there now: a different account, the same address line other = "acct_" + secrets.token_hex(6) with self._conn(self.control) as c: c.execute("insert into accounts values (?,?,?,?,?,?)", (other, NEIGHBOUR["name"], now(), _in(ACCOUNT_TTL), None, scenario)) self.add_address(other, a.get("line", ""), f"Home ({NEIGHBOUR['label']})") out["addresses"].append(rec) return out # -- OAuth: refresh and access tokens (spec 4.4, 4.5, 4.6, 4.7) ------------------------------------------------------ def issue_refresh_token(self, account: str, client_id: str, scopes: tuple[str, ...]) -> str: token = "prt_" + secrets.token_urlsafe(32) with self._conn(self.control) as c: c.execute("insert into refresh_tokens values (?,?,?,?,?,?)", (_hash(token), account, client_id, ",".join(scopes), now(), None)) return token def refresh_grant(self, client_id: str, refresh_token: str, scope: str | None, resource: str | None, origin: str) -> dict: """grant_type=refresh_token with a verified client assertion (spec 4.4): the token must have been issued to this client_id and be live; `scope` may narrow it (invalid_scope otherwise); `resource`, when given, must be this Company's one resource (invalid_target otherwise). Access tokens are opaque, stored hashed, bound to the client.""" with self._conn(self.control) as c: row = c.execute("select r.*, a.expires_at as account_expires from refresh_tokens r join accounts a on a.id = r.account where r.hash = ?", (_hash(refresh_token or ""),)).fetchone() if not row or row["revoked_at"] or row["client_id"] != client_id or _past(row["account_expires"]): raise poppy.PoppyError(400, "invalid_grant", "the refresh token is unknown, revoked, expired, or was issued to another client") have = row["scopes"].split(",") if scope: wanted = scope.split() if not wanted or any(w not in have for w in wanted): raise poppy.PoppyError(400, "invalid_scope", "scope must be a subset of the scopes the refresh token was issued with") granted = [h for h in have if h in wanted] else: granted = have if resource is not None and resource != self.identifier(origin): raise poppy.PoppyError(400, "invalid_target", f"this Company serves one resource, {self.identifier(origin)}") token = "pat_" + secrets.token_urlsafe(32) with self._conn(self.control) as c: c.execute("insert into access_tokens values (?,?,?,?,?,?,?)", (_hash(token), row["account"], client_id, ",".join(granted), row["hash"], _in(TOKEN_TTL), None)) return {"access_token": token, "token_type": "Bearer", "expires_in": TOKEN_TTL, "refresh_token": refresh_token, "scope": " ".join(granted)} def revoke_refresh_token(self, client_id: str, token: str) -> None: """RFC 7009: success whether or not the token exists; only the client it was issued to can revoke it. The access tokens issued under it go with it (the guides: sign-out takes effect at once).""" with self._conn(self.control) as c: h = _hash(token or "") c.execute("update refresh_tokens set revoked_at = ? where hash = ? and client_id = ? and revoked_at is null", (now(), h, client_id)) c.execute("update access_tokens set revoked_at = ? where refresh_hash = ? and revoked_at is null", (now(), h)) def sign_out(self, account: str) -> int: """Every refresh token of the account, with its access tokens (the fixture's "the user disconnected the agent").""" with self._conn(self.control) as c: n = c.execute("update refresh_tokens set revoked_at = ? where account = ? and revoked_at is null", (now(), account)).rowcount c.execute("update access_tokens set revoked_at = ? where account = ? and revoked_at is null", (now(), account)) return n def authenticate_token(self, token: str) -> tuple[str, str, tuple[str, ...]]: """(account, client_id, scopes) for a live access token; else `invalid_token` (section 7).""" with self._conn(self.control) as c: row = c.execute("select t.*, a.expires_at as account_expires from access_tokens t join accounts a on a.id = t.account where t.hash = ?", (_hash(token),)).fetchone() if not row or row["revoked_at"] or _past(row["expires_at"]) or _past(row["account_expires"]): raise poppy.PoppyError(401, "invalid_token", "the access token is expired, revoked or unknown", headers={"www-authenticate": 'Bearer error="invalid_token", error_description="expired, revoked or unknown"'}) return row["account"], row["client_id"], tuple(row["scopes"].split(",")) # -- Sessions (spec 5.3 step 4, 5.4, 3.4) ---------------------------------------------------------------------------- def touch_session(self, claims: poppy.SessionClaims, neg: poppy.Negotiation, account: str | None) -> None: """Look the Session up by (client_id, sid, sub): an unknown combination starts a signed-out Session, a known one continues (spec 5.3). Then two rules this Company enforces: the declaration headers are identical for the life of a Session (spec 3.4 puts the MUST on the agent; a change here is `invalid_session`, so an operation offered under one declaration is never approved under another), and one account per Session (spec 5.4: a token for another account than the Session used before is `session_ended`).""" key = neg.key() with self.lock, self._conn(self.control) as c: row = c.execute("select * from sessions where client_id = ? and sid = ? and sub = ?", (claims.client_id, claims.sid, claims.sub)).fetchone() if row is None: c.execute("insert into sessions values (?,?,?,?,?,?,?,?,?)", (claims.client_id, claims.sid, claims.sub, claims.agent_id, key, account, claims.client_name, now(), now())) return if row["declaration"] != key: raise poppy.PoppyError(400, "invalid_session", "Poppy-Version and Poppy-Extensions must be the same on every request in a Session (spec 3.4); " "start a new Session to change them") if (row["agent_id"] or None) != claims.agent_id: raise poppy.PoppyError(400, "invalid_session", "agent_id changed within the Session (spec 5.2)") if account and row["account"] and row["account"] != account: raise poppy.PoppyError(400, "session_ended", "this Session was signed in to another account before; start a new Session for this one (spec 5.4)") c.execute("update sessions set last_seen = ?, account = ? where client_id = ? and sid = ? and sub = ?", (now(), account or row["account"], claims.client_id, claims.sid, claims.sub)) def session_count(self) -> int: with self._conn(self.control) as c: return c.execute("select count(*) from sessions").fetchone()[0] def account_name(self, account: str) -> str | None: with self._conn(self.control) as c: row = c.execute("select name from accounts where id = ?", (account,)).fetchone() return row["name"] if row else None # -- the Company's own API: what a personal agent uses when it shares, and what the courier reads ------- def _issue_reference(self, account: str, table: str, record_id: int) -> str: ref = "fmr_" + secrets.token_urlsafe(18) with self._conn(self.control) as c: exp = c.execute("select expires_at from accounts where id = ?", (account,)).fetchone()["expires_at"] c.execute("insert into refs values (?,?,?,?,?,?,?,?)", (ref, account, table, record_id, now(), exp, None, None)) return ref def add_address(self, account: str, line: str, label: str) -> dict: if not isinstance(line, str) or not 1 <= len(line) <= 200 or not isinstance(label, str) or not 1 <= len(label) <= 80: raise ContractError(400, "bad_request", "line and label must be short strings") with self.lock, self._conn(self.records) as c: cur = c.execute("insert into addresses (account, label, line, created_at, withdrawn_at) values (?,?,?,?,?)", (account, label, line, now(), None)) rid = cur.lastrowid ref = self._issue_reference(account, "addresses", rid) return {"id": rid, "label": label, "line": line, "reference": ref, "created_at": now(), "forget_me": {"reference": ref, "endpoint_path": ENDPOINT_PATH}} def add_delivery(self, account: str, address_id: int, parcel: str) -> dict: """A delivery to an address: the summary is a derived item, linked by provenance; the invoice is another, kept under a disclosed retention.""" with self.lock, self._conn(self.records) as c: addr = c.execute("select * from addresses where id = ? and account = ? and withdrawn_at is null", (address_id, account)).fetchone() if not addr: raise ContractError(404, "unknown_record", "no such address for this account") summary = f"Parcel {parcel} delivered to {addr['line']}; left at the door." cur = c.execute("insert into deliveries (account, address_id, parcel, summary, delivered_at) values (?,?,?,?,?)", (account, address_id, parcel, summary, now())) did = cur.lastrowid c.execute("insert or ignore into provenance values (?,?,?,?,?)", ("deliveries", did, "addresses", address_id, "summary")) number = f"BP-{now_dt():%Y}-{did:04d}" with self._conn(self.invoices) as c: c.execute("insert into invoices (account, address_id, number, body, issued_at, retain_until) values (?,?,?,?,?,?)", (account, address_id, number, f"Invoice {number}: delivery of parcel {parcel} to {addr['line']}.", now(), _in(INVOICE_RETENTION_DAYS * 86400))) return {"id": did, "parcel": parcel, "summary": summary, "invoice": number} def addresses(self, account: str) -> list[dict]: with self._conn(self.records) as c: rows = c.execute("select * from addresses where account = ? and withdrawn_at is null order by id", (account,)).fetchall() with self._conn(self.control) as c: refs = {r["record_id"]: r["reference"] for r in c.execute("select record_id, reference from refs where account = ? and record_table = 'addresses'", (account,)).fetchall()} return [{"id": r["id"], "label": r["label"], "line": r["line"], "created_at": r["created_at"], "reference": refs.get(r["id"])} for r in rows] def deliveries(self, account: str) -> list[dict]: with self._conn(self.records) as c: rows = c.execute("select * from deliveries where account = ? order by id", (account,)).fetchall() return [{"id": r["id"], "parcel": r["parcel"], "summary": r["summary"], "delivered_at": r["delivered_at"]} for r in rows] def lookup(self, account: str) -> dict | None: """Where the courier would deliver now: the first address it holds that is not withdrawn.""" rows = self.addresses(account) return {"address": rows[0]["line"], "label": rows[0]["label"], "addresses_held": len(rows)} if rows else None def restore_address(self, account: str, address_id: int) -> dict: """The Company's own undo path. A withdrawn record has a tombstone and cannot come back.""" with self._conn(self.control) as c: tomb = c.execute("select * from tombstones where record_key = ? and account = ?", (f"addresses:{address_id}", account)).fetchone() if tomb: raise ContractError(410, "withdrawn", "this record was withdrawn under a ForgetMe operation and cannot be restored", operation=tomb["operation"]) with self._conn(self.records) as c: row = c.execute("select * from addresses where id = ? and account = ?", (address_id, account)).fetchone() if not row: raise ContractError(404, "unknown_record", "no such address for this account") c.execute("update addresses set withdrawn_at = null where id = ?", (address_id,)) return {"id": address_id, "restored": True} def _append_archive(self, entry: dict) -> None: with self.archive.open("a", encoding="utf-8") as f: f.write(json.dumps(entry) + "\n") # -- the contract: preview ----------------------------------------------------------------------------- def _reference(self, account: str, ref) -> dict: if not isinstance(ref, str) or not forgetme.REFERENCE.match(ref): raise ContractError(400, "missing_reference", "scope 'item' needs the opaque reference this Company issued for the record; " "a request without one is refused, it never means account-wide") with self._conn(self.control) as c: r = c.execute("select * from refs where reference = ?", (ref,)).fetchone() if not r or r["account"] != account: # another account's reference looks exactly like an unknown one raise ContractError(404, "unknown_reference", "no record with that reference for the signed-in account") if _past(r["expires_at"]): raise ContractError(410, "reference_expired", "that reference has expired; ask the Company for the record again") return dict(r) def _scope(self, body: dict, scopes: tuple[str, ...]) -> str: scope = body.get("scope", "item") if scope not in forgetme.SCOPES: raise ContractError(400, "bad_scope", f"scope must be one of {list(forgetme.SCOPES)}; account-wide withdrawal is scope 'account', asked for explicitly") if scope == "account" and body.get("reference") is not None: raise ContractError(400, "bad_scope", "scope 'account' takes no reference") if scope == "account" and FORGET_ME_SCOPE["account"] not in scopes: raise poppy.PoppyError(403, "insufficient_scope", "account-wide withdrawal needs the scope forget-me:account, granted separately; " "forget-me:item never implies it", headers={"www-authenticate": 'Bearer error="insufficient_scope", scope="forget-me:account"'}, scope="forget-me:account") return scope def _address_rows(self, account: str, ids: list[int] | None) -> list[sqlite3.Row]: with self._conn(self.records) as c: if ids is None: return c.execute("select * from addresses where account = ? order by id", (account,)).fetchall() q = ",".join("?" * len(ids)) return c.execute(f"select * from addresses where account = ? and id in ({q}) order by id", (account, *ids)).fetchall() def _resolve(self, account: str, scopes: tuple[str, ...], body: dict) -> dict: """Validate; return what the operation is about. No side effects.""" for k in body: if k not in ("scope", "reference", "exceptions", "idempotency_key"): raise ContractError(400, "bad_request", f"unknown field {k!r}") scope = self._scope(body, scopes) if scope == "item": r = self._reference(account, body.get("reference")) if r["withdrawn_at"] and r["operation"]: # the record is under (or past) an operation: follow that one unless it ended short prior = self.load_op(r["operation"]) if prior and (prior["state"] in ("accepted", "running") or (prior["state"] == "done" and prior["outcome"]["overall"] in forgetme.SETTLED)): raise ContractError(409, "double_submit", "that record already has an operation; follow it instead of submitting again", operation=prior["id"], state=prior["state"]) rows = self._address_rows(account, [r["record_id"]]) if not rows: if r["operation"]: raise ContractError(409, "double_submit", "that record was removed under an earlier operation; follow it", operation=r["operation"], state=(self.load_op(r["operation"]) or {}).get("state", "done")) raise ContractError(404, "unknown_reference", "no record with that reference for the signed-in account") records = [{"table": "addresses", "id": rows[0]["id"], "reference": r["reference"], "label": rows[0]["label"], "line": rows[0]["line"], "created_at": rows[0]["created_at"]}] target = {"reference": r["reference"], "label": rows[0]["label"], "text": rows[0]["line"], "kind": "address", "saved_at": rows[0]["created_at"]} else: rows = [x for x in self._address_rows(account, None) if not x["withdrawn_at"]] with self._conn(self.control) as c: refs = {x["record_id"]: x["reference"] for x in c.execute("select record_id, reference from refs where account = ? and record_table = 'addresses'", (account,)).fetchall()} records = [{"table": "addresses", "id": x["id"], "reference": refs.get(x["id"]), "label": x["label"], "line": x["line"], "created_at": x["created_at"]} for x in rows] target = {"reference": None, "label": f"Everything {self.name} holds for your account", "kind": "account", "text": f"{len(records)} address record{'s' if len(records) != 1 else ''}, their delivery summaries and invoices", "saved_at": None} values = sorted({x["line"] for x in records}) ids = [x["id"] for x in records] exceptions = [] if ids: q = ",".join("?" * len(ids)) with self._conn(self.invoices) as c: inv = c.execute(f"select * from invoices where account = ? and address_id in ({q}) order by id", (account, *ids)).fetchall() for i in inv: if not _past(i["retain_until"]): until = datetime.fromisoformat(i["retain_until"]) exceptions.append({"id": f"fmx_invoice_{i['id']}", "label": f"Invoice {i['number']}", "text": "Carries the delivery address; kept 90 days under tax law.", "holders": ["invoices"], "party": self.name, "default": "keep", "options": [{"value": "keep", "label": f"Kept until {_day(until)}, then erased"}], "reason": "retention disclosed: tax law, 90 days", "retained_until": i["retain_until"]}) return {"scope": scope, "target": target, "values": values, "records": records, "exceptions": exceptions} def preview(self, account: str, scopes: tuple[str, ...], body: dict) -> dict: what = self._resolve(account, scopes, body) holders = [{"holder": h, "title": t, "kind": k, "retention": "persistent", "what": w, "party": self.name} for h, (t, k, w) in HOLDERS.items()] changes = [ f"{self.name} stops returning the record at once and deletes it by id", "delivery summaries derived from it are rebuilt without the address (provenance kept at write time)", "the residue the deletion leaves in the database is erased and every byte is scanned for the exact text afterwards", "the legacy export is searched for the exact text; nothing in it is deleted on a guess", "one restore attempt through the Company's own undo path, which must be refused", "one signed portable receipt per holder, verifiable against the keys in the index; no path or value in it", ] terms = {"reference": what["target"]["reference"], "scope": what["scope"], "exceptions": {e["id"]: e["default"] for e in what["exceptions"]}} return {"namespace": forgetme.NAMESPACE, "version": forgetme.VERSION, "scope": what["scope"], "item": what["target"], "holders": holders, "retention": "persistent", "changes": changes, "exceptions": what["exceptions"], "terms": terms, "note": f"The holders are {self.name}'s own stores. Nothing has been changed by this preview."} # -- the contract: submit -------------------------------------------------------------------------------- def load_op(self, op_id: str) -> dict | None: if not forgetme.OPERATION.match(op_id or ""): return None with self._conn(self.control) as c: row = c.execute("select body from ops where id = ?", (op_id,)).fetchone() return json.loads(row["body"]) if row else None def save_op(self, op: dict) -> None: op["updated_at"] = now() with self._conn(self.control) as c: c.execute("insert into ops values (?,?,?,?,?) on conflict(id) do update set body = excluded.body, state = excluded.state, updated_at = excluded.updated_at", (op["id"], op["account"], json.dumps(op), op["state"], op["updated_at"])) def ops_of(self, account: str) -> list[dict]: with self._conn(self.control) as c: return [json.loads(r["body"]) for r in c.execute("select body from ops where account = ? order by rowid", (account,)).fetchall()] def _clash(self, account: str, records: list[dict]) -> dict | None: wanted = {f"{r['table']}:{r['id']}" for r in records} for op in self.ops_of(account): if not wanted & set(op.get("record_keys", [])): continue if op["state"] in ("accepted", "running"): return op if op["state"] == "done" and op["outcome"]["overall"] in forgetme.SETTLED: return op return None # -- Operations extension, version 3: the approval exchange for destructive execution ---------------------------------- def _legible_terms(self, caller: Caller, what: dict, terms: dict, origin: str) -> tuple[dict, str]: """The exact terms of a withdrawal as the person will see them (Operations 3: everything that affects the action, keys named after the request's fields, each value clear on its own), and a summary that stands alone.""" t = what["target"] exceptions = {} retained = [] for e in what["exceptions"]: choice = terms["exceptions"].get(e["id"]) exceptions[e["id"]] = {"choice": choice, "label": e["label"], "reason": e.get("reason"), "retained_until": e.get("retained_until")} if e.get("retained_until"): retained.append(f"{e['label']} kept until {_day(datetime.fromisoformat(e['retained_until']))} under tax law, then erased") legible = { "action": "withdraw", "recipient": {"name": self.name, "issuer": self.identifier(origin)}, "account": caller.account, "scope": terms["scope"], "reference": terms["reference"], "record": {"label": t["label"], "text": t["text"], "kind": t["kind"], "saved_at": t.get("saved_at"), "count": len(what["records"])}, "holders": list(HOLDERS), "performs": [f"{self.name} stops returning the record at once", "deletes it by id and rebuilds the delivery summaries derived from it", "erases the residue the deletion leaves and scans every byte for the exact text", "searches the legacy export for the exact text and deletes nothing in it on a guess", "tries its own undo path once, which must refuse", "signs one portable receipt per holder"], "exceptions": exceptions, "retention_exceptions": retained, } where = f"{self.name}'s address book, delivery summaries, invoices and legacy export" if terms["scope"] == "account": head = f"Withdraw everything {self.name} holds for account {caller.account} ({t['text']}) from {where}." else: head = f"Withdraw {t['label']} ({t['text']}) from {where}, for account {caller.account}." tail = (" " + "; ".join(retained) + ".") if retained else " No record is kept back under a retention." summary = (f"{head} {self.name} stops returning it at once, deletes it by id, erases the residue, scans every byte afterwards and signs " f"one receipt per holder.{tail} Nothing else changes. Valid for {APPROVAL_TTL // 60} minutes.") return legible, summary def _poppy_op(self, operation_id: str, revision: str) -> sqlite3.Row | None: with self._conn(self.control) as c: return c.execute("select * from poppy_ops where operation_id = ? and revision = ?", (operation_id, revision)).fetchone() def _offer(self, caller: Caller, what: dict, terms: dict, terms_hash: str, origin: str, operation_id: str | None) -> poppy.PoppyError: """Operations 4 (APIs): perform nothing, return HTTP 403 approval_required with the operation. The operation is stored under the identity that can approve it (the agent, its User ID, the account) with its revision and expiry.""" legible, summary = self._legible_terms(caller, what, terms, origin) exp = now_dt() + timedelta(seconds=APPROVAL_TTL) revision = f"{int(exp.timestamp())}-{secrets.token_urlsafe(9)}" operation_id = operation_id or ("wd_" + secrets.token_urlsafe(9)) with self._conn(self.control) as c: c.execute("insert into poppy_ops values (?,?,?,?,?,?,?,?,?,?,?,?)", (operation_id, revision, caller.account, caller.client_id, caller.sub, terms_hash, json.dumps(legible), summary, exp.isoformat(timespec="seconds"), now(), None, None)) op = {"operation_id": operation_id, "revision": revision, "summary": summary, "terms": legible, "expires_at": exp.isoformat(timespec="seconds")} return poppy.PoppyError(403, "approval_required", f"{self.name} performs a withdrawal only with an approval of these exact terms, through the " "Operations extension (version 3): send the same request again with a Poppy-Approval header", operation=op) async def submit(self, caller: Caller, body: dict, approval: dict | None, origin: str = "") -> tuple[int, dict]: """ForgetMe v1 submit over Poppy. Destructive execution goes through the Operations extension, version 3: 1. the request must declare `"operations";v="3"` (Operations 2: a Company MUST NOT return operations to a request that doesn't; this Company can't approve a withdrawal any other way, so it refuses with `extension_required`); 2. the ForgetMe retry path and term checks run as before (same key and terms: the same operation; conflict; double submit; terms_incomplete); 3. without a `Poppy-Approval`: nothing is performed, `403 approval_required` carries the operation (id, revision, summary, exact terms, expires_at); 4. with one, the checks of Operations 6, in order: the Session can approve it (same agent, same User ID, signed in to the same account; else the request is handled as if it had no approval); it hasn't been performed (else the original answer comes back, however often the approval is sent, Operations 7); the revision was returned for this operation, hasn't expired, and the request asks for exactly what it describes (else nothing is performed and a new revision under the approval's operation_id comes back, never the one it names); 5. then this Company's policy: it acts on user approvals only; an agent approval is declined (Operations 6, `approval_declined`, nothing performed, no new operation); 6. then the action is performed at most once and the approval is recorded with the operation.""" key = body.get("idempotency_key") if not isinstance(key, str) or not forgetme.IDEMPOTENCY.match(key): raise ContractError(400, "bad_request", "idempotency_key must be 8 to 128 printable ASCII characters, chosen by the client") if not caller.negotiation.uses("operations", "3"): raise poppy.PoppyError(403, "extension_required", "a withdrawal is performed only through the Operations extension, version 3, which this request " "did not declare in Poppy-Extensions; no other approval flow stands in for it", extension="operations") given = body.get("exceptions") if not isinstance(given, dict) or len(given) > forgetme.MAX_EXCEPTIONS or any(not isinstance(k, str) or v not in forgetme.CHOICES for k, v in given.items()): raise ContractError(400, "bad_request", "exceptions must map each exception id to 'keep' or 'delete'") account, scopes = caller.account, caller.scopes # The retry path comes first and resolves nothing: the record may already be withdrawn by the operation the # client is retrying. Same key, same terms: the same operation (also Operations 7: a retry gets the original answer). sent = {"reference": body.get("reference") if body.get("scope", "item") == "item" else None, "scope": body.get("scope", "item"), "exceptions": {k: given[k] for k in sorted(given)}} with self._conn(self.control) as c: row = c.execute("select op from idempotency where account = ? and key_hash = ?", (account, _hash(key))).fetchone() if row: op = self.load_op(row["op"]) if op and op["terms_hash"] == _terms_hash(sent): return 200, self.status_body(op, origin) raise ContractError(409, "conflict", "this idempotency key was already used with different terms", operation=op["id"] if op else None) # Operations 7, before anything is resolved: the approval of an operation already performed gets the answer the # Company gave the first time, however often it is sent and whatever the key (the record is withdrawn by then). if approval is not None: offered = self._poppy_op(approval["operation_id"], approval["revision"]) if offered is not None and offered["performed_op"] and offered["client_id"] == caller.client_id and offered["sub"] == caller.sub \ and offered["account"] == account: done = self.load_op(offered["performed_op"]) if done: return 200, self.status_body(done, origin) what = self._resolve(account, scopes, body) expected = {e["id"] for e in what["exceptions"]} if set(given) != expected: raise ContractError(400, "terms_incomplete", "decide every exception the preview listed, and only those", missing=sorted(expected - set(given)), unexpected=sorted(set(given) - expected)) for e in what["exceptions"]: if given[e["id"]] not in {o["value"] for o in e["options"]}: raise ContractError(400, "terms_incomplete", f"{e['label']} offers no such choice", missing=[], unexpected=[e["id"]]) terms = {"reference": what["target"]["reference"], "scope": what["scope"], "exceptions": {k: given[k] for k in sorted(given)}} th = _terms_hash(terms) async with self.alock(): with self.lock: with self._conn(self.control) as c: row = c.execute("select op from idempotency where account = ? and key_hash = ?", (account, _hash(key))).fetchone() if row: op = self.load_op(row["op"]) if op and op["terms_hash"] == th: return 200, self.status_body(op, origin) raise ContractError(409, "conflict", "this idempotency key was already used with different terms", operation=op["id"] if op else None) offered = None if approval is not None: offered = self._poppy_op(approval["operation_id"], approval["revision"]) # check 1: the Session can approve it (Operations 3): the same agent and User ID, signed in to the same account; # otherwise the request is handled as if it had no approval if offered is not None and (offered["client_id"] != caller.client_id or offered["sub"] != caller.sub or offered["account"] != account): offered, approval = None, None # check 2: not performed already (Operations 7: the same answer, however often the approval is sent, whatever the key) if offered is not None and offered["performed_op"]: done = self.load_op(offered["performed_op"]) if done: return 200, self.status_body(done, origin) clash = self._clash(account, what["records"]) if clash: raise ContractError(409, "double_submit", "that record already has an operation; follow it instead of submitting again", operation=clash["id"], state=clash["state"]) if approval is None: raise self._offer(caller, what, terms, th, origin, None) # check 3: a revision returned for this operation, unexpired, for exactly these terms if offered is None or _past(offered["expires_at"]) or offered["terms_hash"] != th: with self._conn(self.control) as c: known = c.execute("select 1 from poppy_ops where operation_id = ? and client_id = ? and sub = ? and account = ?", (approval["operation_id"], caller.client_id, caller.sub, account)).fetchone() raise self._offer(caller, what, terms, th, origin, approval["operation_id"] if known else None) # this Company's policy: the person decides a withdrawal; an agent's standing instruction is declined if approval["approver"] != "user": raise poppy.PoppyError(403, "approval_declined", f"{self.name} acts on a withdrawal only when the person approved these exact terms themselves", operation_id=approval["operation_id"], revision=approval["revision"], reason=f"Only you can approve a withdrawal of your records at {self.name}; your agent's standing instruction is not enough here.") op_id = "fmo_" + secrets.token_urlsafe(18) stopped = self._stop_retrieval(account, what["records"], op_id) record = {"operation_id": approval["operation_id"], "revision": approval["revision"], "approver": approval["approver"], "approved_at": approval.get("approved_at"), "input_type": approval.get("input_type"), "reference": approval.get("reference"), "client": caller.client_name, "client_id": caller.client_id, "recorded_at": now()} op = {"id": op_id, "account": account, "terms": terms, "terms_hash": th, "scope": what["scope"], "item": what["target"], "records": what["records"], "record_keys": [f"{r['table']}:{r['id']}" for r in what["records"]], "values": what["values"], "exceptions": what["exceptions"], "state": "accepted", "submitted_at": now(), "started_at": None, "erase_started_at": None, "finished_at": None, "retrieval_stopped_at": stopped, "outcome": None, "holders": {}, "queued": [], "log": [], "reconciled": None, "approval": record} self._say(op, f"Approved by the person through {caller.client_name} ({approval['approver']}" f"{', ' + approval['input_type'] if approval.get('input_type') else ''}); operation {approval['operation_id']} revision " f"{approval['revision']}, performed once.") self.save_op(op) with self._conn(self.control) as c: c.execute("insert into idempotency values (?,?,?)", (account, _hash(key), op_id)) c.execute("update poppy_ops set performed_op = ?, approval = ? where operation_id = ? and revision = ?", (op_id, json.dumps({**record, "sid": caller.sid, "sub": caller.sub}), approval["operation_id"], approval["revision"])) asyncio.create_task(asyncio.to_thread(self.execute, op_id)) return 202, self.status_body(op, origin) def _stop_retrieval(self, account: str, records: list[dict], op_id: str) -> str: """Before answering 202: the records stop being returned. Physical cleanup comes later and is recorded apart.""" t = now() with self._conn(self.records) as c: for r in records: c.execute("update addresses set withdrawn_at = ? where id = ? and account = ?", (t, r["id"], account)) with self._conn(self.control) as c: for r in records: c.execute("update refs set withdrawn_at = ?, operation = ? where account = ? and record_table = ? and record_id = ?", (t, op_id, account, r["table"], r["id"])) c.execute("insert or replace into tombstones values (?,?,?,?,?)", (f"{r['table']}:{r['id']}", account, t, None, op_id)) return t # -- execution --------------------------------------------------------------------------------------------- def _say(self, op: dict, text: str) -> None: op["log"].append({"actor": self.name, "text": text, "at": now()}) op["log"] = op["log"][-200:] def _authority_ok(self, op: dict) -> bool: with self._conn(self.control) as c: acct = c.execute("select expires_at from accounts where id = ?", (op["account"],)).fetchone() live = c.execute("select count(*) from refresh_tokens where account = ? and revoked_at is null", (op["account"],)).fetchone()[0] return bool(acct) and not _past(acct["expires_at"]) and live > 0 def _busy_until(self, account: str) -> str | None: with self._conn(self.control) as c: row = c.execute("select busy_until from accounts where id = ?", (account,)).fetchone() return row["busy_until"] if row else None def execute(self, op_id: str) -> dict: """Run an accepted operation: every holder once, queued ones later. Exactly one thread per op id.""" with self.lock: op = self.load_op(op_id) if not op or op["state"] != "accepted": return op or {} op["state"], op["started_at"] = "running", now() self.save_op(op) try: self._say(op, f"Stopped returning the record{'s' if len(op['records']) != 1 else ''} at {op['retrieval_stopped_at']}; now the cleanup, holder by holder.") for holder in HOLDERS: self._run_holder(op, holder) self._finish(op) except Exception as e: # pragma: no cover - the harness itself failing op["state"] = "error" op["outcome"] = {"overall": "error", "sentence": f"The operation failed: {type(e).__name__}", "holders": list(op["holders"].values()), "counts": forgetme.counts(list(op["holders"].values())), "uncertain": True} op["finished_at"] = now() self._say(op, f"fault: {type(e).__name__}") self.save_op(op) return op def _run_holder(self, op: dict, holder: str) -> None: """One holder's step. Sets op['holders'][holder] to a row, and op['queued'] when it must wait.""" if holder == "records": busy = self._busy_until(op["account"]) if busy and not _past(busy): op["holders"][holder] = self._row(holder, "queued", None, "the address book is being rewritten by a batch job; this step runs when it is released", action="queued", unresolved="cleanup pending", op=op) if holder not in op["queued"]: op["queued"].append(holder) self._say(op, "records: busy; the cleanup of the address book is queued and runs when the store is released.") self.save_op(op) return if holder in op["queued"] and not self._authority_ok(op): rec = self._portable(op, holder, "error", ["nothing done: the request lost its authority before this step ran"], before={}, after={}, coverage={"inspected": False, "checks": [], "limits": ["the credential was revoked or the account closed before the queued step ran"]}) op["holders"][holder] = self._row(holder, "error", rec, "the request lost its authority before the queued step ran; nothing was erased", action="nothing done", unresolved="submit again with a live credential", op=op) op["queued"].remove(holder) self._say(op, "records: the queued step found no live authority for this account and erased nothing.") self.save_op(op) return self._records_step(op) if holder in op["queued"]: op["queued"].remove(holder) elif holder == "invoices": self._invoices_step(op) elif holder == "archive": self._archive_step(op) self.save_op(op) def _records_step(self, op: dict) -> None: account, values = op["account"], op["values"] op["erase_started_at"] = op.get("erase_started_at") or now() self.save_op(op) actions = ["active retrieval of the record stopped", "record deleted through the holder's own API, by id"] rebuilt = 0 with self._conn(self.records) as c: for r in op["records"]: derived = c.execute("select derived_table, derived_id from provenance where source_table = ? and source_id = ?", (r["table"], r["id"])).fetchall() for d in derived: if d["derived_table"] == "deliveries": row = c.execute("select parcel, delivered_at from deliveries where id = ?", (d["derived_id"],)).fetchone() if row: c.execute("update deliveries set summary = ?, address_id = null where id = ?", (f"Parcel {row['parcel']} delivered; the address was withdrawn on {op['retrieval_stopped_at'][:10]}.", d["derived_id"])) rebuilt += 1 c.execute("delete from provenance where source_table = ? and source_id = ?", (r["table"], r["id"])) c.execute("delete from addresses where id = ? and account = ?", (r["id"], account)) if rebuilt: actions.append("derived items rebuilt without the withdrawn record") self._say(op, f"records: deleted {len(op['records'])} address record{'s' if len(op['records']) != 1 else ''} by id and rebuilt {rebuilt} delivery summar{'y' if rebuilt == 1 else 'ies'} from provenance.") internal = forget_mod.forget(self.records, make_subject(values), correlation_id=op["id"], issuer=self.issuer) self._keep_internal(op["id"], "records", internal) actions += ["residue the deletion left behind erased", "every byte of the holder scanned for the exact text afterwards"] self._say(op, f"records: the engine erased what the deletion left ({len(internal['before']['findings'])} kind{'s' if len(internal['before']['findings']) != 1 else ''} of residue before, {len(internal['after']['findings'])} after) and scanned every byte.") # one restore attempt through the Company's own undo path, which must be refused prevented = False try: self.restore_address(account, op["records"][0]["id"]) except ContractError as e: prevented = e.code == "withdrawn" actions.append("restore attempted through the holder's own path and refused") self._say(op, "records: tried the Company's own undo path for the record; " + ("refused, as it must be." if prevented else "IT CAME BACK.")) own_live = self._own_live(account, values) residue_after = sum(internal["after"]["findings"].values()) if residue_after or not prevented: outcome, detail, unresolved = "bytes-still-found", "residue was still found after erasing", "the Company must erase again" elif own_live: outcome, detail, unresolved = "bytes-still-found", "the exact text is still in a live record of yours", "another record of yours carries it" else: outcome, detail, unresolved = "inspected-and-clear", f"record deleted, {rebuilt} summar{'y' if rebuilt == 1 else 'ies'} rebuilt, residue erased, every byte scanned", None with self._conn(self.control) as c: for r in op["records"]: c.execute("update tombstones set cleaned_at = ? where record_key = ?", (now(), f"{r['table']}:{r['id']}")) rec = self._portable(op, "records", outcome, actions, before={"residue": sum(internal["before"]["findings"].values()), "exact_text_in_your_records": True}, after={"residue": residue_after, "exact_text_in_your_records": bool(own_live)}, coverage={"inspected": True, "checks": sorted({*internal["before"]["findings"], *internal["after"]["findings"], "exact-text", "provenance"}), "limits": []}, restore={"attempted": True, "prevented": prevented}, physical_cleanup_at=now(), source=internal) op["holders"]["records"] = self._row("records", outcome, rec, detail, action="deleted and erased" if outcome == "inspected-and-clear" else "deleted; not clear", unresolved=unresolved, op=op) def _own_live(self, account: str, values: list[str]) -> int: n = 0 with self._conn(self.records) as c: for v in values: n += c.execute("select count(*) from addresses where account = ? and withdrawn_at is null and line like ?", (account, f"%{v}%")).fetchone()[0] n += c.execute("select count(*) from deliveries where account = ? and summary like ?", (account, f"%{v}%")).fetchone()[0] return n def _invoices_step(self, op: dict) -> None: account, values = op["account"], op["values"] ids = [r["id"] for r in op["records"]] kept, deleted = [], 0 if ids: q = ",".join("?" * len(ids)) with self._conn(self.invoices) as c: for i in c.execute(f"select * from invoices where account = ? and address_id in ({q})", (account, *ids)).fetchall(): if _past(i["retain_until"]): c.execute("delete from invoices where id = ?", (i["id"],)) deleted += 1 else: kept.append(dict(i)) internal = forget_mod.forget(self.invoices, make_subject(values), correlation_id=op["id"], issuer=self.issuer) self._keep_internal(op["id"], "invoices", internal) actions = ["exact text searched for in the holder"] if deleted: actions = ["derived items removed", "residue the deletion left behind erased", "every byte of the holder scanned for the exact text afterwards"] if kept: actions.insert(0, "record kept under a retention the preview disclosed") until = max(k["retain_until"] for k in kept) d = datetime.fromisoformat(until) outcome = "intentionally-retained" detail = f"{', '.join('Invoice ' + k['number'] for k in kept)} kept under tax law until {_day(d)}" unresolved = f"scheduled for erasure on {_day(d)}" self._say(op, f"invoices: {len(kept)} invoice{'s' if len(kept) != 1 else ''} kept under tax law until {_day(d)}, as the preview disclosed; {deleted} past retention deleted.") else: until = None outcome = "inspected-and-clear" if not sum(internal["after"]["findings"].values()) else "bytes-still-found" detail = f"{deleted} invoice{'s' if deleted != 1 else ''} past retention deleted, residue erased, every byte scanned" if deleted else "no invoice of yours carries the exact text" unresolved = None self._say(op, f"invoices: {detail}.") rec = self._portable(op, "invoices", outcome, actions, before={"residue": sum(internal["before"]["findings"].values()), "exact_text_in_your_records": bool(kept or deleted)}, after={"residue": sum(internal["after"]["findings"].values()), "exact_text_in_your_records": bool(kept)}, coverage={"inspected": True, "checks": sorted({*internal["after"]["findings"], "exact-text", "provenance"}), "limits": []}, retained_until=until, physical_cleanup_at=now() if deleted else None, source=internal) op["holders"]["invoices"] = self._row("invoices", outcome, rec, detail, action="kept, as disclosed" if kept else "deleted and erased" if deleted else "inspected", unresolved=unresolved, retained_until=until, op=op) def _archive_step(self, op: dict) -> None: values = op["values"] report = scan(self.archive, make_subject(values).needles) found = any(c.found_in for c in report.canaries) actions = ["exact text searched for in the holder"] if found: outcome, detail, unresolved = "bytes-still-found", "a legacy export holds the exact text; it predates provenance tracking, so it can't be tied to your record without guessing", "a person reviews the export; nothing in it is deleted on a guess" else: outcome, detail, unresolved = "inspected-and-clear", "the legacy export was searched for the exact text: none found", None self._say(op, f"archive: searched the legacy export for the exact text: {'found; a person reviews it, nothing is deleted on a guess' if found else 'none found'}.") rec = self._portable(op, "archive", outcome, actions, before={"residue": 0, "exact_text_in_your_records": found}, after={"residue": 0, "exact_text_in_your_records": found}, coverage={"inspected": True, "checks": ["exact-text"], "limits": [ARCHIVE_LIMIT]}) op["holders"]["archive"] = self._row("archive", outcome, rec, detail, action="searched", unresolved=unresolved, op=op) def _finish(self, op: dict) -> None: rows = [op["holders"][h] for h in HOLDERS if h in op["holders"]] overall = forgetme.worst([r["outcome"] for r in rows]) label = op["item"]["label"] if overall in forgetme.SETTLED: s = f"{label} withdrawn from {self.name}." elif overall == "queued": s = f"{label}: {self.name} stopped returning it; the cleanup of its address book is queued and finishes when the store is released." elif overall == "bytes-still-found": s = f"{label}: {self.name} still found the exact text in {', '.join(r['title'] for r in rows if r['outcome'] == 'bytes-still-found')}. Not done." elif overall == "unsupported": s = f"{label}: a holder at {self.name} can't be inspected." else: s = f"{label}: a step failed at {self.name}." kept = [r for r in rows if r["outcome"] == "intentionally-retained"] if kept: s += " " + kept[0]["detail"][0].upper() + kept[0]["detail"][1:] + "." outstanding = sum(1 for r in rows if r["outcome"] == "queued") op["outcome"] = {"overall": overall, "sentence": s, "holders": rows, "counts": forgetme.counts(rows), "outstanding": outstanding} op["state"] = "done" op["finished_at"] = op.get("finished_at") or now() self._say(op, s) self.save_op(op) def _row(self, holder: str, outcome: str, rec: dict | None, detail: str, *, action: str, unresolved: str | None, op: dict, retained_until: str | None = None) -> dict: title, kind, _ = HOLDERS[holder] row = {"holder": holder, "title": title, "kind": kind, "outcome": outcome, "detail": detail, "party": self.name, "action": action, "evidence": f"{op['id']}.{holder}" if rec else None, "unresolved": unresolved, "at": now(), "retained_until": retained_until} if rec: row["receipt_id"] = f"{op['id']}.{holder}" return row def _portable(self, op: dict, holder: str, outcome: str, actions: list[str], *, before: dict, after: dict, coverage: dict, restore: dict | None = None, retained_until: str | None = None, physical_cleanup_at: str | None = None, source: dict | None = None) -> dict: _, kind, _ = HOLDERS[holder] rec = forgetme.issue(issuer=self.issuer, operation=op["id"], holder=holder, kind=kind, scope=op["scope"], outcome=outcome, actions=actions, before=before, after=after, coverage={**coverage, "scope": COVERAGE_SCOPE}, subject_values=len(op["values"]), key=self.key, retrieval_stopped_at=op["retrieval_stopped_at"], physical_cleanup_at=physical_cleanup_at, restore=restore, retained_until=retained_until, source_receipt=source) forgetme.check_portable(rec, op["values"]) with self._conn(self.control) as c: c.execute("insert or replace into portable values (?,?,?,?)", (f"{op['id']}.{holder}", op["id"], holder, json.dumps(rec))) return rec def _keep_internal(self, op_id: str, holder: str, rec: dict | forget_mod.Queued) -> None: if isinstance(rec, dict): (self.receipts_dir / f"{op_id}.{holder}.json").write_text(json.dumps(rec, indent=1), encoding="utf-8") # -- queued steps, restart ----------------------------------------------------------------------------------- def run_queued(self) -> list[dict]: """Run the queued holder steps whose store is released. Called by the sweep and on every status read of an operation with outstanding rows, so a resumed poll shows the new outcome.""" done = [] with self.lock, self._conn(self.control) as c: ids = [r["id"] for r in c.execute("select id from ops where state = 'done'").fetchall()] for op_id in ids: op = self.load_op(op_id) if not op or not op.get("queued"): continue with self.lock: op = self.load_op(op_id) busy = self._busy_until(op["account"]) if busy and not _past(busy): continue for holder in list(op["queued"]): self._run_holder(op, holder) op["finished_at"] = now() self._finish(op) done.append(op) return done def reconcile(self) -> list[dict]: """After a restart: run what never started; settle what was interrupted after erasing began by scanning again, never erasing again; then the queued steps whose store is free.""" out = [] with self.lock, self._conn(self.control) as c: rows = c.execute("select id, state from ops where state in ('accepted', 'running')").fetchall() for r in rows: op = self.load_op(r["id"]) if op["state"] == "accepted": out.append(self.execute(op["id"])) continue with self.lock: if not op["erase_started_at"]: # nothing was erased: safe to start over op["state"] = "accepted" self.save_op(op) out.append(self.execute(op["id"])) continue note = "the Company restarted during this operation" for holder in HOLDERS: if holder in op["holders"]: continue target = {"records": self.records, "invoices": self.invoices, "archive": self.archive}[holder] report = scan(target, make_subject(op["values"]).needles) found = any(c.found_in for c in report.canaries) own = self._own_live(op["account"], op["values"]) if holder == "records" else found outcome = "inspected-and-clear" if not report.findings and not own else "bytes-still-found" rec = self._portable(op, holder, outcome, ["scanned again after a restart; nothing erased again"], before={"residue": len(report.findings), "exact_text_in_your_records": bool(own)}, after={"residue": len(report.findings), "exact_text_in_your_records": bool(own)}, coverage={"inspected": True, "checks": ["exact-text"], "limits": [note + "; the outcome comes from a fresh scan"]}) op["holders"][holder] = self._row(holder, outcome, rec, f"scanned again after the restart ({note})", action="scanned again", unresolved=None if outcome == "inspected-and-clear" else "the Company must erase again", op=op) op["reconciled"] = f"{note}; the stores were scanned again and the outcome comes from that scan" self._finish(op) out.append(op) out += self.run_queued() return out # -- status and evidence ---------------------------------------------------------------------------------------- def status_body(self, op: dict, origin: str = "") -> dict: ep = self.endpoint(origin) if origin else ENDPOINT_PATH return {"operation": op["id"], "namespace": forgetme.NAMESPACE, "version": forgetme.VERSION, "state": op["state"], "terms": op["terms"], "item": op["item"], "submitted_at": op["submitted_at"], "started_at": op["started_at"], "finished_at": op["finished_at"], "updated_at": op.get("updated_at"), "retrieval_stopped_at": op["retrieval_stopped_at"], "outcome": op["outcome"], "log": op["log"], "reconciled": op.get("reconciled"), "approval": op.get("approval"), "status_url": f"{ep}/operations/{op['id']}", "evidence_url": f"{ep}/operations/{op['id']}/evidence"} def operation(self, account: str, op_id: str) -> dict: op = self.load_op(op_id) if not op or op["account"] != account: # another account's operation looks exactly like an unknown one raise ContractError(404, "unknown_operation", "no operation with that id for the signed-in account") if op.get("queued"): self.run_queued() op = self.load_op(op_id) return op def status(self, account: str, op_id: str, origin: str = "") -> dict: return self.status_body(self.operation(account, op_id), origin) def evidence(self, account: str, op_id: str, origin: str = "") -> dict: op = self.operation(account, op_id) with self._conn(self.control) as c: rows = c.execute("select id, holder, body from portable where op = ? order by rowid", (op_id,)).fetchall() receipts = [{"receipt_id": r["id"], "holder": r["holder"], "party": self.name, "issuer": self.issuer, "issuer_key_url": self.endpoint(origin) if origin else ENDPOINT_PATH, "fingerprint": receipt_mod.fingerprint(json.loads(r["body"])["public_key"]), "receipt": json.loads(r["body"])} for r in rows] return {"operation": op["id"], "state": op["state"], "issuer": self.issuer, "issuer_key_url": self.endpoint(origin) if origin else ENDPOINT_PATH, "receipts": receipts, "observations": [], "reconciled": op.get("reconciled"), "note": "Each receipt is one holder's signed statement: counts, timestamps and vocabulary words, never a path or a value."}