Core assíncrono

Configuração

class govbr_auth.core.GovBrSettings(*, environment: ProviderEnvironment = ProviderEnvironment.PRODUCTION, authorization_url: AnyHttpUrl, token_url: AnyHttpUrl, userinfo_url: AnyHttpUrl, client_id: str, client_secret: SecretStr, redirect_uri: AnyHttpUrl, scope: str = 'openid profile email', transaction_secret: SecretStr, issuer: AnyHttpUrl, jwks_url: AnyHttpUrl, logout_url: AnyHttpUrl | None = None, post_logout_redirect_uri: AnyHttpUrl | None = None, connect_timeout_seconds: Annotated[float, Gt(gt=0)] = 5.0, read_timeout_seconds: Annotated[float, Gt(gt=0)] = 10.0, clock_skew_seconds: Annotated[int, Ge(ge=0)] = 60)[source]

Bases: BaseModel

Validate immutable configuration for a Gov.br OAuth provider.

model_config = {'extra': 'forbid', 'frozen': True, 'hide_input_in_errors': True, 'str_strip_whitespace': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

environment: ProviderEnvironment
authorization_url: AnyHttpUrl
token_url: AnyHttpUrl
userinfo_url: AnyHttpUrl
client_id: str
client_secret: SecretStr
redirect_uri: AnyHttpUrl
scope: str
transaction_secret: SecretStr
issuer: AnyHttpUrl
jwks_url: AnyHttpUrl
logout_url: AnyHttpUrl | None
post_logout_redirect_uri: AnyHttpUrl | None
connect_timeout_seconds: Annotated[float, Gt(gt=0)]
read_timeout_seconds: Annotated[float, Gt(gt=0)]
clock_skew_seconds: Annotated[int, Ge(ge=0)]
classmethod validate_nonempty_text(value: str) → str[source]

Reject empty values needed to create a valid OAuth request.

classmethod validate_nonempty_secret(value: SecretStr) → SecretStr[source]

Reject whitespace-only credentials without exposing their contents.

validate_url_schemes() → GovBrSettings[source]

Require HTTPS except for loopback-only configuration.

validate_logout_configuration() → GovBrSettings[source]

Require a complete, paired logout configuration.

validate_official_provider_environment() → GovBrSettings[source]

Reject official Gov.br endpoints from another deployment.

class govbr_auth.core.ProviderEnvironment(*values)[source]

Bases: StrEnum

Identify the Gov.br provider deployment used by the application.

PRODUCTION = 'production'
STAGING = 'staging'
LOCAL = 'local'

Cliente e autorização

class govbr_auth.core.GovBrClient(settings: GovBrSettings, transactions: TransactionCodec, validator: IdTokenValidator, http: AsyncClient)[source]

Bases: object

Coordinate authorization, token exchange, validation, and userinfo I/O.

__init__(settings: GovBrSettings, transactions: TransactionCodec, validator: IdTokenValidator, http: AsyncClient) → None[source]

Store validated configuration and injected collaborators.

property settings: GovBrSettings

Expose immutable configuration to framework boundary policies.

authorization_url(*, now: datetime) → AuthorizationRequest[source]

Create an authorization request bound to a protected transaction.

validate_state(state: str, *, now: datetime) → None[source]

Validate a callback state without exchanging an authorization code.

logout_url() → str[source]

Build the configured provider logout URL.

async exchange_code(*, code: str, state: str, now: datetime) → AuthenticationResult[source]

Exchange a one-time authorization transaction for validated tokens.

async userinfo(access_token: SecretStr, *, expected_subject: str) → GovBrUser[source]

Fetch user information bound to the validated ID-token subject.

class govbr_auth.core.AuthorizationBuilder(settings: GovBrSettings, transactions: TransactionCodec)[source]

Bases: object

Build Gov.br OAuth authorization requests bound to protected transactions.

__init__(settings: GovBrSettings, transactions: TransactionCodec) → None[source]

Store the validated provider configuration and transaction collaborator.

build(*, now: datetime) → AuthorizationRequest[source]

Create a transaction and encode its nonce and PKCE challenge in the redirect URL.

build_logout() → str[source]

Build the provider logout URL from the configured fixed return URI.

AuthorizationBuilder.build_logout() constrói o redirecionamento de logout usando exclusivamente post_logout_redirect_uri configurado.

class govbr_auth.core.AuthenticationResult(tokens: TokenSet, id_token_claims: Mapping[str, object])[source]

Bases: object

Return validated tokens and a shallowly immutable ID-claim mapping.

The top-level mapping cannot be changed. Nested values retain the mutability provided by the token decoder.

tokens: TokenSet
id_token_claims: Mapping[str, object]
__init__(tokens: TokenSet, id_token_claims: Mapping[str, object]) → None

Transações e validação

class govbr_auth.core.EncryptedTransactionCodec(secret: SecretStr, ttl: timedelta = datetime.timedelta(seconds=300))[source]

Bases: object

Protect OAuth transactions without retaining process-local state.

__init__(secret: SecretStr, ttl: timedelta = datetime.timedelta(seconds=300)) → None[source]
issue(*, now: datetime) → tuple[str, AuthTransaction][source]

Create and protect a new OAuth transaction.

decode(state: str, *, now: datetime) → AuthTransaction[source]

Authenticate and decode an OAuth transaction.

class govbr_auth.core.TransactionCodec(*args, **kwargs)[source]

Bases: Protocol

Define stateless OAuth transaction protection operations.

issue(*, now: datetime) → tuple[str, AuthTransaction][source]

Create and protect a new OAuth transaction.

decode(state: str, *, now: datetime) → AuthTransaction[source]

Authenticate and decode an OAuth transaction.

__init__(*args, **kwargs)
class govbr_auth.core.IdTokenValidator(*, settings: GovBrSettings)[source]

Bases: object

Validate signed ID tokens against configured identity and JWKS data.

__init__(*, settings: GovBrSettings) → None[source]
validate(id_token: SecretStr, expected_nonce: SecretStr, *, jwks: Mapping[str, object], now: datetime) → Mapping[str, object][source]

Return verified claims or raise a stable domain error.

Parameters:
  • id_token – Compact JWT received from the token endpoint.

  • expected_nonce – Nonce bound to the originating authorization transaction.

  • jwks – Provider JSON Web Key Set used for this validation call.

  • now – Trusted current time used for deterministic temporal validation.

Returns:

The verified ID token claims.

Raises:
  • InvalidIdTokenError – If any cryptographic or claim validation fails.

  • ValueError – If now does not carry explicit timezone information.

Modelos

class govbr_auth.core.AuthTransaction(*, transaction_id: str, code_verifier: SecretStr, nonce: SecretStr, issued_at: datetime, expires_at: datetime)[source]

Bases: BaseModel

Store the short-lived values created for one OAuth authorization flow.

model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

transaction_id: str
code_verifier: SecretStr
nonce: SecretStr
issued_at: datetime
expires_at: datetime
classmethod validate_transaction_id(value: str) → str[source]

Reject blank identifiers that cannot safely bind an OAuth transaction.

classmethod validate_code_verifier(value: SecretStr) → SecretStr[source]

Require the ASCII unreserved verifier syntax defined by RFC 7636.

classmethod validate_nonce(value: SecretStr) → SecretStr[source]

Reject blank nonce secrets without exposing their contents.

classmethod validate_timezone_aware_datetime(value: datetime) → datetime[source]

Reject transaction timestamps that do not carry an explicit timezone.

validate_expiration() → AuthTransaction[source]

Reject transactions whose expiration does not follow their issuance.

class govbr_auth.core.GovBrUser(*, sub: str, name: str | None = None, social_name: str | None = None, given_name: str | None = None, family_name: str | None = None, middle_name: str | None = None, nickname: str | None = None, preferred_username: str | None = None, profile: str | None = None, picture: str | None = None, website: str | None = None, email: str | None = None, email_verified: bool | None = None, gender: str | None = None, birthdate: str | None = None, zoneinfo: str | None = None, locale: str | None = None, phone_number: str | None = None, phone_number_verified: bool | None = None, address: GovBrAddress | None = None, updated_at: int | None = None)[source]

Bases: BaseModel

Represent the standard OpenID Connect claims exposed for a Gov.br user.

model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

sub: str
name: str | None
social_name: str | None
given_name: str | None
family_name: str | None
middle_name: str | None
nickname: str | None
preferred_username: str | None
profile: str | None
picture: str | None
website: str | None
email: str | None
email_verified: bool | None
gender: str | None
birthdate: str | None
zoneinfo: str | None
locale: str | None
phone_number: str | None
phone_number_verified: bool | None
address: GovBrAddress | None
updated_at: int | None
classmethod validate_subject(value: str) → str[source]

Reject blank OpenID Connect subject identifiers.

property subject: str

Return the stable subject while preserving sub on the wire.

class govbr_auth.core.TokenSet(*, access_token: SecretStr, id_token: SecretStr, token_type: Literal['Bearer'], expires_in: Annotated[int, Gt(gt=0)], scope: str)[source]

Bases: BaseModel

Store the OAuth tokens returned by a successful authorization flow.

model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

access_token: SecretStr
id_token: SecretStr
token_type: Literal['Bearer']
expires_in: Annotated[int, Gt(gt=0)]
scope: str
classmethod validate_tokens(value: SecretStr) → SecretStr[source]

Reject blank OAuth tokens without exposing their contents.

classmethod validate_scope(value: str) → str[source]

Reject blank scope values that cannot represent an OAuth request.

Erros públicos

class govbr_auth.core.GovBrAuthError[source]

Bases: Exception

Represent a Gov.br authentication failure with a stable error code.

code: str = 'govbr_auth_error'
class govbr_auth.core.InvalidStateError[source]

Bases: GovBrAuthError

Represent a rejected OAuth state value.

code: str = 'invalid_state'
class govbr_auth.core.InvalidIdTokenError[source]

Bases: GovBrAuthError

Represent a rejected OpenID Connect ID token.

code: str = 'invalid_id_token'