Spaces:
Runtime error
Runtime error
BIM Query Deploy
Claude Opus 4.7 (1M context)
deploy: pick up JWKS/ES256 support from monorepo
0a556f1 Download app/services/auth.py from 12mhsssss/bimquery-api: direct link, hf CLI and curl.
- Browser
- Download file 6.47 kB
-
https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/services/auth.py
- Command line
-
hf download hf://spaces/12mhsssss/bimquery-api/app/services/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/12mhsssss/bimquery-api/resolve/main/app/services/auth.py
6.47 kB
| # Copyright (C) 2026 Mattia Zatelli | |
| # | |
| # This program is free software: you can redistribute it and/or modify | |
| # it under the terms of the GNU Affero General Public License as published by | |
| # the Free Software Foundation, either version 3 of the License, or | |
| # (at your option) any later version. | |
| # | |
| # This program is distributed in the hope that it will be useful, | |
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
| # GNU Affero General Public License for more details. | |
| # | |
| # You should have received a copy of the GNU Affero General Public License | |
| # along with this program. If not, see <https://www.gnu.org/licenses/>. | |
| """ | |
| Authentication service. | |
| Supports two credential types: | |
| 1. X-Api-Key — single shared API key from .env (used by self-hosted / internal callers). | |
| 2. Authorization: Bearer <jwt> — JWTs from any identity provider. Two verification | |
| paths, tried in order: | |
| - If JWT_JWKS_URL is set, fetch public keys from JWKS and verify with the | |
| algorithm declared in the token header (e.g. ES256 for Supabase projects). | |
| - Otherwise (or as fallback), verify HS256 with the shared JWT_SECRET. | |
| Each unique `sub` claim is treated as its own tenant. | |
| """ | |
| import hashlib | |
| import hmac | |
| import logging | |
| import time | |
| from typing import Any, Dict, List, Optional | |
| import httpx | |
| from jose import JWTError, jwt | |
| from app.core.config import get_settings | |
| logger = logging.getLogger(__name__) | |
| settings = get_settings() | |
| # JWKS cache (in-memory, per process). Refetched after _JWKS_TTL_S so key | |
| # rotations on the IdP propagate without a restart. | |
| _JWKS_TTL_S = 3600 | |
| _jwks_cache: Dict[str, Any] = {"url": "", "keys": [], "fetched_at": 0.0} | |
| def _fetch_jwks(url: str) -> List[Dict[str, Any]]: | |
| now = time.time() | |
| if ( | |
| _jwks_cache["url"] == url | |
| and _jwks_cache["keys"] | |
| and (now - _jwks_cache["fetched_at"]) < _JWKS_TTL_S | |
| ): | |
| return _jwks_cache["keys"] | |
| try: | |
| response = httpx.get(url, timeout=10) | |
| response.raise_for_status() | |
| keys = response.json().get("keys", []) | |
| _jwks_cache.update({"url": url, "keys": keys, "fetched_at": now}) | |
| return keys | |
| except Exception as e: | |
| logger.warning(f"JWKS fetch failed for {url}: {e}") | |
| return _jwks_cache["keys"] if _jwks_cache["url"] == url else [] | |
| def _verify_with_jwks(token: str) -> Optional[Dict[str, Any]]: | |
| """Verify a JWT against the configured JWKS endpoint.""" | |
| if not settings.JWT_JWKS_URL: | |
| return None | |
| try: | |
| header = jwt.get_unverified_header(token) | |
| except JWTError as e: | |
| logger.info(f"JWT header parse failed: {e}") | |
| return None | |
| kid = header.get("kid") | |
| alg = header.get("alg") | |
| if not kid or not alg: | |
| return None | |
| keys = _fetch_jwks(settings.JWT_JWKS_URL) | |
| matching = next((k for k in keys if k.get("kid") == kid), None) | |
| if matching is None: | |
| # Key not in cache — force a refresh in case the IdP rotated. | |
| _jwks_cache["fetched_at"] = 0 | |
| keys = _fetch_jwks(settings.JWT_JWKS_URL) | |
| matching = next((k for k in keys if k.get("kid") == kid), None) | |
| if matching is None: | |
| logger.info(f"JWT kid={kid} not present in JWKS") | |
| return None | |
| try: | |
| return jwt.decode( | |
| token, | |
| matching, | |
| algorithms=[alg], | |
| audience=settings.JWT_AUDIENCE or None, | |
| options={"verify_aud": bool(settings.JWT_AUDIENCE)}, | |
| ) | |
| except JWTError as e: | |
| logger.info(f"JWT JWKS verification failed: {e}") | |
| return None | |
| def _verify_with_secret(token: str) -> Optional[Dict[str, Any]]: | |
| """Verify a JWT against the shared HS256 secret.""" | |
| if not settings.JWT_SECRET: | |
| return None | |
| try: | |
| return jwt.decode( | |
| token, | |
| settings.JWT_SECRET, | |
| algorithms=["HS256"], | |
| audience=settings.JWT_AUDIENCE or None, | |
| options={"verify_aud": bool(settings.JWT_AUDIENCE)}, | |
| ) | |
| except JWTError as e: | |
| logger.info(f"JWT HS256 verification failed: {e}") | |
| return None | |
| class AuthService: | |
| """Validates API keys and bearer JWTs.""" | |
| async def introspect_api_key(self, api_key: str) -> Dict[str, Any]: | |
| """Validate the shared API key from settings.""" | |
| if not settings.API_KEY: | |
| logger.error("API_KEY not configured in environment") | |
| return {"valid": False} | |
| if not hmac.compare_digest(api_key, settings.API_KEY): | |
| return {"valid": False} | |
| key_hash = hashlib.sha256(api_key.encode()).hexdigest() | |
| return { | |
| "valid": True, | |
| "auth_type": "api_key", | |
| "tenant_id": settings.TENANT_ID, | |
| "api_key_hash": key_hash, | |
| "rate_limit": { | |
| "rps": settings.RATE_LIMIT_DEFAULT_RPS, | |
| "burst": settings.RATE_LIMIT_DEFAULT_BURST, | |
| }, | |
| } | |
| async def introspect_jwt(self, token: str) -> Dict[str, Any]: | |
| """Validate a bearer JWT. | |
| Tries the configured JWKS endpoint first (asymmetric algorithms | |
| like ES256 used by modern Supabase projects), then falls back to | |
| HS256 with the shared JWT_SECRET. Uses the `sub` claim as | |
| `tenant_id` for per-user isolation. | |
| """ | |
| payload = _verify_with_jwks(token) or _verify_with_secret(token) | |
| if payload is None: | |
| return {"valid": False} | |
| sub = payload.get("sub") | |
| if not sub: | |
| return {"valid": False} | |
| # Derive a stable per-user pseudo-hash so downstream code that keys off | |
| # api_key_hash (project ownership, idempotency, etc.) still works. | |
| tenant_key_hash = hashlib.sha256(f"jwt:{sub}".encode()).hexdigest() | |
| return { | |
| "valid": True, | |
| "auth_type": "jwt", | |
| "tenant_id": sub, | |
| "api_key_hash": tenant_key_hash, | |
| "email": payload.get("email"), | |
| "rate_limit": { | |
| "rps": settings.RATE_LIMIT_DEFAULT_RPS, | |
| "burst": settings.RATE_LIMIT_DEFAULT_BURST, | |
| }, | |
| } | |
| async def validate_request_scopes(self, required_scopes: list, user_scopes: list) -> bool: | |
| if not required_scopes: | |
| return True | |
| return any(scope in user_scopes for scope in required_scopes) | |
| # Global auth service instance | |
| auth_service = AuthService() | |