Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
7c38dc1
docs: Added CLAUDE.md with AGENTS.md and references
rmad17 Oct 12, 2026
d83179f
Merge branch 'main' into feat/claude-md
rmad17 Oct 26, 2026
fccc24a
docs: Updated claude.md and references
rmad17 Oct 26, 2026
95994a7
Merge branch 'main' into feat/claude-md
rmad17 Oct 28, 2026
9d05a16
docs: sync claude.md with #151 and read python floor from pyproject
rmad17 Oct 29, 2026
93e5c77
docs: correct jti check and drop point-in-time counts
rmad17 Oct 29, 2026
c606ffe
docs: correct imprecise claims in claude.md and references
rmad17 Oct 29, 2026
951c8db
docs: align claude.md and references with source behavior
rmad17 Nov 4, 2026
dce6058
docs: split colon-joined clause in claude.md
rmad17 Nov 5, 2026
bf0c82f
Merge branch 'main' into feat/claude-md
rmad17 Nov 10, 2026
42f3f20
docs: consolidate agent guidelines into AGENTS.md and sync with telem…
rmad17 Nov 10, 2026
1b88e1c
docs: scope typed-error rules to new code in agent guidelines
rmad17 Nov 10, 2026
909a3b2
docs: describe what publish.yml does in the release guidelines
rmad17 Nov 10, 2026
f93e477
docs: split long agent guideline bullets into sub-bullets
rmad17 Nov 10, 2026
9d1688e
docs: split long common pitfalls into sub-points
rmad17 Nov 10, 2026
54522c0
docs: list freezegun in the requirements.txt coverage note
rmad17 Nov 10, 2026
c2c19d2
docs: correct the default httpx timeout in agent guidelines
rmad17 Nov 10, 2026
73e57b9
docs: fix comma splice in the custom_fetch pitfall
rmad17 Nov 10, 2026
65a5dae
docs: remove internal handle and unverified claims from agent guidelines
rmad17 Nov 10, 2026
b23e6b3
Merge branch 'main' of github.com:auth0/auth0-api-python into feat/cl…
rmad17 Nov 23, 2026
938bc07
docs: align agent guidelines with source and the Python 3.10 floor
rmad17 Nov 23, 2026
b386cfd
docs: address remaining review threads in agent guidelines
rmad17 Nov 25, 2026
50385e2
docs: note that interpolated exception text can include input fragments
rmad17 Nov 25, 2026
bded4ca
docs: describe the decoder error fragment without a test reference
rmad17 Nov 25, 2026
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ __pycache__/
#Environments
.env
.venv
.venv-*
env/

#Session Cache
Expand Down
153 changes: 153 additions & 0 deletions AGENTS.md

Large diffs are not rendered by default.

78 changes: 78 additions & 0 deletions references/code-style.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Code Style

## Naming

- `snake_case` functions, methods, and options. `PascalCase` classes. `UPPER_SNAKE` module constants (`RESERVED_PARAMS`, `TOKEN_EXCHANGE_GRANT_TYPE`).
- Private helpers carry a leading underscore (`_discover`, `_fetch_jwks`, `_prepare_error`) and sit together after the public methods of `ApiClient`. The one pre-existing exception is `_resolve_allowed_domains`, above `verify_request`. Leave it there.
- Error classes end in `Error` and live in `errors.py`.
- Type hints use builtin generics (`dict[str, Any]`, `list[str]`) and `X | None` unions. `Optional` remains only for the quoted forward references in `config.py`. ruff `UP` `target-version` is kept equal to the `pyproject.toml` Python floor.

## Errors

Every error subclasses `BaseAuthError`. A new error category defines its HTTP mapping. A specialization of an existing category (`MissingOrganizationError`, `OrganizationNotAllowedError` under `VerifyAccessTokenError`) inherits it:

```python
class DomainsResolverError(BaseAuthError):
"""Error raised when domains resolver function fails."""

def get_status_code(self) -> int:
return 500

def get_error_code(self) -> str:
return "domains_resolver_error"
```

Wrap third-party failures in a typed error and chain the cause:

```python
# Good (api_client.py, _resolve_allowed_domains)
try:
result = self._allowed_domains(context)
if asyncio.iscoroutine(result) or asyncio.isfuture(result):
result = await result
except Exception as e:
raise DomainsResolverError(
f"Domains resolver function failed: {str(e)}"
) from e
```

Interpolating `str(e)` is acceptable here because the resolver is integrator code. Do not interpolate exception text that can carry token contents or a response body.

```python
# Bad
def get_token(self, options):
client = httpx.Client()
resp = client.post(url, data=options)
if resp.status_code != 200:
print(resp.text)
return None
return resp.json()
```

The snippet has six violations, in order. It is sync and untyped in an async SDK, the client has no `options.timeout`, the OAuth parameters are unfiltered (no `RESERVED_PARAMS` check), it prints a possibly token-bearing body, it returns a `None` a caller can mistake for success, and it lets an unvalidated response into the public API.

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`.

## Patterns

- **Options object:** all configuration goes through `ApiClientOptions`. `ApiClient.__init__` raises `ConfigurationError` or `MissingRequiredArgumentError` at construction for `audience`, the `domain` / `domains` combination, `client_id` without `domain`, the cache settings, `organization_policy` / `organization_id`, `scope_matching`, and `client_info`. Not validated there: `timeout`, `dpop_iat_leeway`, `dpop_iat_offset`, and the format of a single `domain`. A bad entry in a `domains` list raises a plain `ValueError` from `normalize_domain`.
- **Async I/O:** network calls use `httpx.AsyncClient`, or the integrator's `custom_fetch` when provided. Public verification and token methods are `async def`.
- **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`.
- **Token store:**
- **Interfaces.** `AbstractTokenStore` ABC with `get` / `set` / `delete` plus `encrypt` / `decrypt`, separate from `CacheAdapter`. `IndexedTokenStore` adds `add_index_member` / `list_index_members` for `scope_matching="non_strict"`.
- **Encryption helpers.** They are opt-in. The SDK never calls them, so a store encrypts in its own `get` / `set`.
- **Internals.** Cache classes and key builders live in `_internal/` and are not public.
- **Failures.** A store `get` failure is logged and treated as a miss. A `set` failure is logged and the fresh token is still returned. A malformed entry from a custom store can still raise, since `expires_at` reaches `is_fresh` outside the `try` in the client credentials and OBO paths, while the Token Vault cache checks its type first.
- **Docstrings:** Google style with `Args:` / `Returns:` / `Raises:` sections on public methods. `verify_dpop_proof` predates this convention and uses a numbered list instead.
- **Placement:** `api_client.py` has the banner `# ===== Private Methods =====`, and `_internal/obo_cache.py` has a lowercase `# ===== Private methods =====`. In `api_client.py`, new public methods go above the banner after the existing ones, and new helpers below it. In files without a banner, put new code next to related code or at the end, never at an arbitrary position.

## Comments and docstrings

Enforced on every change (code, tests, docs, commit messages):

1. **Comments earn their place.** Only a non-obvious why: a protocol citation (`# RFC 9449`), a security decision, an intentional omission. Never restate the line below. Default to one sharp line or none.
2. **Docstring format.** One-line description, then `Args`, then `Returns` / `Raises`. No design rationale. That belongs in the PR description.
3. **Plain hyphens only.** No em or en dashes in comments, docstrings, commit messages, or Markdown.
4. **No semicolon clause-splicing.** Split independent clauses into separate sentences.
5. **No internal references.** No ticket numbers, planning-doc paths, internal links, or references to other SDKs as a comparison or justification. PR bodies follow the PR template instead, whose References section is where tickets and links go.
6. **Helpers stay grouped.** Never interleave a private helper between public methods.
42 changes: 42 additions & 0 deletions references/commands.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Commands

The install, CI test, and lint commands match `.github/workflows/test.yml` (Poetry and Python versions are set there). `poetry install`, `poetry run pytest`, and `poetry build` also appear in `CONTRIBUTING.md`. The rest are local conveniences that no CI step runs.

```bash
# Install dependencies (CI runs this only on a venv cache miss)
poetry install --no-interaction --no-root
# Install the package (CI runs this every time)
poetry install --no-interaction

# Run all unit tests (CI command)
poetry run pytest -v --cov=src --cov-report=term-missing --cov-report=xml

# Run all unit tests (short form, pyproject addopts already adds --cov=src)
poetry run pytest

# Fast loop without coverage
poetry run pytest --no-cov -q

# Lint (CI-enforced)
poetry run ruff check .

# Auto-fix lint issues (review the diff and keep it scoped to your change)
poetry run ruff check . --fix

# Show formatting state only (not a CI gate, so never apply it repo-wide)
poetry run ruff format --check .

# Build sdist and wheel into dist/
poetry build

# Clean generated artifacts
rm -rf dist/ .coverage coverage.xml .pytest_cache .ruff_cache
find . -path ./.venv\* -prune -o -name __pycache__ -type d -prune -exec rm -rf {} +
```

## Not available here

- **No typecheck command.** mypy/pyright are not in `pyproject.toml` and no CI step runs them.
- **No integration/e2e tier.** The suite runs on `pytest-httpx` mocks, and nothing in `src/`, `tests/`, or CI reads Auth0 tenant credentials.

`publish.yml` (manual `workflow_dispatch`) builds and runs the RL scanner, creates the GitHub release, then builds and publishes to PyPI.
31 changes: 31 additions & 0 deletions references/docs-update.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Docs Update Rules

A PR that changes public API, configuration, or integration patterns is not complete until the matching docs are updated in the same PR.

## Tracked docs

| Doc | Covers | Exists |
|-----|--------|--------|
| `README.md` | Install, `ApiClient` setup, verification, connection tokens, custom token exchange, OBO, client credentials, DPoP modes and options, MCD summary, anonymous callers, organization policy, client telemetry | present |
| `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 |
| `docs/Caching.md` | Cache defaults, TTL/max entries, custom `CacheAdapter`, tuning | present |
| `docs/MultipleCustomDomain.md` | `domains` list and resolver modes, hybrid mode, resolver security requirements, MCD with DPoP, errors, migration | present |
| `docs/TokenStorage.md` | `token_store`, cache key shapes per flow, expiry buffer, implementing `AbstractTokenStore` and `IndexedTokenStore`, at-rest encryption, `scope_matching` | present |
| `docs/OrganizationPolicy.md` | `organization_policy` modes, `organization_id` allowlist, configuration and verification errors, enforcement on token exchange | present |

## When you change code, update these docs

| When this changes | Update |
|-------------------|--------|
| A public `ApiClient` method added, removed, renamed, or its arguments change | `README.md` (relevant numbered section), `EXAMPLES.md` (affected samples) |
| `ApiClientOptions` parameter added, removed, or default changed | `README.md` (setup and the DPoP "Configuration Options" example if DPoP-related), plus `docs/Caching.md` for `cache_*` or `docs/MultipleCustomDomain.md` for `domain` / `domains` |
| `CacheAdapter` interface or `InMemoryCache` behaviour | `docs/Caching.md` ("CacheAdapter API", "Default Behavior") |
| Domain resolver context, MCD validation, or resolver errors | `docs/MultipleCustomDomain.md`, `README.md` section 7 |
| Bearer/DPoP verification behaviour or error codes | `README.md` sections 3 and 6, `EXAMPLES.md` (Bearer, DPoP sections) |
| 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)" |
| `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 |
| `organization_policy` / `organization_id` behaviour or their errors, or when `get_token_on_behalf_of` / `get_access_token_for_connection` verify the incoming token | `docs/OrganizationPolicy.md` (incl. "Token Exchange"), `README.md` section 9 |
| Discovery or JWKS outage handling (`AuthServerUnavailableError`) | `README.md` section 3, `docs/MultipleCustomDomain.md` "Issuer Rejection", `EXAMPLES.md` "Telling an Outage from an Invalid Token" |
| `client_info` or the `Auth0-Client` / `User-Agent` headers (`telemetry.py`) | `README.md` section 10 |
| New exported symbol in `__init__.py` | `EXAMPLES.md` (add a usage sample) |
| Supported Python version or install method | `README.md` "Install the SDK" |
Comment thread
kishore7snehil marked this conversation as resolved.
Resolved
26 changes: 26 additions & 0 deletions references/flow-map.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Flow Map

Before changing a flow, read its entry points and supporting helpers. Public methods are in `ApiClient` (`api_client.py`) above the `# ===== Private Methods =====` banner, and helpers are below it, except `_resolve_allowed_domains`, which sits above `verify_request`.

| Flow | Entry points | Also read | Docs |
|------|--------------|-----------|------|
| Request verification (Bearer + DPoP) | `verify_request` | `verify_access_token`, `verify_dpop_proof`, `_prepare_error`, `_build_www_authenticate`, `errors.py` | `README.md` sections 3 and 6, `EXAMPLES.md` "Bearer Authentication", "DPoP Authentication" |
| Access token verification | `verify_access_token` | `_resolve_allowed_domains`, `_discover`, `_fetch_jwks`, `_validate_claims_presence`, `utils.normalize_domain`, `utils.is_auth_server_outage`, `get_unverified_header` / `get_unverified_payload`, `AuthServerUnavailableError` | `README.md` section 3, `EXAMPLES.md` "Telling an Outage from an Invalid Token" |
| Organization policy | `verify_access_token`, options `organization_policy` / `organization_id` | `ApiClient.__init__` validation, `MissingOrganizationError`, `OrganizationNotAllowedError`. `get_token_on_behalf_of` / `get_access_token_for_connection` apply it only with a `token_store` and no `verified=` | `docs/OrganizationPolicy.md` (incl. "Token Exchange"), `README.md` section 9 |
| DPoP proof verification | `verify_dpop_proof` (checks the proof only, `verify_request` enforces `cnf.jkt`) | `utils.normalize_url_for_htu`, `sha256_base64url`, `calculate_jwk_thumbprint`, options `dpop_enabled` / `dpop_required` / `dpop_iat_leeway` / `dpop_iat_offset` | `README.md` section 6, `EXAMPLES.md` "Direct DPoP Proof Verification" |
| Connection access token (Token Vault) | `get_access_token_for_connection` | `GetAccessTokenForConnectionError`, `ApiError`, `_discover` (token endpoint), `_internal/token_vault_cache.py`, `VerifiedToken` (`verified=`) | `README.md` section 4, `EXAMPLES.md` "Access Token for a Connection (Token Vault)", `docs/TokenStorage.md` |
| Custom token exchange | `get_token_by_exchange_profile` | `_apply_extra`, `RESERVED_PARAMS`, `MAX_ARRAY_VALUES_PER_KEY`, `GetTokenByExchangeProfileError` | `README.md` section 5 |
| On Behalf Of exchange | `get_token_on_behalf_of` | delegates to `get_token_by_exchange_profile`, returns `types.OnBehalfOfTokenResult`, `_internal/obo_cache.py`, `_internal/cache_keys.py`, `VerifiedToken` (`verified=`), option `scope_matching` | `README.md` "On Behalf Of Token Exchange", `EXAMPLES.md` "On Behalf Of Token Exchange", `docs/TokenStorage.md` |
| Client credentials (M2M) | `get_client_credentials_token` | `GetClientCredentialsTokenError`, `ApiError`, `_internal/cache_keys.m2m_cache_key`, `types.ClientCredentialsTokenResult` | `README.md` "Client Credentials for Server-to-Server Calls", `EXAMPLES.md` "Client Credentials for Server-to-Server Calls", `docs/TokenStorage.md` |
| Token store (minted-token caching) | option `token_store` (`AbstractTokenStore`, `IndexedTokenStore`) | `token_store.py`, `encryption.py`, `_internal/cache_expiry.py`, `TokenSet`, `VerifiedToken` | `docs/TokenStorage.md` |
| Delegation inspection | `get_current_actor`, `get_delegation_chain` (`act.py`) | none (`act.py` does not use `types.ActClaim`) | `README.md` / `EXAMPLES.md` "Inspecting Delegation After Token Verification" |
| Multiple Custom Domains | `ApiClientOptions(domains=...)` | `_resolve_allowed_domains`, `utils.normalize_domain`, `types.DomainsResolverContext`, `DomainsResolverError` | `docs/MultipleCustomDomain.md`, `README.md` section 7 |
| Discovery / JWKS caching | `CacheAdapter`, `InMemoryCache` (`cache.py`) | `_discover`, `_fetch_jwks`, `utils.parse_cache_control_max_age` | `docs/Caching.md` |
| Anonymous callers | no dedicated code, verified like any token | `act.py` is unrelated, `sub` starts with `anon@` | `README.md` section 8, `EXAMPLES.md` "Anonymous Callers" |
Comment thread
kishore7snehil marked this conversation as resolved.
Resolved
| Client telemetry | option `client_info` | `telemetry.py` (`build_telemetry_headers`, `validate_client_info`), `ApiClient.__init__` (raises `ConfigurationError` on an invalid `client_info`, sets `_telemetry_headers`), `headers=` on `fetch_oidc_metadata` / `fetch_jwks` and the token endpoint calls. `custom_fetch` receives no headers | `README.md` section 10 |

Tests: `tests/test_api_client.py` covers every `ApiClient` flow, `tests/test_act.py` the delegation helpers, `tests/test_cache.py` the cache, `tests/test_utils.py` the utils, `tests/test_token_store.py` the token store, encryption, and cache keys, and `tests/test_telemetry.py` the telemetry headers.

With a `token_store`, `get_token_on_behalf_of` and `get_access_token_for_connection` call `verify_access_token` without `request_url` or `request_headers` when `verified=` is omitted, so a dynamic MCD resolver receives `None` for both. Pass `verified=` from a prior `verify_request` or `verify_access_token` call in that case.

Two rules cut across every flow: never fetch from a token-derived host unless it passed the allowlist (single-domain mode only fetches the configured `domain`), and in new code fail closed with a typed error on every failure path. A cold-cache discovery outage in the token methods raises a raw `httpx` error.
41 changes: 41 additions & 0 deletions references/git-workflow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Git Workflow

## Branch naming

Merged PR branches mostly use `feat/<topic>`, `fix/<topic>`, `docs/<topic>`, `chore/<topic>`, `ci/<topic>`, or `release/<version>` (e.g. `release/1.0.0b10`). A few have no prefix or a one-off prefix such as `feature/` or `temp/`. Dependabot opens `dependabot/...` branches. Base branch is `main`.

## Commit messages

Conventional Commits prefixes (`feat:`, `fix:`, `docs:`, `chore:`, `refactor:`) with an optional scope such as `fix(token-vault):`, lowercase subject, no trailing period. Example: `docs: add 403 guidance for anonymous caller blocking in EXAMPLES.md`. No commit linter is configured. Older commits do not all follow this, so match the prefix style for new work.

## Pull requests

`.github/PULL_REQUEST_TEMPLATE.md` sections:

- **Changes:** what and why, endpoints and classes/methods added, deleted, deprecated, or changed, screenshots of UI changes, a usage summary for public API changes, and alternative designs considered
- **References:** supporting links (tickets, community posts)
- **Testing:** how to test, with checkboxes for unit coverage, integration coverage, and latest-platform testing
- **Checklist:** Auth0 contribution guidelines, Code of Conduct, all tests passing

The template asks for the classes and methods added, deleted, deprecated, or changed, so build that list from the diff of the public surface (`__init__.py` `__all__`, `ApiClient` public methods, `ApiClientOptions`, `errors.py`).

## CI workflows

From `.github/workflows/`.

- **Build and Test** (`test.yml`): `pytest` + `ruff check .` across the Python version matrix in that workflow, on PR, merge group, and push to `main`
- **CodeQL** (`codeql.yml`): on PR, merge group, push to `main`, and a weekly schedule
- **SCA** (`sca_scan.yml`): Snyk against `requirements.txt`, with suppressions in `.snyk`. Runs on push to `main` or `master` only, so it does not run on a PR
- **Claude Code PR Review** (`claude-code-review.yml`): on issue comments, PR review comments, and submitted reviews

`ruff format` is not a check. Reformatting untouched files adds unrelated changes to the diff.

## Releases

- **Version source.** `.version` is the source. `.shiprc` keeps `pyproject.toml` in step with it.
- **Who cuts a release.** `publish.yml` (manual dispatch, gated on the RL scan), not an agent editing version files.
- **What one `publish.yml` run does.**
- Takes the release notes from the `release/<version>` PR body.
- Creates the GitHub release and its tag.
- Builds and publishes to PyPI.
- **`CHANGELOG.md`.** Nothing in `.github/workflows/`, `.github/actions/`, or `.shiprc` writes it. Release PRs change it together with the version files.
Loading