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: object

Catalog + 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 aclose() → None[source]

Close the injected store if it exposes aclose(). Idempotent.

async authorizer_for(request: Request) → Authorizer[source]

Build an Authorizer for request (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_roles given).

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 TestClient not used as a context manager) should call validate_routes() themselves, e.g. in an architecture test.

Raises:

ConfigurationError – AUTH_MIDDLEWARE_DISABLED is set and allow_disabled_for_development is 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 pass authz=).

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 permission in scope.

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_DISABLED is set: the synthetic user is rejected with 401.

Parameters:
  • permission – Permission name (a StrEnum member is accepted).

  • scope – Where the scope comes from. Defaults to the global scope.

  • authz – An Authz or a function of the request returning one; default Authz.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:

True only if the authenticated principal holds permission in scope; False for 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: object

Immutable catalog: role -> permissions plus permission and scope metadata.

Build it with from_mapping() or from_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.

StrEnum members 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() → frozenset[str][source]

Return all permission names.

permissions_for(role: str) → frozenset[str][source]

Return the permissions granted by role.

Raises:

CatalogError – Unknown role.

roles() → frozenset[str][source]

Return all role names.

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.

spec(permission: str) → PermissionSpec[source]

Return the spec of permission.

Raises:

UnknownPermissionError – Not in the catalog.

to_mapping() → dict[str, Any][source]

Return a plain dict; from_mapping(**...) of it rebuilds the catalog.

class auth_middleware.authz.engine.Authorizer(catalog: PermissionCatalog, resolvers: Sequence[RoleResolver])[source]

Bases: object

Decides 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:

  1. catalog.spec(permission) (unknown -> UnknownPermissionError).

  2. The permission’s scope kind must equal scope.kind (else ScopeKindMismatchError).

  3. Ask every resolver; union the roles and merge attributes (later resolvers win on key clashes).

  4. No result: ScopeNotVisibleError if the scope kind hides existence, else PermissionDeniedError.

  5. Permission not in the union of the roles’ permissions -> PermissionDeniedError.

  6. Return the AuthzContext.

Raises:
  • UnknownPermissionError – Programming error.

  • ScopeKindMismatchError – Programming error.

  • ScopeNotVisibleError – Principal has no active assignment in scope.

  • PermissionDeniedError – Principal lacks the permission.

async check(principal: Principal, permission: str, scope: ScopeRef) → DecisionKind[source]

Return the decision kind without raising for the three outcomes.

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: object

Validated 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) and after_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_id role in scope.

Raises:
  • UnknownRoleError – Role not in the catalog.

  • ScopeKindMismatchError – Role belongs to another scope kind.

  • RevisionConflictError – Already actively assigned.

async change_role(principal_id: str, scope: ScopeRef, role: str, *, expected_revision: int) → Assignment[source]

Change the role of an active assignment (optimistic concurrency).

async members(scope: ScopeRef) → Sequence[Assignment][source]

Return every assignment of scope.

async revoke(principal_id: str, scope: ScopeRef, *, expected_revision: int) → Assignment[source]

Revoke an active assignment (optimistic concurrency).

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: object

Decorator over any AssignmentStore (and AssignmentAdmin if it is one).

get_assignment caches positive and negative results; a negative entry lives at most ttl_seconds / 4. Writes through this instance invalidate the affected key at once. list_assignments and list_for_scope are 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 aclose() → None[source]

Close the wrapped store if it exposes aclose().

async assign(new: NewAssignment) → Assignment[source]
async change_role(principal_id: str, scope: ScopeRef, role: str, *, expected_revision: int) → Assignment[source]
async get_assignment(principal_id: str, scope: ScopeRef) → Assignment | None[source]
invalidate(principal_id: str, scope: ScopeRef | None = None) → None[source]

Drop one entry, or every entry of principal_id when scope is None.

async list_assignments(principal_id: str) → Sequence[Assignment][source]
async list_for_scope(scope: ScopeRef) → Sequence[Assignment][source]
async revoke(principal_id: str, scope: ScopeRef, *, expected_revision: int) → Assignment[source]
auth_middleware.authz.events.audit_hook(audit: AuditLogger) → Callable[[DecisionEvent], None][source]

Build an on_decision hook that logs through AuditLogger.

Levels: DENIED WARNING, NOT_VISIBLE INFO, ALLOWED DEBUG, except sensitive permissions 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).

auth_middleware.authz.events.metrics_hook(collector: MetricsCollector) → Callable[[DecisionEvent], Awaitable[None]][source]

Build an on_decision hook counting decisions per kind and permission.

Stores

class auth_middleware.authz.stores.memory.InMemoryAssignmentStore[source]

Bases: object

Implements AssignmentStore and AssignmentAdmin over a dict.

Writes are serialized with an asyncio.Lock. State is per instance and per process; it is a real implementation, not a mock.

__init__() → None[source]
async assign(new: NewAssignment) → Assignment[source]
async change_role(principal_id: str, scope: ScopeRef, role: str, *, expected_revision: int) → Assignment[source]
async get_assignment(principal_id: str, scope: ScopeRef) → Assignment | None[source]
async list_assignments(principal_id: str) → Sequence[Assignment][source]
async list_for_scope(scope: ScopeRef) → Sequence[Assignment][source]
async revoke(principal_id: str, scope: ScopeRef, *, 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: object

AssignmentStore + AssignmentAdmin over a SQL table.

Three ways to inject a session:

  1. async_sessionmaker: a short session per call (singleton store).

  2. A callable returning an async context manager yielding a session.

  3. An already open AsyncSession (per-request store built by a StoreFactory): 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 (None for the cross-scope list_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 assign(new: NewAssignment) → Assignment[source]
async change_role(principal_id: str, scope: ScopeRef, role: str, *, expected_revision: int) → Assignment[source]
async get_assignment(principal_id: str, scope: ScopeRef) → Assignment | None[source]
async list_assignments(principal_id: str) → Sequence[Assignment][source]
async list_for_scope(scope: ScopeRef) → Sequence[Assignment][source]
async revoke(principal_id: str, scope: ScopeRef, *, 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: object

AssignmentStore + AssignmentAdmin over 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. None uses 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 aclose() → None[source]

Stop the dedicated worker pool, if any (PynamoDB manages its client).

async assign(new: NewAssignment) → Assignment[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 get_assignment(principal_id: str, scope: ScopeRef) → Assignment | None[source]
async list_assignments(principal_id: str) → Sequence[Assignment][source]

List a principal’s scopes via the GSI (eventually consistent).

async list_for_scope(scope: ScopeRef) → Sequence[Assignment][source]
async revoke(principal_id: str, scope: ScopeRef, *, expected_revision: int) → Assignment[source]
supports_attributes = True
static table_definition(table_name: str, *, billing: Literal['PAY_PER_REQUEST'] = 'PAY_PER_REQUEST', index_name: str = 'by-principal') → dict[str, Any][source]

Return boto3 create_table keyword arguments for the table.