OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
Add user/pass support
Mike Fortman7f875d6e741c
diff --git a/frontend/app/login/page.tsx b/frontend/app/login/page.tsxindex 5b577e901..e6683dac0 100644--- a/frontend/app/login/page.tsx+++ b/frontend/app/login/page.tsx@@ -2,25 +2,94 @@import { Loader2 } from "lucide-react";import { useRouter, useSearchParams } from "next/navigation";-import { Suspense, useEffect } from "react";+import { Suspense, useEffect, useState } 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();+ const { isLoading, isAuthenticated, isNoAuthMode, isIbmAuthMode, login } =+ useAuth();const router = useRouter();const searchParams = useSearchParams();const redirect = searchParams.get("redirect") || "/chat";- // Redirect if already authenticated, in no-auth mode, or IBM auth modeuseEffect(() => {- if (!isLoading && (isAuthenticated || isNoAuthMode || isIbmAuthMode)) {+ if (!isLoading && (isAuthenticated || isNoAuthMode)) {router.push(redirect);}- }, [isLoading, isAuthenticated, isNoAuthMode, isIbmAuthMode, router, redirect]);+ }, [isLoading, isAuthenticated, isNoAuthMode, router, redirect]);if (isLoading) {return (@@ -33,7 +102,7 @@ function LoginPageContent() {);}- if (isAuthenticated || isNoAuthMode || isIbmAuthMode) {+ if (isAuthenticated || isNoAuthMode) {return null; // Will redirect in useEffect}@@ -45,10 +114,14 @@ function LoginPageContent() {<h1 className="text-2xl font-medium font-chivo">Welcome to OpenRAG</h1>- <Button onClick={login} className="w-80 gap-1.5" size="lg">- <GoogleLogo className="h-4 w-4" />- Continue with Google- </Button>+ {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>+ )}</div></div></div>diff --git a/frontend/contexts/auth-context.tsx b/frontend/contexts/auth-context.tsxindex 3b36667ad..fd25302e0 100644--- a/frontend/contexts/auth-context.tsx+++ b/frontend/contexts/auth-context.tsx@@ -25,6 +25,7 @@ interface AuthContextType {isNoAuthMode: boolean;isIbmAuthMode: boolean;login: () => void;+ loginWithIbm: (username: string, password: string) => Promise<void>;logout: () => Promise<void>;refreshAuth: () => Promise<void>;}@@ -50,6 +51,7 @@ export function AuthProvider({ children }: AuthProviderProps) {const [isIbmAuthMode, setIsIbmAuthMode] = useState(false);const checkAuth = useCallback(async () => {+ setIsLoading(true);try {const response = await fetch("/api/auth/me");@@ -61,12 +63,19 @@ export function AuthProvider({ children }: AuthProviderProps) {}const data = await response.json();+ console.log("[checkAuth] /api/auth/me response:", data);// Check auth mode flagsif (data.ibm_auth_mode) {setIsIbmAuthMode(true);setIsNoAuthMode(false);setUser(data.authenticated && data.user ? data.user : null);+ console.log(+ "[checkAuth] IBM auth mode — authenticated:",+ data.authenticated,+ "user:",+ data.user,+ );} else if (data.no_auth_mode) {setIsNoAuthMode(true);setIsIbmAuthMode(false);@@ -82,6 +91,7 @@ export function AuthProvider({ children }: AuthProviderProps) {}setIsLoading(false);+ console.log("[checkAuth] done — isLoading: false");} catch (error) {console.error("Auth check failed:", error);// Network error - backend not ready, keep loading and retry@@ -97,7 +107,9 @@ export function AuthProvider({ children }: AuthProviderProps) {return;}if (isIbmAuthMode) {- console.log("Login attempted in IBM auth mode - ignored (auth managed by IBM Watsonx Data)");+ console.log(+ "Login attempted in IBM auth mode - ignored (auth managed by IBM Watsonx Data)",+ );return;}@@ -159,6 +171,31 @@ export function AuthProvider({ children }: AuthProviderProps) {});};+ const loginWithIbm = async (username: string, password: string) => {+ console.log("[loginWithIbm] posting to /api/auth/ibm/login");+ const response = await fetch("/api/auth/ibm/login", {+ method: "POST",+ headers: {+ Authorization: "Basic " + btoa(username + ":" + password),+ },+ });+ console.log(+ "[loginWithIbm] response status:",+ response.status,+ "ok:",+ response.ok,+ );+ console.log(+ "[loginWithIbm] response cookies after login:",+ document.cookie,+ );+ if (!response.ok) {+ const data = await response.json().catch(() => ({}));+ throw new Error(data.detail || "Login failed");+ }+ await checkAuth();+ };+const logout = async () => {// Don't allow logout in no-auth mode or IBM auth modeif (isNoAuthMode || isIbmAuthMode) {@@ -187,10 +224,11 @@ export function AuthProvider({ children }: AuthProviderProps) {const value: AuthContextType = {user,isLoading,- isAuthenticated: !!user || isIbmAuthMode,+ isAuthenticated: !!user,isNoAuthMode,isIbmAuthMode,login,+ loginWithIbm,logout,refreshAuth,};diff --git a/src/api/auth.py b/src/api/auth.pyindex be8612054..324f44c24 100644--- a/src/api/auth.py+++ b/src/api/auth.py@@ -1,6 +1,6 @@from typing import Optional-from fastapi import Depends, Request+from fastapi import Depends, HTTPException, Requestfrom fastapi.responses import JSONResponsefrom utils.telemetry import TelemetryClient, Category, MessageId@@ -20,6 +20,8 @@ class AuthInitBody(BaseModel):redirect_uri: Optional[str] = None++class AuthCallbackBody(BaseModel):connection_id: strauthorization_code: str@@ -129,3 +131,30 @@ async def auth_logout()return response+++async def ibm_login(request: Request):+ """IBM login endpoint — Basic Auth header is validated by Traefik in production.++ When running without Traefik (local dev), this endpoint sets an ibm-auth-basic+ session cookie from the Basic Auth header so subsequent requests are authenticated.+ """+ from config.settings import IBM_AUTH_ENABLED++ if not IBM_AUTH_ENABLED:+ raise HTTPException(status_code=404, detail="IBM auth is not enabled")++ response = JSONResponse({"status": "ok"})++ # Persist the Basic Auth header as a cookie so /auth/me and other endpoints+ # can authenticate subsequent requests (Traefik handles this in production).+ auth_header = request.headers.get("Authorization", "")+ if auth_header.startswith("Basic "):+ response.set_cookie(+ "ibm-auth-basic",+ auth_header,+ httponly=True,+ samesite="lax",+ )++ return responsediff --git a/src/config/settings.py b/src/config/settings.pyindex 09f7e9210..732c68940 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -785,8 +785,16 @@ class AppClients:)def create_user_opensearch_client(self, jwt_token: str):- """Create OpenSearch client with user's JWT token for OIDC auth"""- headers = {"Authorization": f"Bearer {jwt_token}"}+ """Create OpenSearch client with user's auth token.++ If jwt_token already contains an auth scheme (e.g. "Basic ..." or "Bearer ..."),+ it is used verbatim. Otherwise it is wrapped as a Bearer token.+ """+ if jwt_token.startswith(("Basic ", "Bearer ")):+ auth_header = jwt_token+ else:+ auth_header = f"Bearer {jwt_token}"+ headers = {"Authorization": auth_header}return AsyncOpenSearch(hosts=[{"host": OPENSEARCH_HOST, "port": OPENSEARCH_PORT}],diff --git a/src/dependencies.py b/src/dependencies.pyindex e35c34e3f..884e4366d 100644--- a/src/dependencies.py+++ b/src/dependencies.py@@ -90,53 +90,88 @@ def get_flows_service(services: dict = Depends(get_services)):# ─────────────────────────────────────────────def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:- """Extract and validate the IBM AMS JWT from ibm-lh-console-session cookie.+ """Authenticate via IBM AMS — cookie-first, Basic Auth fallback.- If *required* is True, raises HTTP 401 on missing/invalid token.+ 1. ibm-lh-console-session cookie: JWT validated with IBM's public key.+ 2. Authorization: Basic header: decoded for user identity; Traefik has+ already validated the credentials, so we trust the header as-is and+ store the full header value to forward to OpenSearch.++ If *required* is True, raises HTTP 401 when neither is present/valid.If *required* is False, returns None instead of raising."""+ import base64import auth.ibm_auth as ibm_authfrom config.settings import IBM_JWT_PUBLIC_KEY_URL- ibm_token = request.cookies.get("ibm-lh-console-session")- if not ibm_token:- if required:- raise HTTPException(status_code=401, detail="IBM session cookie missing")- request.state.user = None- return None-- claims = ibm_auth.validate_ibm_jwt(ibm_token, ibm_auth._cached_public_key)-- # On validation failure, try re-fetching the public key once (key rotation)- if claims is None and IBM_JWT_PUBLIC_KEY_URL:+ # ── Option 1: cookie-based JWT ──────────────────────────────────────+ # Cookie name may include an instance UUID suffix, e.g.+ # ibm-lh-console-session-cd4fcbaf-6a3a-4a05-80af-92df02f64c54+ logger.info("IBM auth: cookies received by backend", cookie_keys=list(request.cookies.keys()))+ ibm_token = next(+ (v for k, v in request.cookies.items() if k.startswith("ibm-lh-console-session")),+ None,+ )+ logger.info("IBM auth: ibm_token found", found=ibm_token is not None)+ if ibm_token:+ claims = ibm_auth.validate_ibm_jwt(ibm_token, ibm_auth._cached_public_key)+ logger.info("IBM auth: JWT validation result", claims_found=claims is not None, public_key_loaded=ibm_auth._cached_public_key is not None)++ # On validation failure, try re-fetching the public key once (key rotation)+ if claims is None and IBM_JWT_PUBLIC_KEY_URL:+ try:+ import httpx+ from cryptography.hazmat.primitives.serialization import load_pem_public_key+ with httpx.Client(timeout=10.0) as client:+ resp = client.get(IBM_JWT_PUBLIC_KEY_URL)+ resp.raise_for_status()+ pem = resp.json().get("public_key", "")+ if isinstance(pem, str):+ pem = pem.encode("utf-8")+ ibm_auth._cached_public_key = load_pem_public_key(pem)+ logger.info("IBM public key refreshed (key rotation detected)")+ claims = ibm_auth.validate_ibm_jwt(ibm_token, ibm_auth._cached_public_key)+ except Exception as exc:+ logger.warning("Failed to refresh IBM public key", error=str(exc))++ if claims is not None:+ user = User(+ user_id=claims.get("uid") or claims["sub"],+ email=claims.get("username", claims["sub"]),+ name=claims.get("display_name", claims.get("username", claims["sub"])),+ picture=None,+ provider="ibm_ams",+ jwt_token=ibm_token, # raw IBM JWT forwarded to OpenSearch as Bearer+ )+ request.state.user = user+ return user++ # ── Option 2: Basic Auth header or ibm-auth-basic cookie ────────────+ # The cookie is set by our ibm_login endpoint when Traefik is not present (local dev).+ auth_header = request.headers.get("Authorization", "") or request.cookies.get("ibm-auth-basic", "")+ if auth_header.startswith("Basic "):try:- import httpx- from cryptography.hazmat.primitives.serialization import load_pem_public_key- with httpx.Client(timeout=10.0) as client:- resp = client.get(IBM_JWT_PUBLIC_KEY_URL)- resp.raise_for_status()- ibm_auth._cached_public_key = load_pem_public_key(resp.content)- logger.info("IBM public key refreshed (key rotation detected)")- claims = ibm_auth.validate_ibm_jwt(ibm_token, ibm_auth._cached_public_key)- except Exception as exc:- logger.warning("Failed to refresh IBM public key", error=str(exc))-- if claims is None:- if required:- raise HTTPException(status_code=401, detail="Invalid or expired IBM session")- request.state.user = None- return None+ decoded = base64.b64decode(auth_header[6:]).decode("utf-8")+ username = decoded.split(":", 1)[0]+ except Exception:+ username = "unknown"++ user = User(+ user_id=username,+ email=username,+ name=username,+ picture=None,+ provider="ibm_ams_basic",+ jwt_token=auth_header, # full "Basic <value>" forwarded to OpenSearch+ )+ request.state.user = user+ return user- user = User(- user_id=claims.get("uid") or claims["sub"],- email=claims.get("username", claims["sub"]),- name=claims.get("display_name", claims.get("username", claims["sub"])),- picture=None,- provider="ibm_ams",- jwt_token=ibm_token, # raw IBM JWT passed directly to OpenSearch- )- request.state.user = user- return user+ # ── Neither present ──────────────────────────────────────────────────+ if required:+ raise HTTPException(status_code=401, detail="IBM authentication required")+ request.state.user = None+ return None# ─────────────────────────────────────────────diff --git a/src/main.py b/src/main.pyindex c537c741a..156522e61 100644--- a/src/main.py+++ b/src/main.py@@ -1540,9 +1540,8 @@ async def create_app():"/auth/callback", auth.auth_callback, methods=["POST"], tags=["internal"])app.add_api_route("/auth/me", auth.auth_me, methods=["GET"], tags=["internal"])- app.add_api_route(- "/auth/logout", auth.auth_logout, methods=["POST"], tags=["internal"]- )+ app.add_api_route("/auth/logout", auth.auth_logout, methods=["POST"], tags=["internal"])+ app.add_api_route("/auth/ibm/login", auth.ibm_login, methods=["POST"], tags=["internal"])# Connector endpointsapp.add_api_route("/connectors", connectors.list_connectors, methods=["GET"], tags=["internal"])diff --git a/src/services/auth_service.py b/src/services/auth_service.pyindex 72361964f..07902cbef 100644--- a/src/services/auth_service.py+++ b/src/services/auth_service.py@@ -506,7 +506,7 @@ class AuthService:# IBM auth mode: user is set by get_optional_user from IBM cookieif IBM_AUTH_ENABLED:user = getattr(request.state, "user", None)- if user and user.provider == "ibm_ams":+ if user and user.provider in ("ibm_ams", "ibm_ams_basic"):return {"authenticated": True,"ibm_auth_mode": True,