Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

cookie update

Mike Fortman6f4c65c788ec
diff --git a/src/api/auth.py b/src/api/auth.py
index 324f44c24..1071be2dd 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -134,10 +134,14 @@ async def auth_logout(
async def ibm_login(request: Request):
- """IBM login endpoint — Basic Auth header is validated by Traefik in production.
+ """IBM login endpoint.
- When running without Traefik (local dev), this endpoint sets an ibm-auth-basic
- session cookie from the Basic Auth header so subsequent requests are authenticated.
+ Production: Traefik intercepts the request, validates Basic credentials
+ with AMS, and sets the ibm-openrag-session cookie before forwarding here.
+ This handler just returns 200 — no cookie work needed.
+
+ Local dev (no Traefik): stores the Basic Auth header in ibm-auth-basic
+ cookie so subsequent requests can be authenticated by _get_ibm_user.
"""
from config.settings import IBM_AUTH_ENABLED
@@ -146,15 +150,15 @@ async def ibm_login(request: Request):
response = JSONResponse({"status": "ok"})
- # Persist the Basic Auth header as a cookie so /auth/me and other endpoints
- # can authenticate subsequent requests (Traefik handles this in production).
- auth_header = request.headers.get("Authorization", "")
- if auth_header.startswith("Basic "):
- response.set_cookie(
- "ibm-auth-basic",
- auth_header,
- httponly=True,
- samesite="lax",
- )
+ # Local dev fallback only — in production Traefik sets ibm-openrag-session.
+ if not request.cookies.get("ibm-openrag-session"):
+ auth_header = request.headers.get("Authorization", "")
+ if auth_header.startswith("Basic "):
+ response.set_cookie(
+ "ibm-auth-basic",
+ auth_header,
+ httponly=True,
+ samesite="lax",
+ )
return response
diff --git a/src/auth/ibm_auth.py b/src/auth/ibm_auth.py
index c685da1d6..f99daca4f 100644
--- a/src/auth/ibm_auth.py
+++ b/src/auth/ibm_auth.py
@@ -1,9 +1,10 @@
-"""IBM AMS JWT validation helper.
+"""IBM AMS JWT helper.
-Validates JWTs from the `ibm-lh-console-session` cookie issued by IBM
-Watsonx Data (lakehouse). The public key is fetched from IBM_JWT_PUBLIC_KEY_URL
-at startup and cached in-process. On validation failure the key is re-fetched
-once to handle key rotation.
+decode_ibm_jwt — decode without signature verification (Traefik has already
+ validated the token before it reaches the backend).
+validate_ibm_jwt — full RS256 validation for optional use when
+ IBM_JWT_PUBLIC_KEY_URL is configured.
+fetch_ibm_public_key — fetch and cache IBM's public key PEM.
"""
import httpx
import jwt
@@ -13,15 +14,25 @@ from utils.logging_config import get_logger
logger = get_logger(__name__)
-# Module-level cache; populated by fetch_ibm_public_key() at startup.
+# Module-level cache; populated by fetch_ibm_public_key() if called.
_cached_public_key = None
-async def fetch_ibm_public_key(url: str):
- """Fetch IBM's JWT public key PEM from *url* and cache it.
+def decode_ibm_jwt(token: str) -> dict | None:
+ """Decode *token* without signature verification.
- Returns the loaded public key object.
+ Used for the ibm-openrag-session cookie path where Traefik has already
+ validated the JWT. Returns the claims dict, or None if decoding fails.
"""
+ try:
+ return jwt.decode(token, options={"verify_signature": False})
+ except jwt.DecodeError as exc:
+ logger.warning("IBM JWT decode failed", error=str(exc))
+ return None
+
+
+async def fetch_ibm_public_key(url: str):
+ """Fetch IBM's JWT public key PEM from *url* and cache it."""
global _cached_public_key
logger.info("Fetching IBM JWT public key", url=url)
async with httpx.AsyncClient(timeout=10.0) as client:
@@ -30,7 +41,6 @@ async def fetch_ibm_public_key(url: str):
data = resp.json()
public_key_pem = data.get("public_key")
if not public_key_pem:
- logger.error("IBM JWT public key not found in response")
raise ValueError("IBM JWT public key not found in response")
if isinstance(public_key_pem, str):
public_key_pem = public_key_pem.encode("utf-8")
@@ -40,10 +50,9 @@ async def fetch_ibm_public_key(url: str):
def validate_ibm_jwt(token: str, public_key) -> dict | None:
- """Validate *token* with *public_key*.
+ """Validate *token* with *public_key* (full RS256 + expiry check).
- Returns the decoded claims dict on success, or ``None`` on any failure
- (expired, bad signature, missing claims, etc.).
+ Returns the decoded claims dict on success, or None on any failure.
"""
if public_key is None:
logger.warning("IBM JWT validation skipped — no public key loaded")
diff --git a/src/dependencies.py b/src/dependencies.py
index 884e4366d..04ddb6fa9 100644
--- a/src/dependencies.py
+++ b/src/dependencies.py
@@ -90,50 +90,23 @@ def get_flows_service(services: dict = Depends(get_services)):
# ─────────────────────────────────────────────
def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:
- """Authenticate via IBM AMS — cookie-first, Basic Auth fallback.
+ """Authenticate via IBM AMS.
- 1. ibm-lh-console-session cookie: JWT validated with IBM's public key.
- 2. Authorization: Basic header: decoded for user identity; Traefik has
- already validated the credentials, so we trust the header as-is and
- store the full header value to forward to OpenSearch.
+ 1. ibm-openrag-session cookie — set by Traefik after validating credentials
+ with AMS. JWT is decoded without re-validation (Traefik already validated).
+ 2. ibm-auth-basic cookie — local dev fallback set by our ibm_login endpoint
+ when Traefik is not present.
- If *required* is True, raises HTTP 401 when neither is present/valid.
+ If *required* is True, raises HTTP 401 when neither is present.
If *required* is False, returns None instead of raising.
"""
import base64
import auth.ibm_auth as ibm_auth
- from config.settings import IBM_JWT_PUBLIC_KEY_URL
-
- # ── Option 1: cookie-based JWT ──────────────────────────────────────
- # Cookie name may include an instance UUID suffix, e.g.
- # ibm-lh-console-session-cd4fcbaf-6a3a-4a05-80af-92df02f64c54
- logger.info("IBM auth: cookies received by backend", cookie_keys=list(request.cookies.keys()))
- ibm_token = next(
- (v for k, v in request.cookies.items() if k.startswith("ibm-lh-console-session")),
- None,
- )
- logger.info("IBM auth: ibm_token found", found=ibm_token is not None)
- if ibm_token:
- claims = ibm_auth.validate_ibm_jwt(ibm_token, ibm_auth._cached_public_key)
- logger.info("IBM auth: JWT validation result", claims_found=claims is not None, public_key_loaded=ibm_auth._cached_public_key is not None)
-
- # On validation failure, try re-fetching the public key once (key rotation)
- if claims is None and IBM_JWT_PUBLIC_KEY_URL:
- try:
- import httpx
- from cryptography.hazmat.primitives.serialization import load_pem_public_key
- with httpx.Client(timeout=10.0) as client:
- resp = client.get(IBM_JWT_PUBLIC_KEY_URL)
- resp.raise_for_status()
- pem = resp.json().get("public_key", "")
- if isinstance(pem, str):
- pem = pem.encode("utf-8")
- ibm_auth._cached_public_key = load_pem_public_key(pem)
- logger.info("IBM public key refreshed (key rotation detected)")
- claims = ibm_auth.validate_ibm_jwt(ibm_token, ibm_auth._cached_public_key)
- except Exception as exc:
- logger.warning("Failed to refresh IBM public key", error=str(exc))
+ # ── Option 1: ibm-openrag-session cookie (production via Traefik) ───
+ ibm_token = request.cookies.get("ibm-openrag-session")
+ if ibm_token:
+ claims = ibm_auth.decode_ibm_jwt(ibm_token)
if claims is not None:
user = User(
user_id=claims.get("uid") or claims["sub"],
@@ -141,14 +114,13 @@ def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:
name=claims.get("display_name", claims.get("username", claims["sub"])),
picture=None,
provider="ibm_ams",
- jwt_token=ibm_token, # raw IBM JWT forwarded to OpenSearch as Bearer
+ jwt_token=ibm_token,
)
request.state.user = user
return user
- # ── Option 2: Basic Auth header or ibm-auth-basic cookie ────────────
- # The cookie is set by our ibm_login endpoint when Traefik is not present (local dev).
- auth_header = request.headers.get("Authorization", "") or request.cookies.get("ibm-auth-basic", "")
+ # ── Option 2: ibm-auth-basic cookie (local dev, no Traefik) ─────────
+ auth_header = request.cookies.get("ibm-auth-basic", "")
if auth_header.startswith("Basic "):
try:
decoded = base64.b64decode(auth_header[6:]).decode("utf-8")
@@ -162,7 +134,7 @@ def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:
name=username,
picture=None,
provider="ibm_ams_basic",
- jwt_token=auth_header, # full "Basic <value>" forwarded to OpenSearch
+ jwt_token=auth_header,
)
request.state.user = user
return user
diff --git a/src/main.py b/src/main.py
index 156522e61..c2572fa9c 100644
--- a/src/main.py
+++ b/src/main.py
@@ -1275,15 +1275,9 @@ async def initialize_services():
# Generate JWT keys if they don't exist
generate_jwt_keys()
- # Pre-fetch IBM JWT public key when IBM auth is enabled
- from config.settings import IBM_AUTH_ENABLED, IBM_JWT_PUBLIC_KEY_URL
+ from config.settings import IBM_AUTH_ENABLED
if IBM_AUTH_ENABLED:
- if not IBM_JWT_PUBLIC_KEY_URL:
- logger.error("IBM_AUTH_ENABLED=true but IBM_JWT_PUBLIC_KEY_URL is not set")
- raise RuntimeError("IBM_JWT_PUBLIC_KEY_URL must be set when IBM_AUTH_ENABLED=true")
- from auth.ibm_auth import fetch_ibm_public_key
- await fetch_ibm_public_key(IBM_JWT_PUBLIC_KEY_URL)
- logger.info("IBM auth mode enabled", public_key_url=IBM_JWT_PUBLIC_KEY_URL)
+ logger.info("IBM auth mode enabled — JWT validation delegated to Traefik")
# Initialize clients (now async to generate Langflow API key)
try: