Skip to content

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

Python

Support IBM header auth and persist credentials

Edwin Josed07a65c6d51e
diff --git a/frontend/app/login/page.tsx b/frontend/app/login/page.tsx
index e6683dac0..1a6aeba38 100644
--- a/frontend/app/login/page.tsx
+++ b/frontend/app/login/page.tsx
@@ -2,81 +2,12 @@
import { Loader2 } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
-import { Suspense, useEffect, useState } from "react";
+import { Suspense, useEffect } from "react";
import GoogleLogo from "@/components/icons/google-logo";
import Logo from "@/components/icons/openrag-logo";
import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
import { useAuth } from "@/contexts/auth-context";
-function IbmLoginForm({ onSuccess }: { onSuccess: () => void }) {
- const { loginWithIbm } = useAuth();
- const [username, setUsername] = useState("");
- const [password, setPassword] = useState("");
- const [error, setError] = useState<string | null>(null);
- const [isSubmitting, setIsSubmitting] = useState(false);
-
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- setError(null);
- setIsSubmitting(true);
- try {
- await loginWithIbm(username, password);
- onSuccess();
- } catch (err) {
- setError(err instanceof Error ? err.message : "Login failed");
- } finally {
- setIsSubmitting(false);
- }
- };
-
- return (
- <form onSubmit={handleSubmit} className="flex flex-col gap-4 w-80">
- <div className="flex flex-col gap-1.5">
- <Label htmlFor="username">Username</Label>
- <Input
- id="username"
- type="text"
- autoComplete="username"
- value={username}
- onChange={(e) => setUsername(e.target.value)}
- required
- disabled={isSubmitting}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <Label htmlFor="password">Password</Label>
- <Input
- id="password"
- type="password"
- autoComplete="current-password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- required
- disabled={isSubmitting}
- />
- </div>
- {error && <p className="text-sm text-destructive">{error}</p>}
- <Button
- type="submit"
- className="w-full"
- size="lg"
- disabled={isSubmitting}
- >
- {isSubmitting ? (
- <>
- <Loader2 className="h-4 w-4 animate-spin" />
- Signing in…
- </>
- ) : (
- "Sign in"
- )}
- </Button>
- </form>
- );
-}
-
function LoginPageContent() {
const { isLoading, isAuthenticated, isNoAuthMode, isIbmAuthMode, login } =
useAuth();
@@ -86,10 +17,10 @@ function LoginPageContent() {
const redirect = searchParams.get("redirect") || "/chat";
useEffect(() => {
- if (!isLoading && (isAuthenticated || isNoAuthMode)) {
+ if (!isLoading && (isAuthenticated || isNoAuthMode || isIbmAuthMode)) {
router.push(redirect);
}
- }, [isLoading, isAuthenticated, isNoAuthMode, router, redirect]);
+ }, [isLoading, isAuthenticated, isNoAuthMode, isIbmAuthMode, router, redirect]);
if (isLoading) {
return (
@@ -102,7 +33,7 @@ function LoginPageContent() {
);
}
- if (isAuthenticated || isNoAuthMode) {
+ if (isAuthenticated || isNoAuthMode || isIbmAuthMode) {
return null; // Will redirect in useEffect
}
@@ -114,14 +45,10 @@ function LoginPageContent() {
<h1 className="text-2xl font-medium font-chivo">
Welcome to OpenRAG
</h1>
- {isIbmAuthMode ? (
- <IbmLoginForm onSuccess={() => router.push(redirect)} />
- ) : (
- <Button onClick={login} className="w-80 gap-1.5" size="lg">
- <GoogleLogo className="h-4 w-4" />
- Continue with Google
- </Button>
- )}
+ <Button onClick={login} className="w-80 gap-1.5" size="lg">
+ <GoogleLogo className="h-4 w-4" />
+ Continue with Google
+ </Button>
</div>
</div>
</div>
diff --git a/src/config/settings.py b/src/config/settings.py
index 52a288e17..b3d556288 100644
--- a/src/config/settings.py
+++ b/src/config/settings.py
@@ -53,6 +53,7 @@ GOOGLE_OAUTH_CLIENT_SECRET = os.getenv("GOOGLE_OAUTH_CLIENT_SECRET")
IBM_AUTH_ENABLED = os.getenv("IBM_AUTH_ENABLED", "false").lower() in ("true", "1", "yes")
IBM_JWT_PUBLIC_KEY_URL = os.getenv("IBM_JWT_PUBLIC_KEY_URL", "")
IBM_SESSION_COOKIE_NAME = os.getenv("IBM_SESSION_COOKIE_NAME", "ibm-openrag-session")
+IBM_CREDENTIALS_HEADER = os.getenv("IBM_CREDENTIALS_HEADER", "X-IBM-LH-Credentials")
DOCLING_OCR_ENGINE = os.getenv("DOCLING_OCR_ENGINE")
IBM_AUTH_ENABLED = os.getenv("IBM_AUTH_ENABLED", "false").lower() in ("true", "1", "yes")
diff --git a/src/connectors/connection_manager.py b/src/connectors/connection_manager.py
index bbf6bb203..8208db3ea 100644
--- a/src/connectors/connection_manager.py
+++ b/src/connectors/connection_manager.py
@@ -151,6 +151,37 @@ class ConnectionManager:
return connection
return None
+ async def upsert_ibm_credentials(
+ self, user_id: str, basic_credentials: str, username: str
+ ) -> str:
+ """Store or update IBM OpenSearch credentials for a user in connections.json.
+
+ Uses connector_type='ibm_credentials' — this entry is a credentials store only
+ and is never passed to _create_connector.
+ """
+ for conn in self.connections.values():
+ if (
+ conn.connector_type == "ibm_credentials"
+ and conn.user_id == user_id
+ and conn.is_active
+ ):
+ conn.config["basic_credentials"] = basic_credentials
+ conn.config["username"] = username
+ await self.save_connections()
+ return conn.connection_id
+
+ conn_id = str(uuid.uuid4())
+ new_conn = ConnectionConfig(
+ connection_id=conn_id,
+ connector_type="ibm_credentials",
+ name=f"IBM Credentials ({username})",
+ config={"basic_credentials": basic_credentials, "username": username},
+ user_id=user_id,
+ )
+ self.connections[conn_id] = new_conn
+ await self.save_connections()
+ return conn_id
+
async def cleanup_duplicate_connections(self, remove_duplicates=False):
"""
Clean up duplicate connections, keeping only the most recent connection
diff --git a/src/dependencies.py b/src/dependencies.py
index 75108501a..15468dadf 100644
--- a/src/dependencies.py
+++ b/src/dependencies.py
@@ -89,20 +89,54 @@ def get_flows_service(services: dict = Depends(get_services)):
# IBM AMS authentication helper
# ─────────────────────────────────────────────
-def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:
+async def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:
"""Authenticate via IBM AMS.
+ 0. X-IBM-LH-Credentials header (configurable via IBM_CREDENTIALS_HEADER) —
+ injected by Traefik on every forwarded request. Contains Basic credentials
+ for OpenSearch. Decoded and persisted to connections.json per user.
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.
+ If *required* is True, raises HTTP 401 when none 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_SESSION_COOKIE_NAME
+ from config.settings import IBM_SESSION_COOKIE_NAME, IBM_CREDENTIALS_HEADER
+
+ # ── Option 0: Configurable credentials header (Traefik production) ───
+ lh_credentials = request.headers.get(IBM_CREDENTIALS_HEADER, "")
+ if lh_credentials.startswith("Basic "):
+ try:
+ decoded = base64.b64decode(lh_credentials[6:]).decode("utf-8")
+ username = decoded.split(":", 1)[0]
+ except Exception:
+ username = "unknown"
+
+ # Persist credentials to connections.json for reuse by background processes
+ connector_service = request.app.state.services.get("connector_service")
+ if connector_service:
+ await connector_service.connection_manager.upsert_ibm_credentials(
+ user_id=username,
+ basic_credentials=lh_credentials,
+ username=username,
+ )
+
+ user = User(
+ user_id=username,
+ email=username,
+ name=username,
+ picture=None,
+ provider="ibm_ams",
+ jwt_token=lh_credentials,
+ opensearch_username=username,
+ opensearch_credentials=lh_credentials,
+ )
+ request.state.user = user
+ return user
# ── Option 1: ibm-openrag-session cookie (production via Traefik) ───
ibm_token = request.cookies.get(IBM_SESSION_COOKIE_NAME)
@@ -151,7 +185,7 @@ def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:
# Authentication dependencies
# ─────────────────────────────────────────────
-def get_current_user(
+async def get_current_user(
request: Request,
session_manager=Depends(get_session_manager),
) -> User:
@@ -166,7 +200,7 @@ def get_current_user(
# IBM AMS cookie auth takes priority when enabled
if IBM_AUTH_ENABLED:
- return _get_ibm_user(request, required=True)
+ return await _get_ibm_user(request, required=True)
if is_no_auth_mode():
user = AnonymousUser()
@@ -191,7 +225,7 @@ def get_current_user(
return user_with_token
-def get_optional_user(
+async def get_optional_user(
request: Request,
session_manager=Depends(get_session_manager),
) -> Optional[User]:
@@ -206,7 +240,7 @@ def get_optional_user(
# IBM AMS cookie auth takes priority when enabled
if IBM_AUTH_ENABLED:
- return _get_ibm_user(request, required=False)
+ return await _get_ibm_user(request, required=False)
if is_no_auth_mode():
user = AnonymousUser()
diff --git a/src/session_manager.py b/src/session_manager.py
index aea73e0d0..27e4e11ec 100644
--- a/src/session_manager.py
+++ b/src/session_manager.py
@@ -23,6 +23,8 @@ class User:
created_at: datetime = None
last_login: datetime = None
jwt_token: Optional[str] = None
+ opensearch_username: Optional[str] = None
+ opensearch_credentials: Optional[str] = None # Full "Basic <base64>" string
def __post_init__(self):
if self.created_at is None:
@@ -250,10 +252,14 @@ class SessionManager:
# Get the effective JWT token (handles anonymous JWT creation)
jwt_token = self.get_effective_jwt_token(user_id, jwt_token)
+ from config.settings import IBM_AUTH_ENABLED, clients
+
+ # In IBM mode credentials may rotate per-request — always create a fresh client
+ if IBM_AUTH_ENABLED:
+ return clients.create_user_opensearch_client(jwt_token)
+
# Check if we have a cached client for this user
if user_id not in self.user_opensearch_clients:
- from config.settings import clients
-
self.user_opensearch_clients[user_id] = (
clients.create_user_opensearch_client(jwt_token)
)