OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
fix: auth user UI (#1891)
Edwin Josec80d15773761
diff --git a/src/api/documents.py b/src/api/documents.pyindex 7a7ddb18b..227b1edc3 100644--- a/src/api/documents.py+++ b/src/api/documents.py@@ -119,8 +119,10 @@ async def delete_documents_by_filename_core(filename=normalized_filename,error=str(e),)- error_str = str(e)- status_code = 403 if "AuthenticationException" in error_str else 500+ from utils.opensearch_utils import AUTH_ERROR_MESSAGE, is_opensearch_auth_error++ is_auth_error = is_opensearch_auth_error(e)+ status_code = 401 if is_auth_error else 500return ({"success": False,@@ -128,8 +130,8 @@ async def delete_documents_by_filename_core("filename": normalized_filename,"message": None,"error": (- "Access denied: insufficient permissions"- if status_code == 403+ AUTH_ERROR_MESSAGE+ if is_auth_errorelse "An internal error has occurred while deleting documents"),},@@ -231,11 +233,10 @@ async def check_filename_exists(except Exception as e:logger.error("Error checking filename existence", filename=filename, error=str(e))- error_str = str(e)- if "AuthenticationException" in error_str:- return JSONResponse(- {"error": "Access denied: insufficient permissions"}, status_code=403- )+ from utils.opensearch_utils import AUTH_ERROR_MESSAGE, is_opensearch_auth_error++ if is_opensearch_auth_error(e):+ return JSONResponse({"error": AUTH_ERROR_MESSAGE}, status_code=401)else:return JSONResponse({"error": str(e)}, status_code=500)diff --git a/src/api/files.py b/src/api/files.pyindex b88fcf636..226b1de1b 100644--- a/src/api/files.py+++ b/src/api/files.py@@ -5,12 +5,10 @@ Provides server-side file-level views over the chunk-based OpenSearch index,replacing the client-side chunk-to-file aggregation pattern."""-from typing import Optional-from fastapi import Depends, Queryfrom fastapi.responses import JSONResponse-from dependencies import get_session_manager, get_current_user+from dependencies import get_current_user, get_session_managerfrom session_manager import Userfrom utils.logging_config import get_logger@@ -28,10 +26,10 @@ async def list_files(page_size: int = Query(25, ge=1, le=100, description="Items per page"),sort_by: str = Query("filename", description="Sort field"),sort_order: str = Query("asc", regex="^(asc|desc)$", description="Sort order"),- connector_type: Optional[str] = Query(None, description="Filter by connector type"),- mimetype: Optional[str] = Query(None, description="Filter by MIME type"),- owner: Optional[str] = Query(None, description="Filter by owner"),- search: Optional[str] = Query(None, description="Search filename"),+ connector_type: str | None = Query(None, description="Filter by connector type"),+ mimetype: str | None = Query(None, description="Filter by MIME type"),+ owner: str | None = Query(None, description="Filter by owner"),+ search: str | None = Query(None, description="Search filename"),file_service=Depends(_get_file_service),user: User = Depends(get_current_user),):@@ -52,6 +50,10 @@ async def list_files(return JSONResponse(result)except Exception as e:logger.error("Failed to list files", error=str(e))+ from utils.opensearch_utils import AUTH_ERROR_MESSAGE, is_opensearch_auth_error++ if is_opensearch_auth_error(e):+ return JSONResponse({"error": AUTH_ERROR_MESSAGE}, status_code=401)return JSONResponse({"error": "Failed to list files", "detail": str(e)},status_code=500,@@ -62,9 +64,9 @@ async def search_files(q: str = Query(..., min_length=1, description="Search query"),page: int = Query(1, ge=1, description="Page number"),page_size: int = Query(25, ge=1, le=100, description="Items per page"),- connector_type: Optional[str] = Query(None, description="Filter by connector type"),- mimetype: Optional[str] = Query(None, description="Filter by MIME type"),- owner: Optional[str] = Query(None, description="Filter by owner"),+ connector_type: str | None = Query(None, description="Filter by connector type"),+ mimetype: str | None = Query(None, description="Filter by MIME type"),+ owner: str | None = Query(None, description="Filter by owner"),file_service=Depends(_get_file_service),user: User = Depends(get_current_user),):@@ -83,6 +85,10 @@ async def search_files(return JSONResponse(result)except Exception as e:logger.error("Failed to search files", error=str(e))+ from utils.opensearch_utils import AUTH_ERROR_MESSAGE, is_opensearch_auth_error++ if is_opensearch_auth_error(e):+ return JSONResponse({"error": AUTH_ERROR_MESSAGE}, status_code=401)return JSONResponse({"error": "Failed to search files", "detail": str(e)},status_code=500,diff --git a/src/api/knowledge_filter.py b/src/api/knowledge_filter.pyindex 88b19cba3..c9096007b 100644--- a/src/api/knowledge_filter.py+++ b/src/api/knowledge_filter.py@@ -19,6 +19,27 @@ from utils.logging_config import get_loggerlogger = get_logger(__name__)+def _error_response(result: dict) -> JSONResponse:+ """Map a failed knowledge-filter service result to the right HTTP status.++ Distinguishes an OpenSearch authentication failure (credential rejected ->+ 401, re-authenticate) from authorization ("access denied"/owner check ->+ 403). Conflating the two as 403 "insufficient permissions" hides the real+ cause. ``not found`` stays 404; everything else is 500.+ """+ from utils.opensearch_utils import is_opensearch_auth_error++ error_msg = result.get("error", "") or ""+ low = error_msg.lower()+ if "not found" in low or "already deleted" in low:+ return JSONResponse(result, status_code=404)+ if is_opensearch_auth_error(error_msg):+ return JSONResponse(result, status_code=401)+ if "access denied" in low or "insufficient permissions" in low:+ return JSONResponse(result, status_code=403)+ return JSONResponse(result, status_code=500)++def normalize_query_data(query_data: str | dict) -> str:"""Normalize query_data to ensure all required fields exist with defaults.@@ -117,12 +138,7 @@ async def create_knowledge_filter(if result.get("success"):return JSONResponse(result, status_code=201)- else:- error_msg = result.get("error", "")- if "AuthenticationException" in error_msg or "access denied" in error_msg.lower():- return JSONResponse(result, status_code=403)- else:- return JSONResponse(result, status_code=500)+ return _error_response(result)async def search_knowledge_filters(@@ -139,12 +155,7 @@ async def search_knowledge_filters(if result.get("success"):return JSONResponse(result, status_code=200)- else:- error_msg = result.get("error", "")- if "AuthenticationException" in error_msg or "access denied" in error_msg.lower():- return JSONResponse(result, status_code=403)- else:- return JSONResponse(result, status_code=500)+ return _error_response(result)async def get_knowledge_filter(@@ -161,14 +172,7 @@ async def get_knowledge_filter(if result.get("success"):return JSONResponse(result, status_code=200)- else:- error_msg = result.get("error", "")- if "not found" in error_msg.lower():- return JSONResponse(result, status_code=404)- elif "AuthenticationException" in error_msg or "access denied" in error_msg.lower():- return JSONResponse(result, status_code=403)- else:- return JSONResponse(result, status_code=500)+ return _error_response(result)async def update_knowledge_filter(@@ -230,12 +234,7 @@ async def update_knowledge_filter(if result.get("success"):return JSONResponse(result, status_code=200)- else:- error_msg = result.get("error", "")- if "AuthenticationException" in error_msg or "access denied" in error_msg.lower():- return JSONResponse(result, status_code=403)- else:- return JSONResponse(result, status_code=500)+ return _error_response(result)async def delete_knowledge_filter(@@ -252,16 +251,7 @@ async def delete_knowledge_filter(if result.get("success"):return JSONResponse(result, status_code=200)- else:- error_msg = result.get("error", "")- if "not found" in error_msg.lower() or "already deleted" in error_msg.lower():- return JSONResponse(result, status_code=404)- elif (- "access denied" in error_msg.lower() or "insufficient permissions" in error_msg.lower()- ):- return JSONResponse(result, status_code=403)- else:- return JSONResponse(result, status_code=500)+ return _error_response(result)async def subscribe_to_knowledge_filter(@@ -339,14 +329,7 @@ async def list_knowledge_filter_subscriptions(if result.get("success"):return JSONResponse(result, status_code=200)- else:- error_msg = result.get("error", "")- if "not found" in error_msg.lower():- return JSONResponse(result, status_code=404)- elif "access denied" in error_msg.lower():- return JSONResponse(result, status_code=403)- else:- return JSONResponse(result, status_code=500)+ return _error_response(result)async def cancel_knowledge_filter_subscription(diff --git a/src/dependencies.py b/src/dependencies.pyindex 15e549781..6f36add51 100644--- a/src/dependencies.py+++ b/src/dependencies.py@@ -522,6 +522,7 @@ def _stage_jwt_roles(request: Request, claims: dict, user_id: str | None) -> Nonstatus_code=401,detail="User has no OpenRAG roles assigned",)+ logger.debug(f"JWT roles: {jwt_roles}")request.state.jwt_roles = jwt_roles@@ -684,6 +685,64 @@ async def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:# existing DB roles untouched). RBAC on -> extract + 401 if none._stage_jwt_roles(request, claims, user_id)+ from utils.run_mode_utils import is_run_mode_saas++ saas_rbac = is_run_mode_saas() and jwt_roles_enabled()++ # The forwarded end-user JWT is the OpenSearch credential — OpenSearch's+ # openid_auth_domain validates it via the backend JWKS. Build it once; it's+ # used both as the saas+rbac authoritative credential and as the header-less+ # fallback in other modes.+ jwt_user = None+ if ibm_token and user_id:+ jwt_user = User(+ user_id=user_id,+ email=email,+ name=name,+ picture=None,+ provider="ibm_ams",+ jwt_token=f"Bearer {ibm_token}",+ opensearch_username=None,+ opensearch_credentials=None,+ )++ # In SaaS + RBAC the JWT is authoritative: the lakehouse `X-IBM-LH-Credentials`+ # Basic credential must NOT override it (when the gateway began injecting that+ # header, OpenSearch rejected the Basic cred with 401 and every data-plane call+ # surfaced as a misleading 403 "insufficient permissions"). Return before+ # `_resolve_lakehouse_credentials` so its connections-store upsert side effect+ # is also skipped. Mirrors the /v1 surface, which already treats the JWT as+ # primary.+ if saas_rbac:+ if jwt_user:+ logger.debug(+ "[AUTH] User created from forwarded JWT (saas+rbac; lakehouse creds bypassed)"+ )+ request.state.user = jwt_user+ return jwt_user+ # saas + RBAC but no valid forwarded JWT (missing header, undecodable, or no+ # `sub`). Do NOT degrade to lakehouse Basic creds or the debug cookie — that+ # would authenticate (and write DB user/role rows) under a roles-less+ # identity. Fail loud, mirroring get_api_key_user_async's saas_rbac branch.+ request.state.user = None+ if required:+ logger.error(+ "[AUTH] No valid forwarded JWT under saas+RBAC; refusing lakehouse/basic fallback",+ jwt_present=bool(ibm_token),+ )+ raise HTTPException(+ status_code=401,+ detail={+ "error": "invalid_jwt" if ibm_token else "missing_user_jwt",+ "message": (+ "No valid user JWT was forwarded by the gateway. In SaaS/RBAC "+ "mode the gateway must forward the end-user JWT on every request."+ ),+ },+ )+ return None++ # Other modes: lakehouse Basic creds take precedence when present.opensearch_username, lh_credentials = await _resolve_lakehouse_credentials(request, user_id)if lh_credentials:@@ -704,23 +763,12 @@ async def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:request.state.user = userreturn user- if ibm_token and user_id:+ if jwt_user:logger.warning("[AUTH] IBM LH credentials not found in header or connections store. Using JWT token instead.")- user = User(- user_id=user_id,- email=email,- name=name,- picture=None,- provider="ibm_ams",- jwt_token=f"Bearer {ibm_token}",- opensearch_username=None,- opensearch_credentials=None,- )- logger.debug("[AUTH] User created successfully")- request.state.user = user- return user+ request.state.user = jwt_user+ return jwt_userif ibm_token and not user_id:logger.warning("IBM JWT cookie present but could not extract user_id from claims.")diff --git a/src/services/file_service.py b/src/services/file_service.pyindex fee5d96cd..ce3f86786 100644--- a/src/services/file_service.py+++ b/src/services/file_service.py@@ -50,6 +50,12 @@ class FileService:)except Exception as e:logger.error("Failed to list files", error=str(e))+ # An auth failure (OpenSearch rejected the credential) must not be+ # masked as an empty result — surface it so the route returns 401.+ from utils.opensearch_utils import is_opensearch_auth_error++ if is_opensearch_auth_error(e):+ raisereturn {"files": [], "total": 0, "page": page, "page_size": page_size}files = self._parse_aggregation_buckets(result)diff --git a/src/services/knowledge_filter_service.py b/src/services/knowledge_filter_service.pyindex a8c7637b1..90fb05250 100644--- a/src/services/knowledge_filter_service.py+++ b/src/services/knowledge_filter_service.py@@ -206,16 +206,18 @@ class KnowledgeFilterService:return {"success": False, "error": "Failed to delete knowledge filter"}except Exception as e:+ from utils.opensearch_utils import AUTH_ERROR_MESSAGE, is_opensearch_auth_error+error_str = str(e)if "not_found" in error_str or "NotFoundError" in error_str:return {"success": False,"error": "Knowledge filter not found or already deleted",}- elif "AuthenticationException" in error_str:+ elif is_opensearch_auth_error(error_str):return {"success": False,- "error": "Access denied: insufficient permissions",+ "error": AUTH_ERROR_MESSAGE,}else:return {diff --git a/src/utils/opensearch_utils.py b/src/utils/opensearch_utils.pyindex 68390458c..d01ac780e 100644--- a/src/utils/opensearch_utils.py+++ b/src/utils/opensearch_utils.py@@ -38,6 +38,33 @@ class OpenSearchDiskSpaceError(Exception):"""Raised when OpenSearch operations fail due to insufficient disk space."""+# Error strings emitted by OpenSearch when the presented credential is rejected.+# This is an AUTHENTICATION failure (bad/expired/over-ridden credential), not an+# authorization one — callers must surface it as 401, never 403 "insufficient+# permissions", so the real cause isn't masked.+_AUTH_ERROR_INDICATORS = [+ "authenticationexception",+ "unauthorized",+ "authentication failed",+]++AUTH_ERROR_MESSAGE = (+ "Authentication failed: OpenSearch rejected the credential. Please sign in again."+)+++def is_opensearch_auth_error(error: Exception | str) -> bool:+ """Whether *error* is an OpenSearch authentication failure (401).++ Accepts an exception or an already-stringified error message. Distinct from+ authorization ("only the owner can …"): this means the credential OpenRAG+ presented was not accepted at all. Callers should map it to HTTP 401+ (re-authenticate), not 403.+ """+ error_str = str(error).lower()+ return any(indicator in error_str for indicator in _AUTH_ERROR_INDICATORS)++def is_disk_space_error(error: Exception) -> bool:"""Check whether an exception is caused by OpenSearch disk space constraints.diff --git a/tests/unit/dependencies/test_ibm_header_auth.py b/tests/unit/dependencies/test_ibm_header_auth.pyindex f8900b24f..aac5017fb 100644--- a/tests/unit/dependencies/test_ibm_header_auth.py+++ b/tests/unit/dependencies/test_ibm_header_auth.py@@ -97,3 +97,57 @@ async def test_rbac_on_missing_header_401(monkeypatch):with pytest.raises(HTTPException) as exc:await _get_ibm_user(req, required=True)assert exc.value.status_code == 401+++# Default IBM_CREDENTIALS_HEADER (not overridden in tests).+LH_HEADER = "X-IBM-LH-Credentials"+++async def test_saas_rbac_no_jwt_does_not_degrade_to_lakehouse(monkeypatch):+ """saas+RBAC with no forwarded JWT must fail loud, even when the lakehouse+ credentials header is present — it must NOT build a Basic lakehouse user."""+ monkeypatch.setenv("OPENRAG_RBAC_ENFORCE", "true")+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")+ monkeypatch.setattr(+ ibm_auth,+ "decode_ibm_jwt",+ lambda tok: (_ for _ in ()).throw(AssertionError("decode must not run without a JWT")),+ )+ # No JWT header, but lakehouse creds ARE present (the pre-fix degrade path).+ req = _FakeRequest(headers={LH_HEADER: "dGVzdDp0ZXN0"})++ with pytest.raises(HTTPException) as exc:+ await _get_ibm_user(req, required=True)+ assert exc.value.status_code == 401+ assert exc.value.detail["error"] == "missing_user_jwt"+++async def test_saas_rbac_no_jwt_optional_returns_none(monkeypatch):+ """saas+RBAC with no forwarded JWT on an optional endpoint returns None+ (anonymous), not a 401."""+ monkeypatch.setenv("OPENRAG_RBAC_ENFORCE", "true")+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")+ req = _FakeRequest(headers={LH_HEADER: "dGVzdDp0ZXN0"})++ user = await _get_ibm_user(req, required=False)++ assert user is None+++async def test_saas_rbac_jwt_wins_over_lakehouse_header(monkeypatch):+ """saas+RBAC: a valid forwarded JWT is authoritative — the lakehouse header+ must never override it into a Basic credential."""+ monkeypatch.setenv("OPENRAG_RBAC_ENFORCE", "true")+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")+ claims = {"sub": "s1", "username": "alice", "display_name": "Alice", "openrag_roles": ["admin"]}+ monkeypatch.setattr(ibm_auth, "decode_ibm_jwt", lambda tok: claims if tok == "tok" else None)+ req = _FakeRequest(headers={"X-OpenRAG-JWT": "Bearer tok", LH_HEADER: "dGVzdDp0ZXN0"})++ user = await _get_ibm_user(req, required=True)++ assert user is not None+ assert user.jwt_token == "Bearer tok" # Bearer JWT, never "Basic ..."+ assert user.opensearch_credentials is None