CHANGELOG
=========

Version 0.8.0 (2026-11-20)
---------------------------

Attribute-based access control (ABAC) on top of the scoped permissions of 0.7. Everything is opt-in:
``Authz.build(...)`` without ``abac=`` behaves exactly as in 0.7.x. Plan and decisions:
``documentation/PLAN-abac.md``; quality report: ``documentation/QUALITY-REPORT-0.8.0.md``.

Upgrade notes
~~~~~~~~~~~~~

- Nothing to do unless you configure ``abac=``. To store policies and attributes in SQL, run the Alembic
  revision ``b7d2e5f1c3a8`` (``alembic upgrade head``): it only adds the ``authz_policy`` and
  ``authz_attribute`` tables.
- ``Authorizer.authorize/check`` take optional keyword-only ``resource`` and ``request``;
  ``AuthzContext`` and ``DecisionEvent`` gained fields with defaults. ``PermissionCatalog`` accepts an
  optional ``attributes`` declaration; catalogs without it load unchanged.
- ``MetricsCollector.record_authz_decision`` takes an optional ``source``; its output is unchanged
  unless policies are involved.

Added
~~~~~

- ``auth_middleware.authz.abac``: policies (``deny`` / ``require`` / ``permit``) as JSON/TOML data with
  a closed, three-valued condition language (no ``eval``, no regular expressions), validated against the
  catalog and an attribute schema when written; ``restrict`` mode (policies only narrow what roles grant)
  and an **experimental** ``grant`` mode.
- Attributes of the subject (token, assignment, persisted), the resource (the route's loader or persisted)
  and the environment (time, request, allow-listed headers and claims); lazy and loaded at most once per
  decision.
- ``require_permission(..., resource=...)``, ``has_permission(..., resource=...)``,
  ``ResourceFromPath`` / ``ResourceFromQuery`` / ``ResourceFromCallable``, ``permission_extra(..., abac=True)``
  (``x-abac``), ``Authorizer.explain``.
- Stores: in-memory, ``SqlPolicyStore`` / ``SqlAttributeStore`` (PostgreSQL, MySQL, SQLite) and
  ``DynamoDbPolicyStore`` / ``DynamoDbAttributeStore`` (no index), with a public contract suite
  (``auth_middleware.authz.testing``).
- ``PolicyService`` (validated, serialised writes), ``StaticPolicySource`` (TOML/JSON files),
  ``CompositePolicySource`` and ``CachingPolicySource`` (5 s default; other processes see a change only
  after the TTL).
- ``authcli authz policy add|replace|list|show|enable|disable|validate|test`` (``validate`` and ``test`` work
  offline).
- Shadow mode (``enforce = false``), ``hide`` (a denial answers 404), audit fields (``policy_ids``,
  ``shadow_policy_ids``, ``abac_reason``: ids only, never values) and per-policy metrics capped at 100 ids.

Security
~~~~~~~~

- Fail closed everywhere: an unreachable or garbage policy source, a failing attribute provider or loader
  and a poisoned cache entry answer 503, never 200; a missing attribute applies a ``deny``; a stored policy
  that cannot be decoded behaves as a ``deny``; a mismatch of operand types (including a bool against a
  number) is indeterminate.
- Static policies that read a header or a claim nobody allow-listed are rejected at build (the attribute
  would always be absent and a ``deny`` on it would deny everything).

Tooling and tests
~~~~~~~~~~~~~~~~~

- ``make mutation`` (``mutmut``) runs mutation testing on the access-decision code, with a score per module
  and a 90 % floor (``make mutation-report`` lists survivors). The first pass raised the mutation score of
  the ABAC condition language, validation, decision point and cache to 93-100 % by adding boundary,
  exact-message and ``explain`` tests. Results: ``documentation/QUALITY-REPORT-0.8.0.md``.
- ``make bump-version`` rewrites only the ``version`` line of ``[project]`` (it used to replace every
  occurrence of the old number in ``pyproject.toml``, including dependency pins).
- ``make test-floci`` now runs every ``floci`` test under ``tests/authz/integration``; the coverage badge
  of the README is up to date (96 %).

Documentation
~~~~~~~~~~~~~

- New guide "Attribute-Based Access Control" with a cookbook that the test suite validates
  (``examples/abac_policies.toml``, ``examples/abac_example.py``); catalog reference updated.

Version 0.7.1 (2026-11-20)
---------------------------

License change only: no code differs from 0.7.0.

Upgrade notes
~~~~~~~~~~~~~

- The project is now licensed under the **Mozilla Public License 2.0** (MPL-2.0) instead of the MIT
  License. Releases up to and including 0.7.0 remain available under MIT (a published release cannot be
  relicensed retroactively).
- Using the library from closed-source or commercial applications is unchanged: your own code is not
  affected. Only modifications of the library's own files, when distributed, must be published under
  MPL-2.0.

Packaging
~~~~~~~~~

- ``LICENSE`` is the MPL-2.0 text and a new ``NOTICE`` names the copyright holder; ``pyproject.toml``
  declares ``license = "MPL-2.0"`` (SPDX) and ships both files in the distributions.

Version 0.7.0 (2026-11-14)
---------------------------

Scoped permissions (``auth_middleware.authz``), new authentication options and a security review of the whole library.
Everything new is opt-in, **except the behaviour changes listed under "Upgrade notes"**: read them before upgrading
from 0.6.x. Details of the review: ``documentation/QUALITY-REPORT-0.7.0.md``.

Upgrade notes
~~~~~~~~~~~~~

Changes that can affect an existing application, and what to do:

- **``OidcProvider`` requires an audience.** ``OidcProviderSettings.require_audience`` is ``True`` by default: a provider
  built without ``audience`` raises ``ValueError``. Set ``audience`` (recommended) or ``require_audience=False`` (a warning
  is logged). Warnings are also logged when ``accepted_token_types`` is unset (ID tokens are accepted as bearer
  credentials) and when ``jwt_token_verification_disabled`` is on.
- **Group/role/permission guards fail closed** when a provider returns ``None`` (they used to let the request through).
- **Basic auth answers ``401``** for a wrong password (it used to be ``403``), for an unknown user and for a malformed header
  (it used to be ``500``).
- **Identity-provider outages answer ``503`` + ``Retry-After``** instead of ``401`` (new ``IdentityProviderUnavailableException``,
  a subclass of ``InvalidTokenException``). A signed token that cannot become a user (no ``sub``, over-long or malformed
  claims) answers ``401`` instead of ``500``.
- **Cognito ``scope`` mapping is explicit.** ``CognitoGroupsProvider`` / ``CognitoGroupsAsRolesProvider`` no longer turn a
  single ``scope`` such as ``other-api/admin`` into ``admin``. For machine tokens pass ``resource_server="..."`` (only that
  server's scopes map) or an exact ``scope_map={...}``.
- ``CognitoAuthService.forgot_password`` / ``reset_password`` no longer reveal whether a username exists.
- **``svix-ksuid`` moved from the core dependencies to the SQL extras** (``postgres``, ``mysql``, ``sqlalchemy``): code that
  imports ``ksuid`` directly needs one of them or its own dependency.
- ``configure_logger``: loguru ``diagnose`` (local variables in tracebacks, i.e. tokens and passwords) is off unless
  ``LOG_DIAGNOSE`` is set.
- ``AUTHZ_ECHO`` (new) controls SQL statement logging; ``AUTHZ_ECHO_POOL`` no longer enables it, it only echoes the
  connection pool (statements carry bound parameters).
- Folders: the Sphinx sources moved from ``docs_source/`` to ``pages_source/``; ``docs/`` is still the generated site
  (GitHub Pages serves ``/docs``). Project documents (changelog, plan, issues, quality report) now live in
  ``documentation/``; ``CHANGELOG.txt`` moved there from the repository root.

Added
~~~~~

Scoped permissions:

- ``PermissionCatalog``: validated, immutable ``role -> permissions`` with scope kinds, from code or TOML/JSON.
- ``Authorizer`` with two failure modes (no assignment or unknown scope -> ``404``; assignment without the permission ->
  ``403`` naming it) and token-group roles. ``Authz.build(...).install(app)`` wires everything at startup; nothing reads
  the environment.
- FastAPI ``require_permission`` with ``ScopeFromPath`` / ``ScopeFromCallable`` / ``GlobalScope``, ``has_permission``,
  ``ErrorPolicy`` (404/403/401/503), ``x-permission`` in OpenAPI (``permission_extra``, ``declared_permissions``) and
  startup validation of every guarded route. The guard never skips on ``AUTH_MIDDLEWARE_DISABLED``.
- Stores, injected at startup or per request: ``InMemoryAssignmentStore``; ``SqlAssignmentStore`` (SQLAlchemy, injected
  or per-request session, ``before_query`` hook for row-level security, optimistic revisions);
  ``DynamoDbAssignmentStore`` (PynamoDB, consistent reads on the guard path, optional ``max_workers`` pool).
  ``auth_middleware.authz.testing.AssignmentStoreContract`` lets applications test their own adapters.
- ``AssignmentService`` (role validation, ``before_change`` / ``after_change`` hooks, serialised per scope within a
  process), ``authcli authz assign|revoke|list``, an opt-in ``CachingAssignmentStore`` (off by default, TTL <= 60 s) and
  audit/metrics hooks (``audit_hook``, ``metrics_hook``, ``MetricsCollector.record_authz_decision``).
- Alembic revision ``a3f1c9d2b7e4`` creates ``authz_assignment``.

Authentication:

- ``JwtAuthMiddleware`` options (keyword-only, defaults unchanged): ``canonical_bearer_scheme`` (RFC 7235 case-insensitive
  ``Bearer``), ``path_prefix`` (authenticate only a subtree, for mounted apps), ``error_responder`` (custom error responses;
  ``AuthFailure`` never carries the exception text) and ``strict`` (refuse ``AUTH_MIDDLEWARE_DISABLED`` / disabled
  verification at construction).
- ``OidcProviderSettings``: ``accepted_token_types`` and ``forced_jwks_refresh_min_interval_seconds`` (rate-limited JWKS
  refresh on unknown ``kid``, shared by concurrent requests). Hardening checklist in the OIDC docs.
- ``require_authenticated()`` and ``get_identity()`` (+ ``Identity``): fail closed on the placeholder ``synthetic`` user.
- ``match="all"`` on ``require_groups`` / ``require_roles`` / ``require_permissions`` (default ``"any"``).
- ``AsyncCognitoAuthService`` (blocking boto3 calls in a worker thread), ``needs_rehash()`` (upgrade path for legacy or weak
  password hashes), ``JWTProvider.aclose()`` (cancels the background JWKS refresh), ``EntraIDProvider(roles_provider=...)``.
- ``authcli`` starts without the ``sqlalchemy`` extra; commands that need an extra tell you which one.

Security
~~~~~~~~

- **Basic auth no longer logs the submitted password** (it was written in clear at DEBUG). Unknown users cost a password
  hash like wrong passwords (no username enumeration by status or timing), and the hash runs in a worker thread instead of
  blocking the event loop.
- **Lazy ``User`` providers received a repr of the token** (``str(JWTAuthorizationCredentials)``, signature included) when
  built by ``OidcProvider``: permission/group lookups never matched and the repr was logged. They now get the parsed
  credentials; ``User.token`` is the raw JWT.
- ``OidcProvider`` accepted a token whose ``aud`` named another API when ``azp``/``client_id`` matched; those claims now
  only stand in for a *missing* ``aud``.
- ``EntraIDProvider`` pins ``tid`` to the configured tenant (unless ``common``/``organizations``/``consumers``), warns when
  no audience is set and tolerates JWKs without ``use``.
- JWKS cache: concurrent expiry no longer stampedes the identity provider, and stale keys keep being served (30 s retry
  back-off) while it is down.
- Database URLs are logged with the password masked; ``verify_password`` returns ``False`` for corrupt hashes instead of
  raising (zero/negative/huge iteration counts, non-hex salt, non-ASCII values); a loud warning is logged when a middleware
  starts with ``AUTH_MIDDLEWARE_DISABLED``; SQL providers warn when ``id_claim`` is an editable claim (prefer ``sub``).
- The unreachable "no token -> synthetic user" fallback of ``JwtAuthMiddleware`` was removed (fail closed).

Fixes
~~~~~

- ``RateLimiter`` and ``AuditMiddleware`` answered ``500`` to anonymous requests; the limiter leaked a key per identifier
  (now swept) and ``MetricsCollector`` kept every timing forever (now bounded).
- ``JsonCredentialsRepository`` ignored the ``groups`` of its file.
- ``User`` lazy loads survive the cancellation of one awaiting request (client disconnect).
- ``EntraIDProvider`` users were built without the token or the permissions/roles providers (always empty), and its JWKS
  cache settings were read from settings that did not exist (now ``AUTH_MIDDLEWARE_JWKS_CACHE_*``).
- MySQL: ``authz_assignment`` identifiers were compared case- and accent-insensitively (``Abc`` = ``abc``); the columns now
  use ``utf8mb4_bin``.
- ``authz`` hardening before release: a stored role missing from the catalog denies instead of ``500``; invalid scope ids
  from the request (too long, ``*``) answer like an unknown scope; an empty/oversized ``sub`` is unauthenticated; a store
  outage answers ``503`` (``ErrorPolicy.unavailable``); the cache no longer keeps a pre-revocation read that raced an
  invalidation; ``authcli authz assign`` needs ``--catalog`` or ``--no-validate``; ``path_prefix`` must start with ``/``;
  DynamoDB connection/server errors map to ``StoreUnavailableError`` and ids may contain ``#``; only duplicate keys are
  revision conflicts in the SQL store and ``commit=False`` with an owned session is refused.
- ``alembic/env.py`` imported a module that no longer existed.

Packaging
~~~~~~~~~

- New extras: ``postgres`` (SQLAlchemy + asyncpg), ``mysql`` (SQLAlchemy + aiomysql), ``dynamodb`` (PynamoDB) and ``cognito``
  (boto3). ``sqlalchemy`` keeps installing both SQL drivers. ``import auth_middleware.authz`` needs no extra.
- ``starlette`` and ``email-validator`` (imported directly) are now declared dependencies; ``CognitoAuthService`` no longer
  imports an undeclared ``boto3``.
- Dependencies are at their latest stable versions (Sphinx stays on 9.1.x while Python 3.12 is supported). SQLAlchemy 2.1
  makes plain ``postgresql://`` URLs use psycopg 3, so ``alembic.ini`` names ``postgresql+psycopg2://``.
- ``ruff`` also enforces the bandit (``S``), ``ASYNC``, ``PLE``, ``RUF100`` and ``RUF012`` rules; ``make deps-check``
  runs ``deptry``.

Documentation
~~~~~~~~~~~~~

- New "Scoped Permissions" guides (quick start, catalog, stores, FastAPI, operations, migration, API), DynamoDB setup,
  extras in the installation page, a step-by-step section in the README and tested examples
  (``examples/authz_example.py``, ``examples/authz_stores_config.py``).
- Sphinx builds with no warnings (``-W``); stale middleware options (``include_paths``, ``exclude_paths``...) removed.

Tests
~~~~~

- Store tests on DynamoDB, PostgreSQL and MySQL through Floci started with testcontainers (``make test-floci``, marker
  ``floci``, excluded from the default run, own CI job), plus PostgreSQL, DynamoDB Local and moto.
- A hostile-token battery (alg none, algorithm confusion, kid tricks, wrong claims, malformed segments...) runs end to end
  against ``JwtAuthMiddleware`` + ``OidcProvider`` with a local fake JWKS.
- Regression tests for every finding of the review (over 200 new tests); coverage 95 %.

Version 0.6.2 (2026-10-09)
---------------------------

Compatibility
~~~~~~~~~~~~~

- **Python 3.12 and 3.13 are supported again (``requires-python = ">=3.12"``).** The code
  never needed anything specific to 3.14, but a few modules annotated with names that only exist
  under ``TYPE_CHECKING`` (``types/user.py``, ``contracts/jwt_provider.py``,
  ``providers/sqlalchemy/async_database.py``). That is lazy on 3.14 (PEP 649) but raised
  ``NameError`` at import time on 3.12/3.13. They now use ``from __future__ import annotations``.
  The full suite, ``mypy --strict`` and ``ruff`` pass on 3.12.

Bug Fixes
~~~~~~~~~

- **``JwtAuthMiddleware`` answered 500 to a non-Bearer ``Authorization`` scheme** (for example
  ``Basic``). The ``HTTPException`` raised by ``HTTPBearer`` was not handled, so it fell into the
  generic ``except Exception`` branch. It is now returned with its own status and headers (401).
- **A JWT without a ``kid`` header answered 500** (``KeyError: 'kid'`` from key matching), as did a
  JWKS entry without one. Both are now a bad token: 401, like any other token that cannot be matched
  to a signing key.
- **The 500 responses of ``JwtAuthMiddleware`` and ``BasicAuthMiddleware`` no longer include the
  exception text** (``{"detail": "Server error: <message>"}``), which could reveal internals
  (connection strings, paths, SQL). The cause is still logged; the client gets
  ``{"detail": "Internal server error"}``.
- **``BasicAuthMiddleware`` could not be registered with ``add_middleware``** as its README shows:
  ``__init__`` took ``credentials_repository`` before ``app``, so Starlette's ``cls(app, **options)``
  raised ``TypeError``. The signature is now ``(app, credentials_repository, ...)``. Code that passed
  both by keyword is unaffected; code that passed the repository as the first positional argument must
  swap the order.
- **A token whose ``email`` claim is in a special-use domain** (``.local``, ``.localhost``,
  ``.invalid``; typical in homelabs) made ``User`` construction fail and the request answer 500.
  Such addresses are now accepted; malformed ones are still rejected. ``User.email`` is now typed
  ``str | None`` (validated and normalized) instead of ``EmailStr | None``.

Packaging
~~~~~~~~~

- **Ship the ``py.typed`` marker** (PEP 561), so type checkers use the library's annotations
  instead of treating the package as untyped.

Version 0.6.1 (2026-08-11)
---------------------------

Bug Fixes
~~~~~~~~~

- **``User.email`` no longer rejects a blank ``email`` claim.** Some OIDC providers
  (e.g. Authentik) send ``email: ""`` for a user with none configured, instead of
  omitting the claim. ``EmailStr`` validated that as an invalid address and raised
  ``ValidationError`` from inside ``create_user_from_token``, turning a user with no
  email into an unhandled 500 for any caller. A blank/whitespace-only ``email`` is now
  normalized to ``None`` before validation, matching the field's documented optionality.

Version 0.6.0 (2026-08-10)
---------------------------

Breaking Changes
~~~~~~~~~~~~~~~~~

- **Removed ``CognitoProvider``, ``IdentityPoolProvider``, ``IdentityPoolClient``,
  ``IdentityPoolSettings``, ``AWSCredentials``, and ``CognitoAuthzProviderSettings``.**
  ``OidcProvider`` now handles Cognito User Pool tokens directly (see below), so the
  dedicated Cognito provider is no longer needed. Identity Pool support (exchanging
  User Pool tokens for temporary AWS credentials) is removed with no replacement in
  this library — use the AWS SDK directly if you need it.

  **Migration:** replace ``CognitoProvider(settings=CognitoAuthzProviderSettings(...))``
  with ``OidcProvider(settings=OidcProviderSettings(issuer="https://cognito-idp.{region}.amazonaws.com/{user_pool_id}", audience="{app_client_id}"))``.
  ``CognitoGroupsProvider``/``CognitoGroupsAsRolesProvider`` are unchanged and still
  pair with the new provider. ``docs_source/cognito_provider.rst`` is removed;
  Cognito setup is now documented in ``oidc_provider.rst`` and
  ``infrastructure/cognito-setup.rst``.

New Features
~~~~~~~~~~~~

- **``OidcProvider`` generalized to handle ID tokens, access tokens
  (``client_credentials``/M2M), and refresh tokens across any OIDC issuer** —
  including ones that label token type explicitly (Cognito's ``token_use`` claim)
  and ones that don't (Authentik, Keycloak, and other standards-compliant
  providers), via a new heuristic fallback. A new ``TokenType`` enum
  (``auth_middleware.providers.oidc.token_type``) classifies tokens as
  ``ID``/``ACCESS``/``REFRESH``/``UNKNOWN``. Refresh tokens presented as bearer
  credentials are now rejected.
- **Audience verification generalized**: in addition to the standard ``aud``
  claim, ``OidcProvider`` now also accepts a match on any of
  ``client_id_claims`` (``client_id``, ``azp`` by default) — needed because
  Cognito access tokens carry ``client_id`` instead of ``aud``.
- **Machine-to-machine (M2M) detection is now built into ``OidcProvider``**,
  generalizing the Cognito-only ``M2MTokenDetector``. M2M tokens populate
  ``User.is_m2m``/``User.client_id`` and skip ``GroupsProvider``/``RolesProvider``
  lookups. Configurable via new ``OidcProviderSettings`` fields:
  ``token_use_claim``, ``identity_claims``, ``client_id_claims``, and
  ``detect_m2m_tokens`` (set to ``False`` to disable detection entirely).
- **``CognitoGroupsProvider``/``CognitoGroupsAsRolesProvider`` accept a
  ``groups_claim`` constructor parameter** (default ``"cognito:groups"``),
  matching the ``SqlGroupsProvider``/``SqlPermissionsProvider`` ``id_claim``
  pattern, so a custom claim name no longer requires subclassing.

Version 0.5.0 (2026-08-09)
---------------------------

Security Fixes
~~~~~~~~~~~~~~~

- **Token expiration (``exp``) is now validated.** Previously,
  ``CognitoProvider``, ``IdentityPoolProvider``, and ``EntraIDProvider``
  only verified the JWT signature — a correctly-signed but *expired* token
  was still accepted, since ``joserfc.jwt.decode()`` does not check
  registered claims like ``exp``/``nbf``/``iat`` on its own. All three
  providers now reject tokens missing ``exp`` or past their expiration,
  via a new shared ``JWTProvider._validate_registered_claims()`` helper.
  A new ``jwt_leeway`` setting (default ``0``, seconds) is available on
  ``JWTProviderSettings`` (Cognito) and as
  ``AUTH_PROVIDER_AZURE_ENTRA_ID_LEEWAY`` (Entra ID) to tolerate clock
  skew between servers.

  **Action required:** if your tests use hand-crafted tokens without an
  ``exp`` claim, or your servers have significant clock drift from your
  identity provider, add ``exp``/configure ``jwt_leeway`` before
  upgrading.

- **Basic Auth passwords are now hashed with PBKDF2-HMAC-SHA256** (salted,
  600,000 iterations by default), via new ``hash_password()``/
  ``verify_password()`` functions exported from ``auth_middleware``.
  Previously ``BasicAuthMiddleware`` compared an unsalted raw SHA-256
  digest with a non-constant-time comparison. Existing credentials stored
  as unsalted SHA-256 hashes are still accepted for backward
  compatibility, but any new credentials should be created with
  ``hash_password()``.

- **``EntraIDProvider.get_keys()``/``get_openid_config()`` now handle
  errors properly.** Previously ``get_keys()`` had no error handling at
  all, and ``get_openid_config()`` silently swallowed any exception and
  returned ``{}``, which then surfaced as a confusing bare
  ``KeyError: 'jwks_uri'`` in ``load_jwks()``. Both now raise a clean
  ``InvalidTokenException`` (401) on HTTP errors, network errors, or
  malformed responses, matching ``CognitoProvider``'s behavior.

Breaking Changes
~~~~~~~~~~~~~~~~~

- **Removed the singleton pattern from ``CognitoProvider`` and
  ``EntraIDProvider``.** Previously, a second call to
  ``CognitoProvider(settings=...)`` (or ``EntraIDProvider(...)``) silently
  reused the *first* instance and ignored the new settings/providers —
  making it impossible to run two differently-configured instances (e.g.
  two Cognito user pools) in the same process. Each instantiation is now
  independent. ``Provider(settings=A) is Provider(settings=B)`` used to be
  ``True`` and is now ``False``.

- **``AUTH_MIDDLEWARE_DISABLED`` is now consistent across the whole
  library.** With it set, ``require_user()`` used to always raise 401
  (the opposite of "disabled"), and ``BasicAuthMiddleware`` used to always
  raise "No credentials provided" — both now let requests through with a
  synthetic user, consistent with ``JwtAuthMiddleware`` and
  ``require_groups``/``require_roles``/``require_permissions``, which
  already behaved this way.

- **``SqlGroupsProvider``/``SqlPermissionsProvider`` raise ``ValueError``
  instead of ``KeyError``** when a token is missing the identifier claim
  (previously hardcoded to ``"username"``, Cognito's convention). Both
  now accept a constructor argument ``id_claim`` (default ``"username"``,
  unchanged) so they can be used with Entra ID/OIDC tokens, which
  typically use ``"preferred_username"`` or ``"sub"`` instead.

New Features
~~~~~~~~~~~~

- **``OidcProvider``**: a new JWT provider for any standards-compliant
  OpenID Connect identity provider — Authentik, Keycloak, Auth0, Okta, or
  any issuer exposing a ``.well-known/openid-configuration`` discovery
  document. JWKS is discovered automatically (or configured explicitly),
  and ``iss``/``aud``/``exp``/``nbf`` are all validated. Replaces the
  previous "Generic JWT Provider" documentation page, which described
  configuration fields and direct instantiation of the abstract
  ``JWTProvider`` that never actually existed as working code.
  Documented in the new Sphinx pages ``oidc_provider.rst``,
  ``infrastructure/authentik-setup.rst``, and
  ``infrastructure/keycloak-setup.rst``.

Other Changes
~~~~~~~~~~~~~

- ``docs_source/jwt_auth_provider.rst`` renamed to ``docs_source/oidc_provider.rst``
  to match the real, working provider it now documents.

Version 0.4.6 (2026-08-09)
---------------------------

Security Fixes
~~~~~~~~~~~~~~~

- ``python-dotenv`` 1.2.1 → 1.2.2, fixing a symlink-following vulnerability
  in ``set_key()``/``unset_key()`` that could let a local attacker overwrite
  arbitrary files via a crafted symlink (CVE-2026-28684, GHSA-mf9w-mj56-hr94).
- ``requests`` 2.32.5 → 2.34.2 (dev-only, pulled in transitively by
  ``pysonar``), fixing insecure temp file reuse in
  ``extract_zipped_paths()`` (CVE-2026-25645, GHSA-gc5v-m9x4-r6x2). Not
  reachable through normal library usage; auth-middleware never calls
  ``extract_zipped_paths()`` directly.
- ``pysonar`` (dev dependency, used by ``make sonar``) bumped 1.4.0.4676 →
  1.7.0.5143 to relax its pin on ``requests`` (previously locked to
  exactly 2.32.5), which is what unblocked the ``requests`` fix above.

Version 0.4.5 (2026-08-09)
---------------------------

This release consolidates versions 0.4.2-0.4.5, which were published
without individual changelog entries.

Security Fixes
~~~~~~~~~~~~~~~

- **CognitoProvider.verify_token now validates the token's app client.**
  Previously only the JWT signature was checked against the user pool's
  JWKS; since Cognito signs tokens for every app client in a user pool
  with the same keys, any valid token from *any* app client of that pool
  was accepted. When ``user_pool_client_id`` is configured on
  ``CognitoAuthzProviderSettings``, the token's ``aud`` claim (ID tokens)
  or ``client_id`` claim (access tokens) is now checked against it after
  signature verification, and the token is rejected on mismatch. This
  check is optional and skipped when ``user_pool_client_id`` is not
  configured, for backward compatibility. ``IdentityPoolProvider``
  inherits this fix automatically since it extends ``CognitoProvider``.

  If you use ``CognitoProvider`` or ``IdentityPoolProvider``, set
  ``user_pool_client_id`` in ``CognitoAuthzProviderSettings`` to enable
  this check.

Breaking Changes
~~~~~~~~~~~~~~~~~

**Profile management removed.** The ``ProfileProvider`` contract
(``auth_middleware.contracts.profile_provider``) and
``CognitoProfileProvider``
(``auth_middleware.providers.aws.cognito_profile_provider``) have been
deleted, along with the related fields on ``User``, ``JWTProvider`` and
``CognitoProvider``. If you were using profile management, it is no
longer part of this library.

Dependency Updates
~~~~~~~~~~~~~~~~~~~

  PACKAGE               OLD        NEW
  --------------------   --------   --------
  joserfc                1.6.3      1.6.8
  pydantic-settings       2.12.0     2.14.2
  starlette               0.50.0     1.3.1
  fastapi (via starlette) 0.128.0    0.137.1
  cryptography            46.0.7     48.0.1
  urllib3                 2.6.3      2.7.0
  idna                    3.11       3.15
  tornado                 6.5.5      6.5.7
  mako                    1.3.10     1.3.12
  soupsieve               2.8.3      2.8.4

Other Changes
~~~~~~~~~~~~~

- Packaging/build workflow improvements (GitHub Actions release
  workflow, makefile, ``pyproject.toml``).
- README documentation improvements.

Version 0.4.1 (2026-05-02)
---------------------------

Breaking Changes
~~~~~~~~~~~~~~~~

**Guard helpers and checker classes** moved to a dedicated ``guards`` package.
The old top-level module paths have been **deleted** — they no longer exist.

  OLD LOCATION (deleted)                            NEW LOCATION
  -----------------------------------------------   -----------------------------------------------
  auth_middleware.functions                         auth_middleware.guards.functions
  auth_middleware.group_checker                     auth_middleware.guards.group_checker
  auth_middleware.role_checker                      auth_middleware.guards.role_checker
  auth_middleware.permissions_checker               auth_middleware.guards.permissions_checker

**Provider implementations** reorganised into technology-scoped packages.
All old module paths have been **deleted** — they no longer exist.

  OLD LOCATION (deleted)                                           NEW LOCATION
  --------------------------------------------------------------   ---------------------------------------------------
  auth_middleware.providers.authn.cognito_provider                 auth_middleware.providers.aws.cognito_provider
  auth_middleware.providers.authn.cognito_authz_provider_settings  auth_middleware.providers.aws.cognito_authz_provider_settings
  auth_middleware.providers.authn.identity_pool_provider           auth_middleware.providers.aws.identity_pool_provider
  auth_middleware.providers.authn.identity_pool_client             auth_middleware.providers.aws.identity_pool_client
  auth_middleware.providers.authn.identity_pool_settings           auth_middleware.providers.aws.identity_pool_settings
  auth_middleware.providers.authn.jwt_provider_settings            auth_middleware.providers.aws.jwt_provider_settings
  auth_middleware.providers.authz.cognito_groups_provider          auth_middleware.providers.aws.cognito_groups_provider
  auth_middleware.providers.authz.cognito_groups_as_roles_provider auth_middleware.providers.aws.cognito_groups_as_roles_provider
  auth_middleware.providers.profile.cognito_profile_provider       auth_middleware.providers.aws.cognito_profile_provider
  auth_middleware.providers.cognito (COGNITO_*_CLAIM constants)    auth_middleware.providers.aws (same constants)
  auth_middleware.providers.cognito.utils                          auth_middleware.providers.aws.utils
  auth_middleware.providers.exceptions.aws_exception               auth_middleware.providers.aws.aws_exception
  auth_middleware.providers.entra_id.entra_id_provider             auth_middleware.providers.azure.entra_id_provider
  auth_middleware.providers.entra_id.settings                      auth_middleware.providers.azure.settings
  auth_middleware.providers.entra_id.utils                         auth_middleware.providers.azure.utils
  auth_middleware.providers.exceptions.azure_exception             auth_middleware.providers.azure.azure_exception
  auth_middleware.providers.authz.async_database                   auth_middleware.providers.sqlalchemy.async_database
  auth_middleware.providers.authz.async_database_settings          auth_middleware.providers.sqlalchemy.async_database_settings
  auth_middleware.providers.authz.sql_base_model                   auth_middleware.providers.sqlalchemy.sql_base_model
  auth_middleware.providers.authz.sql_groups_provider              auth_middleware.providers.sqlalchemy.sql_groups_provider
  auth_middleware.providers.authz.sql_permissions_provider         auth_middleware.providers.sqlalchemy.sql_permissions_provider

Migration
~~~~~~~~~

Guards:

  # Before (no longer works — ImportError)
  from auth_middleware.functions import require_user, require_groups, require_roles
  from auth_middleware.functions import require_permissions, has_groups, has_roles
  from auth_middleware.functions import has_permissions, get_current_user
  from auth_middleware.group_checker import GroupChecker
  from auth_middleware.role_checker import RoleChecker
  from auth_middleware.permissions_checker import PermissionsChecker

  # After
  from auth_middleware.guards import (
      require_user,
      require_groups,
      require_roles,
      require_permissions,
      has_groups,
      has_roles,
      has_permissions,
      get_current_user,
      GroupChecker,
      RoleChecker,
      PermissionsChecker,
  )

Providers:

  providers.authn.*                        → providers.aws.*
  providers.authz.cognito_*                → providers.aws.cognito_*
  providers.authz.sql_*                    → providers.sqlalchemy.sql_*
  providers.authz.async_database*          → providers.sqlalchemy.async_database*
  providers.profile.*                      → providers.aws.*
  providers.cognito                        → providers.aws
  providers.entra_id.*                     → providers.azure.*
  providers.exceptions.aws_exception       → providers.aws.aws_exception
  providers.exceptions.azure_exception     → providers.azure.azure_exception

Deleted package directories: authn/, authz/, profile/, cognito/, entra_id/, exceptions/

Other Changes
~~~~~~~~~~~~~

- New internal module ``auth_middleware.constants`` introduced with
  ``AUTH_SCHEME_BASIC`` and ``AUTH_SCHEME_BEARER`` constants.
  This module is not part of the public API.

Version 0.4.0 (2026-05-01)
---------------------------

Breaking Changes
~~~~~~~~~~~~~~~~

Provider interfaces / ABCs moved to a dedicated ``contracts`` package.
The old module paths have been **deleted** — they no longer exist.

  OLD LOCATION (deleted)                                    NEW LOCATION
  -------------------------------------------------------  -----------------------------------------------
  auth_middleware.providers.authn.jwt_provider             auth_middleware.contracts.jwt_provider
  auth_middleware.providers.authz.groups_provider          auth_middleware.contracts.groups_provider
  auth_middleware.providers.authz.roles_provider           auth_middleware.contracts.roles_provider
  auth_middleware.providers.authz.permissions_provider     auth_middleware.contracts.permissions_provider
  auth_middleware.providers.profile.profile_provider       auth_middleware.contracts.profile_provider

Migration
~~~~~~~~~

Update your imports to use the new canonical paths:

  # Before (no longer works — ImportError)
  from auth_middleware.providers.authn.jwt_provider import JWTProvider
  from auth_middleware.providers.authz.groups_provider import GroupsProvider
  from auth_middleware.providers.authz.roles_provider import RolesProvider
  from auth_middleware.providers.authz.permissions_provider import PermissionsProvider
  from auth_middleware.providers.profile.profile_provider import ProfileProvider

  # After
  from auth_middleware.contracts import (
      JWTProvider,
      GroupsProvider,
      RolesProvider,
      PermissionsProvider,
      ProfileProvider,
  )

  # Or via top-level package
  from auth_middleware import JWTProvider, GroupsProvider, RolesProvider, PermissionsProvider, ProfileProvider

Other Changes
~~~~~~~~~~~~~

- Provider contracts are now exported from the top-level ``auth_middleware``
  package, making them available via ``from auth_middleware import JWTProvider``
  etc. without knowing the internal module structure.

Version 0.3.x and earlier
--------------------------

See git history for previous changes.
