Skip to content

Protect a FastAPI App

Use caracalai-asgi when a FastAPI, Starlette, or other ASGI app should verify Caracal mandates before request handlers run. This is the provider-side boundary: a partner serving Caracal-governed customers verifies each inbound mandate against the zone’s keys before doing any work.

Terminal window
pip install caracalai-asgi caracalai-revocation

Use a Redis-backed revocation store in production. The in-memory store is only suitable for local development and tests.

from caracalai_asgi import CaracalASGIAuth
from caracalai_revocation import InMemoryRevocationStore
from fastapi import FastAPI, Request
app = FastAPI()
app.add_middleware(
CaracalASGIAuth,
audience="resource://billing-api",
revocations=InMemoryRevocationStore(),
required_scopes=["billing:read"],
routes={
"/payouts": {"required_scopes": ["billing:payout"], "require_delegation": True},
},
exclude=["/healthz"],
)
@app.post("/payouts/create")
async def create_payout(request: Request):
principal = request.state.caracal
return {"actor": principal.sub, "agent": principal.agent_session_id}

With CARACAL_STS_URL and CARACAL_ZONE_ID set — the standard Caracal workload variables — the middleware resolves the issuer and zone itself; you state only your own audience and revocation store. Requests reach your handlers only after the mandate’s signature, issuer, audience, zone, token use, scopes, and revocation anchors all verify.

OptionUse it for
required_scopesRoute-level scope checks.
required_targetsResource-target checks.
require_agentReject non-agent mandates.
require_delegationRequire delegated authority.
max_hop_countLimit delegation depth.
routesApply any of the above per path prefix; the longest matching prefix wins.
  1. Exchange for a mandate that targets the resource.
  2. Call the protected route with Authorization: Bearer <mandate>.
  3. Remove a required scope and confirm the route returns 403.
  4. Revoke the session and confirm the route rejects the old mandate.

Related pages: Mandates and Sessions and Revocation.