OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
fix: Make JWT issuer TLS verification configurable via environment variable (#1747)
Edwin Josef9ed874a1193
diff --git a/.env.example b/.env.exampleindex a44ce3c70..e3e25326b 100644--- a/.env.example+++ b/.env.example@@ -347,6 +347,15 @@ CACHE_BACKEND=memory# - files legacy JSON-only path; DB untouchedOPENRAG_STORAGE_MODE=db+# TLS verification when OpenRAG fetches JWT signing keys from the token iss URL+# (gateway-forwarded JWT / RBAC role sync). Default false (internal issuers).+# Set true when the issuer uses a cert trusted by the pod CA bundle.+# OPENRAG_JWT_ISSUER_VERIFY_TLS=true++# Verify forwarded JWT signatures via iss JWKS (default false).+# Set true when OpenRAG must verify signatures (no trusted upstream auth).+# OPENRAG_JWT_VERIFY_SIGNATURE=true+# RBAC kill switch. Default OFF — the system behaves like the pre-RBAC# release: any authenticated user has full access; API-key role# overrides are also bypassed. Set to `true` to turn the permissionsdiff --git a/cloud_securityconfig/config.yml b/cloud_securityconfig/config.ymlindex 8f836da59..82726c5f2 100644--- a/cloud_securityconfig/config.yml+++ b/cloud_securityconfig/config.yml@@ -13,9 +13,9 @@ config:challenge: falseconfig:openid_connect_url: "http://openrag-backend:8000/.well-known/openid-configuration"- subject_key: "sub"+ subject_key: "user_id"jwt_header: "Authorization" # expects Bearer token- roles_key: "roles"+ roles_key: "user_roles"authentication_backend:type: noopdiff --git a/cloud_securityconfig/roles_mapping.yml b/cloud_securityconfig/roles_mapping.ymlindex 8329b5911..8a0025462 100644--- a/cloud_securityconfig/roles_mapping.yml+++ b/cloud_securityconfig/roles_mapping.yml@@ -7,7 +7,6 @@ openrag_user_role:hosts: []backend_roles:- "openrag_user"- - "all_access"all_access:users:diff --git a/src/api/settings/endpoints.py b/src/api/settings/endpoints.pyindex 1e2368025..a9345caff 100644--- a/src/api/settings/endpoints.py+++ b/src/api/settings/endpoints.py@@ -84,7 +84,7 @@ from services.docling_service import DoclingConfig, get_docling_preset_configsfrom session_manager import Userfrom utils import provider_health_cachefrom utils.langflow_utils import LangflowNotReadyError, wait_for_langflow-from utils.logging_config import get_logger, log_opensearch_env+from utils.logging_config import get_logger, log_bootstrap_envfrom utils.telemetry import Category, MessageId, TelemetryClientfrom utils.version_utils import OPENRAG_VERSION@@ -779,7 +779,7 @@ async def onboarding(try:await TelemetryClient.send_event(Category.ONBOARDING, MessageId.ORB_ONBOARD_START)- log_opensearch_env(logger, "onboarding")+ log_bootstrap_env(logger, "onboarding")# Get current configurationcurrent_config = get_openrag_config()diff --git a/src/app/lifespan.py b/src/app/lifespan.pyindex ee481e589..0e3ebe846 100644--- a/src/app/lifespan.py+++ b/src/app/lifespan.py@@ -25,7 +25,7 @@ from config.settings import (get_opensearch_username,)from services.startup_orchestrator import startup_tasks-from utils.logging_config import get_logger, log_opensearch_env+from utils.logging_config import get_logger, log_bootstrap_envfrom utils.telemetry import Category, MessageId, TelemetryClientlogger = get_logger(__name__)@@ -203,7 +203,7 @@ async def run_startup(app: FastAPI):await mcp_lifespan_ctx.__aenter__()logger.info("FastMCP lifespan started")- log_opensearch_env(logger, "startup")+ log_bootstrap_env(logger, "startup")# One-shot OpenSearch security bootstrap driven by the platform's# service JWT. Runs synchronously (before startup_tasks) so thediff --git a/src/config/settings.py b/src/config/settings.pyindex 280667e73..b12e59353 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -210,6 +210,28 @@ def get_jwt_auth_header() -> str:return os.getenv("OPENRAG_JWT_AUTH_HEADER", "Authorization")+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+ issuers with cluster/self-signed certs; set true when the issuer uses a+ public or pod-trusted CA."""+ return os.getenv("OPENRAG_JWT_ISSUER_VERIFY_TLS", "false").strip().lower() in (+ "true",+ "1",+ "yes",+ )+++def get_jwt_verify_signature() -> bool:+ """When true, verify forwarded JWTs via issuer JWKS; when false, decode+ claims only (upstream auth must have authenticated the caller)."""+ return os.getenv("OPENRAG_JWT_VERIFY_SIGNATURE", "false").strip().lower() in (+ "true",+ "1",+ "yes",+ )++DOCLING_OCR_ENGINE = os.getenv("DOCLING_OCR_ENGINE")SEGMENT_WRITE_KEY = os.getenv("SEGMENT_WRITE_KEY", "")ENVIRONMENT = os.getenv("ENVIRONMENT", "")diff --git a/src/config/utils.py b/src/config/utils.pyindex 813a5a9fc..c2baad6e8 100644--- a/src/config/utils.py+++ b/src/config/utils.py@@ -157,3 +157,25 @@ def verify_jwt_from_issuer(iss=issuer,)return None+++def resolve_jwt_claims(token: str | None) -> dict[str, Any] | None:+ """Resolve claims from a forwarded JWT (header or session token).++ When ``OPENRAG_JWT_VERIFY_SIGNATURE`` is true, verifies the signature via+ the token's ``iss`` JWKS URL. Otherwise decodes without verification,+ trusting that upstream auth already validated the caller.+ """+ if not token or not str(token).strip():+ return None++ from config.settings import get_jwt_issuer_verify_tls, get_jwt_verify_signature++ if get_jwt_verify_signature():+ logger.debug("JWT claims: verifying signature")+ return verify_jwt_from_issuer(token, verify_tls=get_jwt_issuer_verify_tls())++ from auth import ibm_auth++ logger.debug("JWT claims: decode only (signature verification disabled)")+ return ibm_auth.decode_ibm_jwt(token)diff --git a/src/dependencies.py b/src/dependencies.pyindex 97d8bb6bf..b2b8574df 100644--- a/src/dependencies.py+++ b/src/dependencies.py@@ -514,7 +514,7 @@ async def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:PLATFORM_USERNAME,get_jwt_auth_header,)- from config.utils import verify_jwt_from_issuer+ from config.utils import resolve_jwt_claims# ── Option -1: Environment variable override (local dev/calls) ───────@@ -554,9 +554,11 @@ async def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:ibm_token = (raw_jwt[7:].strip() if raw_jwt.startswith("Bearer ") else raw_jwt.strip()) or None- claims = verify_jwt_from_issuer(ibm_token, verify_tls=True)++ claims = resolve_jwt_claims(ibm_token)else:ibm_token = request.cookies.get(IBM_SESSION_COOKIE_NAME)+ claims = Noneuser_id = Noneemail = Nonename = None@@ -564,10 +566,15 @@ async def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:# _stage_jwt_roles when a valid JWT subject is present.request.state.jwt_roles = Noneif ibm_token:- logger.debug("[AUTH] IBM JWT token found in request cookies")- claims = ibm_auth.decode_ibm_jwt(ibm_token)+ if claims is None:+ logger.debug("[AUTH] IBM JWT token found in request cookies")+ claims = ibm_auth.decode_ibm_jwt(ibm_token)if claims is not None:- logger.debug("[AUTH] IBM JWT claims decoded successfully")+ logger.debug(+ "[AUTH] JWT claims resolved"+ if jwt_roles_enabled()+ else "[AUTH] IBM JWT claims decoded successfully"+ )sub = claims.get("sub")if not sub:logger.warning(@@ -805,7 +812,7 @@ async def get_api_key_user_async(# _attach_db_user_id), with a 401 when no recognized role is present.from auth.jwt_roles import jwt_roles_enabledfrom config.settings import get_jwt_auth_header- from config.utils import verify_jwt_from_issuer+ from config.utils import resolve_jwt_claimsraw_jwt = request.headers.get(get_jwt_auth_header(), "")logger.debug(@@ -815,7 +822,7 @@ async def get_api_key_user_async()if raw_jwt and raw_jwt.strip():token = raw_jwt[7:].strip() if raw_jwt.startswith("Bearer ") else raw_jwt.strip()- claims = verify_jwt_from_issuer(token, verify_tls=True)+ claims = resolve_jwt_claims(token)sub = claims.get("sub") if claims else Noneif sub:user = User(diff --git a/src/services/dls_principal_service.py b/src/services/dls_principal_service.pyindex 07cfa73ec..be8d91c83 100644--- a/src/services/dls_principal_service.py+++ b/src/services/dls_principal_service.py@@ -238,29 +238,65 @@ class DLSPrincipalService:self._index_checked = Truedef _get_opensearch_client(self) -> Any | None:+ # An explicitly injected client wins; otherwise build (once) an+ # admin-identity client using the same run-mode switching as the+ # startup security bootstrap (app/lifespan.py) and onboarding+ # (api/settings/endpoints.py): SaaS -> platform service-token JWT;+ # on-prem/OSS -> OpenSearch basic auth.if self.opensearch_client is not None:return self.opensearch_client+ if self._admin_opensearch_client is not None:+ return self._admin_opensearch_clienttry:from config.settings import (- IBM_AUTH_ENABLED,- OPENSEARCH_PASSWORD,- OPENSEARCH_USERNAME,clients,+ get_openrag_service_token,+ get_opensearch_password,+ get_opensearch_username,+ )+ from utils.run_mode_utils import (+ is_run_mode_on_prem,+ is_run_mode_saas,)- if IBM_AUTH_ENABLED:- if not OPENSEARCH_PASSWORD:+ if is_run_mode_saas():+ service_token = get_openrag_service_token()+ if not service_token:+ logger.warning(+ "DLS principal OpenSearch client unavailable: saas mode "+ "but OPENRAG_SERVICE_TOKEN is not set"+ )return None- if self._admin_opensearch_client is None:- self._admin_opensearch_client = clients.create_basic_opensearch_client(- OPENSEARCH_USERNAME,- OPENSEARCH_PASSWORD,+ self._admin_opensearch_client = clients.create_opensearch_client_from_jwt(+ service_token+ )+ logger.info("DLS principal service: saas mode, using platform service token")+ else:+ mode = "on_prem" if is_run_mode_on_prem() else "oss"+ username = get_opensearch_username()+ password = get_opensearch_password()+ if not password:+ logger.warning(+ "DLS principal OpenSearch client unavailable: "+ f"{mode} mode but OpenSearch password is not set")- return self._admin_opensearch_client+ return None+ self._admin_opensearch_client = clients.create_basic_opensearch_client(+ username,+ password,+ )+ logger.info(+ f"DLS principal service: {mode} mode, using OpenSearch basic auth",+ admin_username=username,+ )- return clients.opensearch- except Exception:+ return self._admin_opensearch_client+ except Exception as e:+ logger.warning(+ "Failed to build DLS principal OpenSearch client",+ error=str(e),+ )return None@staticmethoddiff --git a/src/utils/logging_config.py b/src/utils/logging_config.pyindex e4ac702e7..4f4d1349b 100644--- a/src/utils/logging_config.py+++ b/src/utils/logging_config.py@@ -292,14 +292,16 @@ def get_logger(name: str = None) -> structlog.BoundLogger:return structlog.get_logger()-def log_opensearch_env(logger, stage: str) -> None:- """Log effective OpenSearch-related env values for a given stage.+def log_bootstrap_env(logger, stage: str) -> None:+ """Log effective bootstrap / run-mode env values for a given stage.- Logs the parsed booleans as resolved in config.settings for a given stage.+ Logs parsed booleans from config.settings (OpenSearch bootstrap, JWT auth, run mode)."""from config.settings import (OPENRAG_BOOTSTRAP_OS_SECURITY_ON_STARTUP,OPENRAG_SKIP_OS_SECURITY_SETUP,+ get_jwt_issuer_verify_tls,+ get_jwt_verify_signature,)from utils.run_mode_utils import get_run_mode@@ -309,6 +311,8 @@ def log_opensearch_env(logger, stage: str) -> None:run_mode=get_run_mode(),bootstrap_os_security_on_startup=OPENRAG_BOOTSTRAP_OS_SECURITY_ON_STARTUP,skip_os_security_setup=OPENRAG_SKIP_OS_SECURITY_SETUP,+ jwt_verify_signature=get_jwt_verify_signature(),+ jwt_issuer_verify_tls=get_jwt_issuer_verify_tls(),)diff --git a/src/utils/opensearch_init.py b/src/utils/opensearch_init.pyindex f365e1f5e..5475d4202 100644--- a/src/utils/opensearch_init.py+++ b/src/utils/opensearch_init.py@@ -186,6 +186,9 @@ async def _ensure_opensearch_index():async def init_index(opensearch_client=None, admin_username: str = None):"""Initialize OpenSearch index and security roles"""os_client = opensearch_client or clients.opensearch+ # Tracks the most recent OpenSearch operation so the except block can name+ # the failing step (TransportError stringifies to just "TransportError(500, '')").+ step = "wait_for_opensearch"try:await wait_for_opensearch(opensearch_client)@@ -202,14 +205,17 @@ async def init_index(opensearch_client=None, admin_username: str = None):else:from utils.opensearch_utils import setup_opensearch_security+ step = "setup_opensearch_security"await setup_opensearch_security(os_client, admin_username=admin_username)+ step = "build_index_body"config = get_openrag_config()embedding_model = config.knowledge.embedding_modelindex_body = await create_index_body()index_name = get_index_name()+ step = f"documents_index:{index_name}"if not await os_client.indices.exists(index=index_name):await os_client.indices.create(index=index_name, body=index_body)logger.info(@@ -281,6 +287,7 @@ async def init_index(opensearch_client=None, admin_username: str = None):},}+ step = f"knowledge_filters_index:{knowledge_filter_index_name}"if not await os_client.indices.exists(index=knowledge_filter_index_name):await os_client.indices.create(index=knowledge_filter_index_name, body=knowledge_filter_index_body@@ -326,6 +333,7 @@ async def init_index(opensearch_client=None, admin_username: str = None):error=str(e),)+ step = f"api_keys_index:{API_KEYS_INDEX_NAME}"if not await os_client.indices.exists(index=API_KEYS_INDEX_NAME):await os_client.indices.create(index=API_KEYS_INDEX_NAME, body=API_KEYS_INDEX_BODY)logger.info("Created API keys index", index_name=API_KEYS_INDEX_NAME)@@ -335,6 +343,7 @@ async def init_index(opensearch_client=None, admin_username: str = None):index_name=API_KEYS_INDEX_NAME,)+ step = f"dls_principal_index:{DLS_PRINCIPAL_INDEX_NAME}"if not await os_client.indices.exists(index=DLS_PRINCIPAL_INDEX_NAME):await os_client.indices.create(index=DLS_PRINCIPAL_INDEX_NAME,@@ -357,11 +366,25 @@ async def init_index(opensearch_client=None, admin_username: str = None):{"principal_labels": ACL_PRINCIPAL_LABELS_MAPPING},)+ step = "configure_alerting_security"await configure_alerting_security()except Exception as e:from utils.opensearch_utils import OpenSearchDiskSpaceError, is_disk_space_error+ # TransportError stringifies to just "TransportError(500, '')" — surface+ # the failing step plus the OpenSearch status/error/body it carries.+ err_fields = {+ "failed_step": step,+ "error": str(e),+ "error_repr": repr(e),+ }+ if hasattr(e, "status_code"):+ err_fields["os_status_code"] = getattr(e, "status_code", None)+ err_fields["os_error"] = getattr(e, "error", None)+ err_fields["os_info"] = getattr(e, "info", None)+ logger.error("init_index failed", **err_fields)+if is_disk_space_error(e):logger.error("OpenSearch disk space exceeded watermark. Index creation failed.")raise OpenSearchDiskSpaceError(diff --git a/tests/unit/config/test_jwt_gateway_claims.py b/tests/unit/config/test_jwt_gateway_claims.pynew file mode 100644index 000000000..d63f3c947--- /dev/null+++ b/tests/unit/config/test_jwt_gateway_claims.py@@ -0,0 +1,48 @@+"""resolve_jwt_claims: verify vs decode-only modes."""++import sys+from pathlib import Path+from unittest.mock import MagicMock++import pytest++ROOT = Path(__file__).resolve().parent.parent.parent.parent+SRC = ROOT / "src"+if str(SRC) not in sys.path:+ sys.path.insert(0, str(SRC))++import auth.ibm_auth as ibm_auth # noqa: E402+import config.utils as config_utils # noqa: E402++[email protected]("token", [None, "", " "])+def test_resolve_empty_token_returns_none(token):+ assert config_utils.resolve_jwt_claims(token) is None+++def test_resolve_verify_mode_calls_verify_jwt_from_issuer(monkeypatch):+ monkeypatch.setenv("OPENRAG_JWT_VERIFY_SIGNATURE", "true")+ verify = MagicMock(return_value={"sub": "alice"})+ monkeypatch.setattr(config_utils, "verify_jwt_from_issuer", verify)+ decode = MagicMock()+ monkeypatch.setattr(ibm_auth, "decode_ibm_jwt", decode)++ result = config_utils.resolve_jwt_claims("Bearer tok")++ assert result == {"sub": "alice"}+ verify.assert_called_once()+ decode.assert_not_called()+++def test_resolve_decode_mode_calls_decode_ibm_jwt(monkeypatch):+ monkeypatch.delenv("OPENRAG_JWT_VERIFY_SIGNATURE", raising=False)+ verify = MagicMock()+ monkeypatch.setattr(config_utils, "verify_jwt_from_issuer", verify)+ decode = MagicMock(return_value={"sub": "bob"})+ monkeypatch.setattr(ibm_auth, "decode_ibm_jwt", decode)++ result = config_utils.resolve_jwt_claims("tok")++ assert result == {"sub": "bob"}+ verify.assert_not_called()+ decode.assert_called_once_with("tok")diff --git a/tests/unit/dependencies/test_jwt_header_auth.py b/tests/unit/dependencies/test_jwt_header_auth.pyindex 231b22018..97ee6321b 100644--- a/tests/unit/dependencies/test_jwt_header_auth.py+++ b/tests/unit/dependencies/test_jwt_header_auth.py@@ -3,9 +3,9 @@Covers the shared role-staging helper ``_stage_jwt_roles`` and the JWT-headerbranch of ``get_api_key_user_async`` in ``src/dependencies.py``.-The branch verifies a gateway-forwarded JWT (config.utils.verify_jwt_from_issuer)+The branch resolves a forwarded JWT (config.utils.resolve_jwt_claims)and, when valid, makes the JWT the source of identity; under RBAC it also-supplies/enforces roles. We monkeypatch ``verify_jwt_from_issuer`` (no real keys+supplies/enforces roles. We monkeypatch ``resolve_jwt_claims`` (no real keysneeded) and ``_attach_db_user_id`` (no DB needed) to isolate the dependencylogic, and drive RBAC on/off via ``OPENRAG_RBAC_ENFORCE``."""@@ -91,7 +91,7 @@ def _patch_attach(monkeypatch):def _patch_verify(monkeypatch, claims):- monkeypatch.setattr(config_utils, "verify_jwt_from_issuer", lambda *a, **k: claims)+ monkeypatch.setattr(config_utils, "resolve_jwt_claims", lambda *a, **k: claims)@pytest.mark.asyncio@@ -169,9 +169,9 @@ async def test_no_header_does_not_engage_jwt_path(monkeypatch):monkeypatch.setenv("IBM_AUTH_ENABLED", "false")def _boom(*a, **k): # must never be called when no header present- raise AssertionError("verify_jwt_from_issuer should not run without the header")+ raise AssertionError("resolve_jwt_claims should not run without the header")- monkeypatch.setattr(config_utils, "verify_jwt_from_issuer", _boom)+ monkeypatch.setattr(config_utils, "resolve_jwt_claims", _boom)req = _FakeRequest({})with pytest.raises(HTTPException) as exc:diff --git a/tests/unit/services/test_dls_principal_client_selection.py b/tests/unit/services/test_dls_principal_client_selection.pynew file mode 100644index 000000000..931fde400--- /dev/null+++ b/tests/unit/services/test_dls_principal_client_selection.py@@ -0,0 +1,99 @@+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[3]+SRC = ROOT / "src"+if str(SRC) not in sys.path:+ sys.path.insert(0, str(SRC))+++def _make_service():+ from services.dls_principal_service import DLSPrincipalService++ # connector_service is unused by _get_opensearch_client; ttl=0 avoids the+ # DLS_PRINCIPAL_REFRESH_TTL_SECONDS import path.+ return DLSPrincipalService(connector_service=object(), refresh_ttl_seconds=0)+++def test_injected_client_wins():+ sentinel = object()+ from services.dls_principal_service import DLSPrincipalService++ service = DLSPrincipalService(+ connector_service=object(),+ opensearch_client=sentinel,+ refresh_ttl_seconds=0,+ )+ assert service._get_opensearch_client() is sentinel+++def test_saas_uses_service_token(monkeypatch):+ from config import settings+ from utils import run_mode_utils++ sentinel = object()+ monkeypatch.setattr(run_mode_utils, "is_run_mode_saas", lambda: True)+ monkeypatch.setattr(settings, "get_openrag_service_token", lambda: "svc-jwt-token")+ captured = {}++ def fake_from_jwt(token):+ captured["token"] = token+ return sentinel++ monkeypatch.setattr(settings.clients, "create_opensearch_client_from_jwt", fake_from_jwt)++ service = _make_service()+ client = service._get_opensearch_client()++ assert client is sentinel+ assert captured["token"] == "svc-jwt-token"+ # Built once and cached for subsequent calls.+ assert service._get_opensearch_client() is sentinel+++def test_saas_without_service_token_returns_none(monkeypatch):+ from config import settings+ from utils import run_mode_utils++ monkeypatch.setattr(run_mode_utils, "is_run_mode_saas", lambda: True)+ monkeypatch.setattr(settings, "get_openrag_service_token", lambda: None)++ service = _make_service()+ assert service._get_opensearch_client() is None+++def test_oss_uses_basic_auth(monkeypatch):+ from config import settings+ from utils import run_mode_utils++ sentinel = object()+ monkeypatch.setattr(run_mode_utils, "is_run_mode_saas", lambda: False)+ monkeypatch.setattr(run_mode_utils, "is_run_mode_on_prem", lambda: False)+ monkeypatch.setattr(settings, "get_opensearch_username", lambda: "admin")+ monkeypatch.setattr(settings, "get_opensearch_password", lambda: "secret")+ captured = {}++ def fake_basic(username, password):+ captured["creds"] = (username, password)+ return sentinel++ monkeypatch.setattr(settings.clients, "create_basic_opensearch_client", fake_basic)++ service = _make_service()+ client = service._get_opensearch_client()++ assert client is sentinel+ assert captured["creds"] == ("admin", "secret")+++def test_on_prem_without_password_returns_none(monkeypatch):+ from config import settings+ from utils import run_mode_utils++ monkeypatch.setattr(run_mode_utils, "is_run_mode_saas", lambda: False)+ monkeypatch.setattr(run_mode_utils, "is_run_mode_on_prem", lambda: True)+ monkeypatch.setattr(settings, "get_opensearch_username", lambda: "admin")+ monkeypatch.setattr(settings, "get_opensearch_password", lambda: None)++ service = _make_service()+ assert service._get_opensearch_client() is None