Skip to main content

Configuration

Unlike django-rls (which reads a Django settings dict), FastAPI has no global settings object, so configuration is an explicit RLSConfig value object. The preferred path is to hand a config to the RLS facade; a process-wide active config also exists for the low-level context API.

from fastapi_rls import RLSConfig, RLS

config = RLSConfig(require_context=True, default_roles="app_user")
rls = RLS(engine=engine, config=config)

Options

OptionDefaultMeaning
require_contextFalseRaise RLSContextRequiredError when a query helper runs with no identity set
transaction_per_requestTrueThe session dependency wraps each request in a transaction and uses SET LOCAL
reset_context_on_checkoutTrueInstall the pool-checkin scrub backstop on a sync engine
audit_logFalseEmit structured INFO logs on context set/clear
default_roles"public"Default TO clause for policies ("public" or a comma-separated identifier list)
default_permissiveTruePolicies are PERMISSIVE by default (vs RESTRICTIVE)
key_prefix"rls"Session-variable namespace, e.g. rls.tenant_id
registered_context_keys()Extra context keys (beyond user/tenant) that connection hygiene should scrub

RLSConfig is a frozen dataclass. Derive variants with with_overrides:

prod = RLSConfig().with_overrides(require_context=True, default_roles="app_user")

Helper methods: full_key("tenant_id")"rls.tenant_id"; all_context_keys() → every key hygiene clears.

The active (global) config

The low-level context API consults a process-wide active config. Set it with configure:

from fastapi_rls import configure, RLSConfig, get_config

configure(RLSConfig(require_context=True)) # replace
configure(default_roles="app_user") # override fields of the current one
get_config() # read the active config

In an application, prefer passing an explicit config= to RLS(...) over mutating the global — configure is a convenience for scripts and tests.

From environment variables

RLSConfig.from_env() builds a config from FASTAPI_RLS_-prefixed variables:

config = RLSConfig.from_env() # reads FASTAPI_RLS_* from the environment
VariableMaps to
FASTAPI_RLS_REQUIRE_CONTEXTrequire_context
FASTAPI_RLS_AUDIT_LOGaudit_log
FASTAPI_RLS_DEFAULT_ROLESdefault_roles
FASTAPI_RLS_DEFAULT_PERMISSIVEdefault_permissive
FASTAPI_RLS_KEY_PREFIXkey_prefix
FASTAPI_RLS_REGISTERED_CONTEXT_KEYSregistered_context_keys (comma-separated)
FASTAPI_RLS_RESET_CONTEXT_ON_CHECKOUTreset_context_on_checkout
FASTAPI_RLS_TRANSACTION_PER_REQUESTtransaction_per_request

Booleans accept 1/true/yes/on (case-insensitive).

Validation

RLSConfig validates on construction: key_prefix must be a simple identifier, and default_roles must be a non-empty string. Invalid values raise ConfigurationError.