OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
feat: Add flag to skip OpenSearch security setup (#1603)
Edwin Jose2869a1120278
diff --git a/src/config/settings.py b/src/config/settings.pyindex 7c158b4ec..501f8d3d0 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -84,6 +84,28 @@ DOCLING_SERVE_VERIFY_SSL = os.getenv("DOCLING_SERVE_VERIFY_SSL", "true").lower()"yes",)++# Skip the OpenSearch security context setup (roles, role mappings,+# all_access admin pin). When true, OpenRAG assumes the security context+# is managed externally (e.g., by Traefik in CPD or by a SaaS platform+# operator).+#+# Default depends on OPENRAG_RUN_MODE:+# * saas / on_prem (CPD) -> "true" (the platform owns the security context)+# * anything else (oss) -> "false" (today's behaviour preserved)+# An explicit OPENRAG_SKIP_OS_SECURITY_SETUP value always wins, so an+# operator can force-enable the setup in SaaS for a one-off bootstrap.+def _resolve_skip_os_security_default() -> str:+ run_mode = os.getenv("OPENRAG_RUN_MODE", "").strip().lower()+ if run_mode in ("saas", "on_prem"):+ return "true"+ return "false"+++OPENRAG_SKIP_OS_SECURITY_SETUP = os.getenv(+ "OPENRAG_SKIP_OS_SECURITY_SETUP", _resolve_skip_os_security_default()+).lower() in ("true", "1", "yes")+# Enable FastAPI's `debug` mode (verbose tracebacks in HTTP error responses# on the FastAPI app instance). Named explicitly so it isn't confused with# logging-level "debug" or other unrelated debug flags.diff --git a/src/services/startup_orchestrator.py b/src/services/startup_orchestrator.pyindex 834c0b4bd..f6d7646fd 100644--- a/src/services/startup_orchestrator.py+++ b/src/services/startup_orchestrator.py@@ -9,6 +9,7 @@ server URLs, and reapplies user settings if Langflow flows were reset.from config.settings import (DISABLE_INGEST_WITH_LANGFLOW,FETCH_OPENRAG_DOCS_AT_STARTUP,+ OPENRAG_SKIP_OS_SECURITY_SETUP,clients,get_openrag_config,)@@ -65,17 +66,26 @@ async def startup_tasks(services):# Index will be created after onboarding when we know the embedding modelawait wait_for_opensearch()- # Setup OpenSearch security (roles and mappings) after connection is established- try:- from utils.opensearch_utils import setup_opensearch_security-- await setup_opensearch_security(clients.opensearch)- logger.info("OpenSearch security configuration completed successfully")- except Exception as e:- logger.warning(- "Failed to setup OpenSearch security configuration - continuing anyway",- error=str(e),+ # Setup OpenSearch security (roles and mappings) after connection is established.+ # Skip entirely when the platform manages the security context externally+ # (SaaS / CPD): the call would otherwise either fail with 403/401 or+ # overwrite a curated config.+ if OPENRAG_SKIP_OS_SECURITY_SETUP:+ logger.info(+ "Skipping OpenSearch security setup at startup "+ "(OPENRAG_SKIP_OS_SECURITY_SETUP=true)")+ else:+ try:+ from utils.opensearch_utils import setup_opensearch_security++ await setup_opensearch_security(clients.opensearch)+ logger.info("OpenSearch security configuration completed successfully")+ except Exception as e:+ logger.warning(+ "Failed to setup OpenSearch security configuration - continuing anyway",+ error=str(e),+ )if DISABLE_INGEST_WITH_LANGFLOW:await _ensure_opensearch_index()diff --git a/src/utils/opensearch_init.py b/src/utils/opensearch_init.pyindex f197b987e..f15991029 100644--- a/src/utils/opensearch_init.py+++ b/src/utils/opensearch_init.py@@ -10,6 +10,7 @@ from config.settings import (API_KEYS_INDEX_NAME,IBM_AUTH_ENABLED,INDEX_BODY,+ OPENRAG_SKIP_OS_SECURITY_SETUP,PLATFORM_AUTH_DEV_MODE,clients,get_index_name,@@ -99,9 +100,20 @@ async def init_index(opensearch_client=None, admin_username: str = None):try:await wait_for_opensearch(opensearch_client)- from utils.opensearch_utils import setup_opensearch_security+ # Skip security setup when the platform manages it externally+ # (SaaS / CPD). Index creation below still runs — SaaS / CPD+ # deployments still need indices, they just don't want OpenRAG+ # touching roles or role mappings.+ if OPENRAG_SKIP_OS_SECURITY_SETUP:+ logger.info(+ "Skipping OpenSearch security setup during init_index "+ "(OPENRAG_SKIP_OS_SECURITY_SETUP=true)",+ admin_username=admin_username,+ )+ else:+ from utils.opensearch_utils import setup_opensearch_security- await setup_opensearch_security(os_client, admin_username=admin_username)+ await setup_opensearch_security(os_client, admin_username=admin_username)config = get_openrag_config()embedding_model = config.knowledge.embedding_modeldiff --git a/tests/unit/services/test_skip_os_security_setup_startup.py b/tests/unit/services/test_skip_os_security_setup_startup.pynew file mode 100644index 000000000..0c368200c--- /dev/null+++ b/tests/unit/services/test_skip_os_security_setup_startup.py@@ -0,0 +1,126 @@+"""OPENRAG_SKIP_OS_SECURITY_SETUP gates the startup_orchestrator call to+setup_opensearch_security.++Two cases:+ * Flag false (default): setup_opensearch_security is invoked.+ * Flag true: it is NOT invoked, skip log line is emitted.+"""++import sys+from pathlib import Path+from unittest.mock import AsyncMock, MagicMock, patch++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))+++def _services_stub():+ """Minimal services dict — only models_service is touched before the+ OpenSearch security block, and we want its call to fail loudly so the+ test fails fast if it changes."""+ models = MagicMock()+ models.update_model_registry = AsyncMock()+ return {"models_service": models}+++async def test_setup_runs_when_flag_false(monkeypatch):+ """Default (flag false): setup_opensearch_security is called."""+ import services.startup_orchestrator as orchestrator++ monkeypatch.setattr(orchestrator, "OPENRAG_SKIP_OS_SECURITY_SETUP", False)+ monkeypatch.setattr(orchestrator, "DISABLE_INGEST_WITH_LANGFLOW", False)+ # IBM_AUTH_ENABLED is imported lazily inside startup_tasks().+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False, raising=False)++ setup_mock = AsyncMock()+ with (+ patch("utils.opensearch_utils.setup_opensearch_security", setup_mock),+ patch.object(orchestrator, "wait_for_opensearch", AsyncMock()),+ patch.object(orchestrator, "init_index", AsyncMock()),+ patch.object(orchestrator, "configure_alerting_security", AsyncMock()),+ patch.object(+ orchestrator,+ "_reingest_default_docs_on_upgrade_if_needed",+ AsyncMock(return_value=False),+ ),+ patch.object(orchestrator, "_update_mcp_server_urls", AsyncMock()),+ ):+ # Force the post-security work to exit early — config.edited=False+ # short-circuits both the recovery init_index and the flow check.+ with patch.object(+ orchestrator,+ "get_openrag_config",+ MagicMock(+ return_value=MagicMock(edited=False, knowledge=MagicMock(embedding_model=None))+ ),+ ):+ services = _services_stub()+ services["task_service"] = MagicMock()+ services["document_service"] = MagicMock()+ services["langflow_file_service"] = MagicMock()+ services["session_manager"] = MagicMock()+ services["langflow_mcp_service"] = MagicMock()+ services["flows_service"] = MagicMock(ensure_flows_exist=AsyncMock(return_value=set()))+ await orchestrator.startup_tasks(services)++ assert setup_mock.await_count == 1, (+ "setup_opensearch_security must run when OPENRAG_SKIP_OS_SECURITY_SETUP is false"+ )+++async def test_setup_skipped_when_flag_true(monkeypatch):+ """Flag true: setup_opensearch_security is NOT called."""+ import services.startup_orchestrator as orchestrator++ monkeypatch.setattr(orchestrator, "OPENRAG_SKIP_OS_SECURITY_SETUP", True)+ monkeypatch.setattr(orchestrator, "DISABLE_INGEST_WITH_LANGFLOW", False)+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False, raising=False)++ setup_mock = AsyncMock()+ # Spy on the orchestrator's bound logger so we can assert the skip line+ # was emitted without depending on caplog propagation through the+ # project's custom logger wrapper.+ logger_spy = MagicMock()+ monkeypatch.setattr(orchestrator, "logger", logger_spy)++ with (+ patch("utils.opensearch_utils.setup_opensearch_security", setup_mock),+ patch.object(orchestrator, "wait_for_opensearch", AsyncMock()),+ patch.object(orchestrator, "init_index", AsyncMock()),+ patch.object(orchestrator, "configure_alerting_security", AsyncMock()),+ patch.object(+ orchestrator,+ "_reingest_default_docs_on_upgrade_if_needed",+ AsyncMock(return_value=False),+ ),+ patch.object(orchestrator, "_update_mcp_server_urls", AsyncMock()),+ ):+ with patch.object(+ orchestrator,+ "get_openrag_config",+ MagicMock(+ return_value=MagicMock(edited=False, knowledge=MagicMock(embedding_model=None))+ ),+ ):+ services = _services_stub()+ services["task_service"] = MagicMock()+ services["document_service"] = MagicMock()+ services["langflow_file_service"] = MagicMock()+ services["session_manager"] = MagicMock()+ services["langflow_mcp_service"] = MagicMock()+ services["flows_service"] = MagicMock(ensure_flows_exist=AsyncMock(return_value=set()))+ await orchestrator.startup_tasks(services)++ assert setup_mock.await_count == 0, (+ "setup_opensearch_security must NOT run when OPENRAG_SKIP_OS_SECURITY_SETUP is true"+ )+ info_messages = [call.args[0] for call in logger_spy.info.call_args_list if call.args]+ assert any("Skipping OpenSearch security setup at startup" in msg for msg in info_messages), (+ f"expected skip log line not emitted; got: {info_messages}"+ )diff --git a/tests/unit/test_skip_os_security_default.py b/tests/unit/test_skip_os_security_default.pynew file mode 100644index 000000000..173d2588f--- /dev/null+++ b/tests/unit/test_skip_os_security_default.py@@ -0,0 +1,40 @@+"""The OPENRAG_SKIP_OS_SECURITY_SETUP default flips with OPENRAG_RUN_MODE.++ * saas / on_prem (CPD) -> default "true" (platform owns security context)+ * anything else -> default "false" (today's behaviour)++An explicit OPENRAG_SKIP_OS_SECURITY_SETUP always wins.+"""++import sys+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parent.parent.parent+SRC = ROOT / "src"+if str(SRC) not in sys.path:+ sys.path.insert(0, str(SRC))++from config.settings import _resolve_skip_os_security_default # noqa: E402+++ "run_mode, expected",+ [+ ("", "false"), # unset -> default oss path+ ("oss", "false"),+ ("OSS", "false"),+ ("saas", "true"),+ ("SaaS", "true"),+ ("on_prem", "true"),+ ("ON_PREM", "true"),+ ("unknown-mode", "false"), # unrecognised falls back to false+ ],+)+def test_default_resolves_from_run_mode(monkeypatch, run_mode, expected):+ if run_mode:+ monkeypatch.setenv("OPENRAG_RUN_MODE", run_mode)+ else:+ monkeypatch.delenv("OPENRAG_RUN_MODE", raising=False)+ assert _resolve_skip_os_security_default() == expecteddiff --git a/tests/unit/test_skip_os_security_setup_init_index.py b/tests/unit/test_skip_os_security_setup_init_index.pynew file mode 100644index 000000000..531a4fc8a--- /dev/null+++ b/tests/unit/test_skip_os_security_setup_init_index.py@@ -0,0 +1,122 @@+"""OPENRAG_SKIP_OS_SECURITY_SETUP gates the init_index() call to+setup_opensearch_security, but does NOT skip index creation.++Three cases:+ * Flag false (default): security setup IS called.+ * Flag true: security setup is NOT called.+ * Flag true: index creation still runs (docs / knowledge_filters /+ api_keys indices) so SaaS / CPD deployments still+ get usable indices.+"""++import sys+from pathlib import Path+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++ROOT = Path(__file__).resolve().parent.parent.parent+SRC = ROOT / "src"+if str(SRC) not in sys.path:+ sys.path.insert(0, str(SRC))+++def _fake_os_client():+ client = MagicMock()+ # Treat every indices.exists() as False so the create branch runs.+ client.indices.exists = AsyncMock(return_value=False)+ client.indices.create = AsyncMock()+ client.indices.get_settings = AsyncMock(return_value={})+ client.indices.put_settings = AsyncMock()+ client.cluster.put_settings = AsyncMock()+ return client+++async def test_security_setup_called_when_flag_false(monkeypatch):+ import utils.opensearch_init as init_mod++ monkeypatch.setattr(init_mod, "OPENRAG_SKIP_OS_SECURITY_SETUP", False)+ monkeypatch.setattr(init_mod, "IBM_AUTH_ENABLED", False)+ monkeypatch.setattr(init_mod, "PLATFORM_AUTH_DEV_MODE", False)++ os_client = _fake_os_client()+ setup_mock = AsyncMock()++ with (+ patch("utils.opensearch_utils.setup_opensearch_security", setup_mock),+ patch.object(init_mod, "wait_for_opensearch", AsyncMock()),+ patch.object(+ init_mod, "create_index_body", AsyncMock(return_value={"settings": {}, "mappings": {}})+ ),+ patch.object(init_mod, "get_index_name", return_value="documents"),+ ):+ await init_mod.init_index(opensearch_client=os_client, admin_username="alice")++ assert setup_mock.await_count == 1+ args, kwargs = setup_mock.await_args+ assert args[0] is os_client+ assert kwargs.get("admin_username") == "alice"+++async def test_security_setup_skipped_when_flag_true(monkeypatch):+ import utils.opensearch_init as init_mod++ monkeypatch.setattr(init_mod, "OPENRAG_SKIP_OS_SECURITY_SETUP", True)+ monkeypatch.setattr(init_mod, "IBM_AUTH_ENABLED", False)+ monkeypatch.setattr(init_mod, "PLATFORM_AUTH_DEV_MODE", False)++ os_client = _fake_os_client()+ setup_mock = AsyncMock()+ # Spy the bound logger; the project's wrapper doesn't propagate to caplog.+ logger_spy = MagicMock()+ monkeypatch.setattr(init_mod, "logger", logger_spy)++ with (+ patch("utils.opensearch_utils.setup_opensearch_security", setup_mock),+ patch.object(init_mod, "wait_for_opensearch", AsyncMock()),+ patch.object(+ init_mod, "create_index_body", AsyncMock(return_value={"settings": {}, "mappings": {}})+ ),+ patch.object(init_mod, "get_index_name", return_value="documents"),+ ):+ await init_mod.init_index(opensearch_client=os_client, admin_username="bob")++ assert setup_mock.await_count == 0+ info_messages = [call.args[0] for call in logger_spy.info.call_args_list if call.args]+ assert any(+ "Skipping OpenSearch security setup during init_index" in msg for msg in info_messages+ ), f"expected skip log line not emitted; got: {info_messages}"+++async def test_index_creation_still_runs_when_flag_true(monkeypatch):+ """Skipping security setup must NOT skip index creation."""+ import utils.opensearch_init as init_mod++ monkeypatch.setattr(init_mod, "OPENRAG_SKIP_OS_SECURITY_SETUP", True)+ monkeypatch.setattr(init_mod, "IBM_AUTH_ENABLED", False)+ monkeypatch.setattr(init_mod, "PLATFORM_AUTH_DEV_MODE", False)++ os_client = _fake_os_client()++ with (+ patch("utils.opensearch_utils.setup_opensearch_security", AsyncMock()),+ patch.object(init_mod, "wait_for_opensearch", AsyncMock()),+ patch.object(+ init_mod, "create_index_body", AsyncMock(return_value={"settings": {}, "mappings": {}})+ ),+ patch.object(init_mod, "get_index_name", return_value="documents"),+ ):+ await init_mod.init_index(opensearch_client=os_client)++ # The three indices: documents, knowledge_filters, api_keys.+ created_indices = {+ call.kwargs.get("index") for call in os_client.indices.create.await_args_list+ }+ assert "documents" in created_indices+ assert "knowledge_filters" in created_indices+ assert "api_keys" in created_indices, (+ "api_keys index creation must still run when security setup is skipped"+ )