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
7 changes: 1 addition & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,8 @@ jobs:
- name: Security lint (bandit)
run: bandit -c pyproject.toml -r .

# PYSEC-2026-1325 (ecdsa) has no fix version — it is ecdsa's documented
# lack of side-channel resistance, reachable only for ES* JWT algorithms,
# and this service signs RS256. CVE-2026-85394 (python-jose) has no fix
# version and needs HS256 to be accepted; the only jwt.decode call pins
# algorithms=[RS256]. Rationale in full in scripts/audit.sh.
- name: Known CVEs (pip-audit)
run: pip-audit -r requirements.txt --ignore-vuln PYSEC-2026-1325 --ignore-vuln CVE-2026-85394
run: pip-audit -r requirements.txt

- name: Dead code (vulture)
run: vulture . --config pyproject.toml
Expand Down
367 changes: 184 additions & 183 deletions CASCADE-app/package-lock.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions CASCADE-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"lucide-react": "^1.17.0",
"maplibre-gl": "^6.4.1",
"nanoid": "^6.0.1",
"next": "^16.2.6",
"next": "^16.4.0",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"tailwind-merge": "^3.6.0",
Expand All @@ -49,7 +49,7 @@
"@types/react-dom": "^19",
"autoprefixer": "^10.5.0",
"eslint": "^9.39.4",
"eslint-config-next": "^16.2.10",
"eslint-config-next": "^16.4.0",
"graphology-types": "^0.24.8",
"knip": "^6.24.0",
"madge": "^8.0.0",
Expand Down
3 changes: 2 additions & 1 deletion CASCADE-app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
"node_modules",
".next/dev/types/validator.ts"
]
}
2 changes: 1 addition & 1 deletion CASCADE-backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ OIDC_SCOPES=openid email profile
# JWT validation
# ---------------------------------------------------------------------------

JWT_ALGORITHM=RS256 # RS256 (asymmetric, recommended) or HS256
JWT_ALGORITHM=RS256 # RS256, RS384 or RS512 (asymmetric only)
JWT_AUDIENCE=cascade-api # must match the "aud" claim in the token

# NOTE: there is deliberately no rate-limiting setting yet — nothing enforces
Expand Down
52 changes: 35 additions & 17 deletions CASCADE-backend/auth/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from typing import Any, Optional

import httpx
from jose import jwt
import jwt

from config import get_settings

Expand Down Expand Up @@ -68,21 +68,29 @@ async def fetch_jwks(force: bool = False) -> dict[str, Any]:

def _jwks_has_kid(jwks: dict[str, Any], kid: Optional[str]) -> bool:
if kid is None:
# No kid in the token header — let jose try every cached key.
# No kid in the token header — every cached key is tried.
return True
return any(k.get("kid") == kid for k in jwks.get("keys", []))


def _candidate_keys(jwks: dict[str, Any], kid: Optional[str]) -> list[jwt.PyJWK]:
"""The JWKS keys that may have signed a token with this `kid`: the matching
one, or every signing key when the header names none. Keys PyJWT cannot use
(another key type, a missing algorithm backend) are skipped."""
keys = jwt.PyJWKSet.from_dict(jwks).keys if jwks.get("keys") else []
return [k for k in keys if kid is None or k.key_id == kid]


async def _decode_verified(token: str, audience: Optional[str]) -> dict[str, Any]:
"""Signature-, audience-, and issuer-verify a JWT and return its claims.

Shared by verify_token (access token) and verify_id_token (id token); the
two differ only in expected audience. Raises jose.JWTError / ValueError on
two differ only in expected audience. Raises jwt.PyJWTError / ValueError on
an invalid, expired, wrong-audience, or wrong-issuer token.
"""
if not audience:
# No configured audience means jose would skip the aud check; fail
# closed rather than accept a token minted for any other client.
# No configured audience would skip the aud check; fail closed rather
# than accept a token minted for any other client.
raise ValueError("No audience configured; cannot verify token.")

kid = jwt.get_unverified_header(token).get("kid")
Expand All @@ -94,19 +102,29 @@ async def _decode_verified(token: str, audience: Optional[str]) -> dict[str, Any

issuer = (await fetch_oidc_config()).get("issuer")
if not issuer:
# jose treats issuer=None as "do not validate iss"; fail closed instead
# of silently dropping the issuer binding this function intends to enforce.
# An issuer of None would skip the iss check; fail closed instead of
# silently dropping the issuer binding this function intends to enforce.
raise ValueError("OIDC discovery document has no issuer; cannot verify token.")

settings = get_settings()
return jwt.decode(
token,
jwks,
algorithms=[settings.jwt_algorithm],
audience=audience,
issuer=issuer,
options={"verify_at_hash": False},
)
candidates = _candidate_keys(jwks, kid)
if not candidates:
raise jwt.InvalidKeyError(f"No signing key in the JWKS for kid={kid}.")
last: jwt.PyJWTError = jwt.InvalidSignatureError("No key verified the signature.")
for key in candidates:
try:
# `algorithms` is the only accepted list: an HS256 token is refused
# before any key is used, which is what blocks algorithm confusion.
return jwt.decode(
token,
key=key,
algorithms=[settings.jwt_algorithm],
audience=audience,
issuer=issuer,
)
except jwt.InvalidSignatureError as exc: # another key may have signed it
last = exc
raise last


async def verify_token(token: str) -> dict[str, Any]:
Expand All @@ -121,7 +139,7 @@ async def verify_token(token: str) -> dict[str, Any]:
(called from the /callback exchange).

Returns a synthetic admin claim set when auth is disabled (local-only mode).
Raises jose.JWTError / ValueError on invalid or expired tokens.
Raises jwt.PyJWTError / ValueError on invalid or expired tokens.
"""
settings = get_settings()
if not settings.auth_enabled:
Expand Down Expand Up @@ -164,7 +182,7 @@ async def verify_id_token(id_token: str) -> dict[str, Any]:
control. The claim can arrive as a JSON boolean or the string "false"
(Zitadel encodes it as a string), so both are caught. Raises
EmailNotVerifiedError for that one user-actionable case, and
jose.JWTError / ValueError for an otherwise invalid token or missing config.
jwt.PyJWTError / ValueError for an otherwise invalid token or missing config.
"""
settings = get_settings()
claims = await _decode_verified(id_token, settings.oidc_client_id)
Expand Down
4 changes: 3 additions & 1 deletion CASCADE-backend/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ class Settings(BaseSettings):
# cannot be refreshed and dies on access-token expiry, forcing a full
# re-login. Zitadel honours it when the app has the refresh-token grant.
oidc_scopes: str = "openid profile email offline_access"
jwt_algorithm: str = "RS256"
# Only asymmetric algorithms: an HS* algorithm verified against the IdP's
# public keys would let anyone holding those keys forge tokens.
jwt_algorithm: Literal["RS256", "RS384", "RS512"] = "RS256"
jwt_audience: Optional[str] = None
# Zitadel IdP id for the "Continue with Google" shortcut. When set, the app
# advertises the button (GET /api/auth/config) and GET /api/auth/login?idp=google
Expand Down
2 changes: 1 addition & 1 deletion CASCADE-backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ psycopg2-binary==2.9.12 # sync driver — used only in scripts/ and migrati
# Authentication (OAuth2 / OIDC + JWT)
# ---------------------------------------------------------------------------

python-jose[cryptography]==3.5.0 # JWT encode/decode; [cryptography] adds RS256
PyJWT[crypto]==2.15.1 # JWT verify against the IdP's JWKS; [crypto] adds RS256
httpx==0.28.1 # async HTTP — fetches OIDC discovery documents

# ---------------------------------------------------------------------------
Expand Down
14 changes: 1 addition & 13 deletions CASCADE-backend/scripts/audit.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,7 @@ echo "── bandit (security) ────────────────
bandit -c pyproject.toml -r .

echo "── pip-audit (known CVEs) ───────────────────────────"
# PYSEC-2026-1325 (ecdsa): NO fix version exists — it is ecdsa's documented lack
# of side-channel resistance, not a defect an upgrade closes. ecdsa arrives only
# as a transitive dep of python-jose ("ecdsa!=0.15") and is reachable only for
# ES* JWT algorithms; this service signs with RS256 (config.py::jwt_algorithm),
# which python-jose routes through the `cryptography` backend instead. Re-check
# this exception if jwt_algorithm ever moves to an ES* curve.
# CVE-2026-85394 (python-jose, alias CVE-2024-33663): NO fix version exists (3.5.0
# is the latest release). It is an algorithm-confusion forgery of HS256 tokens
# using the public key as the HMAC secret, and only works when the verifier does
# not restrict the accepted algorithms. auth/oauth2.py::decode passes
# `algorithms=[settings.jwt_algorithm]` (RS256) on the only jwt.decode call, so an
# HS256 token is rejected before any key is tried. Re-check if that call changes.
pip-audit -r requirements.txt --ignore-vuln PYSEC-2026-1325 --ignore-vuln CVE-2026-85394
pip-audit -r requirements.txt

echo "── vulture (dead code) ──────────────────────────────"
vulture . --config pyproject.toml
Expand Down
13 changes: 13 additions & 0 deletions CASCADE-backend/test/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,16 @@ def test_development_without_auth_is_local_only_mode(monkeypatch: pytest.MonkeyP
assert settings.auth_enabled is False
assert settings.is_dev is True
assert_production_safe(settings) # dev mode never raises


@pytest.mark.parametrize("algorithm", ["HS256", "HS512", "none"])
def test_jwt_algorithm_refuses_symmetric(monkeypatch: pytest.MonkeyPatch, algorithm: str) -> None:
"""HS* verified against the IdP's public keys lets a key holder forge tokens; only RS* is accepted."""
monkeypatch.setenv("JWT_ALGORITHM", algorithm)
with pytest.raises(ValidationError):
Settings()


def test_jwt_algorithm_accepts_rs(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("JWT_ALGORITHM", "RS384")
assert Settings().jwt_algorithm == "RS384"
114 changes: 114 additions & 0 deletions CASCADE-backend/test/test_jwt_verification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""auth/oauth2.py verifying real signed tokens against a JWKS (PyJWT)."""
from __future__ import annotations

import base64
import hashlib
import hmac
import json
import time
from typing import Any

import jwt
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa

import config
from auth import oauth2

ISSUER = "https://id.example"
CLIENT = "cascade-app"


def _key(kid: str) -> tuple[Any, dict[str, Any]]:
private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_jwk = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(private.public_key()))
return private, {**public_jwk, "kid": kid, "use": "sig", "alg": "RS256"}


KEY_A, JWK_A = _key("a")
KEY_B, JWK_B = _key("b")


def _token(private: Any, kid: str | None = "a", **claims: Any) -> str:
now = int(time.time())
body = {"iss": ISSUER, "aud": CLIENT, "sub": "user-1", "iat": now, "exp": now + 300, **claims}
headers = {"kid": kid} if kid else {}
return jwt.encode(body, private, algorithm="RS256", headers=headers)


@pytest.fixture
def idp(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
"""An IdP whose JWKS holds key `a`; `state["jwks"]` changes what the next fetch returns."""
state: dict[str, Any] = {"jwks": {"keys": [JWK_A]}, "fetches": 0}

async def fetch_jwks(force: bool = False) -> dict[str, Any]:
state["fetches"] += 1
return state["jwks"]

async def fetch_oidc_config() -> dict[str, Any]:
return {"issuer": ISSUER}

settings = config.get_settings().model_copy(
update={"oidc_discovery_url": f"{ISSUER}/.well-known/openid-configuration", "oidc_client_id": CLIENT}
)
monkeypatch.setattr(oauth2, "fetch_jwks", fetch_jwks)
monkeypatch.setattr(oauth2, "fetch_oidc_config", fetch_oidc_config)
monkeypatch.setattr(oauth2, "get_settings", lambda: settings)
return state


async def test_a_valid_token_returns_its_claims(idp: dict[str, Any]) -> None:
claims = await oauth2.verify_token(_token(KEY_A))
assert claims["sub"] == "user-1"


async def test_a_token_without_kid_is_tried_against_every_key(idp: dict[str, Any]) -> None:
idp["jwks"] = {"keys": [JWK_B, JWK_A]}
assert (await oauth2.verify_token(_token(KEY_A, kid=None)))["sub"] == "user-1"


@pytest.mark.parametrize(
"claims",
[{"aud": "another-client"}, {"iss": "https://evil.example"}, {"exp": int(time.time()) - 10}],
ids=["audience", "issuer", "expired"],
)
async def test_a_wrong_audience_issuer_or_expiry_is_refused(idp: dict[str, Any], claims: dict[str, Any]) -> None:
with pytest.raises(jwt.PyJWTError):
await oauth2.verify_token(_token(KEY_A, **claims))


async def test_a_token_signed_by_another_key_is_refused(idp: dict[str, Any]) -> None:
with pytest.raises(jwt.PyJWTError):
await oauth2.verify_token(_token(KEY_B, kid="a"))


async def test_hs256_signed_with_the_public_key_is_refused(idp: dict[str, Any]) -> None:
"""Algorithm confusion (CVE-2026-85394 in python-jose): the public key as an HMAC secret."""
pem = KEY_A.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
der = KEY_A.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)

def b64(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()

now = int(time.time())
header = b64(json.dumps({"alg": "HS256", "typ": "JWT", "kid": "a"}).encode())
body = b64(json.dumps({"iss": ISSUER, "aud": CLIENT, "sub": "attacker", "exp": now + 300}).encode())
for secret in (pem, der):
signature = b64(hmac.new(secret, f"{header}.{body}".encode(), hashlib.sha256).digest())
with pytest.raises(jwt.PyJWTError):
await oauth2.verify_token(f"{header}.{body}.{signature}")


async def test_an_unknown_kid_refetches_the_jwks_once(idp: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None:
"""The IdP rotated its keys: the first fetch lacks `b`, the refetch has it."""
rotated = {"keys": [JWK_A, JWK_B]}
calls: list[bool] = []

async def fetch_jwks(force: bool = False) -> dict[str, Any]:
calls.append(force)
return rotated if force else {"keys": [JWK_A]}

monkeypatch.setattr(oauth2, "fetch_jwks", fetch_jwks)
assert (await oauth2.verify_token(_token(KEY_B, kid="b")))["sub"] == "user-1"
assert calls == [False, True]
Loading