tempest_fastapi_sdk.authz¶
Autorização por objeto: políticas, checagem de permissão e a dependência do FastAPI.
PermissionRegistry
¶
PermissionRegistry(
*,
is_superuser: SuperuserPredicate = _default_superuser,
permission_resolver: PermissionResolver = _default_resolver,
)
A registry of object-level permission rules.
Instantiate your own for isolated rule sets (tests, plugins), or use
the process-wide :data:default_registry via the module-level
:func:permission / :func:has_perm / :func:check_permission
helpers.
Attributes:
| Name | Type | Description |
|---|---|---|
is_superuser |
SuperuserPredicate
|
Bypass predicate. |
permission_resolver |
PermissionResolver
|
Static-permission resolver used as the fallback. |
Initialize the registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
is_superuser
|
SuperuserPredicate
|
Predicate granting a
blanket bypass. Defaults to reading |
_default_superuser
|
permission_resolver
|
PermissionResolver
|
Resolver for the
static permission set. Defaults to reading
|
_default_resolver
|
register
¶
Register check as a rule for permission.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
permission
|
str
|
The permission string (or |
required |
check
|
PermissionCheck
|
The predicate |
required |
clear
¶
Drop every registered rule.
Intended for test isolation — call it in a fixture teardown so
rules registered against :data:default_registry by one test
never leak into the next.
rule
¶
Decorator form of :meth:register.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
permission
|
str
|
The permission string (or |
required |
Returns:
| Type | Description |
|---|---|
Callable[[PermissionCheck], PermissionCheck]
|
Callable[[PermissionCheck], PermissionCheck]: A decorator |
Callable[[PermissionCheck], PermissionCheck]
|
registering the wrapped predicate and returning it |
Callable[[PermissionCheck], PermissionCheck]
|
unchanged. |
has_perm
async
¶
Return whether user holds permission (on obj).
See the module docstring for the full resolution order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
object
|
The user under evaluation ( |
required |
permission
|
str
|
The permission string, e.g.
|
required |
obj
|
object
|
The target object for an object-level check, or
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
Notes
With no object, a rule that did not grant is not the final answer: the static permission set is consulted as well.
check_permission
async
¶
check_permission(
user: object, permission: str, obj: object = None, *, message: str | None = None
) -> None
Raise :class:ForbiddenException unless the permission holds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
object
|
The user under evaluation. |
required |
permission
|
str
|
The permission string. |
required |
obj
|
object
|
The target object, or |
None
|
message
|
str | None
|
Override for the forbidden message. |
None
|
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the permission is denied. |
has_perm
async
¶
has_perm(
user: object,
permission: str,
obj: object = None,
*,
registry: PermissionRegistry | None = None,
) -> bool
Module-level :meth:PermissionRegistry.has_perm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
object
|
The user under evaluation. |
required |
permission
|
str
|
The permission string. |
required |
obj
|
object
|
The target object, or |
None
|
registry
|
PermissionRegistry | None
|
Target registry; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
check_permission
async
¶
check_permission(
user: object,
permission: str,
obj: object = None,
*,
registry: PermissionRegistry | None = None,
message: str | None = None,
) -> None
Module-level :meth:PermissionRegistry.check_permission.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
object
|
The user under evaluation. |
required |
permission
|
str
|
The permission string. |
required |
obj
|
object
|
The target object, or |
None
|
registry
|
PermissionRegistry | None
|
Target registry; |
None
|
message
|
str | None
|
Override for the forbidden message. |
None
|
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the permission is denied. |
permission
¶
permission(
perm: str, *, registry: PermissionRegistry | None = None
) -> Callable[[PermissionCheck], PermissionCheck]
Decorator registering a rule on a registry (default: global).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
perm
|
str
|
The permission string (or |
required |
registry
|
PermissionRegistry | None
|
Target registry;
|
None
|
Returns:
| Type | Description |
|---|---|
Callable[[PermissionCheck], PermissionCheck]
|
Callable[[PermissionCheck], PermissionCheck]: The decorator. |
PermissionMixin
¶
Mixin adding await user.has_perm(perm, obj=...) to a model.
Delegates to :data:default_registry. Mix into a user model
alongside :class:BaseUserModel when you want the ergonomic
user.has_perm(...) call site from the roadmap.
has_perm
async
¶
Return whether this user holds permission (on obj).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
permission
|
str
|
The permission string. |
required |
obj
|
object
|
The target object, or |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
make_permission_checker
¶
make_permission_checker(
permission: str,
*,
get_user: Callable[..., Any],
get_object: Callable[..., Any] | None = None,
registry: PermissionRegistry | None = None,
forbidden_message: str | None = None,
) -> Callable[..., Coroutine[Any, Any, None]]
Build a FastAPI dependency enforcing an object-level permission.
The returned dependency resolves the current user via get_user
and, when get_object is given, the target object via
get_object (both ordinary FastAPI dependencies — they may
themselves Depends on the path params, session, etc.). It then
calls :meth:PermissionRegistry.check_permission, raising
:class:~tempest_fastapi_sdk.exceptions.forbidden.ForbiddenException
when the permission is denied.
Omit get_object for a model-level guard (obj=None).
Example
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
permission
|
str
|
The permission string to enforce, e.g.
|
required |
get_user
|
Callable[..., Any]
|
FastAPI dependency returning the
current user (or |
required |
get_object
|
Callable[..., Any] | None
|
FastAPI dependency
returning the target object; |
None
|
registry
|
PermissionRegistry | None
|
Registry to consult;
|
None
|
forbidden_message
|
str | None
|
Override for the forbidden message. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[..., Coroutine[Any, Any, None]]
|
Callable[..., Coroutine[Any, Any, None]]: An async FastAPI |
Callable[..., Coroutine[Any, Any, None]]
|
dependency raising |
Callable[..., Coroutine[Any, Any, None]]
|
success. |
requires
¶
requires(
*guards: Guard,
user_param: str | None = None,
meta: Mapping[str, Any] | None = None,
include_args: bool = False,
) -> Callable[[F], F]
Run permission guards on the user before the function body.
Each guard receives the current user and either returns it (or
None to leave it unchanged) or raises an
:class:~tempest_fastapi_sdk.exceptions.base.AppException subclass to
deny. Guards run left to right, and a guard's non-None return
becomes the user the next guard — and the decorated function — sees,
which is how the SDK's require_* guards narrow UserT | None to
UserT.
The user parameter is found by annotation: the single parameter typed
as a BaseModel / BaseUserModel subclass. Pass user_param
to name it explicitly, which is also the way to disambiguate a
function taking two user models.
Works on route handlers, controller and service methods, sync or
async. The wrapper keeps the decorated signature, so FastAPI's
dependency injection and the OpenAPI schema are untouched — place it
below the route decorator so the router registers the guarded
function.
A guard may declare an optional second parameter to receive a
dict[str, Any] of metadata, which is what turns one generic guard
into a specific check per call site: meta carries the literals
declared at decoration (meta={"role": "manager"}), and
include_args=True merges the arguments of the call itself (path
params, body, injected dependencies other than the user) into the same
mapping, so an ownership guard can read meta["order_id"]. Guards
that declare one parameter are called exactly as before.
Example
@router.delete(
"/orders/{order_id}",
responses=error_responses(ForbiddenException),
)
@requires(require_active, order_owner, include_args=True)
async def delete_order(
order_id: UUID,
user: UserModel = Depends(get_current_user),
) -> None: ...
def has_role(user: UserModel, meta: dict[str, Any]) -> UserModel:
# Raises ForbiddenException when the declared role is missing.
if meta["role"] not in user.roles:
raise ForbiddenException(message="Role required")
return user
@requires(has_role, meta={"role": "manager"})
async def close_month(
user: UserModel = Depends(get_current_user),
) -> None: ...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*guards
|
Guard
|
One or more guards, applied in order. |
()
|
user_param
|
str | None
|
Name of the parameter carrying the user.
|
None
|
meta
|
Mapping[str, Any] | None
|
Literal metadata handed to every guard that declares a second parameter. Copied at decoration time, so a later mutation of the passed mapping cannot change what the route enforces. |
None
|
include_args
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
Callable[[F], F]: The decorator, returning a wrapper with the same |
Callable[[F], F]
|
signature as the decorated function. |
Raises:
| Type | Description |
|---|---|
TempestPermissionError
|
At decoration time when no guard was
given, a guard is not callable or has the wrong signature, an
|
Warns:
| Type | Description |
|---|---|
GuardContractWarning
|
At call time when a guard raises a
non-:class: |
Notes
Runtime validation cannot see a guard that is never wired or a
dynamic raise. Run tempest permissions --check in CI for
the static half of the same contract.
Guard
module-attribute
¶
A permission guard, sync or async.
Two accepted shapes: (user) -> user | None and
(user, meta: dict[str, Any]) -> user | None. The second one receives
the metadata :func:requires was configured with (meta= literals plus,
under include_args=True, the arguments of the call), which is how one
generic guard becomes a specific check per call site.
Denial is expressed by raising an :class:AppException subclass, never
by returning a falsy value.
declared_guards
¶
declared_guards(fn: Callable[..., Any]) -> tuple[Guard, ...]
Return the guards :func:requires attached to a function.
The counterpart of
:func:tempest_fastapi_sdk.api.error_docs.declared_raises: it lets a
test, a router audit or an admin page read a route's authorization
without calling it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
The (possibly decorated) function. |
required |
Returns:
| Type | Description |
|---|---|
Guard
|
tuple[Guard, ...]: The guards in application order, empty when the |
...
|
function is not decorated with :func: |
guard_metadata
¶
Return the literal metadata :func:requires attached to a function.
Only the meta= literals, which are fixed at decoration time — the
arguments merged by include_args=True exist per call and cannot be
read from the function object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
The (possibly decorated) function. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: A copy of the declared metadata, empty when the |
dict[str, Any]
|
function carries none. |
guarded_user_param
¶
Return the parameter name :func:requires reads the user from.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
The (possibly decorated) function. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The parameter name, or |
str | None
|
not decorated with :func: |
TempestPermissionError
¶
Bases: TypeError
Raised when :func:requires is used incorrectly.
A programming error, not an application error: it fires while the
module is being imported (or on a call that cannot supply the user),
so it must not be caught and converted into an HTTP response. It is a
:class:TypeError because every case it reports is a signature or
contract mismatch.
GuardContractWarning
¶
Bases: UserWarning
Warns that a guard broke its contract at runtime.
Two cases, both of which would otherwise be silent:
- the guard raised an exception outside the :class:
AppExceptionhierarchy, which the API layer answers as HTTP 500 with no errorcode; - the guard returned a value that is not a user model and not
None— almost always a predicate-stylereturn False, whose denial :func:requirescannot honor, since guards deny by raising.
A warning rather than an exception: the decorator must not change the
outcome of a call it is only observing, and a warning is visible in
tests (-W error) and in logs without breaking production traffic.