OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
feat: Workspace OAuth connector overrides + UI (#2040)
Edwin Jose5a3013ef6000
diff --git a/.env.example b/.env.exampleindex 2dcf6bd44..9f9c2fe6a 100644--- a/.env.example+++ b/.env.example@@ -417,6 +417,14 @@ OPENRAG_RUN_MODE=oss# mode: preview is only ever available in the "oss" and "saas" run modes above.# OPENRAG_INGEST_PREVIEW_ENABLED=false+# Feature flag for workspace-level OAuth connector credential overrides+# (default: false = disabled). When true, admins can override the+# env-var-configured OAuth client id/secret per connector from Connector+# Settings, and run a Test Connection check. When false, connectors only+# ever use their env var credentials and the admin UI/API for overrides is+# hidden/disabled.+# OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED=false+# Permission/identity cache backend. Only "memory" is currently wired.# When CACHE_BACKEND=memory the RBAC permission cache and OAuth-subject# cache are per-process, so OpenRAG must run with UVICORN_WORKERS=1 (anddiff --git a/frontend/app/api/mutations/useConnectConnectorMutation.ts b/frontend/app/api/mutations/useConnectConnectorMutation.tsindex d6bf4aa6b..40e653cba 100644--- a/frontend/app/api/mutations/useConnectConnectorMutation.ts+++ b/frontend/app/api/mutations/useConnectConnectorMutation.ts@@ -31,9 +31,13 @@ export const useConnectConnectorMutation = () => {mutationFn: async ({connector,redirectUri,+ purpose = "data_source",}: {connector: Connector;redirectUri: string;+ /** "test" runs a Test Connection check (see Connector Settings) and does+ * not persist a data-source connection on success. */+ purpose?: "data_source" | "test";}): Promise<ConnectResponse> => {const response = await fetch("/api/auth/init", {method: "POST",@@ -42,7 +46,7 @@ export const useConnectConnectorMutation = () => {},body: JSON.stringify({connector_type: connector.type,- purpose: "data_source",+ purpose,name: `${connector.name} Connection`,redirect_uri: redirectUri,}),@@ -64,11 +68,19 @@ export const useConnectConnectorMutation = () => {restoreConnectorQueries(queryClient, context);toast.error(err.message);},- onSuccess: (result, { connector }) => {+ onSuccess: (result, { connector, purpose = "data_source" }) => {if (result.oauth_config) {localStorage.setItem("connecting_connector_id", result.connection_id);localStorage.setItem("connecting_connector_type", connector.type);- localStorage.setItem("auth_purpose", "data_source");+ localStorage.setItem("auth_purpose", purpose);+ if (purpose === "test") {+ localStorage.setItem(+ "test_connection_return_tab",+ "connector-access",+ );+ } else {+ localStorage.removeItem("test_connection_return_tab");+ }const state = isIbmAuthMode? encodeBase64(diff --git a/frontend/app/api/mutations/useConnectorOAuthConfigMutation.ts b/frontend/app/api/mutations/useConnectorOAuthConfigMutation.tsnew file mode 100644index 000000000..2319bdaad--- /dev/null+++ b/frontend/app/api/mutations/useConnectorOAuthConfigMutation.ts@@ -0,0 +1,60 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { connectorOAuthConfigQueryKey } from "../queries/useConnectorOAuthConfigQuery";++export interface SaveConnectorOAuthConfigPayload {+ credentialKey: string;+ client_id?: string;+ client_secret?: string;+}++async function saveConnectorOAuthConfig({+ credentialKey,+ client_id,+ client_secret,+}: SaveConnectorOAuthConfigPayload) {+ const res = await fetch(+ `/api/connectors/oauth-config/${encodeURIComponent(credentialKey)}`,+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ client_id, client_secret }),+ },+ );+ const data = await res.json();+ if (!res.ok)+ throw new Error(data.error || "Failed to save connector credentials");+ return data;+}++export function useSaveConnectorOAuthConfigMutation() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: saveConnectorOAuthConfig,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: connectorOAuthConfigQueryKey });+ },+ });+}++async function clearConnectorOAuthConfig(credentialKey: string) {+ const res = await fetch(+ `/api/connectors/oauth-config/${encodeURIComponent(credentialKey)}`,+ { method: "DELETE" },+ );+ const data = await res.json();+ if (!res.ok)+ throw new Error(data.error || "Failed to clear connector credentials");+ return data;+}++export function useClearConnectorOAuthConfigMutation() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: clearConnectorOAuthConfig,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: connectorOAuthConfigQueryKey });+ },+ });+}diff --git a/frontend/app/api/queries/useConnectorOAuthConfigQuery.ts b/frontend/app/api/queries/useConnectorOAuthConfigQuery.tsnew file mode 100644index 000000000..6fc68038d--- /dev/null+++ b/frontend/app/api/queries/useConnectorOAuthConfigQuery.ts@@ -0,0 +1,31 @@+import { useQuery } from "@tanstack/react-query";++export interface ConnectorOAuthConfigStatus {+ client_id_set: boolean;+ client_id: string | null;+ secret_source: "override" | "env" | "none";+ env_client_id_set: boolean;+}++export type ConnectorOAuthConfigMap = Record<+ string,+ ConnectorOAuthConfigStatus+>;++async function fetchConnectorOAuthConfig(): Promise<ConnectorOAuthConfigMap> {+ const res = await fetch("/api/connectors/oauth-config");+ if (!res.ok) throw new Error("Failed to fetch connector OAuth config");+ const data = await res.json();+ return data.credentials as ConnectorOAuthConfigMap;+}++export const connectorOAuthConfigQueryKey = ["connector-oauth-config"] as const;++export function useConnectorOAuthConfigQuery(options?: { enabled?: boolean }) {+ return useQuery<ConnectorOAuthConfigMap>({+ queryKey: connectorOAuthConfigQueryKey,+ queryFn: fetchConnectorOAuthConfig,+ enabled: options?.enabled ?? true,+ staleTime: 0,+ });+}diff --git a/frontend/app/api/queries/useGetSettingsQuery.ts b/frontend/app/api/queries/useGetSettingsQuery.tsindex 12c08a2bf..c51e16816 100644--- a/frontend/app/api/queries/useGetSettingsQuery.ts+++ b/frontend/app/api/queries/useGetSettingsQuery.ts@@ -80,6 +80,7 @@ export interface Settings {ingest_via_chat?: boolean;show_provider_ingest_settings?: boolean;show_shared_upload_toggle?: boolean;+ show_workspace_oauth_overrides?: boolean;segment_write_key?: string;environment?: string;langflow_port?: string | number | null;diff --git a/frontend/app/auth/callback/page.tsx b/frontend/app/auth/callback/page.tsxindex 8a5bc055f..2fd71e073 100644--- a/frontend/app/auth/callback/page.tsx+++ b/frontend/app/auth/callback/page.tsx@@ -48,6 +48,7 @@ function AuthCallbackContent() {const state = searchParams.get("state");const finalConnectorId =localStorage.getItem("connecting_connector_id") || state;+ const storedConnectorType = localStorage.getItem("connecting_connector_type");const validationError = errorParam? `OAuth error: ${errorParam}`@@ -135,6 +136,19 @@ function AuthCallbackContent() {() => router.push(redirectTo),2000,);+ } else if (result.purpose === "test" || purpose === "test") {+ // Test Connection — token exchange succeeded, credentials work. No+ // connection was persisted (see _handle_test_auth); send the admin+ // back to Connector Settings with a success indicator to toast.+ cleanupOAuthStorage();+ localStorage.removeItem("test_connection_return_tab");+ redirectTimeoutRef.current = setTimeout(+ () =>+ router.push(+ `/settings/connector-access?oauth_test=success&credential=${encodeURIComponent(storedConnectorType || "")}`,+ ),+ 1000,+ );} else {cleanupOAuthStorage();redirectTimeoutRef.current = setTimeout(@@ -145,6 +159,7 @@ function AuthCallbackContent() {},onError: () => {cleanupOAuthStorage();+ localStorage.removeItem("test_connection_return_tab");sessionStorage.removeItem(callbackKey);},},@@ -155,6 +170,7 @@ function AuthCallbackContent() {code,state,finalConnectorId,+ storedConnectorType,validationError,searchParams,isIbmAuthMode,@@ -178,16 +194,29 @@ function AuthCallbackContent() {: null);const isAppAuth = purpose === "app_auth";+ const isTest = purpose === "test";const getTitle = () => {if (status === "processing") {- return isAppAuth ? "Signing you in..." : "Connecting...";+ return isAppAuth+ ? "Signing you in..."+ : isTest+ ? "Testing connection..."+ : "Connecting...";}if (status === "success") {- return isAppAuth ? "Welcome to OpenRAG!" : "Connection Successful!";+ return isAppAuth+ ? "Welcome to OpenRAG!"+ : isTest+ ? "Test Successful!"+ : "Connection Successful!";}if (status === "error") {- return isAppAuth ? "Sign In Failed" : "Connection Failed";+ return isAppAuth+ ? "Sign In Failed"+ : isTest+ ? "Test Failed"+ : "Connection Failed";}};@@ -240,7 +269,15 @@ function AuthCallbackContent() {<p className="text-sm text-red-600">{error}</p></div><Button- onClick={() => router.push(isAppAuth ? "/login" : "/settings")}+ onClick={() =>+ router.push(+ isAppAuth+ ? "/login"+ : isTest+ ? "/settings/connector-access"+ : "/settings",+ )+ }variant="outline"className="w-full">diff --git a/frontend/app/settings/_components/connector-access-section.tsx b/frontend/app/settings/_components/connector-access-section.tsxindex 2157bbb11..0f794e38d 100644--- a/frontend/app/settings/_components/connector-access-section.tsx+++ b/frontend/app/settings/_components/connector-access-section.tsx@@ -1,11 +1,28 @@"use client";import { Loader2 } from "lucide-react";+import { useRouter, useSearchParams } from "next/navigation";import { useEffect, useMemo, useState } from "react";+import { toast } from "sonner";+import { useConnectConnectorMutation } from "@/app/api/mutations/useConnectConnectorMutation";import {+ useClearConnectorOAuthConfigMutation,+ useSaveConnectorOAuthConfigMutation,+} from "@/app/api/mutations/useConnectorOAuthConfigMutation";+import { useConnectorOAuthConfigQuery } from "@/app/api/queries/useConnectorOAuthConfigQuery";+import {+ type ConnectorAccessItem,useGetConnectorAccessQuery,useUpdateConnectorAccessMutation,} from "@/app/api/queries/useGetConnectorsQuery";+import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";+import { LabelWrapper } from "@/components/label-wrapper";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/components/ui/accordion";import { Button } from "@/components/ui/button";import {Card,@@ -14,10 +31,55 @@ import {CardHeader,CardTitle,} from "@/components/ui/card";+import { Input } from "@/components/ui/input";+import { type Status, StatusBadge } from "@/components/ui/status-badge";import { Switch } from "@/components/ui/switch";import { trackButton } from "@/lib/analytics";+interface OAuthCredentialGroup {+ credentialKey: string;+ label: string;+ memberConnectorTypes: string[];+ /** Connector type used to drive the browser OAuth consent check. */+ testConnectorType: string;+}++// Google Drive and Microsoft Graph are the only OAuth-kind connectors today.+// OneDrive + SharePoint share one Microsoft Graph app registration, so they+// collapse into a single credential entry here even though enable/disable+// access stays per connector type.+const OAUTH_CREDENTIAL_GROUPS: OAuthCredentialGroup[] = [+ {+ credentialKey: "google_drive",+ label: "Google Drive",+ memberConnectorTypes: ["google_drive"],+ testConnectorType: "google_drive",+ },+ {+ credentialKey: "microsoft_graph",+ label: "Microsoft Graph (OneDrive & SharePoint)",+ memberConnectorTypes: ["onedrive", "sharepoint"],+ testConnectorType: "onedrive",+ },+];++const OAUTH_MEMBER_TYPES = new Set(+ OAUTH_CREDENTIAL_GROUPS.flatMap((g) => g.memberConnectorTypes),+);++function credentialStatus(entry?: {+ client_id_set: boolean;+ secret_source: "override" | "env" | "none";+}): Status {+ if (!entry) return "not-configured";+ if (entry.client_id_set && entry.secret_source === "override") return "ready";+ if (entry.secret_source === "env") return "fallback";+ return "not-configured";+}+export function ConnectorAccessSection() {+ const router = useRouter();+ const searchParams = useSearchParams();const {data: connectors = [],isLoading,@@ -26,10 +88,42 @@ export function ConnectorAccessSection() {refetch,} = useGetConnectorAccessQuery();const updateAccess = useUpdateConnectorAccessMutation();+ const { data: apiSettings } = useGetSettingsQuery();+ const showOAuthOverrides =+ apiSettings?.show_workspace_oauth_overrides ?? false;+ const { data: oauthConfig = {} } = useConnectorOAuthConfigQuery({+ enabled: showOAuthOverrides,+ });+ const saveOAuthConfig = useSaveConnectorOAuthConfigMutation();+ const clearOAuthConfig = useClearConnectorOAuthConfigMutation();+ const testConnection = useConnectConnectorMutation();+/** Non-null only after the user edits; server data stays the source of truth until then. */const [userDraft, setUserDraft] = useState<Record<string, boolean> | null>(null,);+ const [credentialDrafts, setCredentialDrafts] = useState<+ Record<string, { client_id: string; client_secret: string }>+ >({});++ // Surface the Test Connection result once the OAuth callback redirects back here.+ useEffect(() => {+ const oauthTest = searchParams.get("oauth_test");+ if (!oauthTest) return;+ const credential = searchParams.get("credential");+ if (oauthTest === "success") {+ toast.success(+ credential+ ? `Test connection succeeded (${credential})`+ : "Test connection succeeded",+ );+ } else {+ toast.error("Test connection failed");+ }+ router.replace("/settings/connector-access");+ // Only re-run when the query params themselves change.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [searchParams]);const _serverSnapshot = useMemo(() => connectors.map((c) => `${c.type}:${c.enabled}`).join("|"),@@ -60,15 +154,52 @@ export function ConnectorAccessSection() {return connectors.some((c) => userDraft[c.type] !== c.enabled);}, [connectors, userDraft]);+ const nonOAuthConnectors = showOAuthOverrides+ ? connectors.filter((c) => !OAUTH_MEMBER_TYPES.has(c.type))+ : connectors;++ const renderSwitchRow = (connector: ConnectorAccessItem) => {+ const enabled = userDraft?.[connector.type] ?? connector.enabled;+ return (+ <li+ key={connector.type}+ className="flex items-center justify-between gap-4 rounded-lg bg-muted/20 px-5 py-4"+ >+ <div className="min-w-0">+ <p className="text-sm font-medium">{connector.name}</p>+ <p className="text-xs text-muted-foreground">+ {enabled+ ? "Available in this workspace"+ : "Disabled for this workspace"}+ </p>+ </div>+ <Switch+ checked={enabled}+ disabled={updateAccess.isPending}+ aria-label={`${enabled ? "Disable" : "Enable"} ${connector.name} for this workspace`}+ onCheckedChange={(checked) => {+ setUserDraft((prev) => {+ const base =+ prev ??+ Object.fromEntries(connectors.map((c) => [c.type, c.enabled]));+ return { ...base, [connector.type]: checked };+ });+ }}+ />+ </li>+ );+ };+return (<Card><CardHeader><CardTitle className="text-lg ibm-settings-section-title">- Connectors Permission+ Connector Settings</CardTitle><CardDescription className="text-sm">- Control which connectors are available in this workspace for everyone,- including admins.+ {showOAuthOverrides+ ? "Control which connectors are available in this workspace, and configure OAuth app credentials for connectors that support it — overriding the environment-configured defaults."+ : "Control which connectors are available in this workspace for everyone, including admins."}</CardDescription></CardHeader><CardContent>@@ -95,43 +226,219 @@ export function ConnectorAccessSection() {</div>) : (<>- <ul className="space-y-4">- {connectors.map((connector) => {- const enabled =- userDraft?.[connector.type] ?? connector.enabled;-- return (- <li- key={connector.type}- className="flex items-center justify-between gap-4 rounded-lg bg-muted/20 px-5 py-4"- >- <div className="min-w-0">- <p className="text-sm font-medium">{connector.name}</p>- <p className="text-xs text-muted-foreground">- {enabled- ? "Available in this workspace"- : "Disabled for this workspace"}- </p>- </div>- <Switch- checked={enabled}- disabled={updateAccess.isPending}- aria-label={`${enabled ? "Disable" : "Enable"} ${connector.name} for this workspace`}- onCheckedChange={(checked) => {- setUserDraft((prev) => {- const base =- prev ??- Object.fromEntries(- connectors.map((c) => [c.type, c.enabled]),- );- return { ...base, [connector.type]: checked };- });- }}- />- </li>- );- })}- </ul>+ {showOAuthOverrides && (+ <Accordion type="single" collapsible className="space-y-3 mb-4">+ {OAUTH_CREDENTIAL_GROUPS.map((group) => {+ const memberConnectors = connectors.filter((c) =>+ group.memberConnectorTypes.includes(c.type),+ );+ if (memberConnectors.length === 0) return null;++ const status = oauthConfig[group.credentialKey];+ const draft = credentialDrafts[group.credentialKey] ?? {+ client_id: "",+ client_secret: "",+ };+ const setDraft = (+ patch: Partial<{+ client_id: string;+ client_secret: string;+ }>,+ ) =>+ setCredentialDrafts((prev) => ({+ ...prev,+ [group.credentialKey]: { ...draft, ...patch },+ }));+ const badgeStatus = credentialStatus(status);++ return (+ <AccordionItem+ key={group.credentialKey}+ value={group.credentialKey}+ >+ <AccordionTrigger>+ <div className="flex flex-1 items-center justify-between gap-3 pr-2">+ <span className="text-foreground">{group.label}</span>+ <StatusBadge status={badgeStatus} />+ </div>+ </AccordionTrigger>+ <AccordionContent className="space-y-5">+ <ul className="space-y-3">+ {memberConnectors.map(renderSwitchRow)}+ </ul>++ <div className="space-y-4 border-t pt-4">+ <LabelWrapper+ label="Client ID"+ id={`${group.credentialKey}-client-id`}+ >+ <Input+ id={`${group.credentialKey}-client-id`}+ value={draft.client_id || status?.client_id || ""}+ onChange={(e) =>+ setDraft({ client_id: e.target.value })+ }+ placeholder="OAuth client ID"+ autoComplete="off"+ />+ </LabelWrapper>+ <LabelWrapper+ label="Client Secret"+ id={`${group.credentialKey}-client-secret`}+ >+ <Input+ id={`${group.credentialKey}-client-secret`}+ type="password"+ value={draft.client_secret}+ onChange={(e) =>+ setDraft({ client_secret: e.target.value })+ }+ placeholder={+ status?.secret_source === "env"+ ? "•••••••• (loaded from env)"+ : status?.secret_source === "override"+ ? "•••••••• (saved)"+ : "Enter client secret"+ }+ autoComplete="off"+ />+ </LabelWrapper>++ <div className="flex flex-wrap items-center gap-2 pt-1">+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={+ saveOAuthConfig.isPending ||+ (!draft.client_id.trim() &&+ !draft.client_secret.trim())+ }+ onClick={() => {+ saveOAuthConfig.mutate(+ {+ credentialKey: group.credentialKey,+ client_id:+ draft.client_id.trim() || undefined,+ client_secret:+ draft.client_secret.trim() || undefined,+ },+ {+ onSuccess: () => {+ setCredentialDrafts((prev) => ({+ ...prev,+ [group.credentialKey]: {+ client_id: "",+ client_secret: "",+ },+ }));+ toast.success(+ `Saved ${group.label} credentials`,+ );+ },+ onError: (err) =>+ toast.error(+ err instanceof Error+ ? err.message+ : "Failed to save credentials",+ ),+ },+ );+ }}+ >+ {saveOAuthConfig.isPending ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ "Save"+ )}+ </Button>++ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={+ clearOAuthConfig.isPending ||+ badgeStatus === "not-configured"+ }+ onClick={() => {+ clearOAuthConfig.mutate(group.credentialKey, {+ onSuccess: () =>+ toast.success(+ `Cleared ${group.label} override`,+ ),+ onError: (err) =>+ toast.error(+ err instanceof Error+ ? err.message+ : "Failed to clear credentials",+ ),+ });+ }}+ >+ Clear override+ </Button>++ <Button+ type="button"+ size="sm"+ variant="outline"+ className="ml-auto"+ disabled={+ testConnection.isPending ||+ badgeStatus === "not-configured"+ }+ onClick={() => {+ trackButton({+ CTA: "Test Connector OAuth Connection",+ elementId: `test-connection-${group.credentialKey}`,+ namespace: "settings",+ });+ testConnection.mutate({+ connector: {+ id: group.testConnectorType,+ name: group.label,+ description: "",+ icon: "",+ status: "not_connected",+ type: group.testConnectorType,+ },+ redirectUri: `${window.location.origin}/auth/callback`,+ purpose: "test",+ });+ }}+ >+ {testConnection.isPending ? (+ <>+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ Testing…+ </>+ ) : (+ "Test Connection"+ )}+ </Button>+ </div>+ {group.credentialKey === "microsoft_graph" && (+ <p className="text-xs text-muted-foreground">+ Test Connection runs a Microsoft OAuth consent+ check using OneDrive's app registration — the+ same credentials also apply to SharePoint.+ </p>+ )}+ </div>+ </AccordionContent>+ </AccordionItem>+ );+ })}+ </Accordion>+ )}++ {nonOAuthConnectors.length > 0 && (+ <ul className="space-y-4">+ {nonOAuthConnectors.map(renderSwitchRow)}+ </ul>+ )}+<div className="flex justify-end pt-6"><ButtononClick={() => {diff --git a/frontend/app/settings/_components/settings-nav.tsx b/frontend/app/settings/_components/settings-nav.tsxindex c26ca813e..4a363c734 100644--- a/frontend/app/settings/_components/settings-nav.tsx+++ b/frontend/app/settings/_components/settings-nav.tsx@@ -20,7 +20,7 @@ const TABS = [{ value: "api-keys", label: "API Keys", apiKeysTab: true },{value: "connector-access",- label: "Connectors Permission",+ label: "Connector Settings",perm: "connectors:manage:access",},] as const;diff --git a/frontend/components/ui/status-badge.tsx b/frontend/components/ui/status-badge.tsxindex 002fa6a47..25a51a288 100644--- a/frontend/components/ui/status-badge.tsx+++ b/frontend/components/ui/status-badge.tsx@@ -6,7 +6,10 @@ export type Status =| "unavailable"| "hidden"| "sync"- | "failed";+ | "failed"+ | "ready"+ | "fallback"+ | "not-configured";interface StatusBadgeProps {status: Status;@@ -38,6 +41,18 @@ const statusConfig = {label: "Sync",className: "text-accent-amber-foreground underline",},+ ready: {+ label: "Ready",+ className: "text-accent-emerald-foreground ",+ },+ fallback: {+ label: "Using environment default",+ className: "text-accent-amber-foreground ",+ },+ "not-configured": {+ label: "Not configured",+ className: "text-muted-foreground ",+ },};export const StatusBadge = ({ status, className }: StatusBadgeProps) => {diff --git a/src/api/connectors.py b/src/api/connectors.pyindex c69e8fbe2..c074b87f3 100644--- a/src/api/connectors.py+++ b/src/api/connectors.py@@ -6,7 +6,7 @@ from fastapi.responses import JSONResponse, PlainTextResponsefrom pydantic import BaseModelfrom sqlalchemy.ext.asyncio import AsyncSession-from config.settings import get_index_name+from config.settings import get_index_name, is_workspace_oauth_overrides_enabledfrom connectors.sharepoint.utils import is_valid_sharepoint_urlfrom dependencies import (get_connector_service,@@ -1026,6 +1026,82 @@ async def update_connector_user_access(return JSONResponse({"connectors": connectors})+class UpdateConnectorOAuthConfigBody(BaseModel):+ client_id: str | None = None+ client_secret: str | None = None+++def _oauth_config_unavailable_response() -> JSONResponse:+ return JSONResponse(+ {"error": "Workspace OAuth connector credential overrides are not enabled"},+ status_code=404,+ )+++async def get_connector_oauth_config(+ user: User = Depends(require_permission("connectors:manage:access")),+ session: AsyncSession = Depends(get_db_session),+):+ """Per OAuth-kind connector: whether a workspace credential override is set,+ plus env-var fallback visibility. Never returns the decrypted secret."""+ from services.connector_oauth_config_service import get_oauth_config_status++ if not is_workspace_oauth_overrides_enabled():+ return _oauth_config_unavailable_response()++ status = await get_oauth_config_status(session)+ return JSONResponse({"credentials": status})+++async def update_connector_oauth_config(+ credential_key: str,+ body: UpdateConnectorOAuthConfigBody,+ user: User = Depends(require_permission("connectors:manage:access")),+ session: AsyncSession = Depends(get_db_session),+):+ """Save (partial update) a workspace OAuth client id/secret override."""+ from services.connector_oauth_config_service import get_oauth_config_status, set_oauth_config++ if not is_workspace_oauth_overrides_enabled():+ return _oauth_config_unavailable_response()++ try:+ await set_oauth_config(+ session,+ credential_key,+ body.client_id,+ body.client_secret,+ user.db_user_id or user.user_id,+ )+ await session.commit()+ except ValueError as e:+ logger.error("[CONNECTOR] Invalid OAuth config update", error=str(e))+ return JSONResponse({"error": "Unknown connector credential key"}, status_code=400)++ return JSONResponse({"credentials": await get_oauth_config_status(session)})+++async def delete_connector_oauth_config(+ credential_key: str,+ user: User = Depends(require_permission("connectors:manage:access")),+ session: AsyncSession = Depends(get_db_session),+):+ """Clear a workspace OAuth client id/secret override, reverting to the env var."""+ from services.connector_oauth_config_service import clear_oauth_config, get_oauth_config_status++ if not is_workspace_oauth_overrides_enabled():+ return _oauth_config_unavailable_response()++ try:+ await clear_oauth_config(session, credential_key, user.db_user_id or user.user_id)+ await session.commit()+ except ValueError as e:+ logger.error("[CONNECTOR] Invalid OAuth config clear", error=str(e))+ return JSONResponse({"error": "Unknown connector credential key"}, status_code=400)++ return JSONResponse({"credentials": await get_oauth_config_status(session)})++async def connector_sync(connector_type: str,body: ConnectorSyncBody,diff --git a/src/api/settings/endpoints.py b/src/api/settings/endpoints.pyindex 096f49d97..2d4f2297f 100644--- a/src/api/settings/endpoints.py+++ b/src/api/settings/endpoints.py@@ -74,6 +74,7 @@ from config.settings import (clients,config_manager,get_openrag_config,+ is_workspace_oauth_overrides_enabled,)from dependencies import (get_chat_service,@@ -244,6 +245,7 @@ async def get_settings(ingest_via_chat=OPENRAG_INGEST_VIA_CHAT,show_provider_ingest_settings=OPENRAG_SHOW_PROVIDER_INGEST_SETTINGS,show_shared_upload_toggle=OPENRAG_SHOW_SHARED_UPLOAD_TOGGLE,+ show_workspace_oauth_overrides=is_workspace_oauth_overrides_enabled(),segment_write_key=SEGMENT_WRITE_KEY or None,environment=ENVIRONMENT or None,langflow_port=str(LANGFLOW_PORT),diff --git a/src/api/settings/models.py b/src/api/settings/models.pyindex 9a99ab9b3..ae9a6374c 100644--- a/src/api/settings/models.py+++ b/src/api/settings/models.py@@ -196,6 +196,7 @@ class SettingsResponse(BaseModel):ingest_via_chat: bool = Falseshow_provider_ingest_settings: bool = Falseshow_shared_upload_toggle: bool = False+ show_workspace_oauth_overrides: bool = Falsesegment_write_key: str | None = Noneenvironment: str | None = Nonelangflow_port: str | None = Nonediff --git a/src/app/routes/internal.py b/src/app/routes/internal.pyindex 097a488bc..886a1defe 100644--- a/src/app/routes/internal.py+++ b/src/app/routes/internal.py@@ -235,6 +235,24 @@ def register_internal_routes(app: FastAPI):methods=["PUT"],tags=["internal"],)+ app.add_api_route(+ "/connectors/oauth-config",+ connectors.get_connector_oauth_config,+ methods=["GET"],+ tags=["internal"],+ )+ app.add_api_route(+ "/connectors/oauth-config/{credential_key}",+ connectors.update_connector_oauth_config,+ methods=["PUT"],+ tags=["internal"],+ )+ app.add_api_route(+ "/connectors/oauth-config/{credential_key}",+ connectors.delete_connector_oauth_config,+ methods=["DELETE"],+ tags=["internal"],+ )# Per-connector routes (defaults, configure, bucket listing, etc.) — registered before# the generic /{connector_type}/... routes to avoid path shadowing.for cls in get_connector_classes():diff --git a/src/config/settings.py b/src/config/settings.pyindex 2363c31b2..2f39b511b 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -302,6 +302,19 @@ def is_ingest_preview_flag_enabled() -> bool:return raw in ("true", "1", "yes", "on")+def is_workspace_oauth_overrides_enabled() -> bool:+ """Feature flag for workspace-level OAuth connector credential overrides.++ Default off. Gates: the admin UI + API for setting per-workspace client+ id/secret overrides on OAuth-kind connectors, resolution of those+ overrides in BaseConnector.get_client_id()/get_client_secret() (env vars+ still work either way), and the OAuth "test connection" flow. Set+ ``OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED=true`` to turn it on.+ """+ raw = os.getenv("OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED", "false").strip().lower()+ return raw in ("true", "1", "yes", "on")++def is_cloud_context() -> bool:"""True when connector policy and SaaS settings guards should apply."""from utils.run_mode_utils import is_run_mode_saasdiff --git a/src/connectors/base.py b/src/connectors/base.pyindex 7a9b6b412..48b77b312 100644--- a/src/connectors/base.py+++ b/src/connectors/base.py@@ -52,6 +52,13 @@ class BaseConnector(ABC):CLIENT_ID_ENV_VAR: str = NoneCLIENT_SECRET_ENV_VAR: str = None+ # Key used to look up a workspace-level OAuth credential override+ # (see services.connector_oauth_config_service). Falls back to+ # CONNECTOR_TYPE when unset. Connectors that share one OAuth app+ # registration (e.g. OneDrive + SharePoint both use "microsoft_graph")+ # should set this explicitly so they resolve to the same override.+ OAUTH_CREDENTIAL_KEY: str | None = None+# Stable identifier used in connections.json and on the wire (e.g. "google_drive").CONNECTOR_TYPE: str = None# "oauth" connectors authenticate per-user via OAuth env-var credentials.@@ -94,11 +101,29 @@ class BaseConnector(ABC):except (ValueError, NotImplementedError, RuntimeError):return manager._has_saved_credentials_for_user(cls.CONNECTOR_TYPE, user_id)+ def _oauth_credential_key(self) -> str:+ return self.OAUTH_CREDENTIAL_KEY or self.CONNECTOR_TYPE+def get_client_id(self) -> str:- """Get the OAuth client ID from environment variable"""+ """Get the OAuth client ID.++ Resolution order: per-connection config override, workspace-level+ admin override (see services.connector_oauth_config_service), then+ the environment variable.+ """if not self.CLIENT_ID_ENV_VAR:raise NotImplementedError(f"{self.__class__.__name__} must define CLIENT_ID_ENV_VAR")+ config_client_id = self.config.get("client_id")+ if isinstance(config_client_id, str) and config_client_id.strip():+ return config_client_id++ from services.connector_oauth_config_service import get_cached_client_id++ override = get_cached_client_id(self._oauth_credential_key())+ if override:+ return override+client_id = os.getenv(self.CLIENT_ID_ENV_VAR)if not client_id:raise ValueError(f"Environment variable {self.CLIENT_ID_ENV_VAR} is not set")@@ -106,12 +131,27 @@ class BaseConnector(ABC):return client_iddef get_client_secret(self) -> str:- """Get the OAuth client secret from environment variable"""+ """Get the OAuth client secret.++ Resolution order: per-connection config override, workspace-level+ admin override (see services.connector_oauth_config_service), then+ the environment variable.+ """if not self.CLIENT_SECRET_ENV_VAR:raise NotImplementedError(f"{self.__class__.__name__} must define CLIENT_SECRET_ENV_VAR")+ config_client_secret = self.config.get("client_secret")+ if isinstance(config_client_secret, str) and config_client_secret.strip():+ return config_client_secret++ from services.connector_oauth_config_service import get_cached_client_secret++ override = get_cached_client_secret(self._oauth_credential_key())+ if override:+ return override+secret = os.getenv(self.CLIENT_SECRET_ENV_VAR)if not secret:raise ValueError(f"Environment variable {self.CLIENT_SECRET_ENV_VAR} is not set")diff --git a/src/connectors/google_drive/connector.py b/src/connectors/google_drive/connector.pyindex acd5b1257..da30a9f49 100644--- a/src/connectors/google_drive/connector.py+++ b/src/connectors/google_drive/connector.py@@ -1,6 +1,5 @@import asyncioimport io-import osimport timefrom collections import dequefrom collections.abc import Iterable@@ -121,12 +120,16 @@ class GoogleDriveConnector(BaseConnector):def __init__(self, config: dict[str, Any]) -> None:super().__init__(config)- # Read from config OR env (backend env, not NEXT_PUBLIC_*):- env_client_id = os.getenv(self.CLIENT_ID_ENV_VAR)- env_client_secret = os.getenv(self.CLIENT_SECRET_ENV_VAR)-- client_id = config.get("client_id") or env_client_id- client_secret = config.get("client_secret") or env_client_secret+ # Resolve credentials via the centralized lookup: per-connection config,+ # then the workspace-level admin override, then the environment variable.+ try:+ client_id = self.get_client_id()+ except (ValueError, NotImplementedError):+ client_id = None+ try:+ client_secret = self.get_client_secret()+ except (ValueError, NotImplementedError):+ client_secret = None# Token file default - use data directory for persistencefrom config.paths import get_data_file@@ -136,13 +139,13 @@ class GoogleDriveConnector(BaseConnector):if not isinstance(client_id, str) or not client_id.strip():raise RuntimeError(- f"Missing Google Drive OAuth client_id. "- f"Provide config['client_id'] or set {self.CLIENT_ID_ENV_VAR}."+ f"Missing Google Drive OAuth client_id. Provide config['client_id'], "+ f"set it in Settings → Connector Settings, or set {self.CLIENT_ID_ENV_VAR}.")if not isinstance(client_secret, str) or not client_secret.strip():raise RuntimeError(- f"Missing Google Drive OAuth client_secret. "- f"Provide config['client_secret'] or set {self.CLIENT_SECRET_ENV_VAR}."+ f"Missing Google Drive OAuth client_secret. Provide config['client_secret'], "+ f"set it in Settings → Connector Settings, or set {self.CLIENT_SECRET_ENV_VAR}.")# Normalize incoming IDs from any of the supported alias keysdiff --git a/src/connectors/onedrive/connector.py b/src/connectors/onedrive/connector.pyindex 02950fb25..242318fe6 100644--- a/src/connectors/onedrive/connector.py+++ b/src/connectors/onedrive/connector.py@@ -30,6 +30,8 @@ class OneDriveConnector(BaseConnector):# Required BaseConnector class attributesCLIENT_ID_ENV_VAR = "MICROSOFT_GRAPH_OAUTH_CLIENT_ID"CLIENT_SECRET_ENV_VAR = "MICROSOFT_GRAPH_OAUTH_CLIENT_SECRET" # pragma: allowlist secret+ # Shared with SharePointConnector — both use one Microsoft Graph app registration.+ OAUTH_CREDENTIAL_KEY = "microsoft_graph"# Connector metadataCONNECTOR_TYPE = "onedrive"diff --git a/src/connectors/sharepoint/connector.py b/src/connectors/sharepoint/connector.pyindex 5ba99cc43..4974d3a1b 100644--- a/src/connectors/sharepoint/connector.py+++ b/src/connectors/sharepoint/connector.py@@ -30,6 +30,8 @@ class SharePointConnector(BaseConnector):# Required BaseConnector class attributesCLIENT_ID_ENV_VAR = "MICROSOFT_GRAPH_OAUTH_CLIENT_ID"CLIENT_SECRET_ENV_VAR = "MICROSOFT_GRAPH_OAUTH_CLIENT_SECRET" # pragma: allowlist secret+ # Shared with OneDriveConnector — both use one Microsoft Graph app registration.+ OAUTH_CREDENTIAL_KEY = "microsoft_graph"# Connector metadataCONNECTOR_TYPE = "sharepoint"diff --git a/src/services/auth_service.py b/src/services/auth_service.pyindex f4f526e95..4bdadb75d 100644--- a/src/services/auth_service.py+++ b/src/services/auth_service.py@@ -1,13 +1,17 @@import jsonimport logging-import osimport uuidfrom datetime import UTC, datetime, timedeltaimport httpxfrom fastapi import HTTPException-from config.settings import OAUTH_BROKER_URL, WEBHOOK_BASE_URL, is_no_auth_mode+from config.settings import (+ OAUTH_BROKER_URL,+ WEBHOOK_BASE_URL,+ is_no_auth_mode,+ is_workspace_oauth_overrides_enabled,+)from connectors.registry import get_connector_class, get_connector_classesfrom services.langflow_mcp_service import LangflowMCPServicefrom session_manager import SessionManager@@ -68,12 +72,23 @@ class AuthService:"OAuth credentials not configured. Data source connections require OAuth setup.")- # Validate connector_type based on purpose+ # Validate connector_type based on purpose. "test" (admin Test Connection+ # button, see _handle_test_auth) is validated like "data_source" but does+ # not persist a connection on success. Gated behind the workspace OAuth+ # overrides feature flag — off by default.+ allowed_purposes = (+ ("app_auth", "data_source", "test")+ if is_workspace_oauth_overrides_enabled()+ else ("app_auth", "data_source")+ )if purpose == "app_auth" and connector_type != "google_drive":raise ValueError("Only Google login supported for app authentication")- elif purpose == "data_source" and connector_type not in _data_source_connector_types():+ elif (+ purpose in ("data_source", "test")+ and connector_type not in _data_source_connector_types()+ ):raise ValueError(f"Unsupported connector type: {connector_type}")- elif purpose not in ["app_auth", "data_source"]:+ elif purpose not in allowed_purposes:raise ValueError(f"Unsupported purpose: {purpose}")if not redirect_uri:@@ -132,28 +147,17 @@ class AuthService:auth_endpoint = oauth_class_any.AUTH_ENDPOINTtoken_endpoint = oauth_class_any.TOKEN_ENDPOINT- # src/services/auth_service.py- client_key = getattr(connector_class_any, "CLIENT_ID_ENV_VAR", None)- secret_key = getattr(connector_class_any, "CLIENT_SECRET_ENV_VAR", None)-- def _assert_env_key(name, val):- if not isinstance(val, str) or not val.strip():- raise RuntimeError(- f"{connector_class.__name__} misconfigured: {name} must be a non-empty string "- f"(got {val!r}). Define it as a class attribute on the connector."- )-- _assert_env_key("CLIENT_ID_ENV_VAR", client_key)- _assert_env_key("CLIENT_SECRET_ENV_VAR", secret_key)-- client_id = os.getenv(client_key)- client_secret = os.getenv(secret_key)-- if not client_id or not client_secret:+ # Resolve credentials the same way the connector itself does (per-connection+ # config override -> workspace-level admin override -> env var), so this+ # matches what handle_oauth_callback resolves later for the same connector.+ try:+ connector_instance = connector_class_any({})+ client_id = connector_instance.get_client_id()+ connector_instance.get_client_secret() # validate it's configured; not returned to the frontend+ except (ValueError, NotImplementedError, RuntimeError) as e:raise RuntimeError(- f"Missing OAuth env vars for {connector_class.__name__}. "- f"Set {client_key} and {secret_key} in the environment."- )+ f"Missing OAuth credentials for {connector_class.__name__}: {e}"+ ) from e# Per-connector OAuth prompt: Microsoft uses "select_account" so a one-time# tenant admin consent is reused; Google uses "consent" for refresh tokens.@@ -329,6 +333,8 @@ class AuthService:return await self._handle_app_auth(connection_id, connection_config, token_data, request)+ elif purpose == "test":+ return await self._handle_test_auth(connection_id, connection_config)else:return await self._handle_data_source_auth(connection_id, connection_config)@@ -337,6 +343,21 @@ class AuthService:self.used_auth_codes.discard(authorization_code)raise e+ async def _handle_test_auth(self, connection_id: str, connection_config) -> dict:+ """Handle a Test Connection run — the token exchange already succeeded by+ the time this is called, which proves the active client id/secret work.+ Unlike a real data-source connection, a test must not persist anything:+ no base-URL detection, no webhook subscription, and the temporary+ connection + token file are deleted immediately.+ """+ connector_type = connection_config.connector_type+ await self.connector_service.connection_manager.delete_connection(connection_id)+ return {+ "status": "test_success",+ "connector_type": connector_type,+ "purpose": "test",+ }+async def _handle_app_auth(self, connection_id: str, connection_config, token_data: dict, request=None) -> dict:diff --git a/src/services/connector_oauth_config_service.py b/src/services/connector_oauth_config_service.pynew file mode 100644index 000000000..26eca733a--- /dev/null+++ b/src/services/connector_oauth_config_service.py@@ -0,0 +1,197 @@+"""Workspace-level OAuth client credential overrides for OAuth-kind connectors.++Lets an admin override the env-var-configured OAuth client id/secret per+credential key (e.g. "google_drive", "microsoft_graph" — the latter shared+by OneDrive + SharePoint, see BaseConnector.OAUTH_CREDENTIAL_KEY) from the+UI. Falls back to the connector's env var when no override is stored.++Resolution happens from synchronous, session-less contexts+(BaseConnector.__init__, is_available()), so overrides are kept in a+per-process in-memory cache, warmed once at startup (warm_cache) and+updated synchronously whenever an admin saves/clears credentials. This+mirrors the existing per-process RBAC/OAuth caches — the app already+hard-requires a single uvicorn worker for the same reason, so no+cross-worker staleness is possible.+"""++from __future__ import annotations++import os++from sqlalchemy.ext.asyncio import AsyncSession++from config.settings import is_workspace_oauth_overrides_enabled+from connectors.registry import get_connector_classes+from db.repositories import WorkspaceConfigRepo+from utils.encryption import decrypt_secret, encrypt_secret+from utils.logging_config import get_logger++logger = get_logger(__name__)++OAUTH_CONFIG_SECTION = "connector_oauth_config"++# {credential_key: {"client_id": str | None, "client_secret": str | None}}+# None until warm_cache() runs — treated as "no override" so early-boot+# credential lookups degrade gracefully to env-var-only behavior.+_CACHE: dict[str, dict[str, str | None]] | None = None+++def credential_keys() -> frozenset[str]:+ """OAuth-kind connector credential keys, derived from the registry."""+ return frozenset(+ cls.OAUTH_CREDENTIAL_KEY or cls.CONNECTOR_TYPE+ for cls in get_connector_classes()+ if cls.CONNECTOR_KIND == "oauth"+ )+++def _representative_connector_class(credential_key: str):+ """Any OAuth-kind connector class sharing this credential key (for its env var names)."""+ for cls in get_connector_classes():+ if cls.CONNECTOR_KIND != "oauth":+ continue+ if (cls.OAUTH_CREDENTIAL_KEY or cls.CONNECTOR_TYPE) == credential_key:+ return cls+ return None+++async def warm_cache(session_factory) -> None:+ """Load and decrypt all stored overrides into the in-process cache. Call once at startup."""+ global _CACHE+ if not is_workspace_oauth_overrides_enabled():+ _CACHE = {}+ return+ try:+ async with session_factory() as session:+ stored = await WorkspaceConfigRepo(session).get_section(OAUTH_CONFIG_SECTION) or {}+ except Exception:+ logger.exception("Failed to warm connector OAuth config cache")+ _CACHE = {}+ return++ cache: dict[str, dict[str, str | None]] = {}+ for key, entry in stored.items():+ client_id = entry.get("client_id")+ secret_payload = entry.get("client_secret")+ client_secret = None+ if secret_payload:+ try:+ client_secret = decrypt_secret(secret_payload)+ except Exception:+ logger.error("Failed to decrypt stored OAuth client secret", credential_key=key)+ cache[key] = {"client_id": client_id, "client_secret": client_secret}+ _CACHE = cache+ logger.info("Warmed connector OAuth config cache", keys=list(cache.keys()))+++def get_cached_client_id(credential_key: str) -> str | None:+ if _CACHE is None or not is_workspace_oauth_overrides_enabled():+ return None+ return _CACHE.get(credential_key, {}).get("client_id")+++def get_cached_client_secret(credential_key: str) -> str | None:+ if _CACHE is None or not is_workspace_oauth_overrides_enabled():+ return None+ return _CACHE.get(credential_key, {}).get("client_secret")+++def _set_cache_entry(credential_key: str, client_id: str | None, client_secret: str | None) -> None:+ global _CACHE+ if _CACHE is None:+ _CACHE = {}+ _CACHE[credential_key] = {"client_id": client_id, "client_secret": client_secret}+++def _clear_cache_entry(credential_key: str) -> None:+ global _CACHE+ if _CACHE is None:+ _CACHE = {}+ _CACHE.pop(credential_key, None)+++async def get_oauth_config_status(session: AsyncSession) -> dict[str, dict]:+ """Per credential key: whether an override is set, plus env-var fallback visibility.++ Never returns the decrypted secret.+ """+ stored = await WorkspaceConfigRepo(session).get_section(OAUTH_CONFIG_SECTION) or {}+ status: dict[str, dict] = {}+ for key in sorted(credential_keys()):+ entry = stored.get(key, {})+ client_id = entry.get("client_id")+ client_id_set = isinstance(client_id, str) and bool(client_id.strip())+ secret_set = bool(entry.get("client_secret"))++ cls = _representative_connector_class(key)+ env_client_id_set = bool(cls and os.getenv(cls.CLIENT_ID_ENV_VAR))+ env_client_secret_set = bool(cls and os.getenv(cls.CLIENT_SECRET_ENV_VAR))++ if client_id_set and secret_set:+ secret_source = "override"+ elif env_client_id_set and env_client_secret_set:+ secret_source = "env"+ else:+ secret_source = "none"++ status[key] = {+ "client_id_set": client_id_set,+ "client_id": client_id if client_id_set else None,+ "secret_source": secret_source,+ "env_client_id_set": env_client_id_set,+ }+ return status+++async def set_oauth_config(+ session: AsyncSession,+ credential_key: str,+ client_id: str | None,+ client_secret: str | None,+ actor_user_id: str | None,+) -> None:+ """Partial update: only overwrite fields that were provided (non-empty)."""+ if credential_key not in credential_keys():+ raise ValueError(f"Unknown OAuth credential key: {credential_key}")++ repo = WorkspaceConfigRepo(session)+ stored = await repo.get_section(OAUTH_CONFIG_SECTION) or {}+ entry = dict(stored.get(credential_key, {}))++ resolved_client_id = entry.get("client_id")+ if isinstance(client_id, str) and client_id.strip():+ resolved_client_id = client_id.strip()+ entry["client_id"] = resolved_client_id++ resolved_client_secret_plain = None+ if isinstance(client_secret, str) and client_secret.strip():+ resolved_client_secret_plain = client_secret.strip()+ entry["client_secret"] = encrypt_secret(resolved_client_secret_plain)+ elif entry.get("client_secret"):+ try:+ resolved_client_secret_plain = decrypt_secret(entry["client_secret"])+ except Exception:+ logger.error(+ "Failed to decrypt existing OAuth client secret during update",+ credential_key=credential_key,+ )++ stored[credential_key] = entry+ await repo.upsert(OAUTH_CONFIG_SECTION, stored, actor_user_id=actor_user_id)++ _set_cache_entry(credential_key, resolved_client_id, resolved_client_secret_plain)+++async def clear_oauth_config(+ session: AsyncSession, credential_key: str, actor_user_id: str | None+) -> None:+ if credential_key not in credential_keys():+ raise ValueError(f"Unknown OAuth credential key: {credential_key}")++ repo = WorkspaceConfigRepo(session)+ stored = await repo.get_section(OAUTH_CONFIG_SECTION) or {}+ if credential_key in stored:+ del stored[credential_key]+ await repo.upsert(OAUTH_CONFIG_SECTION, stored, actor_user_id=actor_user_id)++ _clear_cache_entry(credential_key)diff --git a/src/services/startup_orchestrator.py b/src/services/startup_orchestrator.pyindex 6b3eef162..ae359b86a 100644--- a/src/services/startup_orchestrator.py+++ b/src/services/startup_orchestrator.py@@ -45,6 +45,21 @@ async def startup_tasks(services):logger.info("Starting startup tasks")await TelemetryClient.send_event(Category.APPLICATION_STARTUP, MessageId.ORB_APP_START_INIT)+ # Warm the in-process cache of workspace-level OAuth connector credential+ # overrides (see services.connector_oauth_config_service) so BaseConnector's+ # synchronous get_client_id()/get_client_secret() resolve overrides without a+ # DB session. Reuses the same lazy session factory wired into workspace_config_service.+ try:+ from services.connector_oauth_config_service import warm_cache++ await warm_cache(services["workspace_config_service"]._session_factory)+ except Exception as e:+ logger.error(+ "Failed to warm connector OAuth config cache — overrides unavailable "+ "until the next restart, env vars still work",+ error=str(e),+ )+# Update model registry to allow further search calls to be instanttry:models_service = services["models_service"]diff --git a/tests/unit/config/test_workspace_oauth_overrides_flag.py b/tests/unit/config/test_workspace_oauth_overrides_flag.pynew file mode 100644index 000000000..38977e4f1--- /dev/null+++ b/tests/unit/config/test_workspace_oauth_overrides_flag.py@@ -0,0 +1,22 @@+"""Tests for the workspace OAuth connector credential overrides feature flag."""++import pytest++from config.settings import is_workspace_oauth_overrides_enabled+++def test_disabled_by_default(monkeypatch):+ monkeypatch.delenv("OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED", raising=False)+ assert is_workspace_oauth_overrides_enabled() is False++[email protected]("flag", ["true", "1", "yes", "on", "TRUE"])+def test_enabled_with_truthy_values(monkeypatch, flag):+ monkeypatch.setenv("OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED", flag)+ assert is_workspace_oauth_overrides_enabled() is True++[email protected]("flag", ["false", "0", "no", "off", ""])+def test_disabled_with_falsy_values(monkeypatch, flag):+ monkeypatch.setenv("OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED", flag)+ assert is_workspace_oauth_overrides_enabled() is Falsediff --git a/tests/unit/services/test_connector_oauth_config_flag_gating.py b/tests/unit/services/test_connector_oauth_config_flag_gating.pynew file mode 100644index 000000000..c71c32a5c--- /dev/null+++ b/tests/unit/services/test_connector_oauth_config_flag_gating.py@@ -0,0 +1,48 @@+"""The workspace OAuth connector credential override cache must never surface+overrides — even ones already loaded into the in-process cache — while the+OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED feature flag is off."""++import pytest++from services import connector_oauth_config_service as svc++[email protected](autouse=True)+def _reset_cache():+ original = svc._CACHE+ yield+ svc._CACHE = original+++def test_cached_getters_return_none_when_flag_disabled(monkeypatch):+ monkeypatch.delenv("OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED", raising=False)+ svc._CACHE = {"google_drive": {"client_id": "abc", "client_secret": "shh"}}++ assert svc.get_cached_client_id("google_drive") is None+ assert svc.get_cached_client_secret("google_drive") is None+++def test_cached_getters_return_values_when_flag_enabled(monkeypatch):+ monkeypatch.setenv("OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED", "true")+ svc._CACHE = {"google_drive": {"client_id": "abc", "client_secret": "shh"}}++ assert svc.get_cached_client_id("google_drive") == "abc"+ assert svc.get_cached_client_secret("google_drive") == "shh"+++async def test_warm_cache_no_ops_when_flag_disabled(monkeypatch):+ monkeypatch.delenv("OPENRAG_WORKSPACE_OAUTH_OVERRIDES_ENABLED", raising=False)+ svc._CACHE = None++ called = False++ def _session_factory():+ nonlocal called+ called = True+ raise AssertionError("warm_cache should not touch the DB when disabled")++ await svc.warm_cache(_session_factory)++ assert called is False+ assert svc._CACHE == {}