Skip to content

xtr_security.bundle

The xtr-dependency-injection bundle for the xtr security family.

Re-exports the :class:SecurityBundle, every configuration class an application writes, and the factory helpers a third-party bundle extends the family through, so an application configures security from one import.

TokenEndpointAuthMethod module-attribute

TokenEndpointAuthMethod = Literal['none', 'client_secret_basic', 'client_secret_post', 'client_secret_jwt', 'private_key_jwt', 'tls_client_auth', 'self_signed_tls_client_auth']

How the client authenticates at the provider's token endpoint.

HasherConfig module-attribute

HasherConfig = AutoHasherConfig | NativeHasherConfig | Pbkdf2HasherConfig | PlaintextHasherConfig | ServiceHasherConfig

Every kind of hasher config, told apart by its type field.

TokenHandlerConfig module-attribute

TokenHandlerConfig = ServiceTokenHandlerConfig | OidcTokenHandlerConfig | Oauth2TokenHandlerConfig | OidcUserInfoTokenHandlerConfig

Every kind of token-handler configuration, told apart by its type field.

UserProviderConfig module-attribute

UserProviderConfig = InMemoryUserProviderConfig | ChainUserProviderConfig | ServiceUserProviderConfig

Every kind of user-provider configuration, told apart by its type field.

Oauth2TokenHandlerFactory

Bases: TokenHandlerFactoryInterface

Builds a handler that introspects a token with its authorization server.

The scoped client — the application's own, carrying the introspection endpoint's base URI and this resource server's credentials — is built here through :meth:~xtr_http_client_contracts.HttpClientInterface.with_options, unless the configuration names a client service that carries its own. The handler and its signed-response verification live in xtr-security-http's oidc extra (joserfc); the key set a pinned JWKS document describes is imported only when the handler is built, so the bundle carries no JOSE dependency until an application configures one.

key property

key: str

Name this kind of handler oauth2.

config_type property

config_type: type

Build instances of :class:Oauth2TokenHandlerConfig.

create

create(services: ServiceConfigurator, builder: ContainerBuilder, service_id: str, config: object) -> ServiceKey

Register the introspection handler service and return its key.

The handler writes the failures its server's answers explain to the application's logger, and judges a token's times by the application's clock, when the bundles providing them are active.

OidcTokenHandlerFactory

OidcTokenHandlerFactory(closeables: list[_AsyncCloseable] | None = None)

Bases: TokenHandlerFactoryInterface

Builds an OIDC token handler that verifies a third-party issuer's tokens.

The handler and its key-set provider live in xtr-security-http's oidc extra (joserfc); this factory imports them only when it builds one, so the bundle carries no JOSE dependency until an application configures an OIDC firewall. The bundle registers this factory by default only when that extra is importable. Time comes from the wall clock, the injectable now-function the handler takes.

Record where to collect providers to close on shutdown, if anywhere.

key property

key: str

Name this kind of handler oidc.

config_type property

config_type: type

Build instances of :class:OidcTokenHandlerConfig.

with_closeables

with_closeables(closeables: list[_AsyncCloseable]) -> OidcTokenHandlerFactory

Return a copy that records the providers it builds into closeables.

The bundle owns the list and closes every collected provider on shutdown, so the HTTP client a discovery provider lazily builds does not outlive the kernel.

create

create(services: ServiceConfigurator, builder: ContainerBuilder, service_id: str, config: object) -> ServiceKey

Register the OIDC handler service and return its key.

A discovery-backed handler fetches through an HTTP client registered beside it, qualified <service_id>#http_client, so one override replaces every fetch it makes; a static key set fetches nothing and registers none.

OidcUserInfoTokenHandlerFactory

Bases: TokenHandlerFactoryInterface

Builds a handler that reads the userinfo endpoint with the token.

The handler lives in xtr-security-http's oidc extra, so it is imported only when one is built; the factory itself, and the interface the handler is registered under, carry no JOSE dependency.

key property

key: str

Name this kind of handler oidc_user_info.

config_type property

config_type: type

Build instances of :class:OidcUserInfoTokenHandlerConfig.

create

create(services: ServiceConfigurator, builder: ContainerBuilder, service_id: str, config: object) -> ServiceKey

Register the userinfo handler service and return its key.

The handler writes the failures its server's answers explain to the application's logger when the logging bundle is active.

ServiceTokenHandlerFactory

Bases: TokenHandlerFactoryInterface

Uses an access-token handler the application registered as a service.

key property

key: str

Name this kind of handler id.

config_type property

config_type: type

Build instances of :class:ServiceTokenHandlerConfig.

create

create(services: ServiceConfigurator, builder: ContainerBuilder, service_id: str, config: object) -> ServiceKey

Return the key of the handler service the application registered.

TokenHandlerFactoryInterface

Bases: Protocol

Turns one token-handler configuration into a handler service.

key property

key: str

The name of the kind of handler, unique among token-handler factories.

config_type property

config_type: type

The configuration class instances of which this factory builds.

create

create(services: ServiceConfigurator, builder: ContainerBuilder, service_id: str, config: object) -> ServiceKey

Register the handler service and return its key.

Parameters:

  • services (ServiceConfigurator) –

    Where the handler service is registered.

  • builder (ContainerBuilder) –

    The container builder, for reading other definitions.

  • service_id (str) –

    A name unique to the handler being built, for a qualifier when the same handler type serves several firewalls.

  • config (object) –

    The handler configuration, an instance of :attr:config_type.

Returns:

InvalidConfigurationError

Bases: SecurityError, ValueError

A security configuration value the bundle cannot turn into services.

Derives from :class:~xtr_security_core.exception.SecurityError so one except SecurityError still catches everything the family raises, and from :class:ValueError because a bad configuration is a bad argument. It is raised as the configuration is validated — an unknown provider named by a firewall, a firewall that is not stateless, two authenticators of one key — and as the container is built, when a configured authenticator or token handler has no factory to build it, or an entry point cannot be resolved.

AccessTokenFactory

AccessTokenFactory(token_handler_factories: Mapping[str, TokenHandlerFactoryInterface] | None = None)

Bases: StatelessAuthenticatorFactoryInterface

Builds an :class:~xtr_security_http.AccessTokenAuthenticator from configuration.

The token handler is built through the token-handler factory registry the bundle hands this factory (seam S-2): the configured handler's type selects a token-handler factory, which registers the handler service. The named extractors become the extractor the authenticator reads tokens with, chained when more than one. The authenticator is registered as a factory so it can pull the handler, the extractor and the firewall's user provider from the container. The user provider is optional — a token handler may build the user itself — so the factory is a stateless one.

Record the token-handler factories, keyed by their configuration type.

key property

key: str

Name this kind of authenticator access_token.

priority property

priority: int

Run at the default priority; other authenticators order around it.

config_type property

config_type: type

Build instances of :class:AccessTokenConfig.

with_token_handler_factories

with_token_handler_factories(token_handler_factories: Mapping[str, TokenHandlerFactoryInterface]) -> AccessTokenFactory

Return a copy that resolves token handlers through token_handler_factories.

entry_point_kind

entry_point_kind(config: object) -> str

Answer that the bearer challenge is a fallback, never a first choice.

The authenticator answers an unauthenticated request with a bare 401 — no error detail, per RFC 6750 — so when a firewall runs it beside an authenticator with a real challenge (a form login's redirect), the wiring resolves that one as the entry point.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the token handler, the extractor and the authenticator.

The authenticator is built per request: the firewall's user provider it may hold may be one of the request's services.

AuthenticatorFactoryInterface

Bases: Protocol

Turns one authenticator configuration into authenticator services.

The bundle sorts a firewall's factories by priority (highest first), matches each configured authenticator to the factory whose config_type it is an instance of, and calls :meth:create_authenticator to register the services and collect their keys.

key property

key: str

The name of the kind of authenticator, unique among factories.

priority property

priority: int

Where this factory's authenticators sit in a firewall's order; higher first.

config_type property

config_type: type

The configuration class instances of which this factory builds.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the authenticator services and return their keys.

Parameters:

  • services (ServiceConfigurator) –

    Where the authenticator services are registered.

  • builder (ContainerBuilder) –

    The container builder, for reading other definitions.

  • firewall_name (str) –

    The firewall the authenticators belong to.

  • config (object) –

    The authenticator configuration, an instance of :attr:config_type.

  • user_provider (ServiceKey | None) –

    The key of the firewall's user provider, or None when the firewall names none.

Returns:

FormLoginFactory

Bases: AuthenticatorFactoryInterface

Builds a :class:~xtr_security_http.FormLoginAuthenticator from configuration.

The form is rendered at the configured login path and submitted to the check path; a failed login is stored on the session and redirected back to the page, a successful one answered by the target ladder — the default pair of handlers, or the application's own pair wrapped in the custom pair when the configuration names them. The redirect to the login page is a real entry point: an unauthenticated request is sent there to prove itself.

key property

key: str

Name this kind of authenticator form_login.

priority property

priority: int

Run at the default priority; other authenticators order around it.

config_type property

config_type: type

Build instances of :class:FormLoginConfig.

entry_point_kind

entry_point_kind(config: object) -> str

Answer that the redirect to the login page is a real entry point.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the login's handlers and the authenticator over them.

HttpBasicFactory

Bases: AuthenticatorFactoryInterface

Builds an :class:~xtr_security_http.HttpBasicAuthenticator from configuration.

The browser's own credential prompt is the login: the authenticator reads the Authorization: Basic header the request carries and challenges with the configured realm when it is absent or wrong. It needs the firewall's user provider — the credentials are checked against it — and its challenge is a real entry point.

key property

key: str

Name this kind of authenticator http_basic.

priority property

priority: int

Run at the default priority; other authenticators order around it.

config_type property

config_type: type

Build instances of :class:HttpBasicConfig.

entry_point_kind

entry_point_kind(config: object) -> str

Answer that the basic challenge is a real entry point.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the authenticator over the firewall's user provider.

Built per request: the provider it holds may be one of the request's services.

JsonLoginFactory

Bases: AuthenticatorFactoryInterface

Builds a :class:~xtr_security_http.JsonLoginAuthenticator from configuration.

The document is the request's parsed body, its two members read by the dotted paths the configuration names. The login never challenges: it is no entry point — an unauthenticated request is not answered by it, only a request carrying a document is — so a firewall whose only login is this one resolves its entry point elsewhere, and a firewall that needs authentication must name one.

key property

key: str

Name this kind of authenticator json_login.

priority property

priority: int

Run at the default priority; other authenticators order around it.

config_type property

config_type: type

Build instances of :class:JsonLoginConfig.

entry_point_kind

entry_point_kind(config: object) -> str

Answer that the login never challenges an unauthenticated request.

The landed authenticator is no entry point — it implements no entry point interface and starts nothing — so a request it does not answer is not redirected or challenged by it.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the authenticator over the firewall's provider.

Built per request: the provider it holds may be one of the request's services.

LoginLinkFactory

Bases: AuthenticatorFactoryInterface

Builds a :class:~xtr_security_http.LoginLinkAuthenticator from configuration.

The handler that mints and spends the links is a service of the firewall's own, signing each over the user's covered properties until a lifetime from when it was minted. The secret the link is signed with is the application's to supply: the bundle builds and boots without it, and the handler fails naming it the first time it is asked for. The authenticator itself never challenges: a request that follows no link has nothing to spend, so it is no entry point.

With the lock bundle active, a link's uses are counted under the lock every worker shares.

key property

key: str

Name this kind of authenticator login_link.

priority property

priority: int

Run at the default priority; other authenticators order around it.

config_type property

config_type: type

Build instances of :class:LoginLinkConfig.

entry_point_kind

entry_point_kind(config: object) -> str

Answer that a followed link never answers an unauthenticated request.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the handler, the answer handlers and the authenticator over them.

The handler and the authenticator are built per request: the handler holds the firewall's provider, which may be one of the request's services.

OidcLoginFactory

Bases: AuthenticatorFactoryInterface

Builds the OIDC authorization-code login authenticator from configuration.

The provider is discovered from the configured issuer — its endpoints read off the well-known document — and the client authenticates at its token endpoint by the configured method. The login answers on its check path with the default success and failure handlers — a failure sent to the configured failure path — and a token-refresh listener joins the firewall's chain so a stored login renews its access token. A configured token generator registers under the firewall's own name, where the token-generate command finds it.

The discovery, client, verifier, ID-token reader and refresher live in xtr-security-http's oidc extra (joserfc); this factory imports them only when it builds a login, so the bundle carries no JOSE dependency until an application configures one.

key property

key: str

Name this kind of authenticator oidc_login.

priority property

priority: int

Run at the default priority; other authenticators order around it.

config_type property

config_type: type

Build instances of :class:OidcLoginConfig.

entry_point_kind

entry_point_kind(config: object) -> str

Answer that the login redirect is a real entry point.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the provider services, the login and its refresh listener.

RememberMeFactory

Bases: AuthenticatorFactoryInterface

Builds a :class:~xtr_security_http.RememberMeAuthenticator from configuration.

The handler the authenticator spends cookies through is a service of the firewall's own — signed over the user's covered properties, or persisted as a series the application's token provider keeps — registered under the qualifier the firewall's listeners reach it by. The secret the value is signed with is the application's to supply: the bundle builds and boots without it, and the handler fails naming it the first time it is asked for. The authenticator itself never challenges: a request that presents no cookie has nothing to spend, so it is no entry point.

key property

key: str

Name this kind of authenticator remember_me.

priority property

priority: int

Run behind the authenticators that log a request in.

The cookie this authenticator spends must not preempt one: its supports guard refuses a request whose storage already holds a token, and the session-restoring steps and the logins the request itself brings run first, so a lower priority keeps the remembered login from answering where a fresher one already has.

config_type property

config_type: type

Build instances of :class:RememberMeConfig.

entry_point_kind

entry_point_kind(config: object) -> str

Answer that a remembered login never answers an unauthenticated request.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the handler and the authenticator over the firewall's provider.

RemoteUserFactory

Bases: AuthenticatorFactoryInterface

Builds a :class:~xtr_security_http.RemoteUserAuthenticator from configuration.

The request arrives already authenticated by the server in front of the application, so the authenticator only reads the account that server named; it never challenges, because a request with nothing to read is not a request this kind of proof answers.

key property

key: str

Name this kind of authenticator remote_user.

priority property

priority: int

Run ahead of the interactive logins a pre-authenticated request never reaches.

config_type property

config_type: type

Build instances of :class:RemoteUserConfig.

entry_point_kind

entry_point_kind(config: object) -> str

Answer that a pre-authenticated proof never answers an unauthenticated request.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the authenticator reading the account the server in front named.

X509Factory

Bases: AuthenticatorFactoryInterface

Builds an :class:~xtr_security_http.X509Authenticator from configuration.

The request arrives already authenticated by the client's own certificate, so the authenticator only reads the identifier that certificate named; it never challenges, because a request with nothing to read is not a request this kind of proof answers.

key property

key: str

Name this kind of authenticator x509.

priority property

priority: int

Run ahead of the interactive logins a pre-authenticated request never reaches.

config_type property

config_type: type

Build instances of :class:X509Config.

entry_point_kind

entry_point_kind(config: object) -> str

Answer that a pre-authenticated proof never answers an unauthenticated request.

create_authenticator

create_authenticator(services: ServiceConfigurator, builder: ContainerBuilder, firewall_name: str, config: object, user_provider: ServiceKey | None) -> Sequence[ServiceKey]

Register the authenticator reading the client's own certificate.

FirewallConfig dataclass

FirewallConfig(pattern: str | None = None, host: str | None = None, methods: tuple[str, ...] = (), request_matcher: Callable[[ServerRequestInterface], bool] | None = None, security: bool = True, stateless: bool = True, context_key: str | None = None, session_strategy: str = 'migrate', session_cookie: SessionCookieConfig | None = None, provider: str | None = None, user_checker: type | None = None, entry_point: str | None = None, access_denied_handler: type | None = None, scope_denied_handler: type | None = None, authenticators: tuple[object, ...] = (), required_badges: tuple[type, ...] = tuple(), csrf_route_markers: bool = False, logout: LogoutConfig | None = None, switch_user: SwitchUserConfig | None = None, login_throttling: LoginThrottlingConfig | None = None, re_authentication_entry_point: type | None = None, listeners: tuple[str, ...] = tuple())

How a firewall claims requests, and how it authenticates them.

Attributes:

  • pattern (str | None) –

    A regular expression matched against the request path, or None to leave the claim to the other matchers.

  • host (str | None) –

    A regular expression matched against the request host.

  • methods (tuple[str, ...]) –

    The HTTP methods the firewall claims; every method when empty.

  • request_matcher (Callable[[ServerRequestInterface], bool] | None) –

    A callable deciding the claim against the request message, tried last.

  • security (bool) –

    Whether the firewall authenticates at all; False lets every request it claims through untouched.

  • stateless (bool) –

    Whether the firewall keeps no session. A stateful firewall (stateless=False) restores the token its session carries on every request, through the session storage the application registered as a SessionStorageInterface service.

  • context_key (str | None) –

    The name the firewall's security context is stored under in the session — the part after the _security. prefix — or None for the firewall's own name. Two firewalls sharing one session keep their contexts apart by it.

  • session_strategy (str) –

    What a successful login does to the session it reattached — migrate (the default) rotates its ID keeping its attributes, invalidate empties it, none leaves it alone. Meaningful on a stateful firewall only.

  • session_cookie (SessionCookieConfig | None) –

    The cookie the firewall's session ID travels in — its name, path, domain, Secure, HttpOnly, SameSite and lifetime — or None for the session's default, an xtr_session cookie on / that is HttpOnly and SameSite=Lax and Secure exactly when the request came over https; secure=True pins it. Firewalls sharing a context_key share one session, so they name the same cookie. Meaningful on a stateful firewall only.

  • provider (str | None) –

    The name of the user provider the firewall loads users from, or None to leave it to the authenticator.

  • user_checker (type | None) –

    A user-checker service type run around authentication, or None for the default in-memory checker.

  • entry_point (str | None) –

    The name of the authenticator whose challenge answers an unauthenticated request, or None to resolve it automatically.

  • access_denied_handler (type | None) –

    A handler service type answering a denied, fully-authenticated caller, or None for a plain refusal.

  • scope_denied_handler (type | None) –

    A handler service type answering a caller whose token lacks a scope an access rule asks for — wrapped by the bundle's WWW-Authenticate answer — or None for that answer alone.

  • authenticators (tuple[object, ...]) –

    The authenticator configurations the firewall runs, each an instance a registered factory's config_type matches.

  • required_badges (tuple[type, ...]) –

    Badge types every passport must carry to authenticate.

  • csrf_route_markers (bool) –

    Whether the routes this firewall claims prove themselves with IsCsrfTokenValid markers — wiring the forgery-token manager for them even when no login or logout of the firewall asks for a token. The tokens travel in the session the request reattached, so a stateless firewall declaring them fails the build.

  • logout (LogoutConfig | None) –

    The logout the firewall's requests can ask for, or None when the firewall has none.

  • switch_user (SwitchUserConfig | None) –

    The switch-user block the firewall's callers switch by, or None when the firewall has none.

  • login_throttling (LoginThrottlingConfig | None) –

    How the firewall's logins are counted and refused, or None to let every attempt through uncounted.

  • re_authentication_entry_point (type | None) –

    A service type implementing :class:~xtr_security_http.entry_point.re_authentication_entry_point_interface.ReAuthenticationEntryPointInterface, starting a fresh proof for a caller who is already authenticated — or None for a plain 403 refusal.

  • listeners (tuple[str, ...]) –

    The qualifiers of the firewall's listener chain, each naming a listener aliased under :class:~xtr_security_http.firewall.firewall_listener_interface.FirewallListenerInterface. The bundle parks them on the firewall's context definition, where its sorting pass orders them — by priority, highest first — so the chain the context carries runs in that order.

Raises:

to_matcher

to_matcher() -> RequestMatcherInterface

Return the request matcher this firewall claims requests with.

Composes a path, host, method and callable matcher into a chain; a firewall with no constraints becomes a chain of none, which claims every request — the catch-all a last-registered firewall relies on.

Raises:

LoginThrottlingConfig dataclass

LoginThrottlingConfig(secret: str | None = None, global_limit: int = 5, global_interval: str = '15 minutes', local_limit: int = 5, local_interval: str = '15 minutes')

How a firewall's logins are counted and refused.

Attributes:

  • secret (str | None) –

    The secret the counting keys are derived with — the application's to supply, never generated. Checked where it is used: the bundle builds and boots without it, and the listener fails naming it the first time it is asked for.

  • global_limit (int) –

    How many attempts one client address may make.

  • global_interval (str) –

    How long a window of global_limit attempts lasts — "15 minutes", "1 hour 30 minutes", or any span the rate limiter reads.

  • local_limit (int) –

    How many attempts one account from one address may make.

  • local_interval (str) –

    How long a window of local_limit attempts lasts.

LogoutConfig dataclass

LogoutConfig(path: str = '/logout', target_path: str = '/', enable_csrf: bool | None = None, csrf_parameter: str = '_csrf_token', csrf_token_id: str = 'logout', clear_site_data: Sequence[str] | None = None, cookie_clearing: Mapping[str, ClearedCookie] = _no_cookies(), invalidate_session: bool = True, clear_csrf_tokens: bool = False)

How a firewall's requests log out.

Attributes:

  • path (str) –

    The path a request asks for a logout by.

  • target_path (str) –

    Where an unanswered logout redirects to — the home path by default.

  • enable_csrf (bool | None) –

    Whether a logout request must prove itself with a cross-site request forgery token. A logout acts on the caller's behalf, so None — the default — asks for the proof on a stateful firewall, the one a browser's cookie authenticates, and not on a stateless one, which keeps no session to store a token in.

  • csrf_parameter (str) –

    The name the request carries the forgery token under, in its submitted form or its query string.

  • csrf_token_id (str) –

    The id the forgery token is stored under.

  • clear_site_data (Sequence[str] | None) –

    The directives the Clear-Site-Data header carries on the logout's response — "*" or a subset of the directive names — or None for no header.

  • cookie_clearing (Mapping[str, ClearedCookie]) –

    Each cookie a logout clears, mapped to the attributes it was set with.

  • invalidate_session (bool) –

    Whether the logout invalidates the session the request reattached. Meaningful on a stateful firewall only.

  • clear_csrf_tokens (bool) –

    Whether the logout drops every forgery token the request's session minted.

Raises:

SwitchUserConfig dataclass

SwitchUserConfig(role: str = 'ROLE_ALLOWED_TO_SWITCH', parameter: str = '_switch_user', enable_csrf: bool | None = None, csrf_parameter: str = '_csrf_token', csrf_token_id: str = 'switch_user', path: str | None = None)

How a firewall's callers switch to another user.

Attributes:

  • role (str) –

    The role the right to switch is decided by — the caller's token must hold it, weighed against the target user as the subject, so a target who may not be switched to is never switched to.

  • parameter (str) –

    The name a request carries the user to switch to under.

  • enable_csrf (bool | None) –

    Whether a switch asks for a cross-site request forgery token. None — the default — asks on a stateful firewall, where the session keeps the tokens and a browser's cookie authenticates the switch, and not on a stateless one.

  • csrf_parameter (str) –

    The name a request carries the forgery token under.

  • csrf_token_id (str) –

    The id the forgery token is stored under.

  • path (str | None) –

    The dedicated path a switch is asked at, or None to read the parameter on any page the firewall claims.

ChainUserProviderFactory

Bases: UserProviderFactoryInterface

Builds a :class:~xtr_security_core.ChainUserProvider from provider names.

The chain takes a lazy locator over every provider registered under :class:~xtr_security_core.user.user_provider_interface.UserProviderInterface — the same names the security configuration declares them under — and asks it for the ones it names, in order. Because the locator builds nothing until asked, the chain's own name being one of those keys carries no build cycle, so a chain may name another chain.

The chain is built per request: the locator covers every provider, and one of them being a service of the request makes the locator one too.

key property

key: str

Name this kind of provider chain.

config_type property

config_type: type

Build instances of :class:ChainUserProviderConfig.

create

create(services: ServiceConfigurator, builder: ContainerBuilder, provider_name: str, config: object) -> ServiceKey

Register the factory chaining the providers the configuration names, per request.

InMemoryUserProviderFactory

Bases: UserProviderFactoryInterface

Builds an :class:~xtr_security_core.InMemoryUserProvider from a table of users.

key property

key: str

Name this kind of provider in_memory.

config_type property

config_type: type

Build instances of :class:InMemoryUserProviderConfig.

create

create(services: ServiceConfigurator, builder: ContainerBuilder, provider_name: str, config: object) -> ServiceKey

Register the in-memory provider under provider_name and return its key.

Registered as a factory over the user table, not as a built provider: the table may hold env(...) placeholders — a password hash read from the environment — and the container resolves those in what a factory closes over before calling it. A provider built here would keep the placeholders as the users' values.

A table holding none is checked now, so a malformed user fails the build; one holding a placeholder is checked when the provider is built, against the values the variables hold.

Raises:

  • InvalidArgumentError –

    If a user's fields cannot build a user — a non-boolean enabled, say — and the table holds no placeholder.

ServiceUserProviderFactory

Bases: UserProviderFactoryInterface

Uses a user provider the application registered as a service, by type and qualifier.

key property

key: str

Name this kind of provider service.

config_type property

config_type: type

Build instances of :class:ServiceUserProviderConfig.

create

create(services: ServiceConfigurator, builder: ContainerBuilder, provider_name: str, config: object) -> ServiceKey

Return the key of the service the application already registered.

UserProviderFactoryInterface

Bases: Protocol

Turns one user-provider configuration into a provider service.

key property

key: str

The name of the kind of provider, unique among user-provider factories.

config_type property

config_type: type

The configuration class instances of which this factory builds.

create

create(services: ServiceConfigurator, builder: ContainerBuilder, provider_name: str, config: object) -> ServiceKey

Register the provider service and return its key.

Parameters:

  • services (ServiceConfigurator) –

    Where the provider service is registered.

  • builder (ContainerBuilder) –

    The container builder, for reading other definitions.

  • provider_name (str) –

    The name the provider is registered under, used as a qualifier so a firewall resolves it by name.

  • config (object) –

    The provider configuration, an instance of :attr:config_type.

Returns:

AccessControlConfig dataclass

AccessControlConfig(path: str, attribute: str, host: str | None = None, methods: tuple[str, ...] = (), ips: tuple[str, ...] = (), channel: str | None = None, firewall: str | None = None)

A request pattern and the single attribute a matching request must hold.

Rules are tried in order; the first whose path (and, when set, host, methods and ips) matches decides the request, by asking whether the token holds the one attribute. One attribute per rule is deliberate — a rule that needs two conditions is two rules, or a single closure attribute.

Attributes:

  • path (str) –

    A regular expression matched against the request path.

  • attribute (str) –

    The one attribute a matching request must satisfy — "ROLE_ADMIN", "IS_AUTHENTICATED", "PUBLIC_ACCESS", an OAUTH2_SCOPE(...) string.

  • host (str | None) –

    A regular expression matched against the request host, or None.

  • methods (tuple[str, ...]) –

    The HTTP methods the rule applies to; every method when empty.

  • ips (tuple[str, ...]) –

    Client addresses the rule applies to; every address when empty.

  • channel (str | None) –

    The scheme a matching request must arrive over — "https" or "http" — or None to demand none; the channel listener answers a request arriving over the wrong one with a redirect to the same request over the scheme the rule demands.

  • firewall (str | None) –

    The firewall the rule belongs to, or None for any.

Raises:

  • InvalidArgumentError –

    When attribute is empty, path or host is not a valid regular expression, a methods entry is not an HTTP method token, an ips entry is neither an address nor a CIDR network, or channel names a scheme other than "http" or "https".

to_matcher

to_matcher() -> RequestMatcherInterface

Return the request matcher this configuration describes.

Address entries reach the matcher in the canonical CIDR spelling, the prefix as a count of bits, whichever accepted spelling wrote them.

Raises:

AccessDecisionManagerConfig dataclass

AccessDecisionManagerConfig(strategy: _Strategy = 'affirmative', allow_if_all_abstain: bool = False, allow_if_equal_granted_denied: bool = True)

The strategy that turns the voters' answers into one grant or refusal.

Attributes:

  • strategy (_Strategy) –

    How votes are combined — "affirmative" (any grant wins), "consensus" (the majority wins), "unanimous" (one refusal loses), or "priority" (the first non-abstaining voter decides).

  • allow_if_all_abstain (bool) –

    Whether a decision every voter abstained on is granted.

  • allow_if_equal_granted_denied (bool) –

    Whether a consensus tie is granted.

Raises:

build

build() -> AccessDecisionStrategyInterface

Return the strategy object this configuration describes.

AccessTokenConfig dataclass

AccessTokenConfig(token_handler: TokenHandlerConfig, token_extractors: tuple[ExtractorName, ...] = ('header',), realm: str | None = None, resource_metadata_uri: str | None = None, sender_constraint: str | None = None)

A bearer access-token authenticator, built from a token handler.

The handler validates the token and returns the user; the extractors read the token out of the request, tried in the order named — a chain of more than one, the first extractor's scheme documenting the firewall in OpenAPI.

Attributes:

  • token_handler (TokenHandlerConfig) –

    The token-handler configuration a factory builds.

  • token_extractors (tuple[ExtractorName, ...]) –

    The extractors to read the token by, in order — any of "header", "query", "body".

  • realm (str | None) –

    The protection realm named in the WWW-Authenticate challenge.

  • resource_metadata_uri (str | None) –

    The URI the RFC 9728 resource_metadata document lives at, absolutised against the request when it names a path; None omits the parameter from the challenge.

  • sender_constraint (str | None) –

    The qualifier of a registered :class:~xtr_security_http.SenderConstraintInterface service whose challenge the WWW-Authenticate parameters carry, or None for a plain bearer challenge.

Raises:

FormLoginConfig dataclass

FormLoginConfig(login_path: str, check_path: str = '/login_check', username_parameter: str = '_username', password_parameter: str = '_password', post_only: bool = True, form_only: bool = False, enable_csrf: bool = False, csrf_parameter: str = '_csrf_token', csrf_token_id: str = 'authenticate', success_handler: type | None = None, failure_handler: type | None = None)

A form login: the page a form lives on, and the submission that proves it.

The form is rendered at login_path and submitted to check_path — a POST there, its fields read by the names the form gives them. A form carries a session — the page it renders stores its errors in one, the login it lands in rotates it — so it belongs on a stateful firewall only.

Attributes:

  • login_path (str) –

    The path of the page the form lives on; the entry point redirects an unauthenticated request to it.

  • check_path (str) –

    The path the form is submitted to.

  • username_parameter (str) –

    The field the form carries the username under.

  • password_parameter (str) –

    The field the form carries the password under.

  • post_only (bool) –

    Whether only a POST to the check path is the form's submission.

  • form_only (bool) –

    Whether the submission must also carry a form content type.

  • enable_csrf (bool) –

    Whether the form carries a cross-site request forgery token, checked against the session's stored one.

  • csrf_parameter (str) –

    The field the form carries the forgery token under.

  • csrf_token_id (str) –

    The id the forgery token is stored under.

  • success_handler (type | None) –

    The application's own success-handler service type, answered through the bundle's wrapper — or None for the default redirect by the target ladder.

  • failure_handler (type | None) –

    The application's own failure-handler service type, answered through the bundle's wrapper — or None for the default redirect to the login page, the error stored on the session.

Raises:

HttpBasicConfig dataclass

HttpBasicConfig(realm: str = 'Secured')

An HTTP basic authenticator: the credentials the request itself carries.

The browser's own Authorization: Basic header is the login form — no check path, no session — and its failed challenge is the entry point the browser answers with its credential prompt.

Attributes:

  • realm (str) –

    The protection realm named in the WWW-Authenticate challenge the browser labels its prompt with.

Raises:

JsonLoginConfig dataclass

JsonLoginConfig(check_path: str | None = None, username_path: str = 'username', password_path: str = 'password', success_handler: type | None = None, failure_handler: type | None = None)

A JSON login: a document carrying a username and a password.

The document is the request's parsed body — its two members read by the dotted paths the configuration names — and the login is stateless: the request that carries the document is itself the proof, answered with a plain 401 when it fails and no handler is configured.

Attributes:

  • check_path (str | None) –

    The path the document is submitted to, or None for every request carrying a JSON body.

  • username_path (str) –

    The dotted path of the member carrying the username.

  • password_path (str) –

    The dotted path of the member carrying the password.

  • success_handler (type | None) –

    The application's own success-handler service type, or None to let the request reach its endpoint with the token now set.

  • failure_handler (type | None) –

    The application's own failure-handler service type, or None to answer a failed login with a 401 carrying the error's message.

Raises:

LoginLinkConfig dataclass

LoginLinkConfig(check_path: str, path: str, secret: str | None = None, lifetime: int = 600, check_post_only: bool = False, signature_properties: Sequence[str] = ('password',), success_handler: type | None = None, failure_handler: type | None = None, max_uses: int | None = None)

A login-link authenticator: the signed link a request follows to log in.

Attributes:

  • check_path (str) –

    The literal path a followed link arrives at — required, and refused when empty.

  • path (str) –

    The literal path every minted link leads to — required, and refused when empty.

  • secret (str | None) –

    The secret the link's hash is signed with — the application's to supply, never generated. Checked where it is used: the bundle builds and boots without it, and the handler fails naming it the first time it is asked for.

  • lifetime (int) –

    How many seconds a minted link counts until.

  • check_post_only (bool) –

    Whether only a POST to the check path is a followed link.

  • signature_properties (Sequence[str]) –

    The user properties whose digest the link's hash carries, retiring the link when any of them changes.

  • success_handler (type | None) –

    The application's own success-handler service type, or None for the default redirect by the target ladder.

  • failure_handler (type | None) –

    The application's own failure-handler service type, or None for the default answer of a failed login.

  • max_uses (int | None) –

    How many times one link signs in, counted per link in the application's rate-limiter StorageInterface service for as long as the link lasts; None — the default — leaves a link usable until it expires. 1 makes every link single-use.

Raises:

MakeFirewallsEventDispatcherTraceablePass

Wraps every firewall's dispatcher in a :class:TraceableEventDispatcher when tracing.

Tracing follows the event dispatcher bundle's trace setting — in debug mode unless the application chose — so the firewalls' security events are traced, timed and logged to the "event" channel like every other event. Each trace is reset between units of work.

process

process(builder: ContainerBuilder) -> None

Decorate each firewall's dispatcher with a trace, when tracing is on.

MakeFirewallsManagerListenerTraceablePass

Swaps each firewall's manager listener for a traceable one when tracing.

Tracing follows the event dispatcher bundle's trace setting — in debug mode unless the application chose — the same trigger that traces the firewalls' dispatchers, so a traced firewall's chain explains its authentication: the traceable listener wraps each authenticator the supports pass chose, and the tooling reads what they recorded.

The swap happens on the chain the context parks — the plain listener's qualifier gives way to the traceable one's, the same argument the sorting pass orders — so the plain listener stays registered for the traceable one to wrap, and the chain resolves the wrapper alone.

While the profiler's security panel is registered, each traceable listener reports the authenticators it records to it.

process

process(builder: ContainerBuilder) -> None

Swap each firewall's manager listener for a traceable one, when tracing is on.

OidcBackChannelLogoutConfig dataclass

OidcBackChannelLogoutConfig(enable: bool = True, route: str = '/logout/backchannel', lifetime: int = 3600)

The back-channel logout a provider pushes its logout tokens to.

The provider ends one of its sessions and says so out of band — a logout token posted to a public route of this application, verified against the provider's keys and recorded, so the login it names is refused on the browser's next request. The route is the application's to map: the bundle registers the handler service, and the application serves it at route — the path it configured here, the same path the provider is told to push to.

Attributes:

  • enable (bool) –

    Whether the login takes part in a back-channel logout.

  • route (str) –

    The path the application serves the back-channel route at.

  • lifetime (int) –

    How long an ended session is remembered, in seconds — at least as long as a session of this application can stay idle.

Raises:

OidcEndSessionConfig dataclass

OidcEndSessionConfig(enable: bool = True, post_logout_redirect_path: str | None = None)

The provider's own session ended when the application's logout runs.

A logout of a login this provider issued redirects to the provider's end-session endpoint, so the provider's session of that login ends too — the redirect carrying the ID token as its hint and, when one is configured, the page to come back to.

Attributes:

  • enable (bool) –

    Whether the logout redirects to the provider.

  • post_logout_redirect_path (str | None) –

    The path the provider sends the browser back to after it ended its session, or None for the provider's own default.

Raises:

OidcLoginConfig dataclass

OidcLoginConfig(issuer: str, client_id: str, client_secret: str | None = None, token_endpoint_auth_method: TokenEndpointAuthMethod = 'client_secret_basic', scope: str = 'openid', check_path: str = '/oidc/callback', redirect_uri: str | None = None, failure_path: str | None = None, pkce_enabled: bool = True, pkce_method: str = 'S256', user_data_source: str = 'userinfo', user_identifier_claim: str = 'sub', max_age: int | None = None, authorization_params: Mapping[str, str] = _no_authorization_params(), signature_verifier_algorithms: Sequence[str] | None = None, client_authentication_keyset: str | None = None, certificate_options: Mapping[str, str] | None = None, token_generator: OidcTokenGeneratorConfig | None = None, backchannel_logout: OidcBackChannelLogoutConfig | None = None, end_session: OidcEndSessionConfig | None = None)

An OIDC authorization-code login: the provider redirects, the callback authenticates.

The provider is discovered from the issuer — its endpoints read off the well-known document — and the client authenticates at its token endpoint by token_endpoint_auth_method. The login answers on check_path.

Attributes:

  • issuer (str) –

    The provider's issuer URI, the base its discovery document is read from.

  • client_id (str) –

    The client the provider knows this application by.

  • client_secret (str | None) –

    The client's secret, for the secret-bearing endpoint authentication methods; None for the public and TLS ones.

  • token_endpoint_auth_method (TokenEndpointAuthMethod) –

    How the client authenticates at the provider's token endpoint.

  • scope (str) –

    The scopes asked of the provider, space-separated; openid is always asked beside them.

  • check_path (str) –

    The path the provider redirects the login back to.

  • redirect_uri (str | None) –

    The absolute URL of check_path the provider is sent as the redirect URI — the one registered for the client — or None to anchor check_path at the origin each request reached. Set it when the request does not carry the public origin (behind a proxy terminating TLS) or its Host is not trusted.

  • failure_path (str | None) –

    The path a callback that fails is redirected to — a refusal the provider sent back, or a callback failing the login's checks — or None for the failure handler's default login page, /login. Name a page of the application's own when it signs in with nothing else.

  • pkce_enabled (bool) –

    Whether the login proves its code with a PKCE verifier.

  • pkce_method (str) –

    The PKCE challenge method, "S256" or "plain".

  • user_data_source (str) –

    Where the user is read from — the userinfo endpoint or the ID token's claims.

  • user_identifier_claim (str) –

    The claim naming the user.

  • max_age (int | None) –

    The oldest authentication the login accepts, in seconds, or None for no limit.

  • authorization_params (Mapping[str, str]) –

    Extra query parameters the authorization request carries; the login owns the parameters it manages.

  • signature_verifier_algorithms (Sequence[str] | None) –

    The algorithms the ID token's signature is verified against, or None to read the token without verifying its signature.

  • client_authentication_keyset (str | None) –

    A JWKS document carrying the private key the private_key_jwt method signs its assertion with.

  • certificate_options (Mapping[str, str] | None) –

    The certificate the TLS endpoint authentication methods present — local_cert, local_pk and passphrase — carried on the client.

  • token_generator (OidcTokenGeneratorConfig | None) –

    The tokens the token-generate command mints for this firewall, or None when it mints none.

  • backchannel_logout (OidcBackChannelLogoutConfig | None) –

    The back-channel logout the provider's logout tokens are pushed to, or None when the login takes part in none. Needs a stateful firewall.

  • end_session (OidcEndSessionConfig | None) –

    The provider's own session ended when the application's logout runs, or None for a local logout alone.

Raises:

  • InvalidConfigurationError –

    When the issuer or client is missing, when a secret-bearing method has no secret or a public one does, or when the PKCE method or the user-data source is unknown, the redirect URI is no absolute URL of check_path, or the failure path is not an absolute path.

OidcTokenGeneratorConfig dataclass

OidcTokenGeneratorConfig(algorithms: Sequence[str], keyset: str, audience: str | Sequence[str], issuers: Sequence[str], claim: str = 'sub')

The tokens the token-generate command mints for one firewall.

Attributes:

  • algorithms (Sequence[str]) –

    The signature algorithms a minted token may be signed with.

  • keyset (str) –

    A JWKS document carrying the signing keys.

  • audience (str | Sequence[str]) –

    The audience a minted token names — one or several.

  • issuers (Sequence[str]) –

    The issuers a minted token may be issued by; exactly one when the mint does not name one.

  • claim (str) –

    The claim the user identifier is written to.

Raises:

AutoHasherConfig dataclass

AutoHasherConfig(*, type: Literal['auto'] = 'auto')

The secure default: argon2id, verifying bcrypt and PBKDF2 behind it.

Built into a migrating hasher whose best is argon2id, whose extras are bcrypt (only when that backend is installed) and PBKDF2 — so a fresh password is argon2id and a legacy one still verifies and is upgraded.

NativeHasherConfig dataclass

NativeHasherConfig(*, type: Literal['native'] = 'native', algorithm: Literal['argon2id', 'bcrypt'] = 'argon2id', time_cost: int = 3, memory_cost: int = 65536, parallelism: int = 4, cost: int = 12, migrate_from: tuple[HasherConfig, ...] = ())

An argon2id or bcrypt hasher, optionally migrating older hashes.

migrate_from names hashers whose hashes this one should still verify and upgrade: the config is built into a migrating hasher, best first.

Raises:

  • InvalidArgumentError –

    On an unknown algorithm, a non-positive argon2 cost, or a bcrypt cost outside 4 to 31.

Pbkdf2HasherConfig dataclass

Pbkdf2HasherConfig(*, type: Literal['pbkdf2'] = 'pbkdf2', hash_algorithm: str = 'sha512', encode_as_base64: bool = True, iterations: int = 1000, key_length: int = 40, migrate_from: tuple[HasherConfig, ...] = ())

A PBKDF2 hasher, for verifying hashes stored with a salt of their own.

The defaults match the hashes such schemes typically stored. The hash carries no parameters, so this hasher never asks for a rehash; reach it through another config's migrate_from to upgrade what it verifies.

Raises:

  • InvalidArgumentError –

    On a digest the platform does not provide, or a non-positive iteration count or key length.

PlaintextHasherConfig dataclass

PlaintextHasherConfig(*, type: Literal['plaintext'] = 'plaintext', ignore_case: bool = False)

A hasher that stores the password in the clear — for tests only.

ignore_case compares passwords case-insensitively.

ServiceHasherConfig dataclass

ServiceHasherConfig(*, service: type, type: Literal['service'] = 'service', qualifier: str | None = None)

A hasher the container provides, named by its type and an optional qualifier.

The bundle resolves it from the container; built outside a container it has no service to fetch, so the plain builder refuses it.

Raises:

RemoteUserConfig dataclass

RemoteUserConfig(type: Literal['remote_user'] = 'remote_user', user_key: str = 'REMOTE_USER')

A pre-authenticated authenticator reading the account the server named.

A server that authenticated the request before the application saw it writes the account it identified as into the environment the request arrives with, under one key; this authenticator reads that key and takes its value as the username, proven by the server in front.

Attributes:

  • user_key (str) –

    The environment key the server in front wrote the authenticated account under.

X509Config dataclass

X509Config(type: Literal['x509'] = 'x509', user_key: str = 'SSL_CLIENT_S_DN_Email', credentials_key: str = 'SSL_CLIENT_S_DN', credential_user_identifier: str = 'emailAddress')

A pre-authenticated authenticator reading the client's certificate.

The server the request arrived through verified the client's certificate and wrote its claims into the environment; this authenticator reads the email address out of it, or the whole distinguished name when there is no email, taking the identifier it finds as the username, proven by the certificate's own signature.

Attributes:

  • user_key (str) –

    The environment key the server wrote the verified certificate's email address under.

  • credentials_key (str) –

    The environment key the server wrote the whole distinguished name under.

  • credential_user_identifier (str) –

    The distinguished-name identifier the username is read out of when the email key is absent; emailAddress also answers its dotted OID spelling.

RefuseStatefulFirewallsWithoutSessionStoragePass

Fails the build for a stateful firewall with no session storage registered.

The security bundle registers this after the container's remove-if-missing pass has settled and before the firewall chains are sorted, so the refusal is heard before any chain is ordered.

process

process(builder: ContainerBuilder) -> None

Refuse every stateful firewall whose context listener was dropped.

Raises:

  • InvalidConfigurationError –

    When a stateful firewall's context listener is gone — no SessionStorageInterface service is registered for it to store sessions through.

RegisterGlobalSecurityEventListenersPass

Gives every firewall's dispatcher the main dispatcher's listeners of the security events.

A firewall dispatches its security events on a dispatcher of its own, so that a listener can hear one firewall alone. One declared on the main dispatcher — an application's @as_event_listener on :class:LoginSuccessEvent, the credentials check every firewall shares — hears every firewall's: this pass adds it to each, by priority, after the firewall's own listeners of the same priority.

The security bundle registers it after the event dispatcher bundle's :class:~xtr_event_dispatcher.bundle.RegisterListenersPass, which works out both sets of listeners.

process

process(builder: ContainerBuilder) -> None

Merge the main dispatcher's security listeners into each firewall's.

RememberMeConfig dataclass

RememberMeConfig(handler: RememberMeHandlerName = 'signature', secret: str | None = None, name: str = 'REMEMBERME', lifetime: int = 31536000, path: str = '/', domain: str | None = None, secure: bool | None = None, httponly: bool = True, samesite: str | None = None, always_remember_me: bool = False, remember_me_parameter: str = '_remember_me', signature_properties: Sequence[str] | None = None, token_provider: str | None = None, success_handler: type | None = None, failure_handler: type | None = None)

A remember-me authenticator: the cookie that outlives the session.

Attributes:

  • handler (RememberMeHandlerName) –

    Which handler stages and spends the cookie — "signature" for a value signed over the user's covered properties, or "persistent" for a series of values the application's token provider keeps, detecting theft by a series replaying a value its provider no longer holds.

  • secret (str | None) –

    The secret the cookie's value is signed with — the application's to supply, never generated. Checked where it is used: the bundle builds and boots without it, and the handler fails naming it the first time it is asked for.

  • name (str) –

    The name the cookie travels under.

  • lifetime (int) –

    How many seconds the cookie lives for.

  • path (str) –

    The path the cookie answers on.

  • domain (str | None) –

    The domain the cookie answers on, or None for the request's own host.

  • secure (bool | None) –

    Whether the cookie travels over HTTPS only; None, the default, makes it Secure exactly when the request came over https.

  • httponly (bool) –

    Whether the cookie is hidden from the page's scripts.

  • samesite (str | None) –

    The cross-site policy the cookie carries — "lax", "strict", "none" — or None for the browser's default.

  • always_remember_me (bool) –

    Whether every login is remembered without the request asking.

  • remember_me_parameter (str) –

    The name a request carries its ask under.

  • signature_properties (Sequence[str] | None) –

    The user properties whose digest a persisted value carries, retiring the series when any of them changes; the password alone when None.

  • token_provider (str | None) –

    The qualifier of the application's :class:~xtr_security_core.user.token_provider_interface.TokenProviderInterface service a persistent handler keeps its series in — required by the persistent handler, checked where it is used, never at build.

  • success_handler (type | None) –

    The application's own success-handler service type, or None for the default redirect by the target ladder.

  • failure_handler (type | None) –

    The application's own failure-handler service type, or None for the default redirect to the login page.

Raises:

to_options

to_options() -> dict[str, object]

Return the cookie's shape as the handler's options read it.

SecurityBundle

SecurityBundle()

Bases: Bundle[SecurityConfig]

Configures the xtr security family from one :class:SecurityConfig.

Start with the strategy the configuration has not changed yet.

build

build(builder: ContainerBuilder) -> None

Autoconfigure every application voter, and register the firewall dispatchers' passes.

The firewalls' dispatchers and manager listeners are traced before the decorations resolve, and take the main dispatcher's security listeners once the event dispatcher bundle's RegisterListenersPass has worked both out. The firewalls' listener chains are ordered after every bundle's process hook, so a listener another bundle adds to one is sorted with the rest.

The firewall itself runs as one listener per lifecycle event, loaded here so the scan finds it whatever the application configures.

load_extension

load_extension(config: SecurityConfig, services: ServiceConfigurator, builder: ContainerBuilder) -> None

Register the security services from config.

process

process(builder: ContainerBuilder) -> None

Collect every tagged voter and build the decision manager over them.

Runs after every bundle loaded, so the builder holds every voter — the built-ins and every application voter the autoconfiguration tagged. Each is aliased to :class:~xtr_security_core.authorization.voter.voter_interface.VoterInterface under a qualifier of its own, so the manager gathers them from a Mapping and orders them as collected; the bundle wraps each in a :class:~xtr_security_core.TraceableVoter when tracing is on.

With a console, security:hash-password is handed the configured user classes, the first of which it hashes for by default.

shutdown async

shutdown() -> None

Close every discovery key-set provider's HTTP client built this run.

An OIDC firewall's discovery provider lazily opens an HTTP client; those that opened one are collected here so the client does not outlive the kernel. The sink is emptied in place: the OIDC factories the extension bound hold this very list, so a run after this one records into the same sink and is closed by the next shutdown.

Every provider is closed even when one fails, so one leaking client cannot keep the others open; the sink is cleared whatever happens, and the failures are re-raised together as an :class:ExceptionGroup.

Raises:

SecurityConfig dataclass

SecurityConfig(firewalls: Mapping[str, FirewallConfig] = _no_firewalls(), providers: Mapping[str, UserProviderConfig] = _no_providers(), password_hashers: Mapping[type | str, HasherConfig] = _no_hashers(), role_hierarchy: Mapping[str, Sequence[str]] = _no_role_hierarchy(), access_control: tuple[AccessControlConfig, ...] = (), access_decision_manager: AccessDecisionManagerConfig = AccessDecisionManagerConfig(), http_port: int = 80, https_port: int = 443, expose_security_errors: ExposeSecurityLevel = ExposeSecurityLevel.NONE, trace_votes: bool | None = None, authenticator_factories: tuple[AuthenticatorFactoryInterface, ...] = _default_authenticator_factories(), token_handler_factories: tuple[TokenHandlerFactoryInterface, ...] = _default_token_handler_factories(), user_provider_factories: tuple[UserProviderFactoryInterface, ...] = _default_user_provider_factories())

Everything the security bundle builds from, defaulted to a working nothing.

Attributes:

  • firewalls (Mapping[str, FirewallConfig]) –

    The firewalls, in the order they are matched — first match wins — keyed by name.

  • providers (Mapping[str, UserProviderConfig]) –

    The user providers, keyed by the name firewalls refer to.

  • password_hashers (Mapping[type | str, HasherConfig]) –

    The hasher each user class, "module:Class" string or declared name is hashed by.

  • role_hierarchy (Mapping[str, Sequence[str]]) –

    The roles each role reaches, expanding a token's roles.

  • access_control (tuple[AccessControlConfig, ...]) –

    The access-control rules, tried in order.

  • access_decision_manager (AccessDecisionManagerConfig) –

    How the voters' answers become one decision.

  • http_port (int) –

    The port plain http answers on, spelled out in a channel redirect when it is not 80.

  • https_port (int) –

    The port https answers on, spelled out in a channel redirect when it is not 443.

  • expose_security_errors (ExposeSecurityLevel) –

    How much of an authentication failure reaches the client.

  • trace_votes (bool | None) –

    Whether every vote is announced as an event; None follows the kernel's debug flag.

  • authenticator_factories (tuple[AuthenticatorFactoryInterface, ...]) –

    The factories that build firewalls' authenticators; the built-ins plus any a bundle prepended.

  • token_handler_factories (tuple[TokenHandlerFactoryInterface, ...]) –

    The factories that build access-token handlers.

  • user_provider_factories (tuple[UserProviderFactoryInterface, ...]) –

    The factories that build user providers.

Raises:

  • InvalidConfigurationError –

    When a firewall names a provider that is not declared, when a chain user provider names a provider that is not declared, or when a PBKDF2 hasher is configured as a top-level password_hashers value rather than inside another hasher's migrate_from. A firewall's entry point is checked against its authenticators at build time, where they have been assigned.

SortFirewallListenersPass

Puts each firewall's listener chain in the order it runs.

A firewall's chain is its context definition's listeners argument: the qualifiers of its listeners — each aliased under :class:~xtr_security_http.firewall.firewall_listener_interface.FirewallListenerInterface — in the order they were gathered. This pass sorts every chain by the priority its listeners declare, higher first, keeping the gathering order of listeners that share a priority; then it settles the @FirewallListenerOrder constraints a listener declares against its neighbours, which only reorder listeners that share a priority — a constraint that would need a listener to cross one fails the build, naming the firewall, so a listener cannot displace the chain's ordering by mistake.

A firewall whose context carries no listeners argument is left untouched, so a configuration that gathers no chain builds exactly as before.

The security bundle registers this after every bundle's process hook, so a listener another bundle adds to a chain is ordered with the rest.

process

process(builder: ContainerBuilder) -> None

Sort every firewall's listener chain, in place.

Raises:

  • InvalidConfigurationError –

    When a chain names a qualifier no firewall listener is aliased under, when a listener declares no integer priority of its own, or when the declared constraints cannot be met within their priorities.

Oauth2TokenHandlerConfig dataclass

Oauth2TokenHandlerConfig(introspection_base_uri: str | None = None, credentials: str | tuple[str, str] | None = None, client: type | None = None, audiences: Sequence[str] = _no_audiences(), issuer: str | None = None, claim: str | None = None, allowed_time_drift: int = 0, cache: type | None = None, cache_key_prefix: str = 'oauth2_introspection', cache_ttl: int = 60, signed_response_algorithms: Sequence[str] | None = None, signed_response_keyset: str | None = None, signed_response_enforce: bool = True, signed_response_discovery_cache: type | None = None, signed_response_discovery_cache_key: str | None = None, type: Literal['oauth2'] = 'oauth2')

A handler that introspects a token with its authorization server (RFC 7662).

The introspection endpoint is reached through a scoped client — the application's own HTTP client carrying the endpoint's base URI and this resource server's credentials — or through the client service the application registered instead. A cache service keeps the introspection responses of active tokens for cache_ttl seconds; a signed response (RFC 9701) is verified against signed_response_keyset or against the keys the issuer's metadata publishes, read through the signed_response_discovery_cache service.

Attributes:

  • introspection_base_uri (str | None) –

    The URI the RFC 7662 introspection endpoint answers at, unless client names a service.

  • credentials (str | tuple[str, str] | None) –

    The basic credentials the introspection endpoint asks this resource server for — "client:secret" or the two as a tuple — or None when the endpoint asks for none.

  • client (type | None) –

    The type of a registered :class:~xtr_http_client_contracts.HttpClientInterface service that reaches the introspection endpoint, or None to scope the application's own client.

  • audiences (Sequence[str]) –

    The identifiers of this resource server, one of which the aud of the response must name; empty skips the check.

  • issuer (str | None) –

    The authorization server's identifier, checked against the iss of the response, or None to skip the check.

  • claim (str | None) –

    The claim holding the user identifier, or None to read sub and fall back to username.

  • allowed_time_drift (int) –

    The tolerance, in seconds, on the time claims.

  • cache (type | None) –

    The type of a registered :class:~xtr_cache_contracts.CacheInterface service that keeps the introspection responses of active tokens, or None to introspect on every request.

  • cache_key_prefix (str) –

    The prefix of the keys the cached responses land under.

  • cache_ttl (int) –

    How long a cached response is reused, at most.

  • signed_response_algorithms (Sequence[str] | None) –

    The signature algorithms a signed introspection response (RFC 9701) may use, or None to accept plain introspection responses only.

  • signed_response_keyset (str | None) –

    A JWKS document pinning the verifying keys, or None to read them from the issuer's metadata.

  • signed_response_enforce (bool) –

    Whether a response without a signature is refused.

  • signed_response_discovery_cache (type | None) –

    The type of a registered :class:~xtr_cache_contracts.CacheInterface service the metadata keys are read through, or None when none is pinned.

  • signed_response_discovery_cache_key (str | None) –

    The key the metadata document lands under.

  • type (Literal['oauth2']) –

    The discriminator, always "oauth2".

Raises:

  • InvalidConfigurationError –

    When neither introspection_base_uri nor client is given, when credentials name a service client that carries its own, or when the discovery cache is configured without the issuer its metadata URL is built from.

OidcTokenHandlerConfig dataclass

OidcTokenHandlerConfig(issuers: Sequence[str] = _no_issuers(), audience: str = '', algorithms: Sequence[str] = ('RS256',), claim: str = 'sub', leeway: int = 0, enforce_at_jwt_type: bool = False, keyset: str | None = None, discovery_uri: str | None = None, jwks_uri: str | None = None, allow_insecure_http: bool = False, type: Literal['oidc'] = 'oidc')

A handler that verifies a third-party OIDC issuer's access tokens.

The keys the token is verified against come from exactly one source: a keyset JWKS document pinned in the configuration, a discovery_uri the jwks_uri is read from, or a jwks_uri fetched outright. The issuers and audience are the ones a valid token must carry.

Attributes:

  • issuers (Sequence[str]) –

    The issuers a token's iss must be one of.

  • audience (str) –

    The audience a token's aud must contain.

  • algorithms (Sequence[str]) –

    The signature algorithms allowed, asymmetric only.

  • claim (str) –

    The claim the user identifier is read from.

  • leeway (int) –

    The clock skew, in seconds, allowed on the time claims — 0 to 300.

  • enforce_at_jwt_type (bool) –

    Whether the header's typ must be at+jwt.

  • keyset (str | None) –

    A JWKS document pinning the verifying keys, or None.

  • discovery_uri (str | None) –

    An issuer base URI the jwks_uri is discovered from, or None.

  • jwks_uri (str | None) –

    The URI the JWKS is fetched from, or None.

  • allow_insecure_http (bool) –

    Whether a non-https endpoint is allowed, for a development or test issuer.

  • type (Literal['oidc']) –

    The discriminator, always "oidc".

Raises:

  • InvalidConfigurationError –

    When no issuer is given, or the key source is not exactly one of keyset, discovery_uri or jwks_uri, or leeway is outside 0 to 300 seconds.

OidcUserInfoTokenHandlerConfig dataclass

OidcUserInfoTokenHandlerConfig(userinfo_base_uri: str = '', claim: str = 'sub', discovery_cache: type | None = None, discovery_cache_key: str | None = None, type: Literal['oidc_user_info'] = 'oidc_user_info')

A handler that reads the userinfo endpoint with the token (OIDC Core 5.3).

The endpoint is reached through a scoped client — the application's own HTTP client carrying the endpoint's base URI — or, with a discovery cache configured, read off the issuer's discovery document and re-scoped per request.

Attributes:

  • userinfo_base_uri (str) –

    The URI the userinfo endpoint answers at.

  • claim (str) –

    The claim holding the user identifier.

  • discovery_cache (type | None) –

    The type of a registered :class:~xtr_cache_contracts.CacheInterface service the issuer's discovery document is read through, or None to keep the configured endpoint.

  • discovery_cache_key (str | None) –

    The key the discovery document lands under.

  • type (Literal['oidc_user_info']) –

    The discriminator, always "oidc_user_info".

Raises:

ServiceTokenHandlerConfig dataclass

ServiceTokenHandlerConfig(service: type, qualifier: str | None = None, type: Literal['id'] = 'id')

An access-token handler the container provides, named by type and qualifier.

Attributes:

  • service (type) –

    The handler service's type, resolved from the container.

  • qualifier (str | None) –

    The qualifier that selects between registrations, or None.

  • type (Literal['id']) –

    The discriminator, always "id".

Raises:

ChainUserProviderConfig dataclass

ChainUserProviderConfig(providers: tuple[str, ...] = (), type: Literal['chain'] = 'chain')

Several providers tried in turn, by the names they were registered under.

Attributes:

  • providers (tuple[str, ...]) –

    The names of the providers to chain, in the order tried.

  • type (Literal['chain']) –

    The discriminator, always "chain".

Raises:

InMemoryUserProviderConfig dataclass

InMemoryUserProviderConfig(users: Mapping[str, Mapping[str, object]] = _no_users(), type: Literal['in_memory'] = 'in_memory')

Users declared inline, keyed by identifier.

Each value is a mapping of the user's own fields — password, roles, enabled — the way an :class:~xtr_security_core.InMemoryUser is built.

Attributes:

ServiceUserProviderConfig dataclass

ServiceUserProviderConfig(service: type, qualifier: str | None = None, type: Literal['service'] = 'service')

A user provider the container provides, named by its type and a qualifier.

Attributes:

  • service (type) –

    The provider service's type, resolved from the container.

  • qualifier (str | None) –

    The qualifier that selects between registrations, or None.

  • type (Literal['service']) –

    The discriminator, always "service".

Raises:

add_token_handler_factory

add_token_handler_factory(factory: TokenHandlerFactoryInterface) -> Callable[[object], object]

Return a transform appending factory to the token-handler factories.

add_authenticator_factory

add_authenticator_factory(factory: AuthenticatorFactoryInterface) -> Callable[[object], object]

Return a transform appending factory to the authenticator factories.

Raises:

  • InvalidConfigurationError –

    When the transform runs and a factory with factory's key is already registered — two factories keyed the same would make the kind of authenticator they build ambiguous.

add_user_provider_factory

add_user_provider_factory(factory: UserProviderFactoryInterface) -> Callable[[object], object]

Return a transform appending factory to the user-provider factories.