Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,10 @@ concurrency:

jobs:
test:
# Pinned: ubuntu-latest is now 26.04, which has no Python 3.9 build in actions/python-versions
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.9, "3.10", "3.11", "3.12"]
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]

steps:
- name: Checkout code
Expand Down
2 changes: 1 addition & 1 deletion .ruff.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
line-length = 100
target-version = "py39"
target-version = "py310"

[lint]
select = [
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ This library is part of Auth0's Python ecosystem for server-side authentication

### 1. Install the SDK

_This library requires Python 3.9.2+._
_This library requires Python 3.10+._

```shell
pip install auth0-api-python
Expand Down
10 changes: 5 additions & 5 deletions docs/Caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,18 @@ For distributed deployments (multiple servers, containers), use a shared cache b

```python
import json
from typing import Any, Optional
from typing import Any
from auth0_api_python import ApiClient, ApiClientOptions, CacheAdapter

class RedisCache(CacheAdapter):
def __init__(self, redis_client):
self.redis = redis_client

def get(self, key: str) -> Optional[Any]:
def get(self, key: str) -> Any | None:
value = self.redis.get(key)
return json.loads(value) if value else None

def set(self, key: str, value: Any, ttl_seconds: Optional[int] = None) -> None:
def set(self, key: str, value: Any, ttl_seconds: int | None = None) -> None:
serialized = json.dumps(value)
if ttl_seconds:
self.redis.set(key, serialized, ex=ttl_seconds)
Expand Down Expand Up @@ -97,8 +97,8 @@ When the cache is full, the least recently used entry is evicted. A cache miss t

| Method | Signature | Description |
|---|---|---|
| `get` | `(key: str) -> Optional[Any]` | Return cached value or `None` if not found / expired |
| `set` | `(key: str, value: Any, ttl_seconds: Optional[int]) -> None` | Store value with optional TTL |
| `get` | `(key: str) -> Any \| None` | Return cached value or `None` if not found / expired |
| `set` | `(key: str, value: Any, ttl_seconds: int \| None) -> None` | Store value with optional TTL |
| `delete` | `(key: str) -> None` | Remove a single entry |
| `clear` | `() -> None` | Remove all entries |

Expand Down
3 changes: 1 addition & 2 deletions docs/TokenStorage.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ and `delete`. The base class requires a `secret` at construction and provides `e

```python
import time
from typing import Optional

import redis.asyncio as redis

Expand All @@ -84,7 +83,7 @@ class RedisTokenStore(AbstractTokenStore):
super().__init__(secret=secret)
self.redis = redis_client

async def get(self, key: str) -> Optional[TokenSet]:
async def get(self, key: str) -> TokenSet | None:
raw = await self.redis.get(key)
if raw is None:
return None
Expand Down
406 changes: 4 additions & 402 deletions poetry.lock

Large diffs are not rendered by default.

7 changes: 2 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,13 @@ packages = [
]

[tool.poetry.dependencies]
python = ">=3.9.2"
python = ">=3.10"
authlib = "^1.0" # For JWT/OIDC features
requests = "^2.31.0" # If you use requests for HTTP calls (e.g., discovery)
httpx = "^0.28.1"
cryptography = ">=43.0.1"
jwcrypto = "^1.5.7"
ada-url = [
{version = "^1.30.0", python = ">=3.10"},
{version = "^1.27.0", python = ">=3.9,<3.10"}
]
ada-url = "^1.30.0"

[tool.poetry.group.dev.dependencies]
pytest = "^8.0"
Expand Down
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@

authlib>=1.6.12
httpx>=0.28.1
ada-url>=1.32.0; python_version >= "3.10"
ada-url>=1.27.0; python_version < "3.10"
ada-url>=1.32.0
pytest>=8.0
pytest-cov>=4.0
pytest-asyncio>=0.25.3
Expand Down
17 changes: 8 additions & 9 deletions src/auth0_api_python/_internal/cache_keys.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
"""Cache-key builders and scope helpers for the tokens the SDK mints."""

import hashlib
from typing import Optional

from ..utils import get_unverified_payload

_FIELD_SEPARATOR = "\x1f"


def _normalized_scopes(scope: Optional[str]) -> str:
def _normalized_scopes(scope: str | None) -> str:
"""Sort and dedupe scopes so equivalent scope strings produce the same cache key."""
if not scope:
return ""
return " ".join(sorted(set(scope.split())))


def is_covered_by(requested: Optional[str], granted: Optional[str]) -> bool:
def is_covered_by(requested: str | None, granted: str | None) -> bool:
"""True when the requested scopes are all covered by the granted scopes."""
granted_set = set(_normalized_scopes(granted).split())
requested_set = set(_normalized_scopes(requested).split())
Expand Down Expand Up @@ -52,7 +51,7 @@ def _obo_identity_fields(
exchange_tenant: str,
exchange_client_id: str,
audience: str,
org_id: Optional[str],
org_id: str | None,
session_key: str,
) -> list[str]:
"""The fields every OBO cache key shares, namespaced by key kind.
Expand Down Expand Up @@ -81,8 +80,8 @@ def obo_cache_key(
exchange_tenant: str,
exchange_client_id: str,
audience: str,
org_id: Optional[str],
scopes: Optional[str],
org_id: str | None,
scopes: str | None,
session_key: str,
) -> str:
"""Token cache key for an On Behalf Of exchange.
Expand Down Expand Up @@ -112,7 +111,7 @@ def index_cache_key(
exchange_tenant: str,
exchange_client_id: str,
audience: str,
org_id: Optional[str],
org_id: str | None,
session_key: str,
) -> str:
"""Cache key for the OBO token index, scoped to caller, issuer, exchange, audience, org, and session.
Expand All @@ -132,7 +131,7 @@ def index_cache_key(
return sub + ":" + hashlib.sha256(_FIELD_SEPARATOR.join(fields).encode()).hexdigest()


def m2m_cache_key(*, tenant: str, client_id: str, audience: str, scopes: Optional[str]) -> str:
def m2m_cache_key(*, tenant: str, client_id: str, audience: str, scopes: str | None) -> str:
"""Cache key for a client-credentials (M2M) exchange, scoped to tenant, client, audience, and scopes."""
fields = _FIELD_SEPARATOR.join(
["m2m", tenant, client_id, audience, _normalized_scopes(scopes)]
Expand All @@ -141,7 +140,7 @@ def m2m_cache_key(*, tenant: str, client_id: str, audience: str, scopes: Optiona


def token_vault_cache_key(
*, sub: str, connection: str, tenant: str, client_id: str, login_hint: Optional[str] = None
*, sub: str, connection: str, tenant: str, client_id: str, login_hint: str | None = None
) -> str:
"""Cache key for a Token Vault exchange, scoped to tenant, client, caller, connection, and login hint."""
fields = _FIELD_SEPARATOR.join(["token_vault", tenant, client_id, sub, connection, login_hint or ""])
Expand Down
24 changes: 12 additions & 12 deletions src/auth0_api_python/_internal/obo_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import logging
import time
from typing import NamedTuple, Optional, cast
from typing import NamedTuple, cast

from ..token_store import (
AbstractTokenStore,
Expand All @@ -29,7 +29,7 @@ class _OboIdentity(NamedTuple):
sub: str
issuer: str
incoming_client_id: str
org_id: Optional[str]
org_id: str | None
session_key: str


Expand All @@ -54,7 +54,7 @@ def __init__(
self._exchange_client_id = exchange_client_id
self._mode = scope_matching

def identity(self, verified: VerifiedToken) -> Optional[_OboIdentity]:
def identity(self, verified: VerifiedToken) -> _OboIdentity | None:
"""Build the cache identity from verified claims, or None when they lack a usable subject."""
claims = verified.claims
sub = claims.get("sub")
Expand All @@ -77,8 +77,8 @@ def identity(self, verified: VerifiedToken) -> Optional[_OboIdentity]:
)

async def lookup(
self, identity: _OboIdentity, audience: str, scope: Optional[str]
) -> Optional[OnBehalfOfTokenResult]:
self, identity: _OboIdentity, audience: str, scope: str | None
) -> OnBehalfOfTokenResult | None:
"""Return a reusable cached token for this request, or None on a miss."""
if self._mode == "non_strict":
return await self._index_lookup(identity, audience, scope)
Expand All @@ -88,7 +88,7 @@ async def write(
self,
identity: _OboIdentity,
audience: str,
scope: Optional[str],
scope: str | None,
obo_result: OnBehalfOfTokenResult,
) -> None:
"""Store a freshly exchanged token under its granted scopes."""
Expand All @@ -114,7 +114,7 @@ async def write(

# ===== Private methods =====

def _token_key(self, identity: _OboIdentity, audience: str, layout: str, scopes: Optional[str]) -> str:
def _token_key(self, identity: _OboIdentity, audience: str, layout: str, scopes: str | None) -> str:
return obo_cache_key(
layout=layout,
sub=identity.sub,
Expand Down Expand Up @@ -156,7 +156,7 @@ def _well_formed_member(member: object) -> bool:
)

@staticmethod
def _usable_entry(cached: Optional[TokenSet], now: int) -> bool:
def _usable_entry(cached: TokenSet | None, now: int) -> bool:
if cached is None:
return False
if "access_token" not in cached or "expires_at" not in cached:
Expand All @@ -177,8 +177,8 @@ def _hit(cached: TokenSet, now: int) -> OnBehalfOfTokenResult:
return result

async def _strict_lookup(
self, identity: _OboIdentity, audience: str, scope: Optional[str]
) -> Optional[OnBehalfOfTokenResult]:
self, identity: _OboIdentity, audience: str, scope: str | None
) -> OnBehalfOfTokenResult | None:
now = int(time.time())
try:
cached = await self._store.get(self._token_key(identity, audience, "strict", scope))
Expand All @@ -193,8 +193,8 @@ async def _strict_lookup(
return self._hit(cached, now)

async def _index_lookup(
self, identity: _OboIdentity, audience: str, scope: Optional[str]
) -> Optional[OnBehalfOfTokenResult]:
self, identity: _OboIdentity, audience: str, scope: str | None
) -> OnBehalfOfTokenResult | None:
# An unscoped request is covered by every cached token, so never reuse for one.
requested_scopes = _normalized_scopes(scope)
if not requested_scopes:
Expand Down
10 changes: 5 additions & 5 deletions src/auth0_api_python/_internal/token_vault_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import logging
import time
from typing import Any, Optional
from typing import Any

from ..token_store import AbstractTokenStore, TokenSet
from .cache_expiry import is_fresh
Expand All @@ -22,8 +22,8 @@ def __init__(self, token_store: AbstractTokenStore) -> None:
self._store = token_store

def cache_key(
self, tenant: str, client_id: str, sub: Any, connection: str, login_hint: Optional[str] = None
) -> Optional[str]:
self, tenant: str, client_id: str, sub: Any, connection: str, login_hint: str | None = None
) -> str | None:
"""Return the cache key, or None when sub is not a usable string (cache skipped with a warning)."""
if not isinstance(sub, str) or not sub:
logger.warning("Access token has no usable sub claim, skipping Token Vault cache")
Expand All @@ -32,9 +32,9 @@ def cache_key(
sub=sub, connection=connection, tenant=tenant, client_id=client_id, login_hint=login_hint
)

async def lookup(self, key: str) -> Optional[dict]:
async def lookup(self, key: str) -> dict | None:
"""Return a live cached token or None. Miss cases: absent, malformed, expired."""
cached: Optional[TokenSet] = None
cached: TokenSet | None = None
try:
cached = await self._store.get(key)
except Exception as exc:
Expand Down
4 changes: 2 additions & 2 deletions src/auth0_api_python/act.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
"""

from collections.abc import Mapping
from typing import Any, Optional
from typing import Any

from .errors import VerifyAccessTokenError

INVALID_ACT_CLAIM_MESSAGE = "Invalid act claim"


def get_current_actor(claims: Mapping[str, Any]) -> Optional[str]:
def get_current_actor(claims: Mapping[str, Any]) -> str | None:
"""
Return the current actor from the outermost `act.sub`, if present.

Expand Down
Loading
Loading