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:
objectCatalog + 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 authorizer_for(request: Request) Authorizer[source]
Build an
Authorizerforrequest(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_rolesgiven).- 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
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, resource: ResourceSource | None = None, authz: AuthzSource = 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.
resource – Where the resource comes from (ABAC): a
ResourceFromPath/ResourceFromQuery/ResourceFromCallable, optionally with a loader of the resource’s attributes. NeedsAuthz.build(abac=...)(startup validation refuses a guard whose resource would be ignored).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, *, resource: ResourceSource | ResourceContext | None = None, authz: AuthzSource = 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]], attributes: Mapping[str, AttributeSpec] | None = None)[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]], 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.
StrEnummembers 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_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], *, pdp: PolicyDecisionPoint | None = None)[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], *, 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:
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.With ABAC configured: evaluate the applicable policies (deny-overrides;
hideturns a denial intoScopeNotVisibleError).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
hidepolicy 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:
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 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_decisionhook 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_sourceand each policy underabac_policies(denied,permittedorshadow_denied).
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
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:
objectAttribute-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) orgrant(permitpolicies may grant; experimental).policy_cache_ttl – Seconds the policies of a scope are cached (default 5;
0disables 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-Foris believed.clock – Aware-
datetimeclock forenv.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
- 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).
- 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:
objectA stored policy: a
NewPolicyplus 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
- effect: Effect
- classmethod fail_closed(policy_id: str, scope: PolicyScope, permissions: tuple[str, ...] = ('*',)) Policy[source]
A
denythat 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.
- scope: PolicyScope
- status: PolicyStatus
- 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:
objectInput of
PolicyAdmin.create/replace.- Parameters:
id – Human-chosen id,
[a-z0-9][a-z0-9_.-]{0,99}, unique across the store.effect –
deny,requireorpermit.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 –
Falseis 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
- effect: Effect
- 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:
objectWrites 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
permitpolicies (grantmode).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.
- class auth_middleware.authz.abac.pdp.PolicyDecisionPoint(policies: PolicyStore, resolver: AttributeResolver, *, mode: Literal['restrict', 'grant'] = 'restrict')[source]
Bases:
objectLoads, 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) orgrant(permitpolicies 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
permitpolicies (grantmode).
- Raises:
InvalidPolicyError – With
.problemslisting 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;
.pointerlocates it.
- auth_middleware.authz.abac.conditions.evaluate(cond: Node, values: Mapping[str, Any]) Tri[source]
Evaluate
condovervalues(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:
objectCaches
list_policiesper(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
invalidatethat 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]
- invalidate(scope: ScopeRef | None = None) None[source]
Drop one scope’s entry, or everything when
scopeisNone.
- class auth_middleware.authz.abac.sources.StaticPolicySource(policies: Iterable[Policy | NewPolicy | Mapping[str, Any]])[source]
Bases:
objectRead-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
.tomlor.jsonfile.- Raises:
InvalidPolicyError – Unreadable, unsupported or invalid content.
- class auth_middleware.authz.abac.resources.ResourceFromPath(kind: str, param: str, loader: ResourceLoader | None = None)[source]
Bases:
objectResource id read from a path parameter.
- Parameters:
kind – Resource kind (
design).param – Path parameter holding the id.
loader –
loader(request, ref) -> attributes | Nonereading the resource’s attributes from the application’s own data.
- 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:
_SqlBasePolicyStore+PolicyAdminover a SQL table.A stored row that cannot be decoded (a hand-edited table, an old format) is returned as a
denythat 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 (
Nonefor 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.
- 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:
_SqlBaseAttributeStoreover 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 (
Nonescope).commit – Commit after writes when the store owns the session.
- 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:
_DynamoBasePolicyStore+PolicyAdminover 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]
- 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:
_DynamoBaseAttributeStoreover 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]