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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ async def main():
connection = "my-connection" # The Auth0 connection to the upstream idp
access_token = "..." # The Auth0 access token to exchange

await api_client.verify_access_token(access_token) # Verify first so the organization policy applies
connection_access_token = await api_client.get_access_token_for_connection({"connection": connection, "access_token": access_token})
# The returned token is the access token for the upstream idp
print(connection_access_token)
Expand Down
4 changes: 4 additions & 0 deletions docs/OrganizationPolicy.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ api_client = ApiClient(ApiClientOptions(

`organization_id` compares the opaque `org_id` claim value directly (string comparison, no network call). It does not accept or resolve the human-readable Organization name. It must be a non-empty string or a non-empty list of non-empty strings, otherwise `ConfigurationError` is raised at construction.

## Token Exchange

The policy is enforced when a token is verified. `get_token_on_behalf_of()` and `get_access_token_for_connection()` verify the incoming token, and so apply the policy, only when a `token_store` is configured and `verified` is not passed. Without a store, they send the token straight to Auth0 for the exchange and do not check `org_id`. Call `verify_access_token()` first at your API boundary, as in the examples above, so the policy applies before any exchange.

## Error Handling

### Configuration Errors
Expand Down
7 changes: 4 additions & 3 deletions docs/TokenStorage.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ api_client = ApiClient(ApiClientOptions(
))
```

An index member holds a hashed `token_key`, the granted scopes, and an expiry, never a bearer
token, so it is not encrypted. The tokens themselves stay encrypted under their own keys as
described above.
An index member holds a `token_key`, the granted scopes, and an expiry, never a bearer token, so
it is not encrypted. The `token_key` is the caller's `sub` in plain text followed by a hash, so
anyone who can read the store can see which callers have entries. The tokens themselves stay
encrypted under their own keys as described above.
3 changes: 0 additions & 3 deletions src/auth0_api_python/_internal/cache_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ def session_fingerprint(access_token: str) -> str:
except ValueError:
return hashlib.sha256(access_token.encode()).hexdigest()

if not isinstance(payload, dict):
return hashlib.sha256(access_token.encode()).hexdigest()

sid = payload.get("sid")
if isinstance(sid, str) and sid:
return sid
Expand Down
27 changes: 23 additions & 4 deletions src/auth0_api_python/api_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import logging
import math
import time
from collections.abc import Mapping, Sequence
from typing import Any, Optional, Union
Expand Down Expand Up @@ -508,6 +509,8 @@ async def verify_access_token(

# Reject symmetric algorithms
alg = header.get('alg', '')
if not isinstance(alg, str):
raise VerifyAccessTokenError("Token header 'alg' must be a string")
if alg.startswith('HS'):
raise VerifyAccessTokenError(
f"Symmetric algorithm '{alg}' is not supported. "
Expand Down Expand Up @@ -675,7 +678,10 @@ async def verify_dpop_proof(
if not http_method or not http_url:
raise MissingRequiredArgumentError("http_method/http_url")

header = get_unverified_header(proof)
try:
header = get_unverified_header(proof)
except Exception:
raise InvalidDpopProofError("Failed to parse DPoP proof header")

if header.get("typ") != "dpop+jwt":
raise InvalidDpopProofError("Unexpected JWT 'typ' header parameter value")
Expand All @@ -697,7 +703,11 @@ async def verify_dpop_proof(
if jwk_dict.get("crv") != "P-256":
raise InvalidDpopProofError("Only P-256 curve is supported")

public_key = JsonWebKey.import_key(jwk_dict)
try:
public_key = JsonWebKey.import_key(jwk_dict)
except Exception:
raise InvalidDpopProofError("Missing or invalid jwk in header")

try:
claims = self._dpop_jwt.decode(proof, public_key)
except Exception as e:
Expand All @@ -720,14 +730,17 @@ async def verify_dpop_proof(
offset = getattr(self.options, "dpop_iat_offset", 300) # default 5 minutes
leeway = getattr(self.options, "dpop_iat_leeway", 30) # default 30 seconds

if not isinstance(iat, (int, float)):
raise InvalidDpopProofError("Invalid iat claim (must be integer or float)")
if not isinstance(iat, (int, float)) or (isinstance(iat, float) and not math.isfinite(iat)):
raise InvalidDpopProofError("Invalid iat claim (must be a finite number)")

if iat < now - offset:
raise InvalidDpopProofError("DPoP Proof iat is too old")
elif iat > now + leeway:
raise InvalidDpopProofError("DPoP Proof iat is from the future")

if not isinstance(claims["htm"], str):
raise InvalidDpopProofError("htm claim must be a string")

if claims["htm"].lower() != http_method.lower():
raise InvalidDpopProofError("DPoP Proof htm mismatch")

Expand Down Expand Up @@ -871,6 +884,9 @@ async def get_access_token_for_connection(
except (TypeError, ValueError):
raise ApiError("invalid_response", "expires_in is not an integer.", 502)

if expires_in < 0:
raise ApiError("invalid_response", "expires_in cannot be negative.", 502)

result = {
"access_token": access_token,
"expires_in": expires_in,
Expand Down Expand Up @@ -1300,6 +1316,9 @@ async def get_client_credentials_token(
if not isinstance(access_token, str) or not access_token:
raise ApiError("invalid_response", "Missing or invalid access_token in response.", 502)

if expires_in < 0:
raise ApiError("invalid_response", "expires_in cannot be negative.", 502)

cc_result: ClientCredentialsTokenResult = {
"access_token": access_token,
"expires_in": expires_in,
Expand Down
16 changes: 14 additions & 2 deletions src/auth0_api_python/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def _decode_jwt_segment(token: Union[str, bytes], segment_index: int) -> dict:
Decoded segment as dictionary

Raises:
ValueError: If token format is invalid
ValueError: If token format is invalid, or the segment is not a JSON object or is nested too deeply
"""
if isinstance(token, bytes):
token = token.decode("utf-8")
Expand All @@ -181,7 +181,13 @@ def _decode_jwt_segment(token: Union[str, bytes], segment_index: int) -> dict:
segment_b64 = fix_base64_padding(segment_b64)

segment_data = base64.urlsafe_b64decode(segment_b64)
return json.loads(segment_data)
try:
segment = json.loads(segment_data)
except RecursionError:
raise ValueError("Invalid token format: segment is nested too deeply") from None
if not isinstance(segment, dict):
raise ValueError("Invalid token format: segment is not a JSON object")
return segment


def get_unverified_header(token: Union[str, bytes]) -> dict:
Expand All @@ -193,6 +199,9 @@ def get_unverified_header(token: Union[str, bytes]) -> dict:

Returns:
Decoded header as dictionary

Raises:
ValueError: If the token is malformed or its header is not a JSON object or is nested too deeply
"""
return _decode_jwt_segment(token, 0)

Expand All @@ -206,6 +215,9 @@ def get_unverified_payload(token: Union[str, bytes]) -> dict:

Returns:
Decoded payload (claims) as dictionary

Raises:
ValueError: If the token is malformed or its payload is not a JSON object or is nested too deeply
"""
return _decode_jwt_segment(token, 1)

Expand Down
10 changes: 10 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Shared test fixtures and helpers for auth0-api-python tests."""

import base64
import json
import time
import urllib.parse
from typing import Optional
Expand Down Expand Up @@ -98,6 +99,15 @@ def mock_discovery(httpx_mock: HTTPXMock):

# ===== Helper Functions =====

def unsigned_jwt(header, payload) -> str:
"""Build a JWT-shaped string from any JSON values, with a dummy signature."""

def encode(value):
return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip("=")

return f"{encode(header)}.{encode(payload)}.signature"


def last_form(httpx_mock: HTTPXMock) -> dict[str, list[str]]:
"""Helper to read the last posted form data."""
req = httpx_mock.get_requests()[-1]
Expand Down
Loading
Loading