Spaces:
Sleeping
Verify ES256 JWTs via Supabase JWKS (project migrated off HS256)
Browse filesDiagnostic confirmed (via /api/whoami): this Supabase project signs
access tokens with ES256 using an asymmetric key, not HS256 against
the Legacy JWT Secret. Result: every signed-in user was failing
verification and getting treated as anonymous β CRISPR 403 β "session
out of sync" modal on every click.
What this commit ships:
1. requirements.txt β adds PyJWT[crypto]>=2.8.0 (~6 MB), brings in the
cryptography backend needed for ECDSA + JWKS support.
2. auth.py β keeps the legacy HS256 path intact (Supabase anon +
service_role keys are still HS256, and projects that haven't
migrated still need it). Adds two new functions:
_verify_jwt_jwks(token, alg) β uses PyJWT.PyJWKClient against
<project>/auth/v1/.well-known/jwks.json
Cached, refreshes on kid miss.
_verify_jwt_any(token) β reads the JWT header's `alg` and
dispatches to HS256 or JWKS path.
load_auth_into_g now calls _verify_jwt_any instead of _verify_jwt_hs256
directly, so both signing modes work transparently.
3. server.py β /api/whoami uses _verify_jwt_any (so its `verified` field
is accurate for ES256 too) and exposes `decoded_alg` so the algorithm
in use is visible at a glance.
PyJWT is lazy-imported so the module still loads if the dependency
isn't installed (local-dev resilience). JWKS client is lazy-init at
first ES256 request and cached for the process lifetime.
HF Space will do a full Docker rebuild for this push (Python deps
changed). Expect 5β12 min before /api/whoami reports verified=true.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- dee/auth.py +158 -4
- dee/server.py +20 -2
- requirements.txt +8 -0
|
@@ -125,12 +125,18 @@ def _b64_translate(data: str) -> bytes:
|
|
| 125 |
def _verify_jwt_hs256(token: str, secret: str) -> Optional[Dict[str, Any]]:
|
| 126 |
"""Verify an HS256-signed JWT and return its claims, or None on failure.
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
Validates: signature, exp (expiry), nbf (not-before if present), and
|
| 129 |
iat (issued-at, sanity-checks not-in-future-by-more-than-60s). Does
|
| 130 |
not strictly verify `aud` or `iss` β Supabase JWTs have iss=supabase
|
| 131 |
-
and aud=authenticated, which we treat as informational only.
|
| 132 |
-
deployment exposes the JWT to attackers who can mint tokens with the
|
| 133 |
-
same secret, those tokens are valid by design.
|
| 134 |
"""
|
| 135 |
try:
|
| 136 |
header_b64, payload_b64, sig_b64 = token.split(".")
|
|
@@ -167,6 +173,150 @@ def _verify_jwt_hs256(token: str, secret: str) -> Optional[Dict[str, Any]]:
|
|
| 167 |
return None
|
| 168 |
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
# βββ Signed anon cookie βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 171 |
# Format: "<first_at>.<runs>.<issued_at>.<hex_hmac>"
|
| 172 |
#
|
|
@@ -242,10 +392,14 @@ def load_auth_into_g() -> None:
|
|
| 242 |
auth = AuthContext()
|
| 243 |
|
| 244 |
# 1) Try Authorization: Bearer <jwt>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
auth_header = request.headers.get("Authorization", "")
|
| 246 |
if AUTH_ENABLED and auth_header.lower().startswith("bearer "):
|
| 247 |
token = auth_header[7:].strip()
|
| 248 |
-
claims =
|
| 249 |
if claims:
|
| 250 |
auth.user_id = claims.get("sub")
|
| 251 |
auth.email = claims.get("email")
|
|
|
|
| 125 |
def _verify_jwt_hs256(token: str, secret: str) -> Optional[Dict[str, Any]]:
|
| 126 |
"""Verify an HS256-signed JWT and return its claims, or None on failure.
|
| 127 |
|
| 128 |
+
LEGACY path. Supabase used to sign everything with HS256 against the
|
| 129 |
+
Legacy JWT Secret. After May 2026 Supabase migrated this project to
|
| 130 |
+
asymmetric ES256 signing β those tokens are verified by the JWKS
|
| 131 |
+
path below (_verify_jwt_jwks). We keep HS256 alive because:
|
| 132 |
+
- The Supabase anon + service_role API keys are still HS256-signed
|
| 133 |
+
against the Legacy Secret (per Supabase's own UI copy).
|
| 134 |
+
- Projects that haven't migrated yet, or that revert, still need it.
|
| 135 |
+
|
| 136 |
Validates: signature, exp (expiry), nbf (not-before if present), and
|
| 137 |
iat (issued-at, sanity-checks not-in-future-by-more-than-60s). Does
|
| 138 |
not strictly verify `aud` or `iss` β Supabase JWTs have iss=supabase
|
| 139 |
+
and aud=authenticated, which we treat as informational only.
|
|
|
|
|
|
|
| 140 |
"""
|
| 141 |
try:
|
| 142 |
header_b64, payload_b64, sig_b64 = token.split(".")
|
|
|
|
| 173 |
return None
|
| 174 |
|
| 175 |
|
| 176 |
+
# βββ ES256 / RS256 verification via JWKS βββββββββββββββββββββββββββββββ
|
| 177 |
+
# 2026-05-28: Supabase migrated this project's access-token signing from
|
| 178 |
+
# HS256 (Legacy Secret) to ES256 (ECDSA P-256, asymmetric keys). The
|
| 179 |
+
# private key stays with Supabase; we fetch the matching public key from
|
| 180 |
+
# their JWKS endpoint and verify against it.
|
| 181 |
+
#
|
| 182 |
+
# Endpoint shape:
|
| 183 |
+
# https://<project>.supabase.co/auth/v1/.well-known/jwks.json
|
| 184 |
+
#
|
| 185 |
+
# PyJWKClient handles HTTP fetch + caching + kid-based key lookup. We
|
| 186 |
+
# cache one client instance at module level β it caches keys in memory
|
| 187 |
+
# and refetches the JWKS only on kid miss (e.g., after Supabase rotates).
|
| 188 |
+
#
|
| 189 |
+
# Verification uses PyJWT with the cryptography backend (the [crypto]
|
| 190 |
+
# extra in requirements.txt). If PyJWT isn't installed, we degrade to
|
| 191 |
+
# returning None for asymmetric tokens β the legacy HS256 path still
|
| 192 |
+
# works for any users on projects that haven't migrated.
|
| 193 |
+
|
| 194 |
+
_jwks_client = None # lazy-initialized PyJWKClient
|
| 195 |
+
_pyjwt_module = None # lazy-imported jwt module
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _ensure_pyjwt():
|
| 199 |
+
"""Lazy-import PyJWT so the auth module loads even if PyJWT isn't
|
| 200 |
+
installed (graceful local-dev fallback)."""
|
| 201 |
+
global _pyjwt_module
|
| 202 |
+
if _pyjwt_module is None:
|
| 203 |
+
try:
|
| 204 |
+
import jwt as _jwt # PyJWT
|
| 205 |
+
_pyjwt_module = _jwt
|
| 206 |
+
except ImportError:
|
| 207 |
+
logger.warning(
|
| 208 |
+
"PyJWT not installed; ES256/RS256 Supabase tokens cannot be "
|
| 209 |
+
"verified. Install with: pip install 'PyJWT[crypto]'"
|
| 210 |
+
)
|
| 211 |
+
_pyjwt_module = False # sentinel: don't retry import
|
| 212 |
+
return _pyjwt_module or None
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _get_jwks_client():
|
| 216 |
+
"""Lazy-init a PyJWKClient pointing at this project's JWKS endpoint.
|
| 217 |
+
Returns None if Supabase URL isn't configured or PyJWT is missing."""
|
| 218 |
+
global _jwks_client
|
| 219 |
+
if _jwks_client is not None:
|
| 220 |
+
return _jwks_client
|
| 221 |
+
if not SUPABASE_URL:
|
| 222 |
+
return None
|
| 223 |
+
pyjwt = _ensure_pyjwt()
|
| 224 |
+
if pyjwt is None:
|
| 225 |
+
return None
|
| 226 |
+
try:
|
| 227 |
+
_jwks_client = pyjwt.PyJWKClient(
|
| 228 |
+
f"{SUPABASE_URL}/auth/v1/.well-known/jwks.json",
|
| 229 |
+
cache_keys=True,
|
| 230 |
+
max_cached_keys=8,
|
| 231 |
+
)
|
| 232 |
+
except Exception as exc: # noqa: BLE001
|
| 233 |
+
logger.warning("Failed to initialize JWKS client: %s", exc)
|
| 234 |
+
_jwks_client = None
|
| 235 |
+
return _jwks_client
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def _verify_jwt_jwks(token: str, alg: str) -> Optional[Dict[str, Any]]:
|
| 239 |
+
"""Verify an ES256 / RS256 / ES384 / RS512 etc. JWT against the
|
| 240 |
+
Supabase JWKS public keys. Returns claims or None.
|
| 241 |
+
|
| 242 |
+
Same validation surface as _verify_jwt_hs256: signature, exp, nbf,
|
| 243 |
+
iat (with 5-min clock-skew tolerance). audience NOT enforced
|
| 244 |
+
(Supabase uses aud="authenticated" which is informational here)."""
|
| 245 |
+
pyjwt = _ensure_pyjwt()
|
| 246 |
+
if pyjwt is None:
|
| 247 |
+
return None
|
| 248 |
+
client = _get_jwks_client()
|
| 249 |
+
if client is None:
|
| 250 |
+
return None
|
| 251 |
+
try:
|
| 252 |
+
signing_key = client.get_signing_key_from_jwt(token)
|
| 253 |
+
claims = pyjwt.decode(
|
| 254 |
+
token,
|
| 255 |
+
signing_key.key,
|
| 256 |
+
algorithms=[alg],
|
| 257 |
+
options={
|
| 258 |
+
# iss/aud verification disabled β matches the HS256 path.
|
| 259 |
+
# Supabase tokens carry aud="authenticated" which isn't
|
| 260 |
+
# something we need to enforce at the API layer; the user_id
|
| 261 |
+
# in `sub` is what we attribute work to.
|
| 262 |
+
"verify_aud": False,
|
| 263 |
+
"verify_iss": False,
|
| 264 |
+
},
|
| 265 |
+
# 5-min leeway covers minor clock skew between the Supabase
|
| 266 |
+
# auth servers and the HF Space container.
|
| 267 |
+
leeway=300,
|
| 268 |
+
)
|
| 269 |
+
return claims
|
| 270 |
+
except pyjwt.exceptions.InvalidTokenError as exc:
|
| 271 |
+
logger.info("JWKS verify rejected token: %s", exc)
|
| 272 |
+
return None
|
| 273 |
+
except Exception as exc: # noqa: BLE001
|
| 274 |
+
# Network errors fetching JWKS, malformed kid, etc.
|
| 275 |
+
logger.warning("JWKS verify error: %s", exc)
|
| 276 |
+
return None
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def _verify_jwt_any(token: str) -> Optional[Dict[str, Any]]:
|
| 280 |
+
"""Dispatch JWT verification based on the algorithm in the header.
|
| 281 |
+
|
| 282 |
+
Branches:
|
| 283 |
+
- HS256 β legacy HMAC path using SUPABASE_JWT_SECRET
|
| 284 |
+
- ES256/RS256/etc. β JWKS-based asymmetric verification
|
| 285 |
+
|
| 286 |
+
Returns claims on success, None on failure. Always None if AUTH_ENABLED
|
| 287 |
+
is False (caller already checks this, defensive double-guard)."""
|
| 288 |
+
if not token:
|
| 289 |
+
return None
|
| 290 |
+
# Decode header WITHOUT verification to learn the algorithm. We do
|
| 291 |
+
# this with PyJWT if available (cleaner) and fall back to manual
|
| 292 |
+
# base64 + JSON parse otherwise.
|
| 293 |
+
alg = ""
|
| 294 |
+
pyjwt = _ensure_pyjwt()
|
| 295 |
+
if pyjwt is not None:
|
| 296 |
+
try:
|
| 297 |
+
alg = pyjwt.get_unverified_header(token).get("alg", "")
|
| 298 |
+
except Exception:
|
| 299 |
+
alg = ""
|
| 300 |
+
if not alg:
|
| 301 |
+
try:
|
| 302 |
+
header_b64 = token.split(".", 2)[0]
|
| 303 |
+
alg = json.loads(_b64url_decode(header_b64).decode("utf-8")).get("alg", "")
|
| 304 |
+
except Exception:
|
| 305 |
+
return None
|
| 306 |
+
|
| 307 |
+
if alg == "HS256":
|
| 308 |
+
if not SUPABASE_JWT_SECRET:
|
| 309 |
+
return None
|
| 310 |
+
return _verify_jwt_hs256(token, SUPABASE_JWT_SECRET)
|
| 311 |
+
|
| 312 |
+
if alg in ("ES256", "ES384", "ES512", "RS256", "RS384", "RS512"):
|
| 313 |
+
return _verify_jwt_jwks(token, alg)
|
| 314 |
+
|
| 315 |
+
# Unknown algorithm β refuse.
|
| 316 |
+
logger.info("JWT uses unsupported alg=%r; rejecting.", alg)
|
| 317 |
+
return None
|
| 318 |
+
|
| 319 |
+
|
| 320 |
# βββ Signed anon cookie βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 321 |
# Format: "<first_at>.<runs>.<issued_at>.<hex_hmac>"
|
| 322 |
#
|
|
|
|
| 392 |
auth = AuthContext()
|
| 393 |
|
| 394 |
# 1) Try Authorization: Bearer <jwt>
|
| 395 |
+
# _verify_jwt_any dispatches on the JWT's `alg`:
|
| 396 |
+
# HS256 β legacy SUPABASE_JWT_SECRET path
|
| 397 |
+
# ES256/RS256 β JWKS-based asymmetric verification
|
| 398 |
+
# Either path returns the validated claims or None.
|
| 399 |
auth_header = request.headers.get("Authorization", "")
|
| 400 |
if AUTH_ENABLED and auth_header.lower().startswith("bearer "):
|
| 401 |
token = auth_header[7:].strip()
|
| 402 |
+
claims = _verify_jwt_any(token)
|
| 403 |
if claims:
|
| 404 |
auth.user_id = claims.get("sub")
|
| 405 |
auth.email = claims.get("email")
|
|
@@ -456,10 +456,27 @@ def create_app() -> Flask:
|
|
| 456 |
decoded_payload = {}
|
| 457 |
decode_ok = False
|
| 458 |
|
| 459 |
-
# Now check verification
|
|
|
|
|
|
|
|
|
|
| 460 |
verified = False
|
| 461 |
if header_starts_with_bearer and _auth.AUTH_ENABLED:
|
| 462 |
-
verified = _auth.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
|
| 464 |
# Final auth state as the request handler would see it.
|
| 465 |
ctx = _auth.get_auth()
|
|
@@ -479,6 +496,7 @@ def create_app() -> Flask:
|
|
| 479 |
"token_len": token_len,
|
| 480 |
"token_fingerprint": token_fingerprint,
|
| 481 |
"decode_ok": decode_ok,
|
|
|
|
| 482 |
"decoded_iss": decoded_payload.get("iss") if decode_ok else None,
|
| 483 |
"decoded_aud": decoded_payload.get("aud") if decode_ok else None,
|
| 484 |
"decoded_sub_present": bool(decoded_payload.get("sub")) if decode_ok else False,
|
|
|
|
| 456 |
decoded_payload = {}
|
| 457 |
decode_ok = False
|
| 458 |
|
| 459 |
+
# Now check verification. _verify_jwt_any dispatches on the
|
| 460 |
+
# JWT's `alg` β HS256 against the Legacy Secret, ES256/RS256
|
| 461 |
+
# against the JWKS public key β so this reports `verified` for
|
| 462 |
+
# whichever signing mode the Supabase project is currently in.
|
| 463 |
verified = False
|
| 464 |
if header_starts_with_bearer and _auth.AUTH_ENABLED:
|
| 465 |
+
verified = _auth._verify_jwt_any(raw_token) is not None
|
| 466 |
+
|
| 467 |
+
# Also surface the algorithm so we can tell at a glance whether
|
| 468 |
+
# this project is still on Legacy HS256 or has migrated to ES256.
|
| 469 |
+
decoded_alg = ""
|
| 470 |
+
try:
|
| 471 |
+
if raw_token.count(".") == 2:
|
| 472 |
+
_h = raw_token.split(".")[0]
|
| 473 |
+
pad = "=" * (-len(_h) % 4)
|
| 474 |
+
import base64 as _b64
|
| 475 |
+
decoded_alg = json.loads(
|
| 476 |
+
_b64.urlsafe_b64decode((_h + pad).encode("ascii")).decode("utf-8")
|
| 477 |
+
).get("alg", "")
|
| 478 |
+
except Exception:
|
| 479 |
+
decoded_alg = ""
|
| 480 |
|
| 481 |
# Final auth state as the request handler would see it.
|
| 482 |
ctx = _auth.get_auth()
|
|
|
|
| 496 |
"token_len": token_len,
|
| 497 |
"token_fingerprint": token_fingerprint,
|
| 498 |
"decode_ok": decode_ok,
|
| 499 |
+
"decoded_alg": decoded_alg or None,
|
| 500 |
"decoded_iss": decoded_payload.get("iss") if decode_ok else None,
|
| 501 |
"decoded_aud": decoded_payload.get("aud") if decode_ok else None,
|
| 502 |
"decoded_sub_present": bool(decoded_payload.get("sub")) if decode_ok else False,
|
|
@@ -16,3 +16,11 @@ openpyxl>=3.1.0
|
|
| 16 |
# removed on 2026-05-25 when the LLM chat panel was stripped. Re-add
|
| 17 |
# alongside the /api/chat endpoint when the assistant is brought back.
|
| 18 |
# gradio_client>=1.4.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# removed on 2026-05-25 when the LLM chat panel was stripped. Re-add
|
| 17 |
# alongside the /api/chat endpoint when the assistant is brought back.
|
| 18 |
# gradio_client>=1.4.0
|
| 19 |
+
|
| 20 |
+
# PyJWT with the cryptography backend β required for verifying Supabase
|
| 21 |
+
# access tokens after Supabase migrated this project from HS256 (Legacy
|
| 22 |
+
# JWT Secret) to asymmetric ES256 signing. The ES256 public key is
|
| 23 |
+
# fetched from <project>/auth/v1/.well-known/jwks.json by PyJWKClient
|
| 24 |
+
# (with built-in caching). Adds ~6 MB to the image; worth it to keep
|
| 25 |
+
# auth working without rolling Supabase back to legacy keys.
|
| 26 |
+
PyJWT[crypto]>=2.8.0
|