Skip to content

Commit fccc24a

Browse files
committed
docs: Updated claude.md and references
1 parent d83179f commit fccc24a

6 files changed

Lines changed: 45 additions & 24 deletions

File tree

‎CLAUDE.md‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,24 +22,28 @@ src/auth0_api_python/
2222
__init__.py # Public API: everything in __all__ is the supported surface
2323
api_client.py # ApiClient: verify_request, verify_access_token, verify_dpop_proof,
2424
# get_access_token_for_connection, get_token_by_exchange_profile,
25-
# get_token_on_behalf_of; private helpers (_discover, _fetch_jwks, ...) at the end,
25+
# get_token_on_behalf_of, get_client_credentials_token; private helpers (_discover, _fetch_jwks, ...) at the end,
2626
# except _resolve_allowed_domains, which sits above verify_request (leave it there)
2727
config.py # ApiClientOptions (all constructor options and defaults)
2828
errors.py # BaseAuthError hierarchy (status code, OAuth error code, WWW-Authenticate headers)
2929
cache.py # CacheAdapter ABC + InMemoryCache (LRU + TTL) for discovery/JWKS
30+
token_store.py # AbstractTokenStore / IndexedTokenStore ABCs, TokenSet, VerifiedToken (caches tokens the SDK mints)
31+
encryption.py # JWE encrypt/decrypt used by AbstractTokenStore
32+
_internal/ # Cache key builders and OBO / Token Vault cache classes. Private, not in __all__
3033
utils.py # normalize_domain, OIDC/JWKS fetch, unverified header/payload decode, htu normalization
3134
act.py # get_current_actor / get_delegation_chain (RFC 8693 act claim)
3235
types.py # TypedDicts: DomainsResolverContext, OnBehalfOfTokenResult, ActClaim
3336
token_utils.py # Test helpers (token/DPoP proof generators) with a synthetic test key. Not in __all__, but packaged and importable
3437
tests/
3538
conftest.py # Shared fixtures (api_client_confidential, mock_discovery) and httpx mock helpers
36-
test_api_client.py, test_cache.py, test_utils.py, test_act.py
37-
docs/ # Caching.md, MultipleCustomDomain.md (hand-written guides, linked from README)
39+
test_api_client.py, test_cache.py, test_utils.py, test_act.py, test_token_store.py
40+
docs/ # Caching.md, MultipleCustomDomain.md, TokenStorage.md, OrganizationPolicy.md (hand-written guides, linked from README)
3841
README.md, EXAMPLES.md
3942
pyproject.toml # Poetry manifest; source of truth for dependencies
4043
requirements.txt # Hand-maintained runtime + dev dep list for the Snyk SCA workflow (pins can differ from pyproject.toml)
4144
.version, .shiprc # Release version source (.shiprc keeps .version and pyproject.toml in sync)
4245
.ruff.toml # Lint config (CI-enforced)
46+
.snyk # Snyk ignores, including license waivers (e.g. jwcrypto LGPL-3.0)
4347
```
4448

4549
Before changing a flow (Bearer/DPoP verification, token exchange, MCD, caching), read its row in [references/flow-map.md](references/flow-map.md) for entry points, supporting helpers, tests, and docs.
@@ -55,7 +59,7 @@ Before changing a flow (Bearer/DPoP verification, token exchange, MCD, caching),
5559
- Follow existing style and naming. Add new public `ApiClient` methods after the existing public methods, above the `# ===== Private Methods =====` banner in `api_client.py`. Add new private helpers below it. Never reorder existing declarations.
5660
- Add unit tests for new functionality, marked `@pytest.mark.asyncio` when async, mocking HTTP with `pytest-httpx` (no real network calls).
5761
- Raise typed errors from `errors.py` (subclasses of `BaseAuthError` with `get_status_code()` / `get_error_code()`). Wrap third-party failures in a typed error with `raise ... from e`. Inside a catch-all, re-raise this SDK's own errors first (`except VerifyAccessTokenError: raise`, as `verify_access_token` does) so they are not double-wrapped. Never return `None` or a bare `dict` to signal failure, and never leak raw `httpx`/`authlib` errors from public methods.
58-
- Route discovery and JWKS fetches through `fetch_oidc_metadata` / `fetch_jwks` so `custom_fetch` and caching apply. Token endpoint calls use `httpx.AsyncClient(timeout=httpx.Timeout(self.options.timeout))` and map `httpx.TimeoutException` to `ApiError` 504 and `httpx.HTTPError` to 502, as `get_access_token_for_connection` does.
62+
- Route discovery and JWKS fetches through `fetch_oidc_metadata` / `fetch_jwks` so `custom_fetch` and caching apply. Token endpoint calls use `httpx.AsyncClient(timeout=httpx.Timeout(self.options.timeout))` and map `httpx.TimeoutException` to `ApiError` 504 and `httpx.HTTPError` to 502, as `get_access_token_for_connection` and `get_client_credentials_token` do. A discovery or JWKS outage during verification (connection error, timeout, HTTP 5xx or 429, classified by `is_auth_server_outage`) raises `AuthServerUnavailableError` (503), not a 401.
5963
- Export any new public symbol through `__init__.py` `__all__`.
6064
- Update `README.md` and `EXAMPLES.md` (and `docs/*.md` when caching or MCD behaviour changes) in the same PR when changing the public API, `ApiClientOptions`, or supported integration patterns.
6165
- When adding or bumping a runtime dependency in `pyproject.toml`, update `requirements.txt` to match. The SCA scan installs from it, not from Poetry.
@@ -65,11 +69,11 @@ Before changing a flow (Bearer/DPoP verification, token exchange, MCD, caching),
6569

6670
- Any breaking change. Never make one on your own initiative, stop and ask the maintainer before writing it. This includes a renamed or removed public method, a changed signature or default, a new required option, or a raised Python floor.
6771
- Changing an existing error's `get_error_code()` string, `ApiError.code`, or `get_status_code()`. Integrators branch on these and they surface in `WWW-Authenticate`, so treat them as public API. Adding a new error code is not breaking.
68-
- Adding or bumping dependencies (`pyproject.toml`, `poetry.lock`, `requirements.txt`).
69-
- Modifying public API signatures or `ApiClientOptions` defaults (e.g. `dpop_enabled`, `dpop_required`, cache TTL/size, `timeout`).
72+
- Adding or bumping dependencies (`pyproject.toml`, `poetry.lock`, `requirements.txt`). Include a license check, since `.snyk` waives `jwcrypto` (LGPL-3.0) by name.
73+
- Modifying public API signatures or `ApiClientOptions` defaults (e.g. `dpop_enabled`, `dpop_required`, `organization_policy`, `scope_matching`, cache TTL/size, `timeout`).
7074
- Changes to token, DPoP, issuer, or domain validation logic, the allowed algorithm lists, `RESERVED_PARAMS`, or `normalize_domain`.
7175
- Changes to CI/CD configuration (`.github/workflows/`, `.github/actions/`), `.ruff.toml` rule selection, or `.snyk` suppressions.
72-
- Changing the cache key format or what is stored in the cache (affects custom `CacheAdapter` implementations).
76+
- Changing the cache key format or what is stored in a cache (affects custom `CacheAdapter` and `AbstractTokenStore` implementations), including the builders in `_internal/cache_keys.py` and the `TokenSet` shape.
7377

7478
### Never Do
7579

@@ -81,7 +85,8 @@ Before changing a flow (Bearer/DPoP verification, token exchange, MCD, caching),
8185
- Run `ruff format .` repo-wide. It is not a CI gate and the tree is not format-clean (see Common Pitfalls).
8286
- Modify `.venv*/`, `dist/`, `__pycache__/`, `.coverage`, `coverage.xml`.
8387
- Import `token_utils` from library code, or put a real key in it.
84-
- Log, print, or include access tokens, DPoP proofs, client secrets, exchanged tokens, or full token endpoint response bodies in error messages. The SDK has no logger. Do not introduce one that emits these.
88+
- Log, print, or include access tokens, DPoP proofs, client secrets, exchanged tokens, token store values, or full token endpoint response bodies in error messages or logs. The SDK logs through module loggers (`logging.getLogger(__name__)`) and none may emit these. The one documented logged value is the rejected `org_id` warning (`docs/OrganizationPolicy.md`).
89+
- Import `_internal` from outside the package, or lower the 32-character `AbstractTokenStore` secret minimum.
8590
- Break backward compatibility without asking first and getting explicit approval.
8691

8792
---
@@ -92,10 +97,13 @@ Before changing a flow (Bearer/DPoP verification, token exchange, MCD, caching),
9297
- **Never fetch from a token-derived host:** in MCD mode (`domains`), the unverified `iss` is normalized and must pass `_resolve_allowed_domains` before `_discover(issuer=...)` runs. In single-domain mode, discovery always targets the configured `domain`, and the token `iss` is matched against the discovery issuer afterwards. Never pass a token-derived issuer or URL to a fetch without the allowlist check. That turns token input into SSRF.
9398
- **Domain normalization:** `normalize_domain` rejects `http://`, credentials, paths, queries, and fragments. Route every domain or issuer comparison through it.
9499
- **MCD resolver input is untrusted:** `request_url`, `request_headers`, and `unverified_iss` in `DomainsResolverContext` are attacker-influenced. Resolver failures raise `DomainsResolverError`, never fall back to accepting the token (see `docs/MultipleCustomDomain.md` "Security Requirements").
95-
- **Claims:** `iss`, `aud`, `exp`, `iat` are always validated. `required_claims` adds to them, never replaces them.
100+
- **Claims:** `iss`, `aud`, `exp`, `iat` are always validated, and `nbf` is validated when present (non-numeric or future values are rejected). `required_claims` adds to them, never replaces them.
101+
- **Organization policy:** `organization_policy="required"` rejects tokens without an `org_id` claim (`MissingOrganizationError`). `organization_id` is an allowlist valid only with `required` (`OrganizationNotAllowedError`). Both subclass `VerifyAccessTokenError`.
96102
- **DPoP:** proofs must carry `iat`, `ath`, `htm`, `htu`, `jti`. `htu` is compared via `normalize_url_for_htu`, `ath` must match the access token hash, and `cnf.jkt` must match the proof key thumbprint. `dpop_required=True` rejects Bearer. `jti` is checked for presence and type only. There is no replay store, so replay is bounded only by the `dpop_iat_offset` / `dpop_iat_leeway` window.
97103
- **Token exchange:** `RESERVED_PARAMS` blocks overriding OAuth parameters via `extra`, and `MAX_ARRAY_VALUES_PER_KEY` caps array values. Do not weaken either.
98-
- **Errors:** `_prepare_error` builds `WWW-Authenticate` headers. Error messages reach HTTP responses, so keep them generic and free of token contents.
104+
- **Token store caching:** off unless `token_store` is set. With a store, `get_token_on_behalf_of` and `get_access_token_for_connection` verify the token first (unless `verified=` is passed), then key the cache from the verified claims. `AbstractTokenStore` supplies `encrypt` / `decrypt` JWE helpers (HKDF-SHA256, `dir`, `A256CBC-HS512`) and a 32-character minimum secret, but the SDK never calls them. A store must encrypt in its own `get` / `set`, otherwise tokens are stored in plaintext. A cached token is reused only with more than 30 seconds left (`EXPIRY_BUFFER_SECONDS`), a store read failure is a cache miss, and a write failure is logged while the fresh token is still returned. Store exceptions are logged with their message, so a store must keep token values out of exception text. Keys are per flow: OBO folds in issuer, incoming client, exchange tenant and client, audience, `org_id`, session and scopes. M2M uses tenant, client, audience and scopes. Token Vault uses tenant, client, `sub`, connection and `login_hint`.
105+
- **`verified=` is a trust boundary:** a supplied `VerifiedToken` is not re-verified. Only its `access_token` is compared to the token being exchanged, and its claims then build the cache key. Pass only claims returned by `verify_access_token`.
106+
- **Errors:** `_prepare_error` builds `WWW-Authenticate` headers and leaves them empty for status 500 and above (`AuthServerUnavailableError`, 503, is the one that reaches it via `verify_request`). Error messages reach HTTP responses, so keep them generic and free of token contents.
99107
- **Anonymous callers:** tokens with `sub` starting `anon@` verify like any token. Authorization is the integrator's call, the SDK must not silently accept or reject them.
100108
- **Dependency scanning:** Snyk (`sca_scan.yml`, from `requirements.txt`, on push to `main` only), CodeQL (`codeql.yml`), and ruff `S` (bandit) rules in CI.
101109
- **Vulnerability reports:** go through Auth0's Responsible Disclosure Program (README "Vulnerability Reporting"), never a public issue or PR.
@@ -114,15 +122,15 @@ pytest + pytest-asyncio + pytest-httpx, in `tests/`. The default `poetry run pyt
114122

115123
## Code Style
116124

117-
CI-enforced via `.ruff.toml`: rule sets `E, W, F, I, B, C4, UP, S`, isort import order, py39 target, `S101`/`S105`/`S106` allowed only under `tests/`. New non-secret string constants in `src/` use `# noqa: S105` with a reason (existing sites predate this and omit it). See [references/code-style.md](references/code-style.md) for naming, error patterns, and examples. Read it before adding a class, method, or error type.
125+
CI-enforced via `.ruff.toml`: rule sets `E, W, F, I, B, C4, UP, S, PLC0415` (imports at module top level), isort import order, py39 target, `S101`/`S105`/`S106` allowed only under `tests/`. New non-secret string constants in `src/` use `# noqa: S105` with a reason (existing sites predate this and omit it). See [references/code-style.md](references/code-style.md) for naming, error patterns, and examples. Read it before adding a class, method, or error type.
118126

119127
## Git Workflow
120128

121129
Branches `feat/`, `fix/`, `docs/`, `chore/`, `release/<version>`. Commits use Conventional Commits prefixes. See [references/git-workflow.md](references/git-workflow.md) for PR template sections. Read it when committing or opening a PR.
122130

123131
## Common Pitfalls
124132

125-
The ones that bite most: the Python 3.9 floor (no `X | None`), `ruff format` is not a CI gate, a missing `@pytest.mark.asyncio`, and `custom_fetch` covering only discovery/JWKS. See [references/pitfalls.md](references/pitfalls.md). Read it when a command, test, or CI job behaves unexpectedly.
133+
The ones that bite most: the Python 3.9 floor (no `X | None`), `ruff format` is not a CI gate, a missing `@pytest.mark.asyncio`, function-level imports (`PLC0415`), and `custom_fetch` covering only discovery/JWKS. See [references/pitfalls.md](references/pitfalls.md). Read it when a command, test, or CI job behaves unexpectedly.
126134

127135
## Docs Update Rules
128136

‎references/code-style.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,14 @@ def get_token(self, options): # sync, untyped
5151

5252
Each line is a separate violation: sync in an async SDK, no timeout, unfiltered OAuth parameters, a print of a possibly token-bearing body, a `None` a caller can mistake for success, and an unvalidated response in the public API.
5353

54-
Public errors meant for integrators are exported from `__init__.py` (`ApiError`, `ConfigurationError`, `DomainsResolverError`, `GetTokenByExchangeProfileError`). Others are imported from `auth0_api_python.errors`.
54+
Public errors meant for integrators are exported from `__init__.py` (`ApiError`, `AuthServerUnavailableError`, `ConfigurationError`, `DomainsResolverError`, `GetAccessTokenForConnectionError`, `GetClientCredentialsTokenError`, `GetTokenByExchangeProfileError`, `MissingOrganizationError`, `OrganizationNotAllowedError`, `VerifyAccessTokenError`). Others are imported from `auth0_api_python.errors`.
5555

5656
## Patterns
5757

5858
- **Options object:** all configuration goes through `ApiClientOptions` and is validated in `ApiClient.__init__`, raising `ConfigurationError` or `MissingRequiredArgumentError` at construction rather than at first use.
5959
- **Async I/O:** network calls use `httpx.AsyncClient`, or the integrator's `custom_fetch` when provided. Public verification and token methods are `async def`.
6060
- **Pluggable cache:** `CacheAdapter` ABC with `get` / `set` / `delete` / `clear`. `InMemoryCache` is the default. Entry TTL is `min(Cache-Control max-age, cache_ttl_seconds)` when the discovery/JWKS response sends `max-age`.
61+
- **Token store:** `AbstractTokenStore` ABC with `get` / `set` / `delete` plus `encrypt` / `decrypt`, separate from `CacheAdapter`. The helpers are opt-in: the SDK never calls them, so a store encrypts in its own `get` / `set`. `IndexedTokenStore` adds `add_index_member` / `list_index_members` for `scope_matching="non_strict"`. Cache classes and key builders live in `_internal/` and are not public. A store failure is logged and treated as a miss, never raised to the caller.
6162
- **Docstrings:** Google style with `Args:` / `Returns:` / `Raises:` sections on public methods.
6263
- **Placement:** `api_client.py` has one banner, `# ===== Private Methods =====`. New public methods go above it after the existing ones, new helpers below it. In files without banners, put new code next to related code or at the end, never at an arbitrary position.
6364

‎references/docs-update.md‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@ A PR that changes public API, configuration, or integration patterns is not comp
66

77
| Doc | Covers | Exists |
88
|-----|--------|--------|
9-
| `README.md` | Install, `ApiClient` setup, verification, connection tokens, custom token exchange, OBO, DPoP modes and options, MCD summary, anonymous callers | present |
10-
| `EXAMPLES.md` | OBO exchange, delegation inspection, Bearer and DPoP verification, DPoP modes, anonymous caller patterns | present |
9+
| `README.md` | Install, `ApiClient` setup, verification, connection tokens, custom token exchange, OBO, client credentials, DPoP modes and options, MCD summary, anonymous callers, organization policy | present |
10+
| `EXAMPLES.md` | OBO exchange and caching, client credentials, Token Vault connection tokens, delegation inspection, Bearer and DPoP verification, auth server outage handling, DPoP modes, anonymous caller patterns | present |
1111
| `docs/Caching.md` | Cache defaults, TTL/max entries, custom `CacheAdapter`, tuning | present |
1212
| `docs/MultipleCustomDomain.md` | `domains` list and resolver modes, hybrid mode, resolver security requirements, MCD with DPoP, errors, migration | present |
13+
| `docs/TokenStorage.md` | `token_store`, cache key shapes per flow, expiry buffer, implementing `AbstractTokenStore` and `IndexedTokenStore`, at-rest encryption, `scope_matching` | present |
14+
| `docs/OrganizationPolicy.md` | `organization_policy` modes, `organization_id` allowlist, configuration and verification errors | present |
1315

1416
## When you change code, update these docs
1517

@@ -20,6 +22,9 @@ A PR that changes public API, configuration, or integration patterns is not comp
2022
| `CacheAdapter` interface or `InMemoryCache` behaviour | `docs/Caching.md` ("CacheAdapter API", "Default Behavior") |
2123
| Domain resolver context, MCD validation, or resolver errors | `docs/MultipleCustomDomain.md`, `README.md` section 7 |
2224
| Bearer/DPoP verification behaviour or error codes | `README.md` section 6, `EXAMPLES.md` (Bearer, DPoP sections) |
23-
| Token exchange (connection, exchange profile, OBO) behaviour or errors | `README.md` sections 4 and 5, `EXAMPLES.md` "On Behalf Of Token Exchange" |
25+
| Token exchange (connection, exchange profile, OBO, client credentials) behaviour or errors | `README.md` sections 4 and 5, `EXAMPLES.md` "On Behalf Of Token Exchange", "Client Credentials for Server-to-Server Calls", "Access Token for a Connection (Token Vault)" |
26+
| `token_store`, `scope_matching`, the `AbstractTokenStore` / `IndexedTokenStore` interface, cache keys, or the expiry buffer | `docs/TokenStorage.md`, `README.md` sections 4 and 5, `EXAMPLES.md` caching samples |
27+
| `organization_policy` / `organization_id` behaviour or their errors | `docs/OrganizationPolicy.md`, `README.md` section 9 |
28+
| Discovery or JWKS outage handling (`AuthServerUnavailableError`) | `README.md` section 3, `docs/MultipleCustomDomain.md` "Issuer Rejection", `EXAMPLES.md` "Telling an Outage from an Invalid Token" |
2429
| New exported symbol in `__init__.py` | `EXAMPLES.md` (add a usage sample) |
2530
| Supported Python version or install method | `README.md` "Install the SDK" |

0 commit comments

Comments
 (0)