API Reference¶
Complete reference for all fastapi-topaz public exports.
Configuration¶
TopazConfig¶
Configuration for Topaz authorization. Create once at app startup, use to generate authorization dependencies.
| PARAMETER | DESCRIPTION |
|---|---|
authorizer_options
|
Connection settings for Topaz authorizer
TYPE:
|
policy_path_root
|
Root package name for policies (e.g., "myapp")
TYPE:
|
identity_provider
|
Function to extract user identity from request
TYPE:
|
policy_instance_name
|
Name of policy instance to evaluate
TYPE:
|
policy_instance_label
|
Label for policy instance (defaults to name)
TYPE:
|
resource_context_provider
|
Function to provide additional context
TYPE:
|
policy_path_normalizer
|
Optional callable to transform generated policy paths (e.g., replace hyphens with underscores for valid Rego identifiers)
TYPE:
|
default_policy
|
Optional fallback policy path evaluated when no explicit policy file exists and no policy group matches. All requests still go through Topaz — this only changes which policy is evaluated.
TYPE:
|
policy_groups
|
Optional ordered list of :class:
TYPE:
|
decision_cache
|
Optional cache for authorization decisions
TYPE:
|
max_concurrent_checks
|
Max concurrent authorization checks for bulk operations (default: 10)
TYPE:
|
check_timeout
|
gRPC deadline in seconds applied to each authorization call (default: 5.0). Set to None to disable the deadline.
TYPE:
|
on_error
|
Response when the authorization call itself fails and the circuit breaker gives no fallback decision, for the middleware and every dependency. Both values fail closed:
TYPE:
|
circuit_breaker
|
Optional circuit breaker for graceful degradation
TYPE:
|
audit_logger
|
Optional audit logger for authorization decisions
TYPE:
|
metrics
|
Optional Prometheus metrics collector. When combined with circuit_breaker and no user-provided on_state_change callback, circuit transitions and the state gauge are recorded automatically (a user-provided callback takes precedence).
TYPE:
|
tracing
|
Optional OpenTelemetry tracing
TYPE:
|
insecure
|
Use a plaintext (non-TLS) gRPC channel to the authorizer. Local development only — never enable against a production Topaz.
TYPE:
|
expose_deny_reason
|
Include the evaluated policy path and check source in 403 response bodies. This leaks policy structure to clients — enable for development and debugging only, never in production.
TYPE:
|
Source code in src/fastapi_topaz/config.py
check_decision
async
¶
check_decision(request: Request, policy_path: str, decision: str, resource_context: ResourceContext | None = None, source: str = 'dependency', policy_resolution_source: str | None = None) -> bool
Check an authorization decision, using cache if available.
This is the core authorization check method that handles caching, circuit breaker logic, and can be used directly for custom authorization logic.
When audit_logger is configured, every call emits exactly one audit
event, regardless of caller (middleware, dependency, or manual API).
Source code in src/fastapi_topaz/config.py
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 | |
is_allowed
async
¶
is_allowed(request: Request, policy_path: str, resource_context: ResourceContext | None = None, decision: str = 'allowed', source: str = 'manual') -> bool
Check if an action is allowed without raising an exception.
This is a non-raising alternative to require_policy_allowed that returns True/False instead of raising HTTPException(403). Useful for UI patterns where you need to check permissions without blocking (e.g., showing/hiding edit or delete buttons).
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The FastAPI request object
TYPE:
|
policy_path
|
Full policy path (e.g., "webapp.PUT.documents")
TYPE:
|
resource_context
|
Optional resource context dict
TYPE:
|
decision
|
Decision to check (default: "allowed")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if allowed, False otherwise |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
Authorizer errors the circuit breaker does not turn into a fallback decision (no breaker configured, or a non-failure code such as INVALID_ARGUMENT) propagate to the caller. |
Example
Source code in src/fastapi_topaz/config.py
check_relation
async
¶
check_relation(request: Request, object_type: str, object_id: str, relation: str, subject_type: str = 'user', source: str = 'manual') -> bool
Check a ReBAC relation without raising an exception.
This is a non-raising alternative to require_rebac_allowed that returns True/False instead of raising HTTPException(403). Useful for checking if a user has a specific relationship with an object.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The FastAPI request object
TYPE:
|
object_type
|
Type of object (e.g., "document", "folder")
TYPE:
|
object_id
|
ID of the object to check
TYPE:
|
relation
|
Relation to check (e.g., "can_read", "can_write", "can_delete")
TYPE:
|
subject_type
|
Subject type (default: "user")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the relation exists, False otherwise |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
Authorizer errors the circuit breaker does not turn into a fallback decision (no breaker configured, or a non-failure code such as INVALID_ARGUMENT) propagate to the caller. |
Example
Source code in src/fastapi_topaz/config.py
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 | |
check_relations
async
¶
check_relations(request: Request, object_type: str, object_id: str, relations: list[str], subject_type: str = 'user', source: str = 'manual', batch: bool = False) -> dict[str, bool]
Check multiple ReBAC relations at once without raising exceptions.
This method checks multiple relations concurrently and returns a dict mapping relation names to boolean results. Useful for fetching all permissions for an object in a single call (e.g., to populate a permissions object in an API response).
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The FastAPI request object
TYPE:
|
object_type
|
Type of object (e.g., "document", "folder")
TYPE:
|
object_id
|
ID of the object to check
TYPE:
|
relations
|
List of relations to check (e.g., ["can_read", "can_write", "can_delete"])
TYPE:
|
subject_type
|
Subject type (default: "user")
TYPE:
|
batch
|
Evaluate all relations in a single Topaz call instead of
one call per relation. Requires the
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, bool]
|
Dict mapping relation names to boolean results |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
Authorizer errors the circuit breaker does not turn into a fallback decision (no breaker configured, or a non-failure code such as INVALID_ARGUMENT) propagate to the caller. |
Example
@app.get("/documents/{id}")
async def get_document(id: int, request: Request):
doc = await fetch_document(id)
permissions = await config.check_relations(
request,
object_type="document",
object_id=str(id),
relations=["can_read", "can_write", "can_delete", "can_share"],
)
# permissions = {"can_read": True, "can_write": True, "can_delete": False, "can_share": False}
return {"document": doc, "permissions": permissions}
Source code in src/fastapi_topaz/config.py
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 | |
invalidate_cache
async
¶
invalidate_cache(identity_value: str | None = None, policy_path: str | None = None, object_id: str | None = None) -> int
Invalidate cached decisions matching all provided criteria (AND).
Use after permission changes (e.g. revoking a user's access) so cached decisions do not keep serving stale grants until TTL expiry.
Delegates to decision_cache.invalidate(...) when the configured
backend implements it; backends without an invalidate method are
skipped. The stale fallback cache is always cleared entirely.
| PARAMETER | DESCRIPTION |
|---|---|
identity_value
|
Invalidate entries for this identity
TYPE:
|
policy_path
|
Invalidate entries for this policy path
TYPE:
|
object_id
|
Invalidate entries for this object ID
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of entries removed from the decision cache (0 when the |
int
|
backend has no |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no criterion is provided. |
Source code in src/fastapi_topaz/config.py
health
async
¶
Report authorization readiness for health/readiness endpoints.
| PARAMETER | DESCRIPTION |
|---|---|
ping
|
Also call the authorizer's Info RPC to verify reachability. Ping failures are reported in the result, never raised.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Dict with keys: |
dict[str, Any]
|
open or a requested ping failed), |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
or None when not requested). |
Source code in src/fastapi_topaz/config.py
policy_path_for ¶
Generate the policy path for a given HTTP method and route path.
Useful for debugging, testing, or previewing what policy path will be generated for a given route.
| PARAMETER | DESCRIPTION |
|---|---|
method
|
HTTP method (e.g., "GET", "POST")
TYPE:
|
route_path
|
URL path pattern (e.g., "/documents/{id}")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The policy path that would be used for authorization |
Example
config.policy_path_for("GET", "/documents/{id}") "myapp.GET.documents.__id"
Source code in src/fastapi_topaz/config.py
DecisionCache¶
Simple in-memory TTL cache for authorization decisions.
| PARAMETER | DESCRIPTION |
|---|---|
ttl_seconds
|
Time-to-live for cache entries (default: 60 seconds)
TYPE:
|
max_size
|
Maximum number of entries to cache (default: 1000)
TYPE:
|
get
async
¶
get(identity_value: str, policy_path: str, decision: str, resource_context: ResourceContext | None, *, identity_type: str = '', policy_instance: str = '') -> bool | None
Get a cached decision, or None if not cached or expired.
Source code in src/fastapi_topaz/cache.py
set
async
¶
set(identity_value: str, policy_path: str, decision: str, resource_context: ResourceContext | None, value: bool, *, identity_type: str = '', policy_instance: str = '') -> None
Cache a decision.
Source code in src/fastapi_topaz/cache.py
invalidate
async
¶
invalidate(identity_value: str | None = None, policy_path: str | None = None, object_id: str | None = None) -> int
Remove cached decisions matching all provided criteria (AND).
| PARAMETER | DESCRIPTION |
|---|---|
identity_value
|
Remove entries for this identity
TYPE:
|
policy_path
|
Remove entries for this policy path
TYPE:
|
object_id
|
Remove entries whose resource context had this object_id
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of entries removed. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no criterion is provided (use :meth: |
Source code in src/fastapi_topaz/cache.py
size ¶
Authorization Dependencies¶
require_policy_allowed¶
Async dependency that raises HTTPException(403) if policy denies access.
When the authorizer call itself fails, raises 403 or 503 per config.on_error.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Topaz configuration
TYPE:
|
policy_path
|
Full policy path (e.g., "webapp.POST.api.documents")
TYPE:
|
decision
|
Decision to check (default: "allowed")
TYPE:
|
resource_context
|
Optional resource context dict
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Request], Awaitable[None]]
|
Async dependency function for FastAPI |
Example
Source code in src/fastapi_topaz/dependencies.py
require_policy_auto¶
Async dependency that auto-generates policy path from route and raises HTTPException(403) if denied.
When the authorizer call itself fails, raises 403 or 503 per config.on_error.
The policy path is automatically derived from the HTTP method and route path pattern: - GET /documents -> {root}.GET.documents - POST /documents -> {root}.POST.documents - GET /documents/{id} -> {root}.GET.documents.__id - PUT /users/{user_id}/docs/{doc_id} -> {root}.PUT.users.__user_id.docs.__doc_id
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Topaz configuration
TYPE:
|
decision
|
Decision to check (default: "allowed")
TYPE:
|
resource_context
|
Optional resource context dict
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Request], Awaitable[None]]
|
Async dependency function for FastAPI |
Example
Source code in src/fastapi_topaz/dependencies.py
require_rebac_allowed¶
Async dependency that raises HTTPException(403) if ReBAC check fails.
When the authorizer call itself fails, raises 403 or 503 per config.on_error.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Topaz configuration
TYPE:
|
object_type
|
Type of object (e.g., "document", "folder")
TYPE:
|
relation
|
Relation to check (e.g., "can_write", "can_delete")
TYPE:
|
object_id
|
Static ID, callable to extract from request, or None (uses path param "id")
TYPE:
|
subject_type
|
Subject type (default: "user")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Request], Awaitable[None]]
|
Async dependency function for FastAPI |
Example
Source code in src/fastapi_topaz/dependencies.py
get_authorized_resource¶
Async dependency that checks authorization, then fetches the resource.
Returns resource or raises 403/404.
When the authorizer call itself fails, raises 403 or 503 per config.on_error.
Authorization runs first, so a denied request gets 403 whether or not the resource exists (no existence oracle) and the fetcher is never called.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Topaz configuration
TYPE:
|
resource_fetcher
|
Function that takes (request) and returns resource or
None. Coroutine functions and objects with an async
TYPE:
|
object_type
|
Type of object (e.g., "document")
TYPE:
|
relation
|
Relation to check (e.g., "can_write")
TYPE:
|
object_id
|
Static ID, callable, or None (uses path param "id")
TYPE:
|
subject_type
|
Subject type (default: "user")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Request], Awaitable[T]]
|
Async dependency function that returns the authorized resource |
Example
def fetch_document(request: Request, db: Session) -> Document | None:
doc_id = request.path_params["id"]
return db.query(Document).filter(Document.id == doc_id).first()
@router.put("/documents/{id}")
async def update_document(
document: Document = Depends(
get_authorized_resource(topaz_config, fetch_document, "document", "can_write")
),
):
# document is pre-fetched and authorized
...
Source code in src/fastapi_topaz/dependencies.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
filter_authorized_resources¶
Async dependency that returns an async filter function to remove unauthorized resources.
When the authorizer call itself fails, raises 403 or 503 per config.on_error.
Uses concurrent authorization checks (controlled by config.max_concurrent_checks) and caching (if config.decision_cache is set) for optimal performance.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Topaz configuration
TYPE:
|
object_type
|
Type of object (e.g., "document")
TYPE:
|
relation
|
Relation to check (e.g., "can_read")
TYPE:
|
id_extractor
|
Function to extract ID from resource object
TYPE:
|
subject_type
|
Subject type (default: "user")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Request], Awaitable[Callable[[list[T]], Awaitable[list[T]]]]]
|
Async dependency that returns an async filter function |
Example
Source code in src/fastapi_topaz/dependencies.py
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 | |
require_rebac_hierarchy¶
Async dependency for hierarchical ReBAC authorization.
When the authorizer call itself fails, raises 403 or 503 per config.on_error.
Checks multiple object/relation pairs in a single dependency, reducing boilerplate for nested resources like /orgs/{org}/projects/{proj}/docs/{doc}.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Topaz configuration
TYPE:
|
checks
|
List of (object_type, id_source, relation) tuples. id_source can be: - "param_name" -> request.path_params["param_name"] - "header:X-Name" -> request.headers["X-Name"] - "query:name" -> request.query_params["name"] - "static:value" -> literal "value" - callable -> callable(request)
TYPE:
|
mode
|
Check mode: - "all" (default): All checks must pass (AND). Fails fast. - "any": At least one check must pass (OR). - "first_match": Return on first success.
TYPE:
|
subject_type
|
Subject type (default: "user")
TYPE:
|
optimize
|
Run checks concurrently when possible (default: True)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Request], Awaitable[None]]
|
Async dependency function for FastAPI |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
At factory time, if |
HTTPException(403)
|
If authorization fails based on mode semantics |
Example
Source code in src/fastapi_topaz/dependencies.py
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 | |
HierarchyResult¶
Result of a hierarchy authorization check.
| ATTRIBUTE | DESCRIPTION |
|---|---|
allowed |
Whether the hierarchy check passed
TYPE:
|
checks |
List of (object_type, object_id, relation, result) tuples
TYPE:
|
denied_at |
Object type where access was denied (mode="all")
TYPE:
|
first_match |
Relation that matched first (mode="first_match")
TYPE:
|
as_dict ¶
Middleware¶
TopazMiddleware¶
FastAPI middleware for global authorization (pure ASGI).
Auto-protects all routes by checking policy paths derived from HTTP method and route pattern. Routes are protected unless explicitly excluded.
Policy Resolution Chain (first match wins):
1. Explicit: Route has a .rego file in policies_dir
2. Group: Route matches a :class:PolicyGroup url_pattern
3. Default: config.default_policy is set
4. Generated: Use auto-generated policy path (legacy behaviour)
| PARAMETER | DESCRIPTION |
|---|---|
app
|
The FastAPI application
TYPE:
|
config
|
TopazConfig with authorizer settings
TYPE:
|
exclude_paths
|
Regex patterns for paths to skip (e.g., [r"^/health$", r"^/docs.*"])
TYPE:
|
exclude_methods
|
HTTP methods to skip (default: ["OPTIONS", "HEAD"])
TYPE:
|
on_missing_identity
|
How to handle missing identity: - "deny": Return 401 Unauthorized - "anonymous": Pass anonymous identity to Topaz (let policy decide)
TYPE:
|
on_denied
|
Optional callback to customize 403 response
TYPE:
|
on_error
|
How to respond when the authorization check itself fails
(e.g. authorizer unreachable) and no circuit breaker fallback applies:
- None (default): use
TYPE:
|
policies_dir
|
Optional directory to scan for explicit
TYPE:
|
Source code in src/fastapi_topaz/middleware.py
skip_middleware¶
Decorator to mark a route as excluded from authorization middleware.
The decorated endpoint will not be checked by TopazMiddleware, allowing you to implement custom authorization logic.
from fastapi_topaz import skip_middleware
@app.post("/documents/bulk-import")
@skip_middleware
async def bulk_import(
_=Depends(require_policy_allowed(config, "myapp.admin.bulk_import")),
):
# Custom policy path, not auto-generated
...
Source code in src/fastapi_topaz/middleware.py
SkipMiddleware¶
Marker dependency to skip authorization middleware for a router or route.
Use as a dependency on a router to exclude all routes from middleware authorization:
from fastapi import APIRouter, Depends
from fastapi_topaz import SkipMiddleware
public_router = APIRouter(
prefix="/api/public",
dependencies=[Depends(SkipMiddleware)],
)
@public_router.get("/status") # Automatically excluded from middleware
async def public_status():
return {"status": "ok"}
Circuit Breaker¶
CircuitBreaker¶
Circuit breaker configuration for Topaz authorization.
Prevents cascading failures when Topaz is unavailable by opening the circuit after a threshold of failures, using fallback strategies, and automatically testing for recovery.
| PARAMETER | DESCRIPTION |
|---|---|
failure_threshold
|
Number of consecutive failures before opening circuit
TYPE:
|
success_threshold
|
Number of successes in half-open before closing
TYPE:
|
recovery_timeout
|
Seconds to wait before transitioning to half-open
TYPE:
|
fallback
|
Strategy when circuit is open ("cache_then_deny", "cache_then_allow", "deny", "allow", or custom callable)
TYPE:
|
serve_stale_cache
|
Whether to serve expired cache entries when open
TYPE:
|
stale_cache_ttl
|
Maximum age (seconds) of stale cache to serve
TYPE:
|
failure_exceptions
|
Exception types that count as failures
TYPE:
|
failure_grpc_codes
|
gRPC status codes that count as failures (default: UNAVAILABLE, DEADLINE_EXCEEDED, UNKNOWN, INTERNAL, RESOURCE_EXHAUSTED)
TYPE:
|
on_state_change
|
Callback when circuit state changes
TYPE:
|
on_fallback
|
Callback when fallback is used
TYPE:
|
half_open_max_requests
|
Number of test requests allowed in half-open state
TYPE:
|
Example
status ¶
status() -> CircuitStatus
Get current circuit status for health checks.
Source code in src/fastapi_topaz/circuit_breaker.py
admit
async
¶
admit() -> Admission | None
Let a request through to Topaz, or refuse it.
Returns an :class:Admission when the circuit is closed, or when a
half-open probe slot is free (probe=True). Returns None when the
circuit is open, or half-open with every probe slot taken, and the
fallback should be used. Pass the ticket back when recording the result.
Source code in src/fastapi_topaz/circuit_breaker.py
should_allow_request
async
¶
Check if a request should be allowed through to Topaz.
Returns True if the circuit is closed or if we should test in half-open.
Returns False if the circuit is open and fallback should be used.
Prefer :meth:admit, whose ticket lets the breaker tell probes apart.
Source code in src/fastapi_topaz/circuit_breaker.py
record_success
async
¶
record_success(admission: Admission | None = None) -> None
Record a successful authorization call.
| PARAMETER | DESCRIPTION |
|---|---|
admission
|
The ticket from :meth:
TYPE:
|
Source code in src/fastapi_topaz/circuit_breaker.py
record_failure
async
¶
record_failure(exception: Exception, admission: Admission | None = None) -> None
Record a failed authorization call.
| PARAMETER | DESCRIPTION |
|---|---|
exception
|
The failure.
TYPE:
|
admission
|
The ticket from :meth:
TYPE:
|
Source code in src/fastapi_topaz/circuit_breaker.py
release_probe ¶
release_probe(admission: Admission | None = None) -> None
Free a half-open probe slot for a call that ended without a verdict.
| PARAMETER | DESCRIPTION |
|---|---|
admission
|
The ticket from :meth:
TYPE:
|
Source code in src/fastapi_topaz/circuit_breaker.py
get_fallback_decision
async
¶
get_fallback_decision(request: Request, policy_path: str, resource_context: dict[str, Any], cached_decision: bool | None, error: Exception) -> bool
Get the fallback decision when circuit is open.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The FastAPI request
TYPE:
|
policy_path
|
The policy path being checked
TYPE:
|
resource_context
|
The resource context
TYPE:
|
cached_decision
|
Cached decision (may be stale), or None if not cached
TYPE:
|
error
|
The exception that caused the fallback
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Authorization decision (True/False) |
Source code in src/fastapi_topaz/circuit_breaker.py
reset
async
¶
Reset the circuit breaker to initial state.
Source code in src/fastapi_topaz/circuit_breaker.py
is_failure_exception ¶
Check if an exception should count as a circuit breaker failure.
gRPC errors (including grpc.aio.AioRpcError) count as failures only when their status code is in failure_grpc_codes, so policy errors like INVALID_ARGUMENT or NOT_FOUND do not trip the breaker.
Source code in src/fastapi_topaz/circuit_breaker.py
Admission¶
A ticket for one call let through by :meth:CircuitBreaker.admit.
Pass it back to record_success / record_failure / release_probe
so that, in half-open state, only the calls admitted as probes for the
current half-open period free probe slots and decide recovery.
CircuitState¶
CircuitStatus¶
Audit Logging¶
AuditLogger¶
Audit logger for authorization decisions.
| PARAMETER | DESCRIPTION |
|---|---|
log_allowed
|
Log successful authorizations
TYPE:
|
log_denied
|
Log denied authorizations
TYPE:
|
log_skipped
|
Log skipped/excluded routes
TYPE:
|
log_unauthenticated
|
Log 401 events
TYPE:
|
log_manual_checks
|
Log is_allowed(), check_relations()
TYPE:
|
level_allowed
|
Log level for allowed events
TYPE:
|
level_denied
|
Log level for denied events
TYPE:
|
level_unauthenticated
|
Log level for 401 events
TYPE:
|
level_skipped
|
Log level for skipped events
TYPE:
|
include_resource_context
|
Include resource context in logs. Off by default: resource context often carries user data (emails, names, document attributes) that should not land in logs unreviewed.
TYPE:
|
include_request_headers
|
Include HTTP headers (privacy concern)
TYPE:
|
handler
|
Custom async handler for events
TYPE:
|
Note
The client IP recorded in events is taken from the x-forwarded-for
/ x-real-ip headers when present, which are client-spoofable
unless a trusted reverse proxy strips or sets them. Do not treat the
audit client_ip as authenticated for forensics unless your
deployment guarantees those headers.
log_decision
async
¶
log_decision(request: Request | None, policy_path: str, allowed: bool, *, source: str = 'dependency', check_type: str = 'policy', cached: bool = False, latency_ms: float | None = None, identity_type: str | None = None, identity_value: str | None = None, object_type: str | None = None, object_id: str | None = None, relation: str | None = None, subject_type: str | None = None, resource_context: dict[str, Any] | None = None, policy_resolution_source: str | None = None, reason: str | None = None) -> None
Log an authorization decision.
Source code in src/fastapi_topaz/audit.py
log_batch_check
async
¶
log_batch_check(request: Request | None, object_type: str, object_id: str, results: dict[str, bool], *, latency_ms: float | None = None, identity_value: str | None = None) -> None
Log batch relation check results.
Source code in src/fastapi_topaz/audit.py
log_unauthenticated_event
async
¶
Log unauthenticated access attempt.
Source code in src/fastapi_topaz/audit.py
AuditEvent¶
Structured audit event for authorization decisions.
to_dict ¶
Convert to structured dict for logging.
Source code in src/fastapi_topaz/audit.py
Observability¶
PrometheusMetrics¶
Prometheus metrics collector for authorization decisions.
When two instances share a registry (e.g. two PrometheusMetrics created
with the default global REGISTRY), the second instance reuses the
collectors already registered under the same metric names instead of
raising ValueError: Duplicated timeseries.
| PARAMETER | DESCRIPTION |
|---|---|
prefix
|
Metric name prefix (default: "topaz")
TYPE:
|
include_policy_path
|
Add policy_path label (high cardinality)
TYPE:
|
include_object_type
|
Add object_type label (medium cardinality)
TYPE:
|
include_relation
|
Add relation label (medium cardinality)
TYPE:
|
latency_buckets
|
Histogram buckets for latency
TYPE:
|
registry
|
Custom prometheus registry (default: global)
TYPE:
|
record_auth_request ¶
record_auth_request(source: str, decision: str, check_type: str, policy_path: str | None = None) -> None
Record an authorization request.
Source code in src/fastapi_topaz/observability.py
record_cache_hit ¶
record_cache_miss ¶
record_latency ¶
record_latency(latency_seconds: float, source: str, cached: bool, policy_path: str | None = None) -> None
Record authorization latency.
Source code in src/fastapi_topaz/observability.py
record_topaz_latency ¶
Record actual Topaz call latency.
Source code in src/fastapi_topaz/observability.py
record_error ¶
Record an authorization error.
set_circuit_state ¶
Set circuit breaker state (0=closed, 1=open, 2=half_open).
record_circuit_transition ¶
Record circuit state transition.
Source code in src/fastapi_topaz/observability.py
record_fallback ¶
Record circuit breaker fallback.
Source code in src/fastapi_topaz/observability.py
set_cache_size ¶
OTelTracing¶
OpenTelemetry tracing for authorization decisions.
| PARAMETER | DESCRIPTION |
|---|---|
trace_all_checks
|
Trace all authorization checks
TYPE:
|
trace_cache_operations
|
Include cache lookup/store spans
TYPE:
|
include_identity
|
Add identity to span attributes (privacy risk)
TYPE:
|
include_policy_path
|
Add policy_path to spans
TYPE:
|
include_resource_context
|
Add full resource context (privacy risk)
TYPE:
|
span_name_prefix
|
Prefix for span names
TYPE:
|
start_auth_span ¶
start_auth_span(source: str, check_type: str, policy_path: str | None = None, identity_value: str | None = None) -> Any
Start an authorization span.
Source code in src/fastapi_topaz/observability.py
end_auth_span ¶
end_auth_span(span: Any, decision: str, cached: bool, latency_ms: float, resource_context: dict | None = None) -> None
End an authorization span with results.
Source code in src/fastapi_topaz/observability.py
start_cache_span ¶
Start a cache operation span.
Source code in src/fastapi_topaz/observability.py
end_cache_span ¶
End a cache operation span.
Source code in src/fastapi_topaz/observability.py
start_topaz_span ¶
Start a Topaz request span.
end_topaz_span ¶
End a Topaz request span.
Source code in src/fastapi_topaz/observability.py
record_error ¶
Record an error on a span.
Source code in src/fastapi_topaz/observability.py
get_current_trace_id ¶
Get current trace ID for correlation.
Source code in src/fastapi_topaz/observability.py
Policy Generation¶
annotate_openapi¶
Annotate FastAPI routes with their resolved Topaz policy paths in OpenAPI.
Walks every route (including included routers) and resolves each route through the same policy
resolution chain as :func:generate_rights_matrix (explicit file when
policies_dir is given > policy group > default policy > generated),
then merges x-authz-policy and x-authz-source into each route's
openapi_extra. Existing openapi_extra keys are preserved. When
the methods of one route resolve differently, both keys are written as
{method: value} maps sorted by method; otherwise they are strings.
Routes TopazMiddleware does not authorize (@skip_middleware,
Depends(SkipMiddleware), or the installed middleware's
exclude_paths / exclude_methods) get x-authz-source: skipped
and no x-authz-policy entry.
Call after route registration and before the first schema build (the
schema is cached on first access to app.openapi()). This includes
routes added to a router after it was passed to include_router():
on FastAPI >= 0.137 their annotations are lost otherwise.
| PARAMETER | DESCRIPTION |
|---|---|
app
|
FastAPI application instance
TYPE:
|
config
|
TopazConfig with policy_path_root (and optional default_policy / policy_groups)
TYPE:
|
policies_dir
|
Directory containing
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of routes annotated. |
Source code in src/fastapi_topaz/codegen.py
Re-exported Types¶
These types are re-exported from aserto.client for convenience: