Skip to content

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

Python

fix: forward end-user JWT to MCP/API callers via gateway-placed X-OpenRAG-API-JWT header (#1874)

Edwin Jose7d39bf5ccddc
diff --git a/src/config/settings.py b/src/config/settings.py
index 9adfba9f2..e5cf6df6e 100644
--- a/src/config/settings.py
+++ b/src/config/settings.py
@@ -270,6 +270,26 @@ def get_jwt_auth_header() -> str:
return os.getenv("OPENRAG_JWT_AUTH_HEADER", "Authorization")
+def get_api_jwt_header() -> str:
+ """Secondary, gateway-placed JWT header for the /v1 API/MCP surface only.
+
+ The primary JWT header (``get_jwt_auth_header()``, default ``Authorization``)
+ is stripped by FastMCP's get_http_headers() before an MCP tool call is
+ proxied to the underlying /v1 route, so it never reaches the /v1 auth
+ dependency. The gateway (Traefik) therefore authenticates the MCP/API caller
+ (who supplies X-Username + X-Api-Key) and injects the minted user JWT into
+ this add-on header instead, which FastMCP forwards verbatim. Read per-call so
+ tests can override via monkeypatch.setenv.
+
+ TRUST NOTE: this header is read in addition to Authorization on the /v1
+ surface and is trusted as an identity source. It is gateway-managed: Traefik
+ mints and injects it, and MUST strip any client-supplied value at the edge
+ (standard internal-trust-header hygiene) so callers cannot forge it —
+ important because claims are decode-only unless ``OPENRAG_JWT_VERIFY_SIGNATURE``
+ is enabled."""
+ return os.getenv("OPENRAG_API_JWT_HEADER", "X-OpenRAG-API-JWT")
+
+
def get_jwt_issuer_verify_tls() -> bool:
"""Whether to verify TLS when fetching JWT signing keys from the token's
``iss`` URL (``verify_jwt_from_issuer``). Defaults to false for internal
diff --git a/src/dependencies.py b/src/dependencies.py
index 77236195c..e8807bc5b 100644
--- a/src/dependencies.py
+++ b/src/dependencies.py
@@ -844,13 +844,33 @@ async def get_api_key_user_async(
# the user's roles (synced via request.state.jwt_roles ->
# _attach_db_user_id), with a 401 when no recognized role is present.
from auth.jwt_roles import jwt_roles_enabled
- from config.settings import IBM_AUTH_ENABLED, get_jwt_auth_header
+ from config.settings import (
+ IBM_AUTH_ENABLED,
+ get_api_jwt_header,
+ get_jwt_auth_header,
+ )
from config.utils import resolve_jwt_claims
-
- raw_jwt = request.headers.get(get_jwt_auth_header(), "")
+ from utils.run_mode_utils import is_run_mode_saas
+
+ # SaaS/RBAC: the gateway MUST forward the end-user JWT on every /v1 request.
+ # When it doesn't, we must NOT silently degrade to lakehouse Basic creds —
+ # that path does DB user writes under a degraded identity and can clobber the
+ # shared users row the same person sees on UI login. Fail loud (401) with no
+ # DB side effects instead; explicit orag_ API-key auth still works.
+ saas_rbac = is_run_mode_saas() and jwt_roles_enabled()
+
+ # Primary: the gateway-forwarded JWT header (default Authorization).
+ # Fallback: the API/MCP add-on header — FastMCP strips Authorization before
+ # proxying an MCP tool call to this /v1 handler, so MCP/API callers supply
+ # the JWT in get_api_jwt_header() instead.
+ jwt_header = get_jwt_auth_header()
+ raw_jwt = request.headers.get(jwt_header, "")
+ if not (raw_jwt and raw_jwt.strip()):
+ jwt_header = get_api_jwt_header()
+ raw_jwt = request.headers.get(jwt_header, "")
logger.debug(
"[AUTH] API-key path JWT header lookup",
- header_name=get_jwt_auth_header(),
+ header_name=jwt_header,
jwt_present=bool(raw_jwt and raw_jwt.strip()),
)
if raw_jwt and raw_jwt.strip():
@@ -883,14 +903,14 @@ async def get_api_key_user_async(
# must not silently downgrade to the API-key identity.
logger.error(
"[AUTH] JWT in request header failed verification/decode",
- header_name=get_jwt_auth_header(),
+ header_name=jwt_header,
)
raise HTTPException(
status_code=401,
detail={
"error": "invalid_jwt",
"message": (
- f"The JWT in the '{get_jwt_auth_header()}' header could not be "
+ f"The JWT in the '{jwt_header}' header could not be "
"verified or decoded. Ensure the gateway forwards a valid, "
"unexpired user JWT issued by a trusted identity provider."
),
@@ -898,16 +918,27 @@ async def get_api_key_user_async(
)
# RBAC off + missing/invalid JWT -> fall through to the API-key path.
else:
- from utils.run_mode_utils import is_run_mode_saas
-
- if is_run_mode_saas() and jwt_roles_enabled():
+ if saas_rbac:
# In saas the gateway is responsible for forwarding the end-user
# JWT on every API/MCP request; its absence is a gateway
- # misconfiguration, not a normal client state.
+ # misconfiguration, not a normal client state. Fail fast here —
+ # before any lakehouse / X-Username / API-key fallback — so no DB
+ # user/role write ever runs under a degraded (roles-less) identity.
logger.error(
"[AUTH] JWT not found in request header — run_mode=saas with "
"RBAC enabled requires the gateway to forward the user JWT",
- header_name=get_jwt_auth_header(),
+ header_name=jwt_header,
+ )
+ raise HTTPException(
+ status_code=401,
+ detail={
+ "error": "missing_user_jwt",
+ "message": (
+ "No user JWT was forwarded by the gateway. In SaaS/RBAC "
+ "mode the gateway must forward the end-user JWT on every "
+ "/v1 request."
+ ),
+ },
)
if IBM_AUTH_ENABLED:
# No JWT — fall back to lakehouse Basic credentials (credentials
@@ -965,6 +996,9 @@ async def get_api_key_user_async(
api_key = token
if not api_key:
+ # saas_rbac is already handled by the fail-fast 401 above (no JWT ->
+ # missing_user_jwt), so reaching here means non-saas_rbac: prompt for
+ # an API key as before.
raise HTTPException(
status_code=401,
detail={
diff --git a/src/mcp_http/server.py b/src/mcp_http/server.py
index 66f2cf124..ec35ade22 100644
--- a/src/mcp_http/server.py
+++ b/src/mcp_http/server.py
@@ -2,18 +2,26 @@
FastMCP streamable HTTP server integration.
Exposes all /v1/ FastAPI endpoints as MCP tools over streamable HTTP transport.
-Auth headers passed by MCP clients are forwarded transparently to the underlying
-FastAPI endpoint handlers via FastMCP's internal proxy.
+Auth headers passed by MCP clients are forwarded to the underlying FastAPI
+endpoint handlers via FastMCP's internal proxy.
+
+IMPORTANT: FastMCP's proxy STRIPS the ``Authorization`` header before invoking
+the /v1 handler (it is in get_http_headers()'s exclude set), so neither an
+``Authorization`` JWT nor ``Authorization: Bearer orag_...`` survives the proxy.
+Use ``X-API-Key`` for API keys. For SaaS/IBM auth, the gateway (Traefik)
+authenticates the X-Username/X-Api-Key pair and injects the minted user JWT into
+the add-on ``X-OpenRAG-API-JWT`` header (OPENRAG_API_JWT_HEADER), which FastMCP
+forwards because it is not in the exclude set; the /v1 auth dependency reads it.
Supported authentication methods:
1. OpenRAG API Key:
- X-API-Key: orag_...
- - Authorization: Bearer orag_...
2. IBM Auth (when IBM_AUTH_ENABLED=true):
- X-Username: <ibm_username>
- X-Api-Key: <ibm_api_key>
+ The gateway exchanges these for a user JWT placed in X-OpenRAG-API-JWT.
Usage (MCP client config):
diff --git a/tests/unit/dependencies/test_jwt_header_auth.py b/tests/unit/dependencies/test_jwt_header_auth.py
index f9e030af9..5c17d18a6 100644
--- a/tests/unit/dependencies/test_jwt_header_auth.py
+++ b/tests/unit/dependencies/test_jwt_header_auth.py
@@ -138,6 +138,9 @@ async def test_valid_jwt_rbac_on_no_role_401(monkeypatch, _patch_attach):
await get_api_key_user_async(req, api_key_service=None, session_manager=None)
assert exc.value.status_code == 401
assert exc.value.detail == "User has no OpenRAG roles assigned"
+ # 401 fires inside _stage_jwt_roles, before _attach_request_user -> no DB
+ # user/role write, so a roles-less JWT can never reach _sync_jwt_roles.
+ assert "user" not in _patch_attach
@pytest.mark.asyncio
@@ -302,19 +305,57 @@ async def test_no_jwt_broken_store_still_returns_header_credentials(monkeypatch,
@pytest.mark.asyncio
-async def test_no_jwt_saas_rbac_on_logs_error(monkeypatch, _patch_attach):
- """saas + RBAC enabled + no JWT header -> a clear error is logged and the
- request still proceeds via the credentials-header fallback."""
+async def test_no_jwt_saas_rbac_on_fails_loud_no_db_write(monkeypatch, _patch_attach):
+ """saas + RBAC + no gateway JWT -> fail loud with 401 missing_user_jwt and
+ do NOT silently fall back to lakehouse creds (no DB user/role write).
+
+ A roles-less / wrong-identity LH fallback here is what corrupted the shared
+ users row the same person sees on UI login; under saas_rbac we must 401
+ before any _attach_request_user instead.
+ """
manager, services = _ibm_setup(monkeypatch)
monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
errors: list[str] = []
monkeypatch.setattr(deps.logger, "error", lambda msg, **kw: errors.append(msg))
+ # Even with a valid LH-credentials header present, saas_rbac must not use it.
req = _FakeRequest({"X-IBM-LH-Credentials": _B64}, services=services)
- user = await get_api_key_user_async(req, api_key_service=None, session_manager=None)
+ with pytest.raises(HTTPException) as exc:
+ await get_api_key_user_async(req, api_key_service=None, session_manager=None)
- assert user.jwt_token == f"Basic {_B64}"
+ assert exc.value.status_code == 401
+ assert exc.value.detail["error"] == "missing_user_jwt"
assert any("JWT not found" in m for m in errors)
+ # No DB side effects: _attach_request_user was never reached, and the
+ # LH-credentials store was never written.
+ assert "user" not in _patch_attach
+ assert manager.upserts == []
+
+
+async def test_no_jwt_saas_rbac_on_rejects_api_key_fail_fast(monkeypatch, _patch_attach):
+ """saas + RBAC + no gateway JWT -> fail fast even when a valid orag_ API key
+ is present. In SaaS the gateway JWT is mandatory; the API key must not be
+ consulted, and the key service must never be called (no DB side effects)."""
+ _ibm_setup(monkeypatch)
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+
+ calls: list[str] = []
+
+ class _KeySvc:
+ async def validate_key(self, key):
+ calls.append(key)
+ return {"user_id": "svc-user", "user_email": "[email protected]", "key_id": "k1"}
+
+ req = _FakeRequest({"X-API-Key": "orag_live_key"})
+
+ with pytest.raises(HTTPException) as exc:
+ await get_api_key_user_async(req, api_key_service=_KeySvc(), session_manager=None)
+
+ assert exc.value.status_code == 401
+ assert exc.value.detail["error"] == "missing_user_jwt"
+ assert calls == [] # API key never validated under saas_rbac
+ assert "user" not in _patch_attach # no _attach_request_user / DB write
@pytest.mark.asyncio