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: StoreFactory | None, group_roles: Mapping[str, str] | None, group_scope_kind: str, error_policy: ErrorPolicy, hooks: AuthzHooks, pdp: PolicyDecisionPoint | None = None, policy_source: PolicyStore | None = None, abac: AbacConfig | None = None)[source]

Bases: object

Catalog + store wiring + error policy, held in app.state.authz.

__init__(*, catalog: PermissionCatalog, store: AssignmentStore | None, store_factory: StoreFactory | None, group_roles: Mapping[str, str] | None, group_scope_kind: str, error_policy: ErrorPolicy, hooks: AuthzHooks, pdp: PolicyDecisionPoint | None = None, policy_source: PolicyStore | None = None, abac: AbacConfig | None = None) → None[source]
async aclose() → None[source]

Close the injected stores if they expose 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: StoreFactory | None = None, group_roles: Mapping[str, str] | None = None, group_scope_kind: str = 'global', error_policy: ErrorPolicy | None = None, hooks: AuthzHooks | None = None, abac: AbacConfig | 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).

Parameters:

abac – Attribute-based access control (policies refining the roles). None: exactly the role-based behaviour.

Raises:

ConfigurationError – Invalid combination or unknown role/scope kind, or invalid static policies.

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.

async verify_policies() → None[source]

Startup check of the policy sources (e.g. no id defined twice).

Raises:

ConfigurationError – Two sources define the same policy id.

auth_middleware.authz.guards.require_permission(permission: str, *, scope: ScopeSource | None = None, resource: ResourceSource | None = None, authz: AuthzSource = 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.

  • resource – Where the resource comes from (ABAC): a ResourceFromPath / ResourceFromQuery / ResourceFromCallable, optionally with a loader of the resource’s attributes. Needs Authz.build(abac=...) (startup validation refuses a guard whose resource would be ignored).

  • 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, *, resource: ResourceSource | ResourceContext | None = None, authz: AuthzSource = 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]], attributes: Mapping[str, AttributeSpec] | None = None)[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]], attributes: Mapping[str, AttributeSpec] | None = None) → None[source]
property attributes: AttributeSchema

The attribute schema (built-ins plus the declared attributes).

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"]

[attributes."subject.attrs.clearance"]   # optional, for ABAC policies
type = "int"
Raises:

CatalogError – Unreadable file, unknown extension or invalid content.

classmethod from_mapping(*, scopes: Sequence[ScopeKind], permissions: Sequence[PermissionSpec], roles: Mapping[str, Iterable[str]], attributes: Sequence[AttributeSpec] = ()) → 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.

  • attributes – Attributes policies may read (ABAC, optional).

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], *, pdp: PolicyDecisionPoint | None = None)[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], *, pdp: PolicyDecisionPoint | None = None) → None[source]
Parameters:
  • catalog – The permission catalog.

  • resolvers – Role resolvers, consulted in order.

  • pdp – Optional ABAC decision point. None: exactly the 0.7.0 behaviour.

async authorize(principal: Principal, permission: str, scope: ScopeRef, *, resource: ResourceContext | None = None, request: Request | None = None) → 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. With ABAC configured: evaluate the applicable policies (deny-overrides; hide turns a denial into ScopeNotVisibleError).

  7. Return the AuthzContext.

Parameters:
  • principal – Who acts.

  • permission – Catalog permission.

  • scope – Where.

  • resource – The resource (ABAC only).

  • request – The request (ABAC providers: headers, ip, claims).

Raises:
  • UnknownPermissionError – Programming error.

  • ScopeKindMismatchError – Programming error.

  • ScopeNotVisibleError – Principal has no active assignment in scope, the resource does not exist, or a hide policy denied.

  • PermissionDeniedError – Principal lacks the permission.

  • StoreUnavailableError – A policy source or attribute provider failed.

async check(principal: Principal, permission: str, scope: ScopeRef, *, resource: ResourceContext | None = None, request: Request | None = None) → DecisionKind[source]

Return the decision kind without raising for the three outcomes.

async explain(principal: Principal, permission: str, scope: ScopeRef, *, resource: ResourceContext | None = None, request: Request | None = None, reveal: bool = False) → Explanation[source]

Run the decision and report why, policy by policy (for logs and tools).

Every policy is evaluated (no short-circuit). Attribute values are left out unless reveal; absent attribute names are always listed. Never put the result in an HTTP response.

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 and decisions a shadow (enforce=false) policy would have denied, which log at INFO even when allowed. Events carry ids and permission names only (ABAC: policy ids and the reason, never attribute values).

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.

Without ABAC the counters are exactly the 0.7.0 ones. With policies involved the decision is also counted under by_source and each policy under abac_policies (denied, permitted or shadow_denied).

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.

ABAC

class auth_middleware.authz.abac.config.AbacConfig(policies: ~auth_middleware.authz.ports.PolicyStore | ~collections.abc.Sequence[~auth_middleware.authz.ports.PolicyStore], attributes: ~auth_middleware.authz.ports.AttributeStore | None = None, mode: ~typing.Literal['restrict', 'grant'] = 'restrict', policy_cache_ttl: float = 5.0, claims_allowlist: ~collections.abc.Mapping[str, str] | ~collections.abc.Sequence[str] = (), headers_allowlist: ~collections.abc.Iterable[str] = (), trusted_proxies: ~collections.abc.Iterable[str] = (), clock: ~collections.abc.Callable[[], ~datetime.datetime] = <function _utcnow>, providers: ~collections.abc.Sequence[~auth_middleware.authz.abac.attributes.AttributeProvider] = ())[source]

Bases: object

Attribute-based access control settings.

Parameters:
  • policies – One policy source or several (static files, stores…); several are read as one (earlier wins on a clashing id).

  • attributes – Persisted principal/resource attributes (optional).

  • mode – restrict (policies only narrow what roles grant; default) or grant (permit policies may grant; experimental).

  • policy_cache_ttl – Seconds the policies of a scope are cached (default 5; 0 disables the cache). Other processes see a change only after it.

  • claims_allowlist – Token claims policies may read.

  • headers_allowlist – Request headers policies may read.

  • trusted_proxies – CIDRs whose X-Forwarded-For is believed.

  • clock – Aware-datetime clock for env.now (inject in tests).

  • providers – Extra attribute providers (disjoint path prefixes).

__init__(policies: ~auth_middleware.authz.ports.PolicyStore | ~collections.abc.Sequence[~auth_middleware.authz.ports.PolicyStore], attributes: ~auth_middleware.authz.ports.AttributeStore | None = None, mode: ~typing.Literal['restrict', 'grant'] = 'restrict', policy_cache_ttl: float = 5.0, claims_allowlist: ~collections.abc.Mapping[str, str] | ~collections.abc.Sequence[str] = (), headers_allowlist: ~collections.abc.Iterable[str] = (), trusted_proxies: ~collections.abc.Iterable[str] = (), clock: ~collections.abc.Callable[[], ~datetime.datetime] = <function _utcnow>, providers: ~collections.abc.Sequence[~auth_middleware.authz.abac.attributes.AttributeProvider] = ()) → None
attributes: AttributeStore | None
build(catalog: PermissionCatalog) → tuple[PolicyDecisionPoint, PolicyStore][source]

Validate the static policies and build the decision point.

Returns:

(pdp, policy_source); the source is what the cache wraps.

Raises:

ConfigurationError – Invalid mode/cache or invalid static policies (every problem is listed).

claims_allowlist: Mapping[str, str] | Sequence[str]
clock: Callable[[], datetime]
headers_allowlist: Iterable[str]
mode: Literal['restrict', 'grant']
policies: PolicyStore | Sequence[PolicyStore]
policy_cache_ttl: float
providers: Sequence[AttributeProvider]
sources() → tuple[PolicyStore, ...][source]

The configured sources as a tuple.

trusted_proxies: Iterable[str]
class auth_middleware.authz.abac.types.Policy(id: str, effect: Effect, permissions: tuple[str, ...], scope: PolicyScope, condition: Mapping[str, Any], description: str = '', priority: int = 0, hide: bool = False, enforce: bool = True, status: PolicyStatus = PolicyStatus.ACTIVE, revision: int = 0, created_at: datetime | None = None, updated_at: datetime | None = None)[source]

Bases: object

A stored policy: a NewPolicy plus status, revision and timestamps.

__init__(id: str, effect: Effect, permissions: tuple[str, ...], scope: PolicyScope, condition: Mapping[str, Any], description: str = '', priority: int = 0, hide: bool = False, enforce: bool = True, status: PolicyStatus = PolicyStatus.ACTIVE, revision: int = 0, created_at: datetime | None = None, updated_at: datetime | None = None) → None
condition: Mapping[str, Any]
created_at: datetime | None
description: str
effect: Effect
enforce: bool
classmethod fail_closed(policy_id: str, scope: PolicyScope, permissions: tuple[str, ...] = ('*',)) → Policy[source]

A deny that always applies (stands in for an undecodable policy).

classmethod from_dict(data: Mapping[str, Any]) → Policy[source]

Rebuild a policy from to_dict() (or a hand-written document).

Raises:

InvalidPolicyError – Missing/invalid fields.

classmethod from_new(new: NewPolicy, *, status: PolicyStatus = PolicyStatus.ACTIVE, revision: int = 0, created_at: datetime | None = None, updated_at: datetime | None = None) → Policy[source]

Build a stored policy from a NewPolicy.

hide: bool
id: str
permissions: tuple[str, ...]
priority: int
revision: int
scope: PolicyScope
status: PolicyStatus
to_dict() → dict[str, Any][source]

Return a JSON-serialisable dict (round-trips through from_dict()).

to_new() → NewPolicy[source]

Return the writable part.

updated_at: datetime | None
class auth_middleware.authz.abac.types.NewPolicy(id: str, effect: Effect, permissions: tuple[str, ...], scope: PolicyScope, condition: Mapping[str, Any], description: str = '', priority: int = 0, hide: bool = False, enforce: bool = True)[source]

Bases: object

Input of PolicyAdmin.create / replace.

Parameters:
  • id – Human-chosen id, [a-z0-9][a-z0-9_.-]{0,99}, unique across the store.

  • effect – deny, require or permit.

  • permissions – Exact names or * patterns (design.*, *.write).

  • scope – Where it applies.

  • condition – The raw condition AST (parsed by parse_condition).

  • description – Free text (<= 500 characters).

  • priority – Lower is evaluated first.

  • hide – A denial answers “not visible” (404) instead of 403.

  • enforce – False is shadow mode: evaluated and reported, never enforced.

__init__(id: str, effect: Effect, permissions: tuple[str, ...], scope: PolicyScope, condition: Mapping[str, Any], description: str = '', priority: int = 0, hide: bool = False, enforce: bool = True) → None
condition: Mapping[str, Any]
description: str
effect: Effect
enforce: bool
hide: bool
id: str
permissions: tuple[str, ...]
priority: int
scope: PolicyScope
class auth_middleware.authz.abac.service.PolicyService(admin: PolicyAdmin, catalog: PermissionCatalog, *, allow_permit: bool = False, after_change: Sequence[Callable[[PolicyChange], Awaitable[None] | None]] = ())[source]

Bases: object

Writes policies after validating them against the catalog.

Nothing invalid reaches the store: the policy is checked with validate_policy (every problem reported at once) before any write. Writes to one policy id are serialised within this process; several processes still race, which the store’s revision check resolves (RevisionConflictError).

Parameters:
  • admin – The write side of a policy store.

  • catalog – Permissions, scope kinds and attribute schema.

  • allow_permit – Accept permit policies (grant mode).

  • after_change – Hooks run after each successful write (cache invalidation: CachingPolicySource.on_change; audit; notifications). A failing hook is logged and the first error is re-raised after all have run.

__init__(admin: PolicyAdmin, catalog: PermissionCatalog, *, allow_permit: bool = False, after_change: Sequence[Callable[[PolicyChange], Awaitable[None] | None]] = ()) → None[source]
async create(new: NewPolicy) → Policy[source]

Validate and create a policy.

Raises:
  • InvalidPolicyError – Not valid against the catalog (nothing written).

  • PolicyConflictError – The id exists.

async disable(policy_id: str, *, expected_revision: int) → Policy[source]

Disable a policy (kept as history; it stops applying).

async enable(policy_id: str, *, expected_revision: int) → Policy[source]

Enable a disabled policy.

async get(policy_id: str) → Policy | None[source]

Return a policy (any status) or None.

async replace(policy_id: str, new: NewPolicy, *, expected_revision: int) → Policy[source]

Validate and replace a policy (optimistic concurrency).

class auth_middleware.authz.abac.pdp.PolicyDecisionPoint(policies: PolicyStore, resolver: AttributeResolver, *, mode: Literal['restrict', 'grant'] = 'restrict')[source]

Bases: object

Loads, evaluates and combines the policies of a decision.

__init__(policies: PolicyStore, resolver: AttributeResolver, *, mode: Literal['restrict', 'grant'] = 'restrict') → None[source]
Parameters:
  • policies – Where the policies come from.

  • resolver – Where the attributes come from.

  • mode – restrict (policies only narrow) or grant (permit policies may grant; experimental).

async evaluate(ctx: AttributeRequest, *, explain: bool = False, reveal: bool = False) → AbacOutcome[source]

Run the policy phase.

Parameters:
  • ctx – Principal, permission, scope, resource and request.

  • explain – Evaluate every policy and fill the trace.

  • reveal – Include attribute values in the trace (never for clients).

Raises:
  • ResourceNotFoundError – The resource loader said it does not exist.

  • StoreUnavailableError – A source or provider failed (never an allow).

auth_middleware.authz.abac.validation.validate_policy(policy: Policy | NewPolicy, catalog: PermissionCatalog, *, allow_permit: bool = False) → None[source]

Check a policy against the catalog; report every problem at once.

Parameters:
  • policy – The policy (or the input of a write).

  • catalog – Permissions, scope kinds and declared attributes.

  • allow_permit – Accept permit policies (grant mode).

Raises:

InvalidPolicyError – With .problems listing everything wrong.

auth_middleware.authz.abac.conditions.parse_condition(raw: Mapping[str, Any], *, limits: ConditionLimits = ConditionLimits(max_depth=8, max_nodes=64, max_list=100, max_string=256, max_path=128)) → Node[source]

Parse and validate a condition.

Parameters:
  • raw – The condition as plain data.

  • limits – Depth/size bounds.

Returns:

The immutable AST.

Raises:

ConditionError – Invalid shape or a limit exceeded; .pointer locates it.

auth_middleware.authz.abac.conditions.evaluate(cond: Node, values: Mapping[str, Any]) → Tri[source]

Evaluate cond over values (path -> value; a missing path is absent).

Never raises: anything unexpected is INDETERMINATE.

class auth_middleware.authz.abac.cache.CachingPolicySource(inner: PolicyStore, *, ttl_seconds: float, max_scopes: int = 1000, clock: Callable[[], float]=<built-in function monotonic>, i_understand_stale_authorization: bool = False)[source]

Bases: object

Caches list_policies per (kind, id) for a few seconds.

Policies change rarely, so unlike assignments a short snapshot is reasonable. Other processes see a change only after the TTL; changes made through this instance (PolicyService.after_change -> on_change()) show at once.

Failed loads are not cached and an expired entry is never served when the reload fails (fail closed: the guard answers 503), unlike the JWKS cache. Concurrent misses for one key share a single load. An invalidate that happens while a load is in flight wins: the stale result is not stored.

Parameters:
  • inner – The real source.

  • ttl_seconds – Seconds an entry lives (> 0; <= 60 unless i_understand_stale_authorization).

  • max_scopes – Entries kept; the oldest is evicted.

  • clock – Monotonic clock (inject a fake in tests).

  • i_understand_stale_authorization – Allow a TTL above 60 s.

__init__(inner: PolicyStore, *, ttl_seconds: float, max_scopes: int = 1000, clock: Callable[[], float]=<built-in function monotonic>, i_understand_stale_authorization: bool = False) → None[source]
async aclose() → None[source]

Close the inner source if it exposes aclose().

invalidate(scope: ScopeRef | None = None) → None[source]

Drop one scope’s entry, or everything when scope is None.

invalidate_kind(kind: str) → None[source]

Drop every entry of a scope kind (a kind-wide policy changed).

async list_all(status: PolicyStatus | None = None) → Sequence[Policy][source]
async list_policies(scope: ScopeRef) → Sequence[Policy][source]
on_change(change: Any) → None[source]

PolicyService.after_change hook: invalidate what the change touched.

class auth_middleware.authz.abac.sources.StaticPolicySource(policies: Iterable[Policy | NewPolicy | Mapping[str, Any]])[source]

Bases: object

Read-only policies from code or a TOML/JSON file (versioned with the app).

File shapes:

# JSON
{"policies": [{"id": "...", "effect": "deny", ...}]}

# TOML
[[policies]]
id = "studio-suspended-readonly"
effect = "deny"
permissions = ["*.write"]
scope = {kind = "studio"}
condition = {eq = [{attr = "subject.assignment.tenant_status"}, "suspended"]}
__init__(policies: Iterable[Policy | NewPolicy | Mapping[str, Any]])[source]
Raises:

InvalidPolicyError – A policy is invalid or two share an id.

classmethod from_file(path: str | Path) → StaticPolicySource[source]

Load a .toml or .json file.

Raises:

InvalidPolicyError – Unreadable, unsupported or invalid content.

async list_all(status: PolicyStatus | None = None) → Sequence[Policy][source]
async list_policies(scope: ScopeRef) → Sequence[Policy][source]
property policies: tuple[Policy, ...]

Every policy of the source.

class auth_middleware.authz.abac.resources.ResourceFromPath(kind: str, param: str, loader: ResourceLoader | None = None)[source]

Bases: object

Resource id read from a path parameter.

Parameters:
  • kind – Resource kind (design).

  • param – Path parameter holding the id.

  • loader – loader(request, ref) -> attributes | None reading the resource’s attributes from the application’s own data.

__init__(kind: str, param: str, loader: ResourceLoader | None = None) → None[source]
async resolve(request: Request) → ResourceRef[source]
class auth_middleware.authz.stores.sql_policy.SqlPolicyStore(session_provider: Any, *, table_name: str = 'authz_policy', before_query: Callable[[AsyncSession, ScopeRef | None], Awaitable[None]] | None = None, commit: bool = True)[source]

Bases: _SqlBase

PolicyStore + PolicyAdmin over a SQL table.

A stored row that cannot be decoded (a hand-edited table, an old format) is returned as a deny that always applies and logged at ERROR: it fails closed instead of silently disappearing.

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 kind-wide or cross-scope statements): where an application binds row-level security. Exceptions propagate.

  • commit – Commit after writes when the store owns the session.

__init__(session_provider: Any, *, table_name: str = 'authz_policy', before_query: Callable[[AsyncSession, ScopeRef | None], Awaitable[None]] | None = None, commit: bool = True) → None[source]
async create(new: NewPolicy) → Policy[source]
async get(policy_id: str) → Policy | None[source]
async list_all(status: PolicyStatus | None = None) → Sequence[Policy][source]
async list_policies(scope: ScopeRef) → Sequence[Policy][source]
async replace(policy_id: str, new: NewPolicy, *, expected_revision: int) → Policy[source]
async set_status(policy_id: str, status: PolicyStatus, *, expected_revision: int) → Policy[source]
class auth_middleware.authz.stores.sql_policy.SqlAttributeStore(session_provider: Any, *, table_name: str = 'authz_attribute', before_query: Callable[[AsyncSession, ScopeRef | None], Awaitable[None]] | None = None, commit: bool = True)[source]

Bases: _SqlBase

AttributeStore over a SQL table (principal and resource attributes).

Parameters:
  • session_provider – One of the three shapes in the module docstring.

  • table_name – Table name (a plain SQL identifier).

  • before_query – Awaited before every statement (None scope).

  • commit – Commit after writes when the store owns the session.

__init__(session_provider: Any, *, table_name: str = 'authz_attribute', before_query: Callable[[AsyncSession, ScopeRef | None], Awaitable[None]] | None = None, commit: bool = True) → None[source]
async delete_attributes(ref: EntityRef, *, expected_revision: int) → None[source]
async get_attributes(ref: EntityRef) → EntityAttributes | None[source]
async put_attributes(ref: EntityRef, attributes: Mapping[str, Any], *, expected_revision: int | None) → EntityAttributes[source]
class auth_middleware.authz.stores.dynamodb_policy.DynamoDbPolicyStore(*, table_name: str = 'authz_policy', region: str | None = None, endpoint_url: str | None = None, 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: _DynamoBase

PolicyStore + PolicyAdmin over a 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).

  • 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.

  • aws_secret_access_key – Explicit credentials, for tests only.

  • max_workers – Size of a dedicated thread pool (None: the loop’s default).

__init__(*, table_name: str = 'authz_policy', region: str | None = None, endpoint_url: str | None = None, 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 create(new: NewPolicy) → Policy[source]
async get(policy_id: str) → Policy | None[source]
async list_all(status: PolicyStatus | None = None) → Sequence[Policy][source]
async list_policies(scope: ScopeRef) → Sequence[Policy][source]
async replace(policy_id: str, new: NewPolicy, *, expected_revision: int) → Policy[source]
async set_status(policy_id: str, status: PolicyStatus, *, expected_revision: int) → Policy[source]
class auth_middleware.authz.stores.dynamodb_policy.DynamoDbAttributeStore(*, table_name: str = 'authz_policy', region: str | None = None, endpoint_url: str | None = None, 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: _DynamoBase

AttributeStore over a DynamoDB table (principal and resource attributes).

Takes the same connection arguments as DynamoDbPolicyStore.

__init__(*, table_name: str = 'authz_policy', region: str | None = None, endpoint_url: str | None = None, 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 delete_attributes(ref: EntityRef, *, expected_revision: int) → None[source]
async get_attributes(ref: EntityRef) → EntityAttributes | None[source]
async put_attributes(ref: EntityRef, attributes: Mapping[str, Any], *, expected_revision: int | None) → EntityAttributes[source]