Skip to content

xtr_security_oauth2_server.bundle

The bundle wiring this package's authorization server into an application.

An application lists :class:OAuth2ServerBundle and writes an :class:OAuth2ServerConfig; everything else here is what that configuration is made of.

OAUTH2_SERVER_CHANNEL module-attribute

OAUTH2_SERVER_CHANNEL: Final = 'oauth2_server'

The logging channel this server writes to.

One line is written on it: an authorization request that arrived with no resource owner authenticated, which a client is never told the cause of.

AuthorizationServerConfig dataclass

AuthorizationServerConfig(private_key: str | None = None, private_key_passphrase: str = '', encryption_key: str | None = None, encryption_key_type: Literal['plain', 'key'] = 'plain', issuer: str | None = None, audience: str | None = None, signature_algorithm: str = 'RS256', additional_public_keys: tuple[str, ...] = (), access_token_ttl: timedelta = DEFAULT_ACCESS_TOKEN_TTL, refresh_token_ttl: timedelta = DEFAULT_REFRESH_TOKEN_TTL, auth_code_ttl: timedelta = DEFAULT_AUTH_CODE_TTL, device_code_ttl: timedelta = DEFAULT_DEVICE_CODE_TTL, enable_client_credentials_grant: bool = True, enable_refresh_token_grant: bool = True, enable_auth_code_grant: bool = True, enable_password_grant: bool = False, enable_implicit_grant: bool = False, enable_device_code_grant: bool = True, require_code_challenge_for_public_clients: bool = True, persist_access_token: bool = True, revoke_refresh_tokens: bool = True, response_type_class: type[ResponseTypeInterface] | None = None, device_code_verification_uri: str = '', enable_device_code_verification_uri_complete_generation: bool = True, device_code_polling_interval: int = 5, enable_device_code_polling_interval_visibility: bool = True, enable_revocation_endpoint: bool = True, enable_introspection_endpoint: bool = False, enable_metadata_endpoint: bool = True)

Everything the server issuing tokens is built from.

Buildable with no arguments, because the bundle has to be declarable before any application configures it — but not usable that way: each of private_key, encryption_key and issuer that is still unset is reported by the first service that cannot be built without it, as an :class:~xtr_security_oauth2_server.exception.InvalidConfigurationError naming the setting. There is no safe default for a signing key, for the key this server's own payloads are sealed with, or for the name every token claims to come from.

Validation here is of shape, never of presence: an issuer that is not an origin, a lifetime that is not positive, a polling interval below zero. Presence is reported where a setting is used, so the bundle still builds and boots without one — and the console still runs to mint what is missing.

An issuer read from the environment (env("OAUTH2_SERVER_ISSUER")) or from a parameter ("%app.issuer%") has no value to check yet. A parameter is resolved before the bundle loads, and an environment variable when the first service needing the issuer is built; that is where it is checked, with the same refusal as one written as it stands.

Attributes:

  • private_key (str | None) –

    The key access tokens are signed with, as PEM text or the path of a file holding it.

  • private_key_passphrase (str) –

    The pass phrase that key is encrypted with, or empty for none.

  • encryption_key (str | None) –

    A password, or the base64url of a key's bytes, that authorization codes and refresh tokens are sealed with.

  • encryption_key_type (Literal['plain', 'key']) –

    Which of the two encryption_key is.

  • issuer (str | None) –

    The origin this server is known by, claimed as iss by every token and published as the discovery document's issuer. An origin and nothing more, because the document lives at a fixed path under it.

  • audience (str | None) –

    Who access tokens are addressed to, or None to address the client each was issued to.

  • signature_algorithm (str) –

    How an access token is signed.

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

    Files of further public keys tokens may also be verified against, so a key can be rotated without a flag day.

  • access_token_ttl (timedelta) –

    How long an issued access token lasts.

  • refresh_token_ttl (timedelta) –

    How long an issued refresh token lasts.

  • auth_code_ttl (timedelta) –

    How long an issued authorization code lasts.

  • device_code_ttl (timedelta) –

    How long an issued device code lasts.

  • enable_client_credentials_grant (bool) –

    Whether a client may authenticate as itself.

  • enable_refresh_token_grant (bool) –

    Whether a refresh token may be redeemed.

  • enable_auth_code_grant (bool) –

    Whether the browser redirect flow runs.

  • enable_password_grant (bool) –

    Whether a resource owner's own credentials are accepted. Off: the flow is withdrawn from the protocol, and it hands the password of a person to a client.

  • enable_implicit_grant (bool) –

    Whether a token is handed straight to the browser. Off, for the same reason.

  • enable_device_code_grant (bool) –

    Whether a device with no browser may poll for a token.

  • require_code_challenge_for_public_clients (bool) –

    Whether a client holding no secret must prove possession of a code verifier.

  • persist_access_token (bool) –

    Whether each issued access token is written down, which is what makes withdrawing one before it expires possible.

  • revoke_refresh_tokens (bool) –

    Whether redeeming a refresh token withdraws it.

  • response_type_class (type[ResponseTypeInterface] | None) –

    The response type the token endpoint answers with, or None for the bearer document nearly every deployment hands out.

  • device_code_verification_uri (str) –

    Where a person is told to go to type the user code. Required when the device flow runs: the answer to a device names it, and a device shows it on a screen.

  • enable_device_code_verification_uri_complete_generation (bool) –

    Whether the answer also carries the verification URI with the code already in it.

  • device_code_polling_interval (int) –

    How many seconds a device must wait between polls.

  • enable_device_code_polling_interval_visibility (bool) –

    Whether that interval is told to the device.

  • enable_revocation_endpoint (bool) –

    Whether a client may ask for a token to be withdrawn.

  • enable_introspection_endpoint (bool) –

    Whether a client may ask what this server says about a token. Off by default: it answers questions about tokens issued to other clients, so a deployment turns it on deliberately.

  • enable_metadata_endpoint (bool) –

    Whether this server describes itself.

ClientConfig dataclass

ClientConfig(classname: type[AbstractClient] = Client)

The client class this deployment registers its clients as.

The shipped :class:~xtr_security_oauth2_server.model.client.Client is enough for a deployment that needs nothing of its own. One that needs columns beside the registration — an owning organisation, a contact — names its own class here, maps it itself, and the token tables point at its table instead.

Attributes:

  • classname (type[AbstractClient]) –

    The class registered clients are, which must carry :class:~xtr_security_oauth2_server.model.abstract_client.AbstractClient's registration.

EncryptionKeyPass

Bases: CompilerPassInterface

Reads the encryption key's final value, and hands it to the servers that use it.

An authorization code and a refresh token are this server's own payloads handed to a client and read back later, so they are sealed rather than stored — and both the server that issues them and the server that answers about them have to seal and read with the same key.

The value could have been baked into those definitions while services were being defined, and it would resolve. This exists because an application may override the two parameters after this bundle has had its say, and then the value baked in would be the one nobody chose. A pass runs once every bundle has finished, so what it reads is final — which also makes it the one place worth validating the kind of key, instead of discovering it is unreadable the first time a client redeems a code.

The key itself is never derived here. Stretching a password costs real time on purpose, so it is done once where each server is built, not at build time and not per request.

process

process(builder: ContainerBuilder) -> None

Give each server the encryption key and the kind of key it is.

Raises:

GrantTypePass

Bases: CompilerPassInterface

Hands the authorization server every grant that was tagged, in order.

A grant is a flow, and which flows a deployment runs is the whole of what makes one authorization server different from another. The shipped grants are tagged by the bundle, already carrying the lifetime their tokens last; one an application or an add-on registers is tagged automatically for being a grant at all. Either way it arrives here.

The container holds no method calls and a definition's arguments hold values rather than references, so a grant cannot simply be handed to the server as it is built. Instead each tagged grant is aliased under the grant interface with a qualifier of its own, and the server is given the ordered list of those qualifiers with the lifetime each issues for — which its factory replays, enabling one grant after another in exactly this order.

The description endpoint is given the same qualifiers, so the flows it names are read off the grants the server runs — one an add-on or the application registered among them — rather than off the settings that turn the shipped ones on.

A deployment with no grant at all is refused rather than left with a server that answers unsupported_grant_type to everything: an authorization server that can issue nothing is a deployment mistake, not a configuration.

process

process(builder: ContainerBuilder) -> None

Alias every tagged grant, and give the server and its description their order.

Raises:

MetadataPass

Bases: CompilerPassInterface

Hands the description endpoint every contributor, highest priority first.

An extension that adds a capability has to say so where a client looks, and what it adds is not this package's to know. So each contributor is a service of its own, tagged, and this gathers them.

The same shape as the grants: a tagged contributor is aliased under the contributor interface with a qualifier of its own, and the endpoint is given the ordered list of those qualifiers, which it resolves in that order. Ordering matters only when two contributors publish the same field — then the one with the higher priority wins, and a deployment can say which.

The bundle always tags one contributor that adds nothing, so this collection is never empty: nothing can be injected as an empty collection, and the ordinary deployment has no extension at all.

process

process(builder: ContainerBuilder) -> None

Alias every tagged contributor and give the endpoint the order to read them in.

Raises:

OAuth2AuthenticatorConfig dataclass

OAuth2AuthenticatorConfig()

Put this deployment's access tokens in front of a firewall's routes.

It carries nothing. Everything the authenticator needs is already a decision of the server rather than of one firewall — which keys read a token, which issuer it must claim, what prefix its scopes become roles under — so there is nothing left for a firewall to say but that it accepts these tokens:

FirewallConfig(pattern=r"^/api", authenticators=(OAuth2AuthenticatorConfig(),))

One authenticator is built per firewall even so, because it is handed that firewall's own user provider: the same token names a different user on an API reading its staff from one store and its customers from another.

OAuth2ServerBundle

OAuth2ServerBundle()

Bases: Bundle[OAuth2ServerConfig]

Turns an :class:OAuth2ServerConfig into a working authorization server.

Listing this bundle brings the security family, the clock, the event dispatcher and the HTTP kernel along: tokens are stamped against the clock, every decision point is announced on the dispatcher, the endpoints are served through the kernel's messages, and the firewall key oauth2 is opened on the security configuration.

It builds and boots with no configuration at all, so a fresh application still runs its console and can mint the key and register the clients it is missing. Nothing is read while it builds: an authorization server signs with a key only the deployment holds, says who it is in every token, knows a vocabulary of scopes and reads its clients from a store somebody chose, and each of those is reported by the service that cannot be built without it — an :class:~xtr_security_oauth2_server.exception.InvalidConfigurationError naming the setting and the file it belongs in. Nothing is ever minted on the application's behalf.

What each half of a deployment is made of lives beside this: the stores in _persistence_wiring, the protocol engine in _service_wiring, the endpoints in _endpoint_wiring, and — only where a console is — the commands in _command_wiring.

Hold the persistence wiring, which spans three of the hooks below.

build

build(builder: ContainerBuilder) -> None

Register the passes, and tag every class that is nominally a grant.

prepend_extension

prepend_extension(builder: ContainerBuilder) -> None

Open the firewall key oauth2, and declare this server's logging channel.

load_extension

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

Register everything this deployment's authorization server is made of.

Nothing here reads a key, an issuer or a store. Every setting only the deployment can supply is read where it is used, so this registers a working server and an undescribed one alike.

process

process(builder: ContainerBuilder) -> None

Hand the commands their settings, and refuse a persistence nothing can serve.

Raises:

  • InvalidConfigurationError –

    When this deployment keeps its clients and credentials in a database and the ORM bundle is not active, so nothing would build the connection they live on; or when it named its own stores and one of them is not a registered service.

OAuth2ServerConfig dataclass

OAuth2ServerConfig(authorization_server: AuthorizationServerConfig = AuthorizationServerConfig(), resource_server: ResourceServerConfig = ResourceServerConfig(), scopes: ScopesConfig = ScopesConfig(), persistence: OrmPersistenceConfig | InMemoryPersistenceConfig | CustomPersistenceConfig | None = None, client: ClientConfig = ClientConfig(), role_prefix: str = DEFAULT_ROLE_PREFIX)

Everything this deployment's authorization server is.

Buildable with no arguments, because the bundle must be declarable before an application has written a line of configuration — and the console must keep running on a fresh application, so that the key and the clients it is missing can be minted. It is not usable that way: each setting still missing is reported where it is first needed, by the service that cannot be built without it, as an :class:~xtr_security_oauth2_server.exception.InvalidConfigurationError naming the setting and the file to write it in — never by the build, which would take the console down with it.

persistence is the one choice with no default at all. The three variants are a real decision — a database, this process's memory, or the application's own store — and each registers different services, so guessing one would silently give a deployment a server that forgets every token it issued when the process ends.

Attributes:

CustomPersistenceConfig dataclass

CustomPersistenceConfig(access_token_manager: type[AccessTokenManagerInterface], authorization_code_manager: type[AuthorizationCodeManagerInterface], client_manager: type[ClientManagerInterface], refresh_token_manager: type[RefreshTokenManagerInterface], device_code_manager: type[DeviceCodeManagerInterface], credentials_revoker: type[CredentialsRevokerInterface])

Clients and credentials wherever the application already keeps them.

The bundle registers no store of its own: it aliases each manager interface to the service named here, so an application that already has a client table, or keeps its credentials in something that is not a relational database, answers for all six and the rest of the package is unchanged.

All six are required. Five of them are halves of one store, and the sixth is what withdraws everything issued to a client at once; a deployment answering for some of them and leaving the bundle to answer for the others would have two stores disagreeing about the same token.

Attributes:

  • access_token_manager (type[AccessTokenManagerInterface]) –

    Where issued access tokens are kept.

  • authorization_code_manager (type[AuthorizationCodeManagerInterface]) –

    Where issued authorization codes are kept.

  • client_manager (type[ClientManagerInterface]) –

    Where registered clients are kept.

  • refresh_token_manager (type[RefreshTokenManagerInterface]) –

    Where issued refresh tokens are kept.

  • device_code_manager (type[DeviceCodeManagerInterface]) –

    Where issued device codes are kept.

  • credentials_revoker (type[CredentialsRevokerInterface]) –

    What withdraws everything issued to one client, or to one resource owner.

InMemoryPersistenceConfig dataclass

InMemoryPersistenceConfig()

Clients and credentials in this process, forgotten when it ends.

For tests, and for a demonstration a deployment runs once. Nothing is written down, so every client has to be registered again at each start — and the refresh-token manager's withdrawal is only atomic within one process, which is why a deployment serving more than one does not use this.

OrmPersistenceConfig dataclass

OrmPersistenceConfig(connection: str = 'default', table_prefix: str = 'oauth2_')

Clients and credentials in a database, through the ORM integration.

The package ships the mapping, not the revisions: the tables join the definitions of the named connection while the container is compiled, and the application writes its own revision with orm:migrations:diff.

Attributes:

  • connection (str) –

    The name of the connection the tables belong to and the managers read and write through.

  • table_prefix (str) –

    What every table of this package is named under, so its tables cannot collide with an application's own.

ResourceServerConfig dataclass

ResourceServerConfig(public_key: str | None = None, jwt_leeway: timedelta | None = None)

How an API reading this server's tokens verifies them.

Both settings are optional, and the common deployment sets neither: one process issues the tokens and reads them, so the verifying key is the public half of the signing key and there is no clock to disagree with.

Attributes:

  • public_key (str | None) –

    The key access tokens are verified against, as PEM text or the path of a file holding it, or None to derive it from the signing key. A resource server running apart from the authorization server is the case for setting it: it holds the public half and never the private one.

  • jwt_leeway (timedelta | None) –

    How far the expiry and not-before windows are widened for clocks that disagree, or None for not at all. Every second of leeway is a second a withdrawn-by-expiry token keeps working, so the default is none.

ScopesConfig dataclass

ScopesConfig(available: tuple[str, ...] = (), default: tuple[str, ...] = ())

The scopes a deployment knows, and the ones a client registered with none is given.

available is the whole vocabulary: a request naming anything else is refused, which is what stops a client inventing permissions. The bundle reports an empty available as a missing setting, because a server that knows no scope can grant none.

default is what a client registered naming no scope is given when it is saved. A request naming no scope is granted the scopes its client is registered for — never default itself — so a client that was given the defaults is issued them when it asks for none.

default may be empty, and that is a real choice rather than an oversight: a client registered with no scopes then stays scope-less, the unchanged rule that such a client may ask for any scope applies to it, and a request naming no scope yields a token carrying none.

Attributes:

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

    Every scope a client may ask for.

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

    The scopes a client registered with none is given.