# AllowedBy for Python # How it works Four parties take part: the **agent**, your **app**, the **person**, and a **node** that the person and your app trust. ## Three documents | Document | Who signs it | What it says | |---|---|---| | Passport | The node | Which agent this is, who operates it, and which key it holds | | Grant | The person (passkey) and the node | What the person approved, for which app, for how long, with which limits | | Proof | The agent | This request: method, address, body and time, with the agent's key | The agent sends the first two in `Allowed-By` and the proof in `AllowedBy-Proof`. ## What your app checks The SDK does all of this offline, on each request, in about a millisecond: 1. The passport or grant comes from a node you trust, is not expired, and is not withdrawn. 2. The person's passkey signed exactly this grant, and their identity level is enough for the route. 3. The proof is for this exact request, by the agent the grant names, and was never seen before. 4. The grant covers the action, the resource and the amount. 5. A serious action has an approval made for this request only, and it has not been used. Anything unknown, missing or unreadable is refused. See [error codes](https://docs.allowedby.com/errors) for each refusal. ## Levels: how sure you are of the person | Level | The person | Use it for | |---|---|---| | 0 | is not asked: only the agent is identified | Public or per-agent data | | 1 | tapped a passkey | Everyday actions | | 2 | has a verified legal identity, and tapped a passkey | Orders, contracts, anything hard to undo | | 3 | is verified at the highest level, with a hardware passkey | Payments and signatures of value | ## Classes: how serious the action is | Class | Example | Approval | |---|---|---| | `read` | List notes | Reused until it ends | | `write` | Add a note | Reused until it ends | | `write-hard` | Delete, publish | For that request, once | | `irreversible` | Pay, sign | For that request, once | For the last two, your app creates the approval itself. The agent cannot change what the person will read. ## The node A node issues passports, shows the approval page, and countersigns grants. It learns what was approved, never the data in your app. You choose which nodes to trust: one hosted node, your own, or a signed list. --- # AllowedBy Python SDK The `allowedby` package is the Python SDK and the reference implementation of every AllowedBy SDK. A service uses it to accept AI agents (the **service SDK**); an agent uses it to call those services (the **agent SDK**). The concepts (routes, classes, levels, the approval flow) are explained once in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents); this guide shows them in Python. The rules every SDK follows are in `sdks/CONTRACT.md`. Terms used below: a **node** issues agent passports and asks the person for approval (a passkey tap); a **grant** is the person's signed approval; a **proof** is the agent's signature over one request; **ABY-2** is the specification of how a service verifies a request (in `specs/`). ## Install Install the package from a clone of this repository with `pip install "./sdks/python"`; add the extra of your framework. The package is not on PyPI yet. Python 3.10 or later. Its only dependencies are `cryptography` (Ed25519, P-256, AES key wrap and AES-GCM, which the standard library lacks) and `tzdata` (time zones on systems without a zone database); each integration is an optional extra. Linux and macOS: ```bash git clone https://github.com/yannUpTo/allowedby.git python3 -m venv .venv && . .venv/bin/activate pip install "./allowedby/sdks/python[fastapi]" ``` Windows (PowerShell): ```powershell git clone https://github.com/yannUpTo/allowedby.git python -m venv .venv; .venv\Scripts\Activate.ps1 pip install "./allowedby/sdks/python[fastapi]" ``` Docker (in your image's Dockerfile, with the repository next to it): ```dockerfile FROM python:3.13-slim COPY allowedby/sdks/python /tmp/allowedby RUN pip install --no-cache-dir "/tmp/allowedby[fastapi]" uvicorn ``` | Extra | Installs | For | |---|---|---| | (none) | `cryptography`, `tzdata` | WSGI, the agent, MCP | | `asgi` | `starlette` | ASGI middleware | | `fastapi` | `fastapi`, `starlette` | FastAPI | | `django` | `django` 5.2 to 6 | Django | | `flask` | `flask` | Flask | | `redis` | `redis` | `RedisStore`, shared by every machine | | `langchain` | `langchain-core` | `AllowedByRequestsTool` | | `openai-agents` | `openai-agents` | `allowedby_tools` | ## Quick start A WSGI app that accepts agents is 25 lines with the standard library's server; run it next to the local node. From `sdks/python/examples/quickstart.py`: ```python """Quick start: a WSGI app that accepts AI agents with the person's approval (standard library server).""" import json import os from wsgiref.simple_server import make_server from allowedby import AllowedBy, route aby = AllowedBy( origin=os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), node=os.environ.get("ALLOWEDBY_NODE", "http://localhost"), org={"legal_name": "Notes Ltd", "country": "FR"}, routes=[route("GET", "/notes", "notes:read", level=1, resource="note:*")], templates={"notes:read": "Read your notes"}, ) def notes(environ, start_response): ctx = environ["allowedby.context"] # None outside the route map status, body = ("200 OK", {"notes": [], "person": ctx.human_id}) if ctx else ("404 Not Found", {}) start_response(status, [("Content-Type", "application/json")]) return [json.dumps(body).encode()] app = aby.wsgi(notes) if __name__ == "__main__": make_server("localhost", 8000, app).serve_forever() ``` See it work against the local node (from the repository root): ```bash python demo/run.py # the node on http://localhost, the demo sites python sdks/python/examples/quickstart.py # your app on http://localhost:8000 curl -i http://localhost:8000/notes # 401, WWW-Authenticate: AllowedBy ... passport_required curl http://localhost:8000/.well-known/allowedby # what agents read: templates, keys, signed profile ``` Then let an agent call it, approving on the page that opens (from another terminal): ```bash ALLOWEDBY_NODE=http://localhost APP_URL=http://localhost:8000 python sdks/python/examples/agent_quickstart.py ``` ```powershell $env:ALLOWEDBY_NODE = "http://localhost"; $env:APP_URL = "http://localhost:8000" python sdks/python/examples/agent_quickstart.py ``` With the hosted node, set `ALLOWEDBY_NODE=https://demo.allowedby.com`; the node approves only for origins onboarded on it (see `docs/deploy-saas.md`). ## Routes and templates Each route says which capability, class and identity level a request needs; each capability has a sentence the person reads before approving. ```python from allowedby import AllowedBy, route routes = [ route("GET", "/me", level=0, summary="Who is calling"), # the agent's passport is enough route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}"), route("POST", "/invoices/{id}/pay", "invoices:pay", level=2, resource="invoice:{id}", amount_field="/total", cls=[{"up_to": "1000.00", "class": "write-hard"}, {"class": "irreversible"}]), ] templates = { "notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}", "invoices:pay": {"summary": {"en": "Pay {scope}, up to {amount.max} {amount.currency}"}, "lines": {"en": "Pay {scope}, up to {amount.max} {amount.currency}"}}, } ``` | Argument | Meaning | |---|---| | `method`, `path` | `GET` (also checks `HEAD`), `POST`, `PUT`, `PATCH`, `DELETE`; `{param}` matches one path segment; other segments are ASCII, percent-encoded where a URL needs it (`/caf%C3%A9`). The first match decides: a literal route comes before the parameter route it overlaps, else construction fails | | `capability` | `namespace:action`; none means level 0 (the agent's passport only) | | `cls` | `read`, `write` (approved once, reused), `write-hard`, `irreversible` (the service asks for this exact request, used once), or amount thresholds | | `level` | 0 passport only, 1 passkey, 2 verified identity, 3 eIDAS high | | `resource` | the scope the grant must cover; `{param}` is replaced from the path | | `amount_field`, `currency_field` | JSON pointers to the amount and currency in the body; the grant must cap them | | `authn` | `hardware` or `synced`: the kind of passkey | | `tier` | 0 to 2: the agent's key custody (OAID-3) | | `max_lifetime` | seconds, 60 s to 30 days: shorter than the class maximum | | `summary`, `body` | what agents read in `/openapi.json` | | `mandate`, `disclose`, `disclose_optional`, `authority`, `qes`, `require_link`, `nonce`, `level_profile` | extended features (see Reference) | A bad route or configuration raises `ValueError` at start, saying what to fix: an origin that is not https (http only for localhost), a capability without a template, a route listed twice, a level outside 0-3. A template is a sentence (`"Read your notes"`) or `{"summary": {lang: ...}, "lines": {lang: ...}}` with `{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}` and `{fields}`. The node renders it; the person signs exactly that text. ## Framework recipes Every app below is whole, and CI runs it against a real node, an agent and a person (26 scenarios: levels 0 to 2 and all refusals). Each framework has a thin adapter; every adapter serves the SDK's endpoints, checks every route of the map, and lets other paths through untouched. The SDK's endpoints: `GET /.well-known/allowedby`, `GET /openapi.json`, `GET /.well-known/api-catalog`, `POST /allowedby/callback`, `POST /allowedby/link`. On a route of the map the body (at most `max_body`, 1 MiB by default) is read once and given back to your handler intact; it must be a JSON object. Variants of a protected route never reach your handler unchecked (sdks/CONTRACT.md §2.10): a trailing or doubled `/`, a format suffix (`/notes.json`), a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `_method` in the query or a form) and a path that only decodes to a route (`%2F`) are refused with 400 `invalid_request`. The method and the path are checked again where the framework runs your handler (Flask, Django, Starlette and FastAPI do it by themselves): whatever a layer behind the SDK changed (a `_method` form field, a header, a rewritten path), a handler of a route of the map runs only for the very request the SDK accepted, else the client gets 400. A form POST on a path protected under another method only is your own, streamed and with no size limit. For a bare WSGI or ASGI app the SDK does not know where the router is and refuses such forms; put the guard right around the router to accept them: `aby.wsgi(layer(aby.wsgi_guard(router)), guarded=True)`, or `AllowedByMiddleware(layer(DispatchGuard(router, aby)), aby, guarded=True)`. An app mounted inside the router, with layers of its own that change the method, needs its own guard. **Changed after the check.** A step after the SDK that moves an accepted request, to another value of the same route (`/invoices/4711` rewritten to `/invoices/9`) or to another method (a method override after the middleware), gets 400 `invalid_request`, and its handler never runs: it would act on values the person never approved. The refusal names route templates at most, never a value of the request. Another spelling of the same path (`/invoices/%34711`) is the same request and runs. If the check spent a single-use approval, the SDK gives it back (`release`). Limits: a bare WSGI or ASGI app routes where the SDK cannot see it, so put the guard right around the router as above; where you cannot, put nothing that changes the method or the path after the SDK, and read the path values from `ctx.params`. A wildcard (`/notes/` for `/notes/{id}`), an open pattern or a last newline never runs the handler of a protected route unchecked. Flask, Django, Starlette and FastAPI check what their router chose: a static catch-all and your longer routes run. A bare WSGI or ASGI app (Falcon, Bottle) refuses with 400 a path that would match a route of the map if a parameter took several segments (`DELETE /notes/7/x`). Write the route map without the prefix your app is mounted at; a proxy that strips a prefix must set `SCRIPT_NAME` or `root_path`. A page of your own that looks like one of these is refused too, and the message says so. Declare it, as an exact path (`/notes.json` next to `/notes`) or a template with its method (`("DELETE", "/notes/{id}/comments")`), with the routes above. On Flask, Django, Starlette and FastAPI, which see the handler, a declared page never runs the handler of a protected route, and a page that differs from a protected route by its last `/` only (`/notes/new/` next to `/notes/{id}`, usual in Django) can be declared. A bare WSGI or ASGI app passes a declared page to your app as it is: no wildcard route of a protected handler (Bottle ``, Falcon `{id:path}`) may reach it. There, a page that differs by its last `/` stays refused, and the log says so once. **The handler of a protected route runs only for that route.** Flask, Django, Starlette and FastAPI know, for each route of the map, the handler their router runs for it, and refuse with 400 any other request that would reach it: an alias (`/old/notes/7/archive`), a catch-all that also serves `DELETE /notes/7/archive/x`, a static catch-all that also answers a route of the map, for any method: one view that serves a protected `DELETE` and an unmapped `POST` is refused for the `POST` too, as it runs the same code (and reads its input, the query string included). `unprotected` never lifts this. Split the view, one per method, or map the other method at the same capability and level; the refusal names both. One function that serves two mapped methods of a template (Flask `methods=["GET", "POST"]`) runs the same code for both, so a request checked for one runs it only if that route covers the other: a `GET` mapped at level 1 next to a `POST` at level 3 is refused, and the log names both routes. One function on two routes of other paths (`DELETE /notes/` at level 3 and `DELETE /items/` at level 1) runs for a request checked for one only if that route covers the other: the level-1 request is refused. A `MethodView` (or a Django or Starlette class view) with separate `get()` and `post()` dispatches by method, and each runs for its own route, on any path the view serves (a route of the same method on another path still needs covering). A handler that is protected as a catch-all for another route (a front controller bound to `/home` and to `/`) never runs for a request checked for a route that does not cover that other route. Give each route of the map a handler of its own. A CORS preflight `OPTIONS` that the framework answers itself (Flask's automatic `OPTIONS`, a Starlette route without `OPTIONS`, and a Django class-based view or a Starlette endpoint whose classes, Django's or Starlette's own aside, define only their HTTP handlers, as plain functions, and plain data) is not refused. Anything that runs your code for it ends that: a function view, a decorator or wrapper around `as_view()`, `as_view()` arguments other than plain data (`as_view(dispatch=f)`), a property or a metaclass, route middleware, a `Route` class of your own with its own `handle()`, a `functools.partial` of the endpoint. Then `OPTIONS` is refused. Middleware, error handlers and converters are not the view: they run for every request, on any path. When the router has no handler for a route of the map, requests near it are refused, whatever their method (a `GET` near a `POST` route may run its handler): map only the routes your app serves. A checked request whose matched rule (Flask's `request.url_rule`, Django's `resolver_match`) has the route's own shape names the route's handler at once. Otherwise the SDK finds a route's handler in the router's own rules (Flask's URL map, Starlette's routes and mounts, Django's `path()` patterns, and `re_path()` patterns that are literal text and one-segment named groups, such as `^notes/(?P[0-9a-f]{24})/archive$`): a rule of the route's shape, its converters aside, names it, even when the converter refuses every sample value (``). Where there is no such rule (a regular expression with alternatives, optional parts or a group that may take a `/`), it resolves sample values (`1`, `a`, a UUID); when a catch-all answers them instead, the log says the handler is not known, and requests near the route are refused until its own handler is found. A checked request teaches a handler as the route's only when the rule that matched has the route's own shape, or the router also chooses it for the route's sample values: a literal page (`/api/notes/export` next to `/api/notes/{id}`) serves one value, not the route, so a request checked for the route that reaches it is refused and nothing is learnt. Two routes of one shape, parameter names aside (`/items/{id}` and `/items/{item}`), are one template. A catch-all is never learnt: next to the route's own handler, a checked request that would run one is refused; when the route's own handler is not known and the catch-all is the only handler found for it (a front controller, a router mounted at `/`), it runs for that checked request if the route covers every other route for which that catch-all is protected (every route whose own handler is not known and among whose handlers it is found, and every route for which it is a catch-all under the prefix: a request checked at level 1 never runs a front controller that is also one of a level-3 route's handlers), and the route stays not known. A site-wide or SPA fallback (a `/` rule at the root, as the router shows) is protected for a route only while that route's own handler is not known, so its pages run once every route of the map has a handler of its own (if a route's only handler is the fallback, a front controller, the fallback is that route's handler, protected, and the log names the route); a catch-all under the route's prefix (`/notes//`, or `/notes//` for `/notes/{id}/archive`) stays protected and keeps the route unknown, until the route's own handler is known (a rule of its own shape, which also frees an SPA fallback next to a tenant route `/{org}/notes/{id}`): give the route a rule of its own shape. Limit: a site-wide catch-all that dispatches protected actions on paths no route maps (a legacy `/` controller that deletes at `/legacy/delete?id=7`) is not something the SDK can see, and a front controller shared by routes of different capabilities or resources runs for none of them (covering needs the same capability and resource): give each protected route its own handler. A view class is one handler per set of arguments: `Item.as_view("users", User)` is not the handler of a route served by `Item.as_view("notes", Note)`, and two views of one class with the same arguments are the same handler. A bare WSGI or ASGI app cannot tell: there, next to a protected route that ends in a word (`DELETE /notes/{id}/archive`), a catch-all of yours that also takes longer paths runs `DELETE /notes/7/archive/x` without a check. ```python aby = AllowedBy( origin=os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), node=os.environ.get("ALLOWEDBY_NODE", "http://localhost"), org={"legal_name": "Notes Ltd", "country": "FR"}, routes=routes, templates=templates, unprotected=[("DELETE", "/notes/{id}/comments"), ("GET", "/notes.json")], # your own pages: the app's, unchanged ) ``` A path that is a route of the map cannot be declared. An encoded `?` or `#` in a path segment stays part of the segment. The URL a proof is checked against is the path as the client sent it (ASGI `raw_path`); WSGI and Django give only the decoded path, which the SDK encodes again, so there an encoded reserved character (`%40` for `@`) in a path segment is refused: send it unencoded or serve the API with an ASGI server. ### WSGI `app = aby.wsgi(app)`; the Context is `environ["allowedby.context"]`. See the quick start above (`sdks/python/examples/quickstart.py`). Falcon and Bottle work the same way: their apps, and a plain one with every route, are in `sdks/python/examples/frameworks/`. ### FastAPI From `sdks/python/examples/frameworks/fastapi/app.py`: ```python """FastAPI: the middleware, the Context as a dependency, and FastAPI's OpenAPI with the AllowedBy members. Run: uvicorn app:app --port 8000""" import itertools import os from fastapi import Depends, FastAPI from pydantic import BaseModel, Field from allowedby import AllowedBy, Context, route from allowedby.fastapi import allowedby_context, install aby = AllowedBy( origin=os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), node=os.environ.get("ALLOWEDBY_NODE", "http://localhost"), org={"legal_name": "Notes Interop Ltd", "country": "FR"}, routes=[ route("GET", "/me", level=0, summary="Who is calling"), route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}", summary="Delete a note"), ], templates={"notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}"}, refresh_seconds=float(os.environ.get("ALLOWEDBY_REFRESH_SECONDS", "5")), ) app = FastAPI(title="Notes") install(app, aby) notes: dict[str, list[dict[str, str]]] = {} # person -> their notes ids = itertools.count(1) def person(ctx) -> str: """The person of a level 1 or 2 route (the key of their notes); level 0 has none, and none is invented.""" if ctx is None or ctx.human_id is None: raise LookupError("no person at level 0") return ctx.human_id class Note(BaseModel): text: str = Field(min_length=1, max_length=2000) @app.get("/health") def health() -> dict[str, bool]: return {"ok": True} # not in the route map: yours, unchanged @app.get("/me") def me(ctx: Context = Depends(allowedby_context)) -> dict[str, object]: return {"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level} @app.get("/notes") def list_notes(ctx: Context = Depends(allowedby_context)) -> dict[str, object]: return {"notes": notes.get(person(ctx), [])} @app.post("/notes", status_code=201) def add_note(note: Note, ctx: Context = Depends(allowedby_context)) -> dict[str, str]: nid = str(next(ids)) notes.setdefault(person(ctx), []).append({"id": nid, "text": note.text}) return {"id": nid} @app.delete("/notes/{id}") def delete_note(id: str, ctx: Context = Depends(allowedby_context)) -> dict[str, str]: mine = notes.get(person(ctx), []) for note in [n for n in mine if n["id"] == id]: # in place: a note added meanwhile stays mine.remove(note) return {"deleted": id} ``` `install(app, aby)` adds the middleware and serves FastAPI's own `/openapi.json` with `security` and `x-allowedby` on every operation of the route map (readable from any origin). At start-up it checks that every route of the map has a FastAPI operation with the same method and path; a missing one stops the start. `allowedby_context` answers 403 on a route outside the map; `optional_allowedby_context` returns None there. ### Starlette and any ASGI app From `sdks/python/examples/frameworks/starlette/app.py`: ```python """Starlette: AllowedByMiddleware; the Context is request.state.allowedby. Run: uvicorn app:app --port 8000""" import itertools import json import os from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.responses import JSONResponse from starlette.routing import Route from allowedby import AllowedBy, route from allowedby.asgi import AllowedByMiddleware aby = AllowedBy( origin=os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), node=os.environ.get("ALLOWEDBY_NODE", "http://localhost"), org={"legal_name": "Notes Interop Ltd", "country": "FR"}, routes=[ route("GET", "/me", level=0, summary="Who is calling"), route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}", summary="Delete a note"), ], templates={"notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}"}, refresh_seconds=float(os.environ.get("ALLOWEDBY_REFRESH_SECONDS", "5")), ) notes, ids = {}, itertools.count(1) # person -> their notes def person(ctx) -> str: """The person of a level 1 or 2 route (the key of their notes); level 0 has none, and none is invented.""" if ctx is None or ctx.human_id is None: raise LookupError("no person at level 0") return ctx.human_id def text_of(raw: bytes) -> object: """The body's "text", or None when the body is not a JSON object (the request then gets a 400).""" try: body = json.loads(raw or b"{}") except ValueError: return None return body.get("text") if isinstance(body, dict) else None async def health(request): return JSONResponse({"ok": True}) # not in the route map: yours, unchanged async def me(request): ctx = request.state.allowedby return JSONResponse({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level}) async def list_notes(request): return JSONResponse({"notes": notes.get(person(request.state.allowedby), [])}) async def add_note(request): text = text_of(await request.body()) if not isinstance(text, str) or not 0 < len(text) <= 2000: return JSONResponse({"error": "text: a string of 1 to 2000 characters"}, 400) note = {"id": str(next(ids)), "text": text} notes.setdefault(person(request.state.allowedby), []).append(note) return JSONResponse({"id": note["id"]}, 201) async def delete_note(request): mine = notes.get(person(request.state.allowedby), []) for note in [n for n in mine if n["id"] == request.path_params["id"]]: # in place: a note added meanwhile stays mine.remove(note) return JSONResponse({"deleted": request.path_params["id"]}) app = Starlette( routes=[ Route("/health", health), Route("/me", me), Route("/notes", list_notes, methods=["GET"]), Route("/notes", add_note, methods=["POST"]), Route("/notes/{id}", delete_note, methods=["DELETE"]), ], middleware=[Middleware(AllowedByMiddleware, aby=aby)], ) ``` For a bare ASGI app: `app = AllowedByMiddleware(app, aby)`; the Context is also in `scope["allowedby.context"]` (`sdks/python/examples/frameworks/asgi/app.py`). The check never blocks the event loop: it runs in a worker thread (about 0.3 ms of hand-off, measured). ### Flask From `sdks/python/examples/frameworks/flask/app.py`: ```python """Flask: the AllowedBy extension; the Context is g.allowedby. Run: flask --app app run --port 8000""" import itertools import json import os from flask import Flask, g, request from allowedby import route from allowedby.flask import AllowedBy app = Flask(__name__) app.config["ALLOWEDBY"] = { "origin": os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), "node": os.environ.get("ALLOWEDBY_NODE", "http://localhost"), "org": {"legal_name": "Notes Interop Ltd", "country": "FR"}, "routes": [ route("GET", "/me", level=0, summary="Who is calling"), route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}", summary="Delete a note"), ], "templates": {"notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}"}, "refresh_seconds": float(os.environ.get("ALLOWEDBY_REFRESH_SECONDS", "5")), } AllowedBy(app) notes, ids = {}, itertools.count(1) # person -> their notes def person(ctx) -> str: """The person of a level 1 or 2 route (the key of their notes); level 0 has none, and none is invented.""" if ctx is None or ctx.human_id is None: raise LookupError("no person at level 0") return ctx.human_id def text_of(raw: bytes) -> object: """The body's "text", or None when the body is not a JSON object (the request then gets a 400).""" try: body = json.loads(raw or b"{}") except ValueError: return None return body.get("text") if isinstance(body, dict) else None @app.get("/health") def health(): return {"ok": True} # not in the route map: yours, unchanged @app.get("/me") def me(): return {"agent": g.allowedby.agent, "operator": g.allowedby.operator, "level": g.allowedby.level} @app.get("/notes") def list_notes(): return {"notes": notes.get(person(g.allowedby), [])} @app.post("/notes") def add_note(): text = text_of(request.get_data()) if not isinstance(text, str) or not 0 < len(text) <= 2000: return {"error": "text: a string of 1 to 2000 characters"}, 400 note = {"id": str(next(ids)), "text": text} notes.setdefault(person(g.allowedby), []).append(note) return {"id": note["id"]}, 201 @app.delete("/notes/") def delete_note(note_id): mine = notes.get(person(g.allowedby), []) for note in [n for n in mine if n["id"] == note_id]: # in place: a note added meanwhile stays mine.remove(note) return {"deleted": note_id} ``` `AllowedBy(app, aby=...)` takes an instance instead; `ext.init_app(app)` works for app factories. ### Django From `sdks/python/examples/frameworks/django/app.py`: ```python """Django in one file: settings.ALLOWEDBY and the middleware; the Context is request.allowedby. Run: python app.py runserver 8000""" import itertools import json import os import sys from django.conf import settings from allowedby import route settings.configure( DEBUG=False, ALLOWED_HOSTS=["localhost", "127.0.0.1", "testserver"], ROOT_URLCONF=__name__, SECRET_KEY=os.environ.get("DJANGO_SECRET_KEY", "change-me"), MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware", "allowedby.django.AllowedByMiddleware"], ALLOWEDBY={ "origin": os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), "node": os.environ.get("ALLOWEDBY_NODE", "http://localhost"), "org": {"legal_name": "Notes Interop Ltd", "country": "FR"}, "routes": [ route("GET", "/me", level=0, summary="Who is calling"), route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}", summary="Delete a note"), ], "templates": {"notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}"}, "refresh_seconds": float(os.environ.get("ALLOWEDBY_REFRESH_SECONDS", "5")), }, ) from django.http import JsonResponse # noqa: E402 - after settings.configure from django.urls import path # noqa: E402 from django.views import View # noqa: E402 from django.views.decorators.http import require_http_methods # noqa: E402 notes, ids = {}, itertools.count(1) # person -> their notes def person(ctx) -> str: """The person of a level 1 or 2 route (the key of their notes); level 0 has none, and none is invented.""" if ctx is None or ctx.human_id is None: raise LookupError("no person at level 0") return ctx.human_id def text_of(raw: bytes) -> object: """The body's "text", or None when the body is not a JSON object (the request then gets a 400).""" try: body = json.loads(raw or b"{}") except ValueError: return None return body.get("text") if isinstance(body, dict) else None def health(request): return JsonResponse({"ok": True}) # not in the route map: yours, unchanged def me(request): ctx = request.allowedby return JsonResponse({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level}) class Notes(View): """One view class, one method each: GET /notes (read) and POST /notes (write) are routes of their own, so each runs only for a request checked for it (a single function for both would run the write for a read check: refused).""" def get(self, request): return JsonResponse({"notes": notes.setdefault(person(request.allowedby), [])}) def post(self, request): mine = notes.setdefault(person(request.allowedby), []) text = text_of(request.body) if not isinstance(text, str) or not 0 < len(text) <= 2000: return JsonResponse({"error": "text: a string of 1 to 2000 characters"}, status=400) note = {"id": str(next(ids)), "text": text} mine.append(note) return JsonResponse({"id": note["id"]}, status=201) @require_http_methods(["DELETE"]) def note_view(request, note_id): mine = notes.get(person(request.allowedby), []) for note in [n for n in mine if n["id"] == note_id]: # in place: a note added meanwhile stays mine.remove(note) return JsonResponse({"deleted": note_id}) urlpatterns = [ path("health", health), path("me", me), path("notes", Notes.as_view()), path("notes/", note_view), ] if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) ``` In a project, put `ALLOWEDBY = {...}` in `settings.py` (or a dotted path to an `AllowedBy` instance) and add `"allowedby.django.AllowedByMiddleware"` to `MIDDLEWARE`. A request the SDK accepted is exempt from Django's CSRF check: it carries no cookie credential, and the agent signed this exact method, URL and body. ## The context An accepted request gives the handler a read-only `Context`; setting a field raises `AttributeError`. | Field | Type | Meaning | |---|---|---| | `human_id` | `str \| None` | The person, as a pseudonym specific to your origin (None on level 0 routes) | | `level` | `int` | The identity level actually proven: 0 to 3 | | `agent` | `str` | The agent's passport subject (`did:oaid:...`) | | `operator` | `str \| None` | Who runs the agent: a verified domain, or a node-scoped id | | `capabilities` | `list[str]` | The capabilities of the grant used | | `display` | `dict \| None` | What the person saw and signed: `summary`, `lines`, `lang` | | `gid`, `rev`, `jti` | `str`, `int`, `str` | The grant's id, revision and document id (audit) | | `acting_for` | `dict \| None` | The organisation the person acts for, with its mandate (`org`, `name`, `role`) | | `tenant` | `str \| None` | The `{tenant}` path parameter, when tenants are configured | | `linked_account` | `str \| None` | On a `require_link` route, the account the person is linked to (ABY-3 §6); `None` elsewhere | | `route` | `dict` | The route of the map that matched, after tenant overrides | | `chain` | `list[tuple[str, int]]` | `(gid, rev)` of each grant, leaf first (sub-agents) | | `run`, `call` | `str \| None`, `int \| None` | The agent's run id and call counter from the proof (audit) | | `proof_jti` | `str` | The proof's id (audit) | | `params` | `dict[str, str]` | The route's path values as checked (`{"id": "7"}`): from the normalised path, decoded once. Act on these, never on your own reading of the raw path (`DELETE /notes/7/.` is checked as `/notes/7`) | `ctx.as_dict()` returns the fields as a dict; `repr(ctx)` shows ids only. `aby.personal_data(ctx)` returns the attributes the person chose to share for this grant (extended feature `disclose`). ## Production Keep the keys in one file, share the store between instances, and let the background refresh run. From `sdks/python/examples/production.py`: ```python """Production settings: keys kept across restarts and shared by instances, a Redis store shared by every machine, JSON audit lines on stdout. Several instances behind a load balancer run this same code.""" import os from allowedby import AllowedBy, route from allowedby.redis_store import RedisStore aby = AllowedBy( origin=os.environ["ALLOWEDBY_ORIGIN"], # https://api.example.com, as agents call it node=os.environ["ALLOWEDBY_NODE"], # the node you trust org={"legal_name": "Notes Ltd", "country": "FR", "website": "https://notes.example"}, routes=[route("GET", "/notes", "notes:read", level=1, resource="note:*"), route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}")], templates={"notes:read": "Read your notes", "notes:delete": "Delete note {scope}"}, key_file=os.environ.get("ALLOWEDBY_KEY_FILE", "/run/secrets/allowedby-keys.json"), # one file, every instance store=RedisStore.from_url(os.environ["REDIS_URL"]), # replay set, single use and counters, shared refresh_seconds=5, # node statement and status lists, fetched in the background audit_sink="stdout-json", # one JSON line per decision: codes and ids, no personal data ) ``` - **Keys** (`key_file`): the signing key (Ed25519) and the disclosure key (P-256). Created on first use with mode 0600, atomically, first writer wins (the folder needs hard links, else the start fails with a message); every SDK reads the same JSON format. Without it, both keys are new at each start. Keep the file in a secret store (a mounted secret on Kubernetes or Cloud Run). - **Store**: `MemoryStore` (the default) holds the replay set, single-use consumption and counters for **one process only**. With several processes or machines, use `RedisStore` (atomic with WATCH/MULTI, amounts added as decimals) or `SqliteStore(path)` (one machine, several processes). Expiry follows the SDK's clock. A store that fails refuses the request (503 `status_stale`); it never accepts it. - **Refunds** (sdks/CONTRACT.md, Refund on the SDK's own refusal): the check consumes a single-use approval and adds to the grant's totals and the tenant budget. When the SDK then refuses that request itself before the view (the Flask extension, `wsgi_guard()`, Django's middleware, the ASGI guard's first check: rule 5, a method or path changed after the check), `AllowedBy.release(ctx)` gives back exactly what the check spent, once, so the approval stays usable. A refund the store does not take leaves it spent. Nothing is given back once the view started (the adapters call `started(ctx)` as they hand the request on, so a second dispatch of the same request gets nothing back, and refuse a request already given back, which `started(ctx)` answers with False: it never reaches a view), nor for a refusal of your own (use `refund(ctx)` to give a tenant budget back). - **Trust**: by default the SDK pins the node's key on first fetch (TOFU). For a fixed list of nodes, pass `trust_list=TrustList(jws, service_key)` (OAID-5). - **Refresh**: node statements and status lists are fetched in the background every `refresh_seconds` (status lists at least every 60 s), never on the request path. A failure logs `[verifier] refresh failed` and the SDK keeps serving from its cache within the freshness rules (stale lists refuse with 503). - **Logging**: one line per decision on stdout (method, path, code; never tokens, keys or bodies); `audit_sink="stdout-json"` or a callable adds JSON events (ORG-1 §7.6). - **Origin**: `origin` is the public URL agents call. Behind a proxy, the SDK builds URLs from `origin` and the path the app sees: the proxy must not rewrite the path. Mounted under a prefix (ASGI `root_path`, a Starlette `Mount`, WSGI `SCRIPT_NAME`), the route map is matched on the path without the prefix, and proofs are checked against the full URL the agent called (`origin` + prefix + path). The callback URL, the link route and the links in the discovery documents carry the prefix too. Nodes and agents read `/.well-known/allowedby` at the origin's root: serve it there as well (route it to the same app). ## Agents `Agent` calls AllowedBy APIs for a person; `Wallet` turns it into tools for MCP, LangChain and the OpenAI Agents SDK, which pause while the person approves. From `sdks/python/examples/agent_quickstart.py`: ```python """Agent quick start: call an AllowedBy API as a person's agent. The person approves on their own device.""" import os from allowedby import Agent def tell(message): if message["type"] == "approval_needed": print("Approve on your device. Check the code %s: %s" % (message["code"], message["link"])) agent = Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost"), tell=tell) if __name__ == "__main__": status, body = agent.call("GET", os.environ.get("APP_URL", "http://notes.localhost") + "/notes", action="notes:read") print(status, body) ``` `agent.call(method, url, body, action)` gets a passport (tier 0) from the node, signs the request with a proof, and on a challenge asks the node for an approval, tells the person the link and the binding code, waits for the tap (long polling), and retries once. Standing grants (read and write) are reused while they cover the action. `operator_domain` and `operator_key` let approvals survive a new passport (rebind, ABY-1 §6); `agent.delegate(...)` gives a sub-agent an attenuated grant (ABY-1 §4). A tier 0 passport comes with a new key. The agent keeps the previous key in memory until its passport expires, so a standing grant or a pending approval that names it stays usable. The wait for the person ends before the passport that asked expires. An approval link is shown only when it is on the agent's node, or on the approval page the node names in its signed statement (OAID-2 §3). `node_origin` must be an `https` origin (`http` on this machine only), else `ValueError`. ### MCP The `allowedby-mcp` command is an MCP server over stdio with four tools: `allowedby_discover`, `allowedby_call`, `allowedby_wait`, `allowedby_approvals`. ```bash claude mcp add allowedby -- allowedby-mcp --node https://demo.allowedby.com allowedby-mcp --node http://localhost --no-browser --allow https://notes.example ``` The approval page opens in the person's browser; when the tap takes longer than the call's wait, the tool returns the sentence to show the person verbatim (`tell_the_person`), with a job id for `allowedby_wait`. Approvals are kept in `~/.allowedby/mcp-approvals.json` (`--state`). ### LangChain From `sdks/python/examples/frameworks/langchain/agent.py`: ```python """LangChain: the AllowedBy tools for any LangChain agent. `tell` posts the approval link and code into the conversation; the request tool waits for the person's tap.""" import os from allowedby import Agent from allowedby.langchain import AllowedByDiscoverTool, AllowedByRequestsTool from allowedby.tools import Wallet def tell(message): if message["type"] == "approval_needed": print(message["text"]) # the sentence to show the person, verbatim (link and code) wallet = Wallet(Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost")), tell=tell) tools = [AllowedByDiscoverTool(wallet=wallet), AllowedByRequestsTool(wallet=wallet, wait_seconds=300)] # Give `tools` to your agent: langchain.agents.create_agent(model, tools=tools). ``` ### OpenAI Agents SDK From `sdks/python/examples/frameworks/openai-agents/agent.py`: ```python """OpenAI Agents SDK: the AllowedBy tools as FunctionTools.""" import os from agents import Agent as Assistant from allowedby import Agent from allowedby.openai_agents import INSTRUCTIONS, allowedby_tools from allowedby.tools import Wallet def tell(message): if message["type"] == "approval_needed": print(message["text"]) # the sentence to show the person, verbatim (link and code) wallet = Wallet(Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost")), tell=tell) assistant = Assistant(name="assistant", instructions=INSTRUCTIONS, tools=allowedby_tools(wallet)) # Run: agents.Runner.run_sync(assistant, "Read my notes on https://notes.example") ``` `Wallet(agent, tell, allowed_origins=[...])` restricts the sites the tools may call; `state=path` keeps approvals across restarts in a private file. ## Errors Every refusal is `application/problem+json` with `type: https://allowedby.org/errors/`; 401 answers carry `WWW-Authenticate: AllowedBy ...`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a header is repeated or unreadable | Fix the request | | `passport_required` | 401 | No `Allowed-By` header | The agent gets a passport from its node and retries | | `invalid_signature` | 401 | A signature, proof, chain or `human_sig` check failed, or the proof was replayed | The agent signs a fresh proof; check its clock (-120 s to +60 s) | | `untrusted_node` | 401 | The grant or passport comes from a node this service does not trust | Use a trusted node, or add it (trust list) | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses | Retry later; the node operator fixes its witnesses | | `grant_required` | 401 | The route needs a person's approval and the agent showed only its passport | The agent asks the person (the challenge says what) | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator) | The agent asks for a grant that covers it | | `level_insufficient` | 401 | The person's identity level is below the route's | The person verifies their identity to that level | | `qes_required` | 401 | The route needs a qualified electronic signature | The person signs with a qualified signature | | `authority_required` | 401 | The organisation's co-approvers have not approved | The co-approvers approve | | `mandate_required` | 401 | The route needs a company mandate | The person acts with their company's mandate | | `expired` | 401 | The grant has expired | The agent asks again | | `not_yet_valid` | 401 | The grant's `nbf` is in the future | Check clocks; retry | | `revoked` | 401 | The person or the node withdrew the grant | The agent asks again; respect the person's choice | | `actor_expired` | 401 | The agent's key (passport) expired | The agent gets a new passport and rebinds its grants | | `class_lifetime_exceeded` | 401 | The grant lives longer than the route's class allows | The agent asks for a shorter grant | | `single_use_consumed` | 401 | A one-time grant was already used | The agent asks again for this request | | `capability_denied` | 403 | Not allowed at all (route unknown, operator not accepted, over a ceiling) | Do not retry | | `tier_insufficient` | 403 | The agent's key custody or the passkey kind is too weak | Use a stronger custody tier or passkey | | `human_not_linked` | 403 | The person has not linked their account here | The person links their account (`aby:link`) | | `budget_exceeded` | 403 | The organisation's budget for this action is used up | Wait for the next period or raise the budget | | `rate_limited` | 429 | Too many requests from this agent or operator | Wait (`Retry-After`) | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two grants (depth 1) | Send a shorter chain | | `status_stale` | 503 | The revocation list is too old to decide, or the replay store is unavailable | Retry after `Retry-After` | `allowedby.STATUS` maps every code to its status. ## Testing Run the vectors and the interop test from the repository root, and test your own app offline with `aby.check()`. ```bash pip install -r requirements.txt -e "sdks/python[asgi,fastapi,django,flask,redis,langchain,openai-agents,dev]" python sdks/python/tests/conformance.py # verifier profile: 481/481, runtime profile: 122/122 (cd sdks/python && python -m pytest -q) # unit tests, every adapter, stores, agent tools python sdks/interop/interop.py --cmd "python sdks/interop/reference_app.py" # 26/26 python sdks/python/examples/frameworks/run.py flask fastapi # 26/26 each python sdks/interop/interop.py --agent-cmd "python sdks/python/examples/interop_agent.py" # 7/7 ``` On Windows (PowerShell) the commands are the same; set the interop ports with `$env:INTEROP_PORT_BASE = "19100"` when another run uses the defaults. `REDIS_URL=redis://localhost:6379/0` runs the store tests on a real Redis (`docker run -p 6379:6379 redis:7.4-alpine`); without it they use `fakeredis`. Testing your own app needs no browser and no node: `background_refresh=False` keeps the SDK offline, and `aby.check(method, path, headers, body)` returns its decision. From `sdks/python/examples/testing.py`: ```python """Testing your own app without a browser or a node: `aby.check()` gives the SDK's answer to any request, and `background_refresh=False` keeps the test offline. A request without a passport gets the challenge an agent sees. Run: python testing.py (or with pytest: the test_* functions)""" from allowedby import AllowedBy, route aby = AllowedBy( origin="https://notes.example", node="https://node.example.org", org={"legal_name": "Notes Ltd", "country": "FR"}, routes=[route("GET", "/notes", "notes:read", level=1, resource="note:*"), route("GET", "/health", level=0)], templates={"notes:read": "Read your notes"}, background_refresh=False, # no thread, no fetch: the node is never contacted ) def test_a_request_without_passport_gets_the_challenge(): ctx, refusal = aby.check("GET", "/notes", headers={}) status, problem, headers = refusal assert ctx is None and status == 401 and problem["type"].endswith("/passport_required") assert headers["WWW-Authenticate"] == 'AllowedBy realm="notes.example", error="passport_required"' def test_paths_outside_the_route_map_are_yours(): assert aby.check("GET", "/about", headers={}) == (None, None) def test_discovery_documents(): assert aby.openapi()["paths"]["/notes"]["get"]["x-allowedby"]["capability"] == "notes:read" assert aby.well_known()["templates"]["notes:read"]["summary"]["en"] == "Read your notes" if __name__ == "__main__": for name, fn in list(globals().items()): if name.startswith("test_"): fn() print("ok", name) ``` For an accepted request end to end, run your app under the interop harness (`interop.py --cmd`): it starts a real node, an agent and a person with a software passkey. `sdks/python/tests/conftest.py` shows how the SDK's own tests verify real signed requests offline, with the vectors' node and clock. ## Reference The public API is `allowedby` (service and agent), plus one module per integration. | Name | What | |---|---| | `AllowedBy(origin, node, routes, templates, org, ...)` | The service SDK. Options: `key_file`, `store`, `trust_list`, `refresh_seconds`, `node_max_level`, `clock`, `title`, `version`, `description`, `max_body`, `background_refresh`, `serve_openapi`, `unprotected`, and the extended ones below | | `AllowedBy.check(method, path, headers, body, query)` | `(Context, None)` accepted; `(None, response)` refused; `(None, None)` outside the map | | `AllowedBy.process(...)` | `handle()` then `check()`: what every adapter calls | | `AllowedBy.handle(method, path, headers, body)` | The SDK's own endpoints, or None | | `AllowedBy.wsgi(app, guarded=False)`, `wsgi_guard(app)`, `may_dispatch(method, path, checked)` | WSGI middleware; the check again at dispatch | | `AllowedBy.openapi()`, `well_known()`, `api_catalog()`, `describe(method, path)` | The discovery documents; one operation's OpenAPI members | | `AllowedBy.personal_data(ctx)`, `refund(ctx)`, `release(ctx)`, `started(ctx)`, `link_start(account)`, `unlink(account)` | Disclosed attributes; give a tenant budget back; give back what the check spent for a request the SDK refused itself; mark the request as handed to its handler (no refund after that; False for a request given back, which the adapter refuses); account linking code; remove an account's link (and its pending codes), for an account deleted or a person who asks to be forgotten | | `route(method, path, capability, cls, level, resource, ...)` | One route of the map | | `render(response)` | A response as `(status, headers, bytes)` | | `load_keys(path)` | The key file: `(signing Key, disclosure key)` | | `Context` | The accepted request (read-only) | | `Store` (protocol), `MemoryStore`, `SqliteStore`, `redis_store.RedisStore` | Replay set, single use, counters | | `TrustList(jws, key)` | A signed OAID-5 trust list | | `Reject`, `STATUS` | A refusal (`code`, `status`, `why`); code to status | | `Agent(node, operator, runtime, tell, poll_timeout, operator_domain, operator_key, http_sig)` | The agent SDK: `call`, `delegate`, `adopt`, `rebind`, `ensure_passport`, `wait_for` | | `asgi.AllowedByMiddleware(app, aby, guarded=False)`, `asgi.DispatchGuard(app, aby)` | ASGI middleware; the check again at dispatch | | `fastapi.install(app, aby)`, `allowedby_context`, `optional_allowedby_context`, `enrich_openapi`, `check_routes` | FastAPI | | `django.AllowedByMiddleware`, `django.from_settings()` | Django | | `flask.AllowedBy(app, aby=None)` | Flask extension | | `tools.Wallet(agent, tell, state, allowed_origins)`, `tools.TOOLS`, `tools.INSTRUCTIONS` | Agent tools shared by the integrations | | `mcp.main()`, `mcp.Server`, `mcp.wallet_for(node, ...)` | MCP server (`allowedby-mcp`) | | `langchain.AllowedByRequestsTool`, `langchain.AllowedByDiscoverTool` | LangChain tools | | `openai_agents.allowedby_tools(wallet)` | OpenAI Agents SDK tools | What is implemented (sdks/CONTRACT.md): - **Core** (§2, all of it): configuration checked at construction, the route map, discovery (`/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog`), verification ABY-2 §5 steps 1-10 (proof JWT and RFC 9421, passports, grant chains, `human_sig`, status lists, trust on first use and OAID-5 trust lists, EdDSA and ES256 only), challenges with service-initiated approvals, background refresh, the Context, the stores (memory, SQLite, Redis), the key file, middleware for WSGI, ASGI, FastAPI, Django and Flask. - **Extended** (all of them, as the reference): disclosure callback and JWE decryption (`disclosure`), tenants and tenant budgets (`tenants`), authority policies (`authority_policy`), account linking (`require_link`, `link_start`), AllowedBy-Nonce (`nonce`), company mandates (`mandate`), level profiles (`level_profile`), rate limits (`rate`), the audit sink (`audit_sink`), the admin console (`/allowedby/admin`). - **Agent** (§3): passports, proofs, challenges, approvals, rebind, renewal, sub-agents, and the MCP, LangChain and OpenAI Agents SDK integrations. Version: package 0.1.0, specification set 0.2.14. The full source is `sdks/python/src/allowedby/`. --- # Error codes Every SDK answers the same codes with the same statuses; `tools/docs.py` checks this table and every language guide against the verifier. A refusal is `application/problem+json` with `type: https://allowedby.org/errors/`. A `401` that the agent can resolve also carries a challenge in `WWW-Authenticate: AllowedBy ...` (ABY-2 §6). `429` and `503` carry `Retry-After`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a header is repeated or unreadable | Fix the request | | `passport_required` | 401 | No `Allowed-By` header | The agent gets a passport from its node and retries | | `invalid_signature` | 401 | A signature, proof, chain or `human_sig` check failed, or the proof was replayed | The agent signs a fresh proof; check its clock (-120 s to +60 s) | | `untrusted_node` | 401 | The grant or passport comes from a node this service does not trust | Use a trusted node, or add it (trust list) | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses | Retry later; the node operator fixes its witnesses | | `grant_required` | 401 | The route needs a person's approval and the agent showed only its passport | The agent asks the person (the challenge says what) | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator) | The agent asks for a grant that covers it | | `level_insufficient` | 401 | The person's identity level is below the route's | The person verifies their identity to that level | | `qes_required` | 401 | The route needs a qualified electronic signature | The person signs with a qualified signature | | `authority_required` | 401 | The organisation's co-approvers have not approved | The co-approvers approve | | `mandate_required` | 401 | The route needs a company mandate | The person acts with their company's mandate | | `expired` | 401 | The grant has expired | The agent asks again | | `not_yet_valid` | 401 | The grant's `nbf` is in the future | Check clocks; retry | | `revoked` | 401 | The person or the node withdrew the grant | The agent asks again; respect the person's choice | | `actor_expired` | 401 | The agent's key (passport) expired | The agent gets a new passport and rebinds its grants | | `class_lifetime_exceeded` | 401 | The grant lives longer than the route's class allows | The agent asks for a shorter grant | | `single_use_consumed` | 401 | A one-time grant was already used | The agent asks again for this request | | `capability_denied` | 403 | Not allowed at all (route unknown, operator not accepted, over a ceiling) | Do not retry | | `tier_insufficient` | 403 | The agent's key custody or the passkey kind is too weak | Use a stronger custody tier or passkey | | `human_not_linked` | 403 | The person has not linked their account here | The person links their account (`aby:link`) | | `budget_exceeded` | 403 | The organisation's budget for this action is used up | Wait for the next period or raise the budget | | `rate_limited` | 429 | Too many requests from this agent or operator | Wait (`Retry-After`) | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two grants (depth 1) | Send a shorter chain | | `status_stale` | 503 | The revocation list is too old to decide, or the replay store is unavailable | Retry after `Retry-After` | ## How an agent reacts - **Asks the person, then retries once:** `grant_required`, `grant_insufficient`, `level_insufficient`, `qes_required`, `expired`, `revoked`, `class_lifetime_exceeded`, `single_use_consumed`. - **Gets a new passport or rebinds:** `passport_required`, `actor_expired`. - **Waits, then retries:** `rate_limited`, `status_stale`. - **Signs again, once:** `invalid_signature` (a fresh proof; check the clock and the URL). - **Stops:** every other code. Retrying cannot succeed until someone changes something. --- # Build with an AI assistant Coding assistants integrate AllowedBy well when they read these pages rather than guess. Give them one of the following. ## The documentation as tools (MCP) ```bash claude mcp add --transport http allowedby-docs https://docs.allowedby.com/mcp ``` The assistant can then search the documentation, read a page, get a recipe in your language and look up an error. Any assistant that supports MCP over HTTP can use the same address. ## One file per language Everything needed to accept agents in one language, in one Markdown file: | Language | File | |---|---| | Python | [llms/python.txt](https://docs.allowedby.com/llms/python.txt) | | JavaScript | [llms/js.txt](https://docs.allowedby.com/llms/js.txt) | | Go | [llms/go.txt](https://docs.allowedby.com/llms/go.txt) | | Java | [llms/java.txt](https://docs.allowedby.com/llms/java.txt) | | C# | [llms/dotnet.txt](https://docs.allowedby.com/llms/dotnet.txt) | | PHP | [llms/php.txt](https://docs.allowedby.com/llms/php.txt) | | Ruby | [llms/ruby.txt](https://docs.allowedby.com/llms/ruby.txt) | | Rust | [llms/rust.txt](https://docs.allowedby.com/llms/rust.txt) | The index of every page is [llms.txt](https://docs.allowedby.com/llms.txt), and all guides together are [llms-full.txt](https://docs.allowedby.com/llms-full.txt). Any page is also Markdown at its own address with `.md` added. ## A prompt that works ```text Read https://docs.allowedby.com/llms/python.txt. Then add AllowedBy to this app: - list the routes an agent may call, and propose a capability, class and level for each; ask me before going on; - write the sentence a person will sign for each capability; - add the middleware, and key every query on the person's id from the context; - run the app, show me that a protected route answers 401, and write the tests from the "test" recipe. ``` Change `python` to your language. ## Rules an assistant must keep - Never take the person's identity from the agent's input: use the id in the verified context. - Never catch a refusal and continue. - Never log `Allowed-By`, `AllowedBy-Proof` or a request body. - Use a shared store as soon as there is more than one process, and a key file in production. - Put the middleware outside anything that rewrites the path or the method. A weekly test gives an assistant only these public pages, asks it to integrate AllowedBy in a new app, and runs the end-to-end scenarios on the result. --- # Recipes in Python (each is run against a real node on every version) ## Quickstart A whole app that lets agents in with the person's approval. ```python import os from flask import Flask, g from allowedby import route from allowedby.flask import AllowedBy app = Flask(__name__) app.config["ALLOWEDBY"] = { "origin": os.environ["ALLOWEDBY_ORIGIN"], # your app's public URL "node": os.environ["ALLOWEDBY_NODE"], # the node you trust: people approve there "org": {"legal_name": "Notes Ltd", "country": "FR"}, "routes": [route("GET", "/notes", "notes:read", level=1, resource="note:*")], "templates": {"notes:read": "Read your notes"}, # what the person approves } AllowedBy(app) @app.get("/notes") def list_notes(): return {"notes": [], "person": g.allowedby.human_id} ``` ## See which agent is calling Know the agent and its verified operator, before any person is involved. ```python routes.append(route("GET", "/me", level=0, summary="Which agent is calling")) @app.get("/me") def me(): return {"agent": g.allowedby.agent, "operator": g.allowedby.operator} ``` ## Let an agent read The person approves once with a passkey; the approval is reused until it expires or they withdraw it. ```python routes.append(route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes")) templates["notes:read"] = "Read your notes" @app.get("/notes") def list_notes(): return {"notes": notes.list(g.allowedby.human_id)} ``` ## Let an agent write A change the person can undo: one approval, reused like a read. ```python routes.append(route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:*", summary="Add a note", body={"text": "the note"})) templates["notes:write"] = "Add and change your notes" @app.post("/notes") def add_note(): return notes.add(g.allowedby.human_id, str(request.json.get("text", ""))), 201 ``` ## Ask before deleting A change that is hard to undo: your app asks the person for that exact request, and the approval works once. ```python routes.append(route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}", summary="Delete a note")) templates["notes:delete"] = "Delete {scope}" @app.delete("/notes/") def delete_note(note_id): # The person approved this exact request, and it works once. if not notes.delete(g.allowedby.human_id, note_id): return {"error": "no such note"}, 404 return {"deleted": note_id} ``` ## Take a payment The person approves the amount and the payee; any other amount or payee is refused. ```python routes.append(route("POST", "/payees/{payee}/payments", "payments:send", cls="irreversible", level=2, resource="payee:{payee}", amount_field="/amount", summary="Pay someone", body={"amount": "a decimal string, e.g. 40.00", "currency": "e.g. EUR"})) templates["payments:send"] = "Pay {amount.max} {amount.currency} to {scope}" @app.post("/payees//payments") def pay(payee): # The payee, the amount and the currency are the ones the person approved. payment = request.json return {"paid": payment["amount"], "currency": payment["currency"], "to": payee}, 201 ``` ## Take a high-value payment Level 3: a verified identity and a hardware passkey. Anything weaker is refused. ```python routes.append(route("POST", "/payees/{payee}/transfers", "transfers:send", cls="irreversible", level=3, authn="hardware", resource="payee:{payee}", amount_field="/amount", summary="Send a bank transfer", body={"amount": "a decimal string, e.g. 4000.00", "currency": "e.g. EUR"})) templates["transfers:send"] = "Transfer {amount.max} {amount.currency} to {scope}" @app.post("/payees//transfers") def transfer(payee): # Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. order = request.json return {"sent": order["amount"], "currency": order["currency"], "to": payee, "level": g.allowedby.level}, 201 ``` ## Set a spending limit The person approves an amount per month once; the SDK keeps the total and refuses what goes over. ```python routes.append(route("POST", "/orders", "orders:place", cls="write", level=1, resource="order:new", amount_field="/total", summary="Place an order", body={"total": "a decimal string, e.g. 60.00", "currency": "e.g. EUR"})) templates["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}" @app.post("/orders") def place_order(): # The SDK keeps the total of the period: an order over the limit the person approved never gets here. order = request.json return {"ordered": order["total"], "currency": order["currency"]}, 201 ``` ## Start and cancel a subscription The person approves the plan and its monthly price once; you charge it until they cancel. ```python routes.append(route("POST", "/plans/{plan}/subscription", "plans:subscribe", cls="write-hard", level=1, resource="plan:{plan}", amount_field="/monthly", summary="Subscribe to a plan", body={"monthly": "the price per month, e.g. 12.00", "currency": "EUR"})) routes.append(route("GET", "/subscription", "plans:read", level=1, resource="plan:*", summary="Your subscription")) routes.append(route("DELETE", "/subscription", "plans:cancel", cls="write-hard", level=1, resource="plan:mine", summary="Cancel your subscription")) templates["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel" templates["plans:read"] = "See your subscription" templates["plans:cancel"] = "Cancel your subscription" @app.post("/plans//subscription") def subscribe(plan): # Approved once, with the price: your billing charges it every month (subscriptions.py) until it is cancelled. return subscriptions.start(g.allowedby.human_id, plan, request.json["monthly"]), 201 @app.get("/subscription") def subscription(): return subscriptions.get(g.allowedby.human_id) or ({"error": "no subscription"}, 404) @app.delete("/subscription") def cancel(): return subscriptions.cancel(g.allowedby.human_id) or ({"error": "no subscription"}, 404) ``` ## Accept a sub-agent An agent hands a sub-agent part of its approval, never more, and it ends when the person withdraws the first. ```python routes.append(route("GET", "/notes/{id}/summary", "notes:read", level=1, resource="note:{id}", summary="Summarise one note")) @app.get("/notes//summary") def summarise(note_id): # An agent may hand a sub-agent part of its approval: the SDK checks the chain, and human_id is the same. note = notes.get(g.allowedby.human_id, note_id) if not note: return {"error": "no such note"}, 404 return {"words": len(note["text"].split()), "delegated": len(g.allowedby.chain) > 1} ``` ## Let the person withdraw The person takes an approval back on their node; your app refuses it from the next refresh. ```python routes.append(route("GET", "/export", "notes:export", level=1, resource="note:*", summary="Export your notes")) templates["notes:export"] = "Export your notes" @app.get("/export") def export(): # Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. return {"approval": g.allowedby.gid, "notes": notes.list(g.allowedby.human_id)} ``` ## Serve only the person's own data human_id is the same person every time at your app: look their data up with it. ```python routes.append(route("GET", "/notes/{id}", "notes:read", level=1, resource="note:{id}", summary="Read one note")) @app.get("/notes/") def get_note(note_id): # human_id is this person's id at your app, always the same. Look up with it, never by note_id alone. note = notes.get(g.allowedby.human_id, note_id) return note or ({"error": "no such note"}, 404) ``` ## Refuse in your own handler Your rules still apply: the agent receives your status and your JSON, and can correct itself. ```python routes.append(route("PUT", "/notes/{id}", "notes:write", cls="write", level=1, resource="note:{id}", summary="Change a note", body={"text": "1 to 280 characters"})) @app.put("/notes/") def change_note(note_id): text = str(request.json.get("text", "")) if not 1 <= len(text) <= 280: return {"error": "text: 1 to 280 characters"}, 422 # the agent gets this status and this JSON note = notes.update(g.allowedby.human_id, note_id, text) return note or ({"error": "no such note"}, 404) ``` ## Sell to a company An employee approves for their company, within the mandate it gave them. ```python routes.append(route("POST", "/t/{tenant}/purchases", "purchases:make", cls="write-hard", level=2, mandate=True, resource="tenant:{tenant}:purchase:new", amount_field="/total", summary="Buy for your company", body={"total": "a decimal string, e.g. 300.00", "currency": "e.g. EUR"})) templates["purchases:make"] = "Buy for {amount.max} {amount.currency}" tenants["initech"] = {"name": "Initech", "org": os.environ["INITECH"], "routes": {}} # the company's own site @app.post("/t//purchases") def purchase(tenant): # The person acts for the company, within the mandate it gave them. return {"bought": request.json["total"], "for": g.allowedby.acting_for["name"]}, 201 ``` ## Ask for personal data The person shares what they choose, encrypted to your app. The agent never sees it. ```python routes.append(route("POST", "/tickets", "tickets:buy", cls="write-hard", level=2, resource="ticket:new", disclose=["legal_name"], disclose_optional=["email"], summary="Buy a ticket in the person's name")) templates["tickets:buy"] = "Buy a ticket in your name" settings["disclosure"] = { # why you ask and how long you keep it: the person reads this before sharing "legal_name": {"purpose": {"en": "The name on the ticket"}, "retention_days": 30}, "email": {"purpose": {"en": "To send you the ticket"}, "retention_days": 30}, } @app.post("/tickets") def buy_ticket(): # Sent to your app encrypted, by the person's node. The agent never sees it. person = app.extensions["allowedby"].personal_data(g.allowedby) return {"ticket": "T-1", "named": "legal_name" in person, "emailed": "email" in person}, 201 ``` ## Serve several customers Each customer account has its own approvals, and can tighten your rules. ```python routes.append(route("POST", "/t/{tenant}/orders", "orders:place", cls="write", level=1, resource="tenant:{tenant}:order:new", amount_field="/total", summary="Order for a customer account", body={"total": "a decimal string, e.g. 60.00", "currency": "e.g. EUR"})) templates["orders:place"] = "Order for up to {amount.max} {amount.currency} on {scope}" tenants["umbrella"] = {"name": "Umbrella", "routes": {}} tenants["hooli"] = {"name": "Hooli", "routes": {"orders:place": {"amount_max": "50.00"}}} # can only tighten your rules @app.post("/t//orders") def place_order(tenant): # An approval for one customer's account never works on another's. if tenant not in tenants: return {"error": "no such customer"}, 404 return {"ordered": request.json["total"], "account": g.allowedby.tenant}, 201 ``` ## Require two people Two people of a group approve the same action, each with their own passkey. ```python routes.append(route("POST", "/wires", "wires:send", cls="write-hard", level=2, authority=True, resource="wire:new", amount_field="/amount", summary="Wire money", body={"amount": "a decimal string, e.g. 9000.00", "currency": "e.g. EUR"})) templates["wires:send"] = "Wire {amount.max} {amount.currency}" settings["authority_policy"] = { "groups": {"finance": os.environ["FINANCE"].split(",")}, # the human_id of each member "rules": [{"cap": "wires:send", "group": "finance", "quorum": 2}], } @app.post("/wires") def wire(): # Two people of the group approved this same wire, each with their own passkey. return {"wired": request.json["amount"], "currency": request.json["currency"]}, 201 ``` ## Test your app Run your app's tests without a browser, a phone or a node. ```python from app import app client = app.test_client() def test_a_request_without_a_passport_is_refused(): r = client.get("/notes") assert r.status_code == 401 assert r.json["type"] == "https://allowedby.org/errors/passport_required" def test_agents_see_the_sentence_the_person_approves(): r = client.get("/.well-known/allowedby") assert r.json["templates"]["notes:read"]["summary"]["en"] == "Read your notes" def test_deleting_needs_an_approval_of_that_exact_request(): r = client.get("/openapi.json") assert r.json["paths"]["/notes/{id}"]["delete"]["x-allowedby"]["class"] == "write-hard" ```