Scoped Permissions API Reference
Scoped permissions: catalog, engine, stores and FastAPI guard.
Runtime and guards
- class auth_middleware.authz.runtime.Authz(*, catalog: PermissionCatalog, store: AssignmentStore | None, store_factory: Callable[[Request], AssignmentStore | Awaitable[AssignmentStore]] | None, group_roles: Mapping[str, str] | None, group_scope_kind: str, error_policy: ErrorPolicy, hooks: AuthzHooks)[source]
Bases:
objectCatalog + store wiring + error policy, held in
app.state.authz.- __init__(*, catalog: PermissionCatalog, store: AssignmentStore | None, store_factory: Callable[[Request], AssignmentStore | Awaitable[AssignmentStore]] | None, group_roles: Mapping[str, str] | None, group_scope_kind: str, error_policy: ErrorPolicy, hooks: AuthzHooks) None[source]
- async authorizer_for(request: Request) Authorizer[source]
Build an
Authorizerforrequest(calls the factory once).
- classmethod build(*, catalog: PermissionCatalog, store: AssignmentStore | None = None, store_factory: Callable[[Request], AssignmentStore | Awaitable[AssignmentStore]] | None = None, group_roles: Mapping[str, str] | None = None, group_scope_kind: str = 'global', error_policy: ErrorPolicy | None = None, hooks: AuthzHooks | None = None) Authz[source]
Validate the combination of sources and build the runtime.
Exactly one of
store/store_factory; neither is accepted only for a pure group-based setup (group_rolesgiven).- Raises:
ConfigurationError – Invalid combination or unknown role/scope kind.
- install(app: Starlette, *, allow_disabled_for_development: bool = False) None[source]
Attach to
app:app.state.authz, route validation and shutdown.Route validation runs at lifespan startup. Apps exercised without the lifespan (a
TestClientnot used as a context manager) should callvalidate_routes()themselves, e.g. in an architecture test.- Raises:
ConfigurationError –
AUTH_MIDDLEWARE_DISABLEDis set andallow_disabled_for_developmentis not.
- classmethod of(request: Request) Authz[source]
Return the instance installed on
request.app.- Raises:
ConfigurationError – Not installed on this app (mounted sub-apps have their own
app.state: install on each, or passauthz=).
- validate_routes(app: Starlette) None[source]
Check every guarded route against the catalog.
- Raises:
UnknownPermissionError – A guard uses a permission not in the catalog.
ScopeKindMismatchError – A guard’s scope kind differs from the permission’s.
ConfigurationError – A path-based scope uses a parameter the route lacks.
- auth_middleware.authz.guards.require_permission(permission: str, *, scope: ScopeSource | None = None, authz: Authz | Callable[[Request], Authz] | None = None) Callable[[...], Awaitable[AuthzContext]][source]
Build a FastAPI dependency that enforces
permissioninscope.The store factory is invoked lazily, when the dependency runs; FastAPI resolves the sub-dependencies of a route in declaration order, so a dependency that binds row-level security for the request must be declared before this guard.
The guard never skips when
AUTH_MIDDLEWARE_DISABLEDis set: the synthetic user is rejected with 401.- Parameters:
permission – Permission name (a
StrEnummember is accepted).scope – Where the scope comes from. Defaults to the global scope.
authz – An
Authzor a function of the request returning one; defaultAuthz.of(request)(app.state.authz).
- Returns:
A dependency returning the
AuthzContext.
- async auth_middleware.authz.guards.has_permission(request: Request, permission: str, scope: ScopeRef, *, authz: Authz | Callable[[Request], Authz] | None = None) bool[source]
Non-raising check for use inside handlers.
- Returns:
Trueonly if the authenticated principal holdspermissioninscope;Falsefor any other request outcome (not a member, denied, no user).- Raises:
AuthzError – For programming/configuration mistakes (unknown permission, scope-kind mismatch, role missing from the catalog…) and for an unavailable store: those are not answers, they are bugs or outages.
Catalog and engine
- class auth_middleware.authz.catalog.PermissionCatalog(scopes: Mapping[str, ScopeKind], permissions: Mapping[str, PermissionSpec], roles: Mapping[str, frozenset[str]])[source]
Bases:
objectImmutable catalog:
role -> permissionsplus permission and scope metadata.Build it with
from_mapping()orfrom_file(). It never reads a database: a catalog is code/config versioned with the application.- __init__(scopes: Mapping[str, ScopeKind], permissions: Mapping[str, PermissionSpec], roles: Mapping[str, frozenset[str]]) None[source]
- classmethod from_file(path: Path) PermissionCatalog[source]
Load a catalog from a TOML (
.toml) or JSON (.json) file.Shape:
[[scopes]] name = "studio" hide_existence = true [[permissions]] name = "design.write" scope = "studio" sensitive = false [roles] TIT = ["design.write"]
- Raises:
CatalogError – Unreadable file, unknown extension or invalid content.
- classmethod from_mapping(*, scopes: Sequence[ScopeKind], permissions: Sequence[PermissionSpec], roles: Mapping[str, Iterable[str]]) PermissionCatalog[source]
Build and validate a catalog.
StrEnummembers are accepted wherever a name is expected.- Parameters:
scopes – Declared scope kinds.
permissions – Declared permissions.
roles –
role -> permission names.
- Returns:
The immutable catalog.
- Raises:
CatalogError – Listing all problems found.
- permissions_for(role: str) frozenset[str][source]
Return the permissions granted by
role.- Raises:
CatalogError – Unknown role.
- roles_granting(permission: str) frozenset[str][source]
Return the roles that grant
permission.- Raises:
UnknownPermissionError – Not in the catalog.
- scope_kind(name: str) ScopeKind[source]
Return the declared scope kind
name.- Raises:
CatalogError – Undeclared kind.
- class auth_middleware.authz.engine.Authorizer(catalog: PermissionCatalog, resolvers: Sequence[RoleResolver])[source]
Bases:
objectDecides whether a principal holds a permission in a scope.
Resolvers run sequentially in declaration order, never concurrently: stores may share one database session, which is not safe for concurrent use.
- __init__(catalog: PermissionCatalog, resolvers: Sequence[RoleResolver]) None[source]
- Parameters:
catalog – The permission catalog.
resolvers – Role resolvers, consulted in order.
- async authorize(principal: Principal, permission: str, scope: ScopeRef) AuthzContext[source]
Authorize or raise.
Algorithm:
catalog.spec(permission)(unknown ->UnknownPermissionError).The permission’s scope kind must equal
scope.kind(elseScopeKindMismatchError).Ask every resolver; union the roles and merge attributes (later resolvers win on key clashes).
No result:
ScopeNotVisibleErrorif the scope kind hides existence, elsePermissionDeniedError.Permission not in the union of the roles’ permissions ->
PermissionDeniedError.Return the
AuthzContext.
- Raises:
UnknownPermissionError – Programming error.
ScopeKindMismatchError – Programming error.
ScopeNotVisibleError – Principal has no active assignment in scope.
PermissionDeniedError – Principal lacks the permission.
Service, cache and events
- class auth_middleware.authz.service.AssignmentService(admin: AssignmentAdmin, catalog: PermissionCatalog, *, before_change: Sequence[Callable[[AssignmentChange], Awaitable[None]]] = (), after_change: Sequence[Callable[[AssignmentChange, Assignment], Awaitable[None]]] = ())[source]
Bases:
objectValidated writes over an
AssignmentAdmin, with application hooks.The library ships no domain rule: an application plugs its own into
before_change(raise to veto; nothing is written) andafter_change(cache invalidation, audit, notifications). Example, the “last owner” rule:async def last_owner(change: AssignmentChange) -> None: leaving = change.kind == "revoke" or ( change.kind == "change_role" and change.new_role != "OWNER" ) if leaving and change.old and change.old.role == "OWNER": owners = [ a for a in await service.members(change.scope) if a.role == "OWNER" and a.status.value == "active" ] if len(owners) <= 1: raise LastOwnerRequiredError() service = AssignmentService(admin, catalog, before_change=[last_owner])
Changes of one scope are serialised within this process (the veto hooks and the write run under a per-scope lock), so concurrent requests cannot both pass the same check. Several processes/instances still race (two owners revoking each other on different servers): enforce hard invariants in the store as well (a constraint or transaction of your own adapter).
A role is bound to a scope kind through its permissions: every permission of the role must belong to the kind of the scope it is assigned in.
- Parameters:
admin – The write side of a store.
catalog – Used to validate roles.
before_change – Veto hooks, run in order before any write.
after_change – Hooks run in order after a successful write.
- __init__(admin: AssignmentAdmin, catalog: PermissionCatalog, *, before_change: Sequence[Callable[[AssignmentChange], Awaitable[None]]] = (), after_change: Sequence[Callable[[AssignmentChange, Assignment], Awaitable[None]]] = ()) None[source]
- async assign(principal_id: str, scope: ScopeRef, role: str) Assignment[source]
Give
principal_idroleinscope.- Raises:
UnknownRoleError – Role not in the catalog.
ScopeKindMismatchError – Role belongs to another scope kind.
RevisionConflictError – Already actively assigned.
- class auth_middleware.authz.cache.CachingAssignmentStore(inner: AssignmentStore, *, ttl_seconds: float, max_entries: int = 10000, clock: Callable[[], float]=<built-in function monotonic>, i_understand_stale_authorization: bool = False)[source]
Bases:
objectDecorator over any
AssignmentStore(andAssignmentAdminif it is one).get_assignmentcaches positive and negative results; a negative entry lives at mostttl_seconds / 4. Writes through this instance invalidate the affected key at once.list_assignmentsandlist_for_scopeare never cached. The key is(principal_id, scope.kind, scope.id).- Parameters:
inner – The store to wrap.
ttl_seconds – Entry lifetime; above 60 needs
i_understand_stale_authorization=True.max_entries – Oldest entries are evicted beyond this.
clock – Monotonic clock (injectable for tests).
i_understand_stale_authorization – Allow a TTL above 60 s.
- Raises:
ConfigurationError – Non-positive TTL, or TTL > 60 s without the flag.
- __init__(inner: AssignmentStore, *, ttl_seconds: float, max_entries: int = 10000, clock: Callable[[], float]=<built-in function monotonic>, i_understand_stale_authorization: bool = False) None[source]
- async change_role(principal_id: str, scope: ScopeRef, role: str, *, expected_revision: int) Assignment[source]
- auth_middleware.authz.events.audit_hook(audit: AuditLogger) Callable[[DecisionEvent], None][source]
Build an
on_decisionhook that logs throughAuditLogger.Levels:
DENIEDWARNING,NOT_VISIBLEINFO,ALLOWEDDEBUG, exceptsensitivepermissions which log at INFO even when allowed. Events carry ids and permission names only.- Parameters:
audit – The library’s audit logger (its callback is invoked too).
Stores
- class auth_middleware.authz.stores.memory.InMemoryAssignmentStore[source]
Bases:
objectImplements
AssignmentStoreandAssignmentAdminover a dict.Writes are serialized with an
asyncio.Lock. State is per instance and per process; it is a real implementation, not a mock.- async change_role(principal_id: str, scope: ScopeRef, role: str, *, expected_revision: int) Assignment[source]
- supports_attributes = True
- class auth_middleware.authz.stores.sql.SqlAssignmentStore(session_provider: Any, *, table_name: str = 'authz_assignment', before_query: Callable[[AsyncSession, ScopeRef | None], Awaitable[None]] | None = None, commit: bool = True)[source]
Bases:
objectAssignmentStore+AssignmentAdminover a SQL table.Three ways to inject a session:
async_sessionmaker: a short session per call (singleton store).A callable returning an async context manager yielding a session.
An already open
AsyncSession(per-request store built by aStoreFactory): the store never commits, rolls back or closes it, so reads and writes happen in the caller’s transaction.
- Parameters:
session_provider – One of the three shapes above.
table_name – Table name (a plain SQL identifier).
before_query – Awaited before every statement with the session and the scope (
Nonefor the cross-scopelist_assignments). This is where an application binds row-level security. Exceptions propagate.commit – Commit after writes when the store owns the session. Forced off for an injected open session.
- __init__(session_provider: Any, *, table_name: str = 'authz_assignment', before_query: Callable[[AsyncSession, ScopeRef | None], Awaitable[None]] | None = None, commit: bool = True) None[source]
- async change_role(principal_id: str, scope: ScopeRef, role: str, *, expected_revision: int) Assignment[source]
- supports_attributes = True
- class auth_middleware.authz.stores.dynamodb.DynamoDbAssignmentStore(*, table_name: str, region: str | None = None, endpoint_url: str | None = None, index_name: str = 'by-principal', consistent_read: bool = True, connect_timeout_seconds: int = 5, read_timeout_seconds: int = 10, max_retry_attempts: int = 5, aws_access_key_id: str | None = None, aws_secret_access_key: str | None = None, max_workers: int | None = None)[source]
Bases:
objectAssignmentStore+AssignmentAdminover a single DynamoDB table.- Parameters:
table_name – Existing table (see
table_definition()).region – AWS region; default from the botocore chain.
endpoint_url – Custom endpoint (DynamoDB Local, emulators, tests).
index_name – Name of the by-principal GSI.
consistent_read – Consistent reads on
get_assignment(default, and required to never admit a just-revoked principal). Turning it off accepts staleness: only for callers that explicitly want it.connect_timeout_seconds – botocore connect timeout.
read_timeout_seconds – botocore read timeout.
max_retry_attempts – botocore retries (throttling backoff).
aws_access_key_id – Explicit credentials, for tests only; otherwise the botocore credential chain is used (nothing is read from code).
aws_secret_access_key – Explicit credentials, for tests only.
max_workers – Size of a dedicated thread pool for the blocking PynamoDB calls.
Noneuses the event loop’s default executor, shared with the rest of the application.
- __init__(*, table_name: str, region: str | None = None, endpoint_url: str | None = None, index_name: str = 'by-principal', consistent_read: bool = True, connect_timeout_seconds: int = 5, read_timeout_seconds: int = 10, max_retry_attempts: int = 5, aws_access_key_id: str | None = None, aws_secret_access_key: str | None = None, max_workers: int | None = None) None[source]
- async change_role(principal_id: str, scope: ScopeRef, role: str, *, expected_revision: int) Assignment[source]
- async create_table_if_missing() None[source]
Create the table (and GSI) if absent. Dev/tests only; never implicit.
- async list_assignments(principal_id: str) Sequence[Assignment][source]
List a principal’s scopes via the GSI (eventually consistent).
- supports_attributes = True