Buckets:

download
raw
25.1 kB
# Copyright 2026 Terrene Foundation
# SPDX-License-Identifier: Apache-2.0
"""JWT validation and token creation -- framework-agnostic.
Extracted from ``nexus.auth.jwt`` (SPEC-06). Provides stateless JWT validation
and creation that works independently of any HTTP framework.
The ``JWTValidator`` class handles:
- Multi-algorithm verification (HS256, RS256, ES256, etc.)
- Algorithm confusion attack prevention
- JWK/JWKS support for SSO providers
- Token creation (access + refresh)
- Normalized user extraction from claims
The Starlette/FastAPI ``JWTMiddleware`` remains in Nexus and delegates
to ``JWTValidator`` for the actual crypto work.
"""
from __future__ import annotations
import logging
import math
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Dict, List, Optional, Union
try:
import jwt
except ImportError as _jwt_import_error: # pragma: no cover — optional extra
raise ImportError(
"kailash.trust.auth.jwt requires PyJWT. "
"Install with: pip install 'kailash[trust]'"
) from _jwt_import_error
from kailash.trust.auth.exceptions import ExpiredTokenError, InvalidTokenError
from kailash.trust.auth.models import AuthenticatedUser
logger = logging.getLogger(__name__)
# Supported algorithm sets
_SYMMETRIC_ALGORITHMS = {"HS256", "HS384", "HS512"}
_ASYMMETRIC_ALGORITHMS = {"RS256", "RS384", "RS512", "ES256", "ES384", "ES512"}
__all__ = [
"JWTConfig",
"JWTValidator",
"subject_from_claims",
]
def subject_from_claims(claims: Dict[str, Any]) -> Optional[str]:
"""The subject identifier a set of verified JWT claims names, or ``None``.
THE one place the claim precedence for "who is this token about" is
written. ``sub`` is the RFC 7519 §4.1.2 registered claim and wins; the two
fallbacks are the spellings this SDK's own issuers and common external
providers emit.
Extracted from :meth:`JWTValidator.create_user_from_payload`, which now
calls it, because a SECOND caller appeared:
:class:`~kailash.middleware.communication.api_gateway.APIGateway` verifies
a bearer token directly on the deployments where no gate middleware is
installed, and needs the same answer. Two copies of a precedence rule is
how one of them silently starts disagreeing -- the gateway's own first
attempt read ``payload.get("user_id")`` alone, which is ``None`` for every
token this SDK mints, so the identity it derived was always empty
(``security.md`` § Credential Decode Helpers: one shared helper, never
per-site copies).
Args:
claims: A decoded, ALREADY-VERIFIED JWT payload. This function performs
no verification of any kind and must never be handed the output of
an unverified decode.
Returns:
The subject as a non-empty ``str``, or ``None`` when no claim carries
one.
An integer subject is accepted and rendered -- RFC 7519 calls for a
StringOrURI, but numeric ``sub`` claims are common enough in the wild
that refusing them here would start rejecting tokens this SDK accepted
before the extraction. ``bool`` is excluded explicitly despite being an
``int`` subclass, because ``"True"`` is not an identity. Every other
type -- a nested object, a list, ``None`` -- returns ``None`` rather
than being coerced: ``str()`` of a dict would manufacture a principal
that never existed.
"""
for claim in ("sub", "user_id", "uid"):
if claim not in claims:
continue
value = claims[claim]
if isinstance(value, str) and value:
return value
if isinstance(value, int) and not isinstance(value, bool):
return str(value)
# PRESENT but wrong-shape -> hard None, never fall through.
#
# Falling through let a malformed registered claim be OVERRIDDEN by a
# lower-precedence one: `{"sub": "", "user_id": "mallory"}` resolved to
# `"mallory"`. `sub` is the RFC 7519 registered claim and the one an
# issuer controls; `user_id`/`uid` are the accommodation spellings and
# are NOT in the minter's reserved-claim guard, so a caller who can
# influence extra claims but not `sub` could be promoted by the
# fallback. Latent today (no in-tree caller forwards untrusted kwargs
# into the minter) and closed here rather than left to become
# reachable (`security.md` § Secure-Default: fail closed).
return None
return None
@dataclass
class JWTConfig:
"""JWT validation configuration.
Attributes:
secret: Secret key for HS* algorithms
algorithm: JWT algorithm (HS256, RS256, ES256, etc.)
public_key: Public key for RS*/ES* algorithms
private_key: Private key for token signing (optional)
issuer: Expected token issuer (optional)
audience: Expected token audience (optional)
token_header: Header name for Bearer token (default: Authorization)
token_cookie: Cookie name for token (optional)
token_query_param: Query parameter for token (optional)
exempt_paths: Paths exempt from authentication
jwks_url: URL for JWKS endpoint (for SSO providers)
jwks_cache_ttl: JWKS cache TTL in seconds (default: 3600)
verify_exp: Verify token expiration (default: True)
leeway: Leeway in seconds for exp/nbf claims (default: 0)
api_key_header: Header name for API key auth (default: X-API-Key)
api_key_enabled: Enable API key authentication (default: False)
api_key_validator: Caller-supplied callable invoked to authenticate
an API key presented in the ``api_key_header``. Signature is
``(api_key: str) -> bool | dict`` (an awaitable is also accepted);
return a falsey value to reject, ``True`` to accept, or a claims
dict to accept and populate the authenticated user.
SECURITY -- the validator MUST compare the presented key against
the stored/expected key in **constant time** using
``secrets.compare_digest`` (or ``hmac.compare_digest``), NOT the
``==`` operator. A plain ``==`` (or ``!=``) comparison
short-circuits on the first differing byte, leaking key-prefix
length under a remote-timing oracle and letting an attacker
recover the key one byte at a time. The SDK delegates the
comparison to this callable and cannot enforce it; the caller is
responsible for using a constant-time comparison::
import secrets
STORED_API_KEY = os.environ["SERVICE_API_KEY"]
def validate(api_key: str) -> bool:
# constant-time: does NOT short-circuit on first
# differing byte (unlike ``api_key == STORED_API_KEY``)
return secrets.compare_digest(api_key, STORED_API_KEY)
config = JWTConfig(
secret="your-secret-key-at-least-32-chars!",
api_key_enabled=True,
api_key_validator=validate,
)
``secrets.compare_digest`` is also length-safe: it does not
reveal, via timing, whether the presented key matched the
expected length.
max_token_age_seconds: Absolute token age cap independent of the
``exp`` claim (optional)
on_token_validated: Post-validation hook for stale detection / audit
(optional)
"""
secret: Optional[str] = None
algorithm: str = "HS256"
public_key: Optional[str] = None
private_key: Optional[str] = None
issuer: Optional[str] = None
audience: Optional[Union[str, List[str]]] = None
token_header: str = "Authorization"
token_cookie: Optional[str] = None
token_query_param: Optional[str] = None
exempt_paths: List[str] = field(
default_factory=lambda: [
"/health",
"/metrics",
"/docs",
"/openapi.json",
"/redoc",
"/auth/login",
"/auth/refresh",
"/auth/sso/*",
]
)
jwks_url: Optional[str] = None
jwks_cache_ttl: int = 3600
verify_exp: bool = True
leeway: int = 0
# API key authentication
api_key_header: str = "X-API-Key"
api_key_enabled: bool = False
api_key_validator: Optional[Callable[[str], Any]] = None
# Absolute token age check (independent of exp claim)
max_token_age_seconds: Optional[int] = None
# Post-validation hook for stale detection / audit
on_token_validated: Optional[Callable[[Dict[str, Any]], Any]] = None
# Minimum secret length for symmetric algorithms (NIST SP 800-117 recommends
# key length >= hash output size: 256 bits = 32 bytes for HS256)
MIN_SECRET_LENGTH: int = 32
def __post_init__(self) -> None:
"""Validate configuration after initialization."""
if self.algorithm in _SYMMETRIC_ALGORITHMS:
if not self.secret:
raise ValueError(f"{self.algorithm} requires secret key")
if len(self.secret) < self.MIN_SECRET_LENGTH:
raise ValueError(
f"JWT secret must be at least {self.MIN_SECRET_LENGTH} characters "
f"for {self.algorithm} (got {len(self.secret)}). "
f"Short secrets are vulnerable to brute-force attacks."
)
elif self.algorithm in _ASYMMETRIC_ALGORITHMS:
if not self.public_key and not self.jwks_url:
raise ValueError(f"{self.algorithm} requires public_key or jwks_url")
class JWTValidator:
"""Stateless JWT token verification and creation.
Framework-agnostic JWT processor that handles token verification,
user extraction, and token creation. HTTP middleware (e.g., Nexus
JWTMiddleware) delegates to this class for the actual crypto work.
Usage:
>>> config = JWTConfig(secret="your-secret-key-at-least-32-chars!")
>>> validator = JWTValidator(config)
>>> payload = validator.verify_token(token_string)
>>> user = validator.create_user_from_payload(payload)
"""
def __init__(self, config: JWTConfig):
"""Initialize JWT validator.
Args:
config: JWTConfig instance
"""
self.config = config
# Initialize JWKS client if URL provided
self._jwks_client = None
if self.config.jwks_url:
try:
from jwt import PyJWKClient
self._jwks_client = PyJWKClient(
self.config.jwks_url,
cache_keys=True,
lifespan=self.config.jwks_cache_ttl,
)
except ImportError:
logger.warning(
"PyJWKClient not available. Install pyjwt[crypto] for JWKS support."
)
logger.info("JWTValidator initialized with algorithm=%s", self.config.algorithm)
def is_path_exempt(self, path: str) -> bool:
"""Check if path is exempt from authentication.
Supports exact matching and wildcard patterns (e.g., /auth/sso/*).
"""
for exempt_path in self.config.exempt_paths:
if exempt_path.endswith("/*"):
prefix = exempt_path[:-1] # Remove *
base = exempt_path[:-2] # Remove /*
if path == base or path.startswith(prefix):
return True
elif path == exempt_path:
return True
return False
def verify_token(self, token: str) -> Dict[str, Any]:
"""Verify and decode JWT token.
Includes algorithm confusion attack prevention.
Args:
token: JWT token string
Returns:
Decoded token payload
Raises:
ExpiredTokenError: Token has expired
InvalidTokenError: Token is invalid
"""
try:
# SECURITY: Prevent algorithm confusion attacks
try:
unverified_header = jwt.get_unverified_header(token)
except jwt.exceptions.DecodeError as e:
logger.debug("Malformed token header: %s", e)
raise InvalidTokenError("Malformed token")
token_alg = unverified_header.get("alg", "").lower()
# Explicitly reject 'none' algorithm
if token_alg == "none":
raise InvalidTokenError(
"Algorithm 'none' is not permitted - possible attack attempt"
)
# Verify algorithm matches configuration
if token_alg != self.config.algorithm.lower():
# SECURITY: Don't reveal configured algorithm to potential attacker
logger.warning(
"Algorithm mismatch: token=%s, configured=%s",
unverified_header.get("alg"),
self.config.algorithm,
)
raise InvalidTokenError("Token algorithm mismatch")
# Determine verification key
if self._jwks_client:
signing_key = self._jwks_client.get_signing_key_from_jwt(token)
key = signing_key.key
elif self.config.algorithm in _SYMMETRIC_ALGORITHMS:
key = self.config.secret
else:
key = self.config.public_key
# Build verification options.
# SECURITY (#635, cross-SDK companion to #625): when an issuer is
# configured, the iss claim MUST be present. PyJWT's verify_iss
# only enforces value-equality WHEN the claim is present — a token
# forged without iss is silently accepted otherwise. Layering
# `require: ["iss"]` forces presence and closes the bypass.
options: Dict[str, Any] = {
"verify_exp": self.config.verify_exp,
"verify_iss": self.config.issuer is not None,
"verify_aud": self.config.audience is not None,
}
require_claims: List[str] = []
if self.config.issuer is not None:
require_claims.append("iss")
if self.config.audience is not None:
require_claims.append("aud")
if require_claims:
options["require"] = require_claims
# Decode and verify
payload = jwt.decode(
token,
key,
algorithms=[self.config.algorithm],
issuer=self.config.issuer,
audience=self.config.audience,
leeway=self.config.leeway,
options=options, # type: ignore[arg-type] # PyJWT Options TypedDict
)
# SECURITY: Reject refresh tokens used as access tokens
token_type = payload.get("token_type")
if token_type == "refresh":
raise InvalidTokenError(
"Refresh tokens cannot be used for API authentication"
)
return payload
except ExpiredTokenError:
raise
except InvalidTokenError:
raise
except jwt.ExpiredSignatureError:
raise ExpiredTokenError("Token has expired")
except jwt.InvalidAudienceError:
raise InvalidTokenError("Invalid token audience")
except jwt.InvalidIssuerError:
raise InvalidTokenError("Invalid token issuer")
except jwt.InvalidTokenError as e:
logger.debug("JWT decode error: %s", e)
raise InvalidTokenError("Invalid token")
def check_token_age(self, payload: Dict[str, Any]) -> Optional[str]:
"""Check absolute token age if max_token_age_seconds is configured.
Args:
payload: Decoded JWT payload
Returns:
None if OK, error string if token is too old or invalid
"""
if self.config.max_token_age_seconds is None:
return None
iat = payload.get("iat")
if iat is None:
return None
iat_float = float(iat)
if not math.isfinite(iat_float):
return "Invalid iat claim"
token_age = int(datetime.now(timezone.utc).timestamp()) - int(iat_float)
if token_age < 0:
return "Token issued in the future"
if token_age > self.config.max_token_age_seconds:
return "Token too old"
return None
def create_user_from_payload(self, payload: Dict[str, Any]) -> AuthenticatedUser:
"""Create AuthenticatedUser from JWT payload.
Normalizes different JWT claim formats into a standard user object.
Args:
payload: Decoded JWT payload
Returns:
AuthenticatedUser instance
Raises:
InvalidTokenError: If required claims are missing
"""
# Extract user_id. The precedence lives in `subject_from_claims` so the
# gateway's direct-verification path cannot drift from this one.
user_id = subject_from_claims(payload)
if not user_id:
raise InvalidTokenError("Token missing user identifier (sub)")
# Extract email
email = payload.get("email") or payload.get("preferred_username")
# Extract roles
roles = payload.get("roles", [])
if isinstance(roles, str):
roles = [roles]
role = payload.get("role")
if role and role not in roles:
roles.append(role)
# Extract permissions
permissions = payload.get("permissions", [])
if isinstance(permissions, str):
permissions = permissions.split()
scope = payload.get("scope", "")
if isinstance(scope, str) and scope:
scope_perms = scope.split()
permissions = list(set(permissions + scope_perms))
# Extract tenant_id
tenant_id = (
payload.get("tenant_id")
or payload.get("tid")
or payload.get("organization_id")
)
# Determine provider
issuer = payload.get("iss", "")
provider = self._determine_provider(issuer)
return AuthenticatedUser(
user_id=user_id,
email=email,
roles=roles,
permissions=permissions,
tenant_id=tenant_id,
provider=provider,
raw_claims=payload,
)
# Mapping of trusted issuer hostnames (and their required subdomains)
# to provider labels. Using a hostname-equality / hostname-suffix match
# against ``urlparse(issuer).hostname`` closes the substring bypass that
# CodeQL's ``py/incomplete-url-substring-sanitization`` flagged — e.g.
# a crafted ``https://evilgithub.com/foo`` or
# ``https://attacker.example/?host=login.microsoftonline.com`` would
# satisfy the old substring test but is NOT a real Microsoft / Google /
# Apple / GitHub issuer. The hostname match below rejects both.
_ISSUER_PROVIDERS = (
("login.microsoftonline.com", "azure"),
("sts.windows.net", "azure"), # legacy Azure v1.0 issuer
("accounts.google.com", "google"),
("appleid.apple.com", "apple"),
("github.com", "github"),
("api.github.com", "github"),
("token.actions.githubusercontent.com", "github"), # GitHub Actions OIDC
)
@staticmethod
def _matches_trusted_host(host: str, trusted: str) -> bool:
"""Return True when host is exactly trusted OR a subdomain of trusted.
A suffix match REQUIRES a leading ``.`` separator, so
``evilgithub.com`` does NOT match ``github.com`` but
``api.github.com`` does.
"""
host = host.lower()
trusted = trusted.lower()
return host == trusted or host.endswith("." + trusted)
def _determine_provider(self, issuer: str) -> str:
"""Determine auth provider from JWT issuer URL.
Parses the issuer as a URL and matches the hostname against a
trusted-host allowlist. A substring match on the raw issuer
string is BLOCKED — ``"github.com" in "https://evilgithub.com/..."``
returns True and silently promotes an attacker-controlled issuer
to ``"github"`` provider trust. See CodeQL rule
``py/incomplete-url-substring-sanitization`` and
``rules/security.md`` § Input Validation.
"""
if not issuer:
return "local"
# Parse the issuer as a URL. If it is not a URL (no scheme /
# netloc), fall through to ``"local"`` — we only grant
# provider trust to issuers whose hostname we can verify.
try:
from urllib.parse import urlparse
parsed = urlparse(issuer)
except (ValueError, AttributeError):
return "local"
host = parsed.hostname
if not host:
return "local"
for trusted, provider in self._ISSUER_PROVIDERS:
if self._matches_trusted_host(host, trusted):
return provider
return "local"
# --- Token Creation Methods ---
def create_access_token(
self,
user_id: str,
email: Optional[str] = None,
roles: Optional[List[str]] = None,
permissions: Optional[List[str]] = None,
tenant_id: Optional[str] = None,
expires_minutes: int = 30,
**extra_claims: Any,
) -> str:
"""Create a new access token.
Args:
user_id: User identifier (becomes 'sub' claim)
email: User email
roles: User roles
permissions: User permissions
tenant_id: Tenant identifier
expires_minutes: Token expiration in minutes
**extra_claims: Additional claims to include
Returns:
Encoded JWT token
"""
now = datetime.now(timezone.utc)
exp = now + timedelta(minutes=expires_minutes)
payload: Dict[str, Any] = {
"sub": user_id,
"iat": int(now.timestamp()),
"exp": int(exp.timestamp()),
"token_type": "access",
}
if email:
payload["email"] = email
if roles:
payload["roles"] = roles
if permissions:
payload["permissions"] = permissions
if tenant_id:
payload["tenant_id"] = tenant_id
if self.config.issuer:
payload["iss"] = self.config.issuer
if self.config.audience:
payload["aud"] = self.config.audience
# SECURITY: Prevent extra_claims from overriding security-critical claims
_reserved = {
"sub",
"iat",
"exp",
"iss",
"aud",
"token_type",
"roles",
"permissions",
"tenant_id",
}
unsafe_overrides = set(extra_claims.keys()) & _reserved
if unsafe_overrides:
logger.warning(
"Ignoring reserved claims in extra_claims: %s",
unsafe_overrides,
)
extra_claims = {k: v for k, v in extra_claims.items() if k not in _reserved}
payload.update(extra_claims)
# Determine signing key
if self.config.algorithm in _SYMMETRIC_ALGORITHMS:
key = self.config.secret
else:
if not self.config.private_key:
raise ValueError(
f"Private key required to sign tokens with {self.config.algorithm}"
)
key = self.config.private_key
return jwt.encode(payload, key, algorithm=self.config.algorithm)
def create_refresh_token(
self,
user_id: str,
tenant_id: Optional[str] = None,
expires_days: int = 7,
) -> str:
"""Create a refresh token.
Args:
user_id: User identifier
tenant_id: Tenant identifier
expires_days: Token expiration in days
Returns:
Encoded JWT refresh token
"""
now = datetime.now(timezone.utc)
exp = now + timedelta(days=expires_days)
payload: Dict[str, Any] = {
"sub": user_id,
"iat": int(now.timestamp()),
"exp": int(exp.timestamp()),
"jti": str(uuid.uuid4()),
"token_type": "refresh",
}
if tenant_id:
payload["tenant_id"] = tenant_id
if self.config.issuer:
payload["iss"] = self.config.issuer
# Determine signing key
if self.config.algorithm in _SYMMETRIC_ALGORITHMS:
key = self.config.secret
else:
if not self.config.private_key:
raise ValueError("Private key required for refresh token")
key = self.config.private_key
return jwt.encode(payload, key, algorithm=self.config.algorithm)

Xet Storage Details

Size:
25.1 kB
·
Xet hash:
9ce3909308c740327e6015e292c486b2d652bc0274fe9b73f636e3450bc4a7b2

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.