Skip to content

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

Python

feat: add connectors permissions for Saas (#1782)

Wallgau499a2c5fd899
diff --git a/.env.example b/.env.example
index e259a7c86..276418e31 100644
--- a/.env.example
+++ b/.env.example
@@ -362,6 +362,9 @@ OPENRAG_STORAGE_MODE=db
# system on for multi-user deployments. Available in all run modes.
# OPENRAG_RBAC_ENFORCE=true
+
+
+
# Default role for new users (JWT role sync off). Does not change existing
# users unless OPENRAG_SYNC_DEFAULT_ROLE is also enabled.
# OPENRAG_DEFAULT_ROLE=user
diff --git a/frontend/app/api/mutations/useConnectConnectorMutation.ts b/frontend/app/api/mutations/useConnectConnectorMutation.ts
index 8a7f5c94c..c6eafb0ab 100644
--- a/frontend/app/api/mutations/useConnectConnectorMutation.ts
+++ b/frontend/app/api/mutations/useConnectConnectorMutation.ts
@@ -2,7 +2,15 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useAuth } from "@/contexts/auth-context";
import { encodeBase64 } from "@/lib/utils";
-import type { Connector } from "../queries/useGetConnectorsQuery";
+import type {
+ Connector,
+ ConnectorsMutationContext,
+} from "../queries/useGetConnectorsQuery";
+import {
+ connectorsQueryFilter,
+ restoreConnectorQueries,
+ snapshotConnectorQueries,
+} from "../queries/useGetConnectorsQuery";
interface ConnectResponse {
connection_id: string;
@@ -47,22 +55,12 @@ export const useConnectConnectorMutation = () => {
}
return response.json();
},
- onMutate: async ({ connector }) => {
- // Cancel any outgoing refetches
- await queryClient.cancelQueries({ queryKey: ["connectors"] });
-
- // Snapshot the previous value
- const previousConnectors = queryClient.getQueryData<Connector[]>([
- "connectors",
- ]);
-
- return { previousConnectors };
+ onMutate: async (): Promise<ConnectorsMutationContext> => {
+ await queryClient.cancelQueries(connectorsQueryFilter);
+ return snapshotConnectorQueries(queryClient);
},
- onError: (err, { connector }, context) => {
- // Roll back if mutation fails
- if (context?.previousConnectors) {
- queryClient.setQueryData(["connectors"], context.previousConnectors);
- }
+ onError: (err, _vars, context) => {
+ restoreConnectorQueries(queryClient, context);
toast.error(err.message);
},
onSuccess: (result, { connector }) => {
@@ -93,9 +91,14 @@ export const useConnectConnectorMutation = () => {
} else {
// Direct-auth connector (bucket-kind) — credentials already verified,
// no OAuth redirect needed. Refresh connector status.
- queryClient.invalidateQueries({ queryKey: ["connectors"] });
+ queryClient.invalidateQueries(connectorsQueryFilter);
toast.success(`${connector.name} connected successfully`);
}
},
+ onSettled: (_result, error) => {
+ if (error) {
+ queryClient.invalidateQueries(connectorsQueryFilter);
+ }
+ },
});
};
diff --git a/frontend/app/api/mutations/useDisconnectConnectorMutation.ts b/frontend/app/api/mutations/useDisconnectConnectorMutation.ts
index 71b31d7ff..73676d2d0 100644
--- a/frontend/app/api/mutations/useDisconnectConnectorMutation.ts
+++ b/frontend/app/api/mutations/useDisconnectConnectorMutation.ts
@@ -1,6 +1,15 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
-import type { Connector } from "../queries/useGetConnectorsQuery";
+import type {
+ Connector,
+ ConnectorsMutationContext,
+} from "../queries/useGetConnectorsQuery";
+import {
+ connectorsQueryFilter,
+ restoreConnectorQueries,
+ snapshotConnectorQueries,
+ updateAllConnectorQueries,
+} from "../queries/useGetConnectorsQuery";
export const useDisconnectConnectorMutation = () => {
const queryClient = useQueryClient();
@@ -22,34 +31,22 @@ export const useDisconnectConnectorMutation = () => {
}
return response.json();
},
- onMutate: async (connector) => {
- // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
- await queryClient.cancelQueries({ queryKey: ["connectors"] });
+ onMutate: async (connector): Promise<ConnectorsMutationContext> => {
+ await queryClient.cancelQueries(connectorsQueryFilter);
+ const context = snapshotConnectorQueries(queryClient);
- // Snapshot the previous value
- const previousConnectors = queryClient.getQueryData<Connector[]>([
- "connectors",
- ]);
-
- // Optimistically update to the new value
- if (previousConnectors) {
- queryClient.setQueryData<Connector[]>(
- ["connectors"],
- previousConnectors.map((c) =>
- c.type === connector.type
- ? { ...c, status: "not_connected", connectionId: undefined }
- : c,
- ),
- );
- }
+ updateAllConnectorQueries(queryClient, (connectors) =>
+ connectors.map((c) =>
+ c.type === connector.type
+ ? { ...c, status: "not_connected", connectionId: undefined }
+ : c,
+ ),
+ );
- return { previousConnectors };
+ return context;
},
onError: (err, connector, context) => {
- // If the mutation fails, use the context returned from onMutate to roll back
- if (context?.previousConnectors) {
- queryClient.setQueryData(["connectors"], context.previousConnectors);
- }
+ restoreConnectorQueries(queryClient, context);
toast.error(`Failed to disconnect ${connector.name}: ${err.message}`);
},
onSuccess: (_, connector) => {
@@ -57,7 +54,7 @@ export const useDisconnectConnectorMutation = () => {
},
onSettled: () => {
// Always refetch after error or success to ensure we have the correct data
- queryClient.invalidateQueries({ queryKey: ["connectors"] });
+ queryClient.invalidateQueries(connectorsQueryFilter);
},
});
};
diff --git a/frontend/app/api/queries/useGetConnectorsQuery.ts b/frontend/app/api/queries/useGetConnectorsQuery.ts
index 84a197249..d48c5bea0 100644
--- a/frontend/app/api/queries/useGetConnectorsQuery.ts
+++ b/frontend/app/api/queries/useGetConnectorsQuery.ts
@@ -1,4 +1,113 @@
-import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
+import {
+ type QueryClient,
+ type UseQueryOptions,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
+import { toast } from "sonner";
+import { useAuth } from "@/contexts/auth-context";
+import { useBrand, useIsCloudBrand } from "@/contexts/brand-context";
+import {
+ isConnectorShownInWorkspace,
+ isConnectorTypeVisible,
+ isSaasPolicyContext,
+} from "@/lib/brand";
+
+/** Prefix for all connector list queries (see `connectorsQueryKey`). */
+export const CONNECTORS_QUERY_KEY_ROOT = ["connectors"] as const;
+
+/**
+ * Cache key from policy + deployment filter context (inputs to `getConnectors`).
+ * `cloudContext`: backend `/api/connectors` filtering (server policy).
+ * `applyWorkspacePolicy`: SaaS workspace policy path in the query fn.
+ * `isCloudBrand` / `isIbmAuthMode`: client deployment visibility (`isConnectorTypeVisible`).
+ */
+export function connectorsQueryKey(
+ cloudContext: boolean,
+ applyWorkspacePolicy: boolean,
+ isCloudBrand: boolean,
+ isIbmAuthMode: boolean,
+) {
+ return [
+ ...CONNECTORS_QUERY_KEY_ROOT,
+ cloudContext,
+ applyWorkspacePolicy,
+ isCloudBrand,
+ isIbmAuthMode,
+ ] as const;
+}
+
+export type ConnectorsQueryKey = ReturnType<typeof connectorsQueryKey>;
+
+/** Snapshot of every cached connector list — safe across policy key changes. */
+export type ConnectorsMutationContext = {
+ previousByKey: Array<[ConnectorsQueryKey, Connector[] | undefined]>;
+};
+
+export function snapshotConnectorQueries(
+ queryClient: QueryClient,
+): ConnectorsMutationContext {
+ return {
+ previousByKey: queryClient
+ .getQueriesData<Connector[]>(connectorsQueryFilter)
+ .map(([queryKey, data]) => [queryKey as ConnectorsQueryKey, data]),
+ };
+}
+
+export function restoreConnectorQueries(
+ queryClient: QueryClient,
+ context?: ConnectorsMutationContext,
+): void {
+ context?.previousByKey.forEach(([queryKey, data]) => {
+ if (data !== undefined) {
+ queryClient.setQueryData(queryKey, data);
+ }
+ });
+}
+
+export function updateAllConnectorQueries(
+ queryClient: QueryClient,
+ updater: (connectors: Connector[]) => Connector[],
+): void {
+ queryClient
+ .getQueriesData<Connector[]>(connectorsQueryFilter)
+ .forEach(([queryKey, data]) => {
+ if (data !== undefined) {
+ queryClient.setQueryData(queryKey as ConnectorsQueryKey, updater(data));
+ }
+ });
+}
+
+/** Shared policy context for connector list query key + optimistic updates. */
+export function useConnectorsQueryKey() {
+ const { isIbmAuthMode, cloudContext } = useAuth();
+ const { brand } = useBrand();
+ const isCloudBrand = useIsCloudBrand();
+ const applyWorkspacePolicy = isSaasPolicyContext({
+ isIbmAuthMode,
+ cloudContext,
+ brand,
+ });
+ return {
+ cloudContext,
+ applyWorkspacePolicy,
+ isCloudBrand,
+ isIbmAuthMode,
+ queryKey: connectorsQueryKey(
+ cloudContext,
+ applyWorkspacePolicy,
+ isCloudBrand,
+ isIbmAuthMode,
+ ),
+ };
+}
+
+/** Match every `["connectors", …]` query — required for invalidate/cancel after key shape change. */
+export const connectorsQueryFilter = {
+ queryKey: CONNECTORS_QUERY_KEY_ROOT,
+ exact: false,
+} as const;
interface GoogleDriveFile {
id: string;
@@ -48,9 +157,21 @@ export interface GetConnectorsResponse {
connectors: Connector[];
}
+async function fetchWorkspaceConnectorAccess(): Promise<
+ Record<string, boolean>
+> {
+ const response = await fetch("/api/connectors/workspace-policy");
+ if (!response.ok) return {};
+ const data = await response.json();
+ return data?.access && typeof data.access === "object" ? data.access : {};
+}
+
export const useGetConnectorsQuery = (
options?: Omit<UseQueryOptions<Connector[]>, "queryKey" | "queryFn">,
) => {
+ const { applyWorkspacePolicy, isCloudBrand, isIbmAuthMode, queryKey } =
+ useConnectorsQueryKey();
+
async function getConnectors(): Promise<Connector[]> {
const connectorsResponse = await fetch("/api/connectors");
if (!connectorsResponse.ok) {
@@ -106,13 +227,92 @@ export const useGetConnectorsQuery = (
}),
);
- return connectorsWithStatus;
+ let result = connectorsWithStatus;
+ const deploymentCtx = { isCloudBrand, isIbmAuthMode };
+
+ if (applyWorkspacePolicy) {
+ const storedAccess = await fetchWorkspaceConnectorAccess();
+ result = result.filter((c) =>
+ isConnectorShownInWorkspace(c.type, storedAccess, deploymentCtx),
+ );
+ } else {
+ result = result.filter((c) =>
+ isConnectorTypeVisible(c.type, deploymentCtx),
+ );
+ }
+
+ return result;
}
return useQuery({
- queryKey: ["connectors"],
+ queryKey,
queryFn: getConnectors,
refetchOnMount: "always",
...options,
});
};
+
+export interface ConnectorAccessItem {
+ type: string;
+ name: string;
+ enabled: boolean;
+}
+
+export const CONNECTOR_USER_ACCESS_KEY = ["connector-user-access"] as const;
+
+export const useGetConnectorAccessQuery = (
+ options?: Omit<
+ UseQueryOptions<ConnectorAccessItem[]>,
+ "queryKey" | "queryFn"
+ >,
+) => {
+ async function fetchConnectorAccess(): Promise<ConnectorAccessItem[]> {
+ const response = await fetch("/api/connectors/user-access");
+ if (!response.ok) {
+ throw new Error(
+ `Failed to fetch connectors permission (${response.status})`,
+ );
+ }
+ const data = await response.json();
+ return Array.isArray(data.connectors) ? data.connectors : [];
+ }
+
+ return useQuery({
+ queryKey: CONNECTOR_USER_ACCESS_KEY,
+ queryFn: fetchConnectorAccess,
+ refetchOnWindowFocus: false,
+ ...options,
+ });
+};
+
+export const useUpdateConnectorAccessMutation = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (
+ access: Record<string, boolean>,
+ ): Promise<ConnectorAccessItem[]> => {
+ const response = await fetch("/api/connectors/user-access", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ access }),
+ });
+ if (!response.ok) {
+ const result = await response.json().catch(() => ({}));
+ throw new Error(
+ result.error || "Failed to update connectors permission",
+ );
+ }
+ const data = await response.json();
+ return Array.isArray(data.connectors) ? data.connectors : [];
+ },
+ onSuccess: (connectors) => {
+ queryClient.setQueryData(CONNECTOR_USER_ACCESS_KEY, connectors);
+ queryClient.invalidateQueries(connectorsQueryFilter);
+ toast.success("Connectors permission saved");
+ },
+ onError: (error: Error) => {
+ toast.error(error.message);
+ },
+ });
+};
diff --git a/frontend/app/settings/[tab]/page.tsx b/frontend/app/settings/[tab]/page.tsx
index ef1b44675..bc5ec293d 100644
--- a/frontend/app/settings/[tab]/page.tsx
+++ b/frontend/app/settings/[tab]/page.tsx
@@ -1,14 +1,26 @@
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { redirect } from "next/navigation";
import { getQueryClient } from "@/app/api/get-query-client";
+import {
+ buildSettingsTabAccess,
+ canAccessConnectorAccessTab,
+ canShowRbacGatedSettingsTab,
+} from "@/lib/brand";
import { fetchFromBackend } from "@/lib/fetch-server";
import { AgentSettingsSection } from "../_components/agent-settings-section";
import { ApiKeysSection } from "../_components/api-keys-section";
+import { ConnectorAccessSection } from "../_components/connector-access-section";
import { ConnectorsTab } from "../_components/connectors-tab";
import { IngestSettingsSection } from "../_components/ingest-settings-section";
import ModelProviders from "../_components/model-providers";
-const VALID_TABS = ["connectors", "providers", "langflow", "api-keys"] as const;
+const VALID_TABS = [
+ "connectors",
+ "providers",
+ "langflow",
+ "api-keys",
+ "connector-access",
+] as const;
type Tab = (typeof VALID_TABS)[number];
@@ -27,13 +39,21 @@ async function getTabAuthContext() {
? await meRes.value.json()
: {};
+ const permissions = new Set<string>(
+ Array.isArray(meData.permissions) ? meData.permissions : [],
+ );
+ const rbacEnforced =
+ typeof meData.rbac_enforced === "boolean" ? meData.rbac_enforced : true;
+ const cloudContext =
+ typeof meData.cloud_context === "boolean" ? meData.cloud_context : false;
+
return {
isNoAuthMode: Boolean(authData.no_auth_mode),
isIbmAuthMode: Boolean(authData.ibm_auth_mode),
isAuthenticated: Boolean(authData.authenticated),
- permissions: new Set<string>(
- Array.isArray(meData.permissions) ? meData.permissions : [],
- ),
+ permissions,
+ rbacEnforced,
+ cloudContext,
};
}
@@ -48,10 +68,24 @@ export default async function SettingsTabPage({
redirect("/settings/connectors");
}
- const { isNoAuthMode, isIbmAuthMode, isAuthenticated, permissions } =
- await getTabAuthContext();
+ const {
+ isNoAuthMode,
+ isIbmAuthMode,
+ isAuthenticated,
+ permissions,
+ rbacEnforced,
+ cloudContext,
+ } = await getTabAuthContext();
+
+ const tabAccess = buildSettingsTabAccess({
+ isIbmAuthMode,
+ cloudContext,
+ isNoAuthMode,
+ rbacEnforced,
+ permissions,
+ useClientBrandPolicy: false,
+ });
- // Mirror the visibility logic from settings-nav.tsx
if (
tab === "api-keys" &&
(isIbmAuthMode || (!isAuthenticated && !isNoAuthMode))
@@ -60,13 +94,17 @@ export default async function SettingsTabPage({
}
if (
tab === "providers" &&
- !isNoAuthMode &&
- !permissions.has("providers:write")
+ !canShowRbacGatedSettingsTab("providers:write", tabAccess)
) {
redirect("/settings/connectors");
}
- // Langflow tab edits agent + ingest settings (workspace config) — admin-only.
- if (tab === "langflow" && !isNoAuthMode && !permissions.has("config:write")) {
+ if (tab === "connector-access" && !canAccessConnectorAccessTab(tabAccess)) {
+ redirect("/settings/connectors");
+ }
+ if (
+ tab === "langflow" &&
+ !canShowRbacGatedSettingsTab("config:write", tabAccess)
+ ) {
redirect("/settings/connectors");
}
@@ -110,6 +148,7 @@ export default async function SettingsTabPage({
</div>
)}
{tab === "api-keys" && <ApiKeysSection />}
+ {tab === "connector-access" && <ConnectorAccessSection />}
</HydrationBoundary>
);
}
diff --git a/frontend/app/settings/_components/connector-access-section.tsx b/frontend/app/settings/_components/connector-access-section.tsx
new file mode 100644
index 000000000..ec5bc3c06
--- /dev/null
+++ b/frontend/app/settings/_components/connector-access-section.tsx
@@ -0,0 +1,161 @@
+"use client";
+
+import { Loader2 } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import {
+ useGetConnectorAccessQuery,
+ useUpdateConnectorAccessMutation,
+} from "@/app/api/queries/useGetConnectorsQuery";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Switch } from "@/components/ui/switch";
+
+export function ConnectorAccessSection() {
+ const {
+ data: connectors = [],
+ isLoading,
+ isError,
+ error,
+ refetch,
+ } = useGetConnectorAccessQuery();
+ const updateAccess = useUpdateConnectorAccessMutation();
+ /** 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 serverSnapshot = useMemo(
+ () => connectors.map((c) => `${c.type}:${c.enabled}`).join("|"),
+ [connectors],
+ );
+
+ // Reset draft when server data catches up; keep unsaved edits on refetch/focus.
+ useEffect(() => {
+ setUserDraft((draft) => {
+ if (!draft) return null;
+ const hasUnsavedEdits = connectors.some(
+ (c) => draft[c.type] !== c.enabled,
+ );
+ return hasUnsavedEdits ? draft : null;
+ });
+ }, [serverSnapshot, connectors]);
+
+ const accessForSave = useMemo(
+ () =>
+ Object.fromEntries(
+ connectors.map((c) => [c.type, userDraft?.[c.type] ?? c.enabled]),
+ ),
+ [connectors, userDraft],
+ );
+
+ const isDirty = useMemo(() => {
+ if (!userDraft) return false;
+ return connectors.some((c) => userDraft[c.type] !== c.enabled);
+ }, [connectors, userDraft]);
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-lg ibm-settings-section-title">
+ Connectors Permission
+ </CardTitle>
+ <CardDescription className="text-sm">
+ Control which connectors are available in this workspace for everyone,
+ including admins.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {isLoading ? (
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ Loading…
+ </div>
+ ) : isError ? (
+ <div className="space-y-3 text-sm">
+ <p className="text-destructive">
+ {error instanceof Error
+ ? error.message
+ : "Failed to load connectors permission"}
+ </p>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => refetch()}
+ >
+ Retry
+ </Button>
+ </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>
+ <div className="flex justify-end pt-6">
+ <Button
+ onClick={() =>
+ updateAccess.mutate(accessForSave, {
+ onSuccess: () => setUserDraft(null),
+ })
+ }
+ disabled={updateAccess.isPending || !isDirty}
+ className="min-w-[120px]"
+ size="sm"
+ variant="outline"
+ >
+ {updateAccess.isPending ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Saving…
+ </>
+ ) : (
+ "Save changes"
+ )}
+ </Button>
+ </div>
+ </>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/frontend/app/settings/_components/connector-card.tsx b/frontend/app/settings/_components/connector-card.tsx
index 314284ffd..8abfa78bb 100644
--- a/frontend/app/settings/_components/connector-card.tsx
+++ b/frontend/app/settings/_components/connector-card.tsx
@@ -103,7 +103,7 @@ export default function ConnectorCard({
>
{isConnected || connector?.available
? `${connector.name} is configured.`
- : "Not configured."}
+ : "Allowed for this workspace — OAuth credentials not configured yet."}
</CardDescription>
</div>
</div>
diff --git a/frontend/app/settings/_components/connector-cards.tsx b/frontend/app/settings/_components/connector-cards.tsx
index f4471b686..d2393b26a 100644
--- a/frontend/app/settings/_components/connector-cards.tsx
+++ b/frontend/app/settings/_components/connector-cards.tsx
@@ -9,7 +9,8 @@ import {
useGetConnectorsQuery,
} from "@/app/api/queries/useGetConnectorsQuery";
import { useAuth } from "@/contexts/auth-context";
-import { useIsCloudBrand } from "@/contexts/brand-context";
+import { useBrand } from "@/contexts/brand-context";
+import { isSaasPolicyContext } from "@/lib/brand";
import {
getConnectorDescriptor,
getConnectorDescriptors,
@@ -18,8 +19,14 @@ import ConnectorCard, { type Connector } from "./connector-card";
import ConnectorsSkeleton from "./connectors-skeleton";
export default function ConnectorCards() {
- const { isAuthenticated, isNoAuthMode, isIbmAuthMode } = useAuth();
- const isCloudBrand = useIsCloudBrand();
+ const { isAuthenticated, isNoAuthMode, isIbmAuthMode, cloudContext } =
+ useAuth();
+ const { brand } = useBrand();
+ const isSaasPolicy = isSaasPolicyContext({
+ isIbmAuthMode,
+ cloudContext,
+ brand,
+ });
const router = useRouter();
const [openDialog, setOpenDialog] = useState<string | null>(null);
@@ -43,16 +50,10 @@ export default function ConnectorCards() {
return <Icon />;
}, []);
- const connectors = queryConnectors
- .filter((c) => {
- if (c.type === "ibm_cos" || c.type === "aws_s3") return isIbmAuthMode;
- if (isCloudBrand && c.type === "onedrive") return false;
- return true;
- })
- .map((c) => ({
- ...c,
- icon: getConnectorIcon(c.type),
- })) as Connector[];
+ const connectors = queryConnectors.map((c) => ({
+ ...c,
+ icon: getConnectorIcon(c.type),
+ })) as Connector[];
const handleConnect = async (connector: Connector) => {
connectMutation.mutate({
@@ -79,6 +80,13 @@ export default function ConnectorCards() {
};
if (!connectorsLoading && connectors.length === 0) {
+ if (isSaasPolicy) {
+ return (
+ <p className="text-sm text-muted-foreground">
+ No connectors available or authorized for your organization.
+ </p>
+ );
+ }
return null;
}
diff --git a/frontend/app/settings/_components/settings-nav.tsx b/frontend/app/settings/_components/settings-nav.tsx
index 4baa62745..458f581d8 100644
--- a/frontend/app/settings/_components/settings-nav.tsx
+++ b/frontend/app/settings/_components/settings-nav.tsx
@@ -1,10 +1,15 @@
"use client";
import { usePathname, useRouter } from "next/navigation";
+import { useEffect } from "react";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/settings-tabs";
import { useAuth } from "@/contexts/auth-context";
import { useIsCloudBrand } from "@/contexts/brand-context";
-import { usePermissions } from "@/hooks/use-permissions";
+import { useSettingsTabAccess } from "@/hooks/use-permissions";
+import {
+ canAccessConnectorAccessTab,
+ canShowRbacGatedSettingsTab,
+} from "@/lib/brand";
import { cn } from "@/lib/utils";
const TABS = [
@@ -13,24 +18,56 @@ const TABS = [
// Agent + ingest settings write workspace config (admin-only).
{ value: "langflow", label: "Langflow", perm: "config:write" },
{ value: "api-keys", label: "API Keys", apiKeysTab: true },
+ {
+ value: "connector-access",
+ label: "Connectors Permission",
+ perm: "connectors:manage:access",
+ },
] as const;
export function SettingsNav() {
- const isCloudBrand = useIsCloudBrand();
const pathname = usePathname();
const router = useRouter();
- const { isAuthenticated, isNoAuthMode, isIbmAuthMode } = useAuth();
- const { can } = usePermissions();
+ const {
+ isAuthenticated,
+ isNoAuthMode,
+ isIbmAuthMode,
+ isLoading,
+ permissionsResolved,
+ } = useAuth();
+ const isCloudBrand = useIsCloudBrand();
+ const tabAccess = useSettingsTabAccess();
const currentTab = pathname.split("/").pop() ?? "connectors";
const visibleTabs = TABS.filter((tab) => {
- if ("perm" in tab) return can(tab.perm);
+ if (tab.value === "connector-access") {
+ return canAccessConnectorAccessTab(tabAccess);
+ }
+ if ("perm" in tab) return canShowRbacGatedSettingsTab(tab.perm, tabAccess);
if ("apiKeysTab" in tab)
return (isAuthenticated || isNoAuthMode) && !isIbmAuthMode;
return true;
});
+ const visibleTabKey = visibleTabs.map((tab) => tab.value).join("|");
+ const tabIsVisible = visibleTabs.some((tab) => tab.value === currentTab);
+ const fallbackTab = visibleTabs[0]?.value ?? "connectors";
+
+ useEffect(() => {
+ if (isLoading || !permissionsResolved) return;
+ if (tabIsVisible) return;
+ router.replace(`/settings/${fallbackTab}`);
+ }, [
+ isLoading,
+ permissionsResolved,
+ currentTab,
+ tabIsVisible,
+ fallbackTab,
+ visibleTabKey,
+ router,
+ ]);
+
return (
<Tabs value={currentTab}>
<TabsList
diff --git a/frontend/components/dev-role-toggle.tsx b/frontend/components/dev-role-toggle.tsx
new file mode 100644
index 000000000..504e6ea40
--- /dev/null
+++ b/frontend/components/dev-role-toggle.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+import { toast } from "sonner";
+import {
+ CONNECTOR_USER_ACCESS_KEY,
+ connectorsQueryFilter,
+} from "@/app/api/queries/useGetConnectorsQuery";
+import { useAuth } from "@/contexts/auth-context";
+import { useBrand } from "@/contexts/brand-context";
+import { IBM_THEME_DEV } from "@/lib/brand";
+
+function parseApiError(
+ result: Record<string, unknown>,
+ status: number,
+): string {
+ if (typeof result.error === "string") return result.error;
+ const detail = result.detail;
+ if (typeof detail === "string") return detail;
+ if (Array.isArray(detail)) {
+ const msg = detail
+ .map((d) =>
+ typeof d === "object" && d && "msg" in d ? String(d.msg) : "",
+ )
+ .filter(Boolean)
+ .join("; ");
+ if (msg) return msg;
+ }
+ return `Failed to set role (${status})`;
+}
+
+const DEV_ROLES = [
+ { value: "admin", label: "Admin" },
+ { value: "developer", label: "Developer" },
+ { value: "user", label: "User" },
+ { value: "viewer", label: "Viewer" },
+] as const;
+
+export function DevRoleToggle() {
+ const router = useRouter();
+ const queryClient = useQueryClient();
+ const { roles, isAuthenticated, isNoAuthMode, refreshPermissions } =
+ useAuth();
+ const { brand } = useBrand();
+ const currentRole = DEV_ROLES.find((r) => roles.includes(r.value))?.value;
+
+ const mutation = useMutation({
+ mutationFn: async (role: string) => {
+ const response = await fetch("/api/users/me/dev-role", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ role }),
+ credentials: "include",
+ });
+ if (!response.ok) {
+ const result = (await response.json().catch(() => ({}))) as Record<
+ string,
+ unknown
+ >;
+ throw new Error(parseApiError(result, response.status));
+ }
+ return response.json() as Promise<{ role?: string }>;
+ },
+ onSuccess: async (data) => {
+ await refreshPermissions();
+ await queryClient.invalidateQueries(connectorsQueryFilter);
+ await queryClient.invalidateQueries({
+ queryKey: CONNECTOR_USER_ACCESS_KEY,
+ });
+ router.refresh();
+ const label =
+ DEV_ROLES.find((r) => r.value === data.role)?.label ?? data.role;
+ toast.success(`Switched to ${label}`);
+ },
+ onError: (error: Error) => {
+ toast.error(error.message);
+ },
+ });
+
+ if (
+ !IBM_THEME_DEV ||
+ brand === "oss" ||
+ (!isAuthenticated && !isNoAuthMode)
+ ) {
+ return null;
+ }
+
+ return (
+ <div
+ className="flex items-center gap-0.5 border border-border rounded-full px-0.5"
+ title="Dev only: switch RBAC role for UI testing"
+ >
+ {DEV_ROLES.map((role) => (
+ <button
+ key={role.value}
+ type="button"
+ disabled={mutation.isPending}
+ className={`px-2 h-6 rounded-full text-[11px] font-medium transition-colors disabled:opacity-50 ${
+ currentRole === role.value
+ ? "bg-blue-600 text-white"
+ : "text-foreground hover:bg-blue-600 hover:text-white"
+ }`}
+ onClick={() => mutation.mutate(role.value)}
+ data-testid={`dev-role-${role.value}`}
+ >
+ {role.label}
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/frontend/components/header.tsx b/frontend/components/header.tsx
index b22db36d3..97fc24617 100644
--- a/frontend/components/header.tsx
+++ b/frontend/components/header.tsx
@@ -2,6 +2,7 @@
import { Bell } from "lucide-react";
import { BrandSwitcher } from "@/components/brand-switcher";
+import { DevRoleToggle } from "@/components/dev-role-toggle";
import Logo from "@/components/icons/openrag-logo";
import { UserNav } from "@/components/user-nav";
import { useIsCloudBrand } from "@/contexts/brand-context";
@@ -51,6 +52,7 @@ export function Header() {
{process.env.NEXT_PUBLIC_IBM_THEME_DEV === "true" && (
<>
<BrandSwitcher />
+ <DevRoleToggle />
{/* Separator */}
<div className="w-px h-6 bg-border mx-3" />
</>
diff --git a/frontend/contexts/auth-context.tsx b/frontend/contexts/auth-context.tsx
index 6015e3886..15e668efe 100644
--- a/frontend/contexts/auth-context.tsx
+++ b/frontend/contexts/auth-context.tsx
@@ -8,6 +8,7 @@ import React, {
useEffect,
useState,
} from "react";
+import { hasRbacPermission } from "@/lib/brand";
import { encodeBase64 } from "@/lib/utils";
interface User {
@@ -39,6 +40,10 @@ interface AuthContextType {
* matches the backend behavior.
*/
rbacEnforced: boolean;
+ /** SaaS/cloud context from backend (connector policy, gated settings). */
+ cloudContext: boolean;
+ /** False until the first /api/users/me permissions fetch finishes. */
+ permissionsResolved: boolean;
/** True iff the workspace has been onboarded. Sourced from the public
* GET /api/onboarding-status endpoint (no auth needed). */
isOnboarded: boolean | null;
@@ -257,13 +262,22 @@ export function AuthProvider({ children }: AuthProviderProps) {
// load before /api/users/me responds. The backend is authoritative;
// this is just a UI affordance.
const [rbacEnforced, setRbacEnforced] = useState<boolean>(true);
+ const [cloudContext, setCloudContext] = useState<boolean>(false);
+ const [permissionsResolved, setPermissionsResolved] =
+ useState<boolean>(false);
+
+ const resetPermissionState = useCallback(() => {
+ setPermissions(new Set());
+ setRoles([]);
+ setRbacEnforced(true);
+ setCloudContext(false);
+ }, []);
const fetchPermissions = useCallback(async () => {
try {
const r = await fetch("/api/users/me");
if (!r.ok) {
- setPermissions(new Set());
- setRoles([]);
+ resetPermissionState();
return;
}
const data = await r.json();
@@ -277,11 +291,15 @@ export function AuthProvider({ children }: AuthProviderProps) {
setRbacEnforced(
typeof data?.rbac_enforced === "boolean" ? data.rbac_enforced : true,
);
+ setCloudContext(
+ typeof data?.cloud_context === "boolean" ? data.cloud_context : false,
+ );
} catch {
- setPermissions(new Set());
- setRoles([]);
+ resetPermissionState();
+ } finally {
+ setPermissionsResolved(true);
}
- }, []);
+ }, [resetPermissionState]);
const refreshPermissions = useCallback(async () => {
await fetchPermissions();
@@ -319,23 +337,28 @@ export function AuthProvider({ children }: AuthProviderProps) {
useEffect(() => {
if (user || isNoAuthMode || isIbmAuthMode) {
- fetchPermissions();
+ setPermissionsResolved(false);
+ void fetchPermissions();
} else {
- setPermissions(new Set());
- setRoles([]);
+ resetPermissionState();
+ setPermissionsResolved(true);
}
- }, [user, isNoAuthMode, isIbmAuthMode, fetchPermissions]);
+ }, [
+ user,
+ isNoAuthMode,
+ isIbmAuthMode,
+ fetchPermissions,
+ resetPermissionState,
+ ]);
useEffect(() => {
checkAuth();
}, [checkAuth]);
const can = useCallback(
- (perm: string): boolean => {
- if (isNoAuthMode) return true;
- return permissions.has(perm);
- },
- [permissions, isNoAuthMode],
+ (perm: string): boolean =>
+ hasRbacPermission(perm, { isNoAuthMode, rbacEnforced, permissions }),
+ [permissions, isNoAuthMode, rbacEnforced],
);
const value: AuthContextType = {
@@ -349,6 +372,8 @@ export function AuthProvider({ children }: AuthProviderProps) {
permissions,
roles,
rbacEnforced,
+ cloudContext,
+ permissionsResolved,
isOnboarded,
onboardingStep,
can,
diff --git a/frontend/contexts/brand-context.tsx b/frontend/contexts/brand-context.tsx
index 609ee7d44..8744c876a 100644
--- a/frontend/contexts/brand-context.tsx
+++ b/frontend/contexts/brand-context.tsx
@@ -2,8 +2,15 @@
import { createContext, useContext, useEffect, useState } from "react";
import { useAuth } from "@/contexts/auth-context";
+import {
+ type Brand,
+ DEFAULT_BRAND,
+ isCloudBrand,
+ resolveBrand,
+} from "@/lib/brand";
-export type Brand = "oss" | "ibm";
+export type { Brand } from "@/lib/brand";
+export { IBM_THEME_DEV } from "@/lib/brand";
interface BrandContextValue {
brand: Brand;
@@ -11,7 +18,7 @@ interface BrandContextValue {
}
const BrandContext = createContext<BrandContextValue>({
- brand: "oss",
+ brand: DEFAULT_BRAND,
setBrand: () => {},
});
@@ -24,24 +31,27 @@ function applyBrand(brand: Brand) {
}
export function BrandProvider({ children }: { children: React.ReactNode }) {
- const [brand, setBrandState] = useState<Brand>("oss");
+ const [storedBrand, setStoredBrandState] = useState<Brand>(DEFAULT_BRAND);
const { isIbmAuthMode } = useAuth();
+ // IBM auth always presents as IBM in context; dev OSS/IBM toggle uses localStorage.
+ const brand: Brand = isIbmAuthMode ? "ibm" : storedBrand;
useEffect(() => {
- if (isIbmAuthMode) {
- applyBrand("ibm");
- setBrandState("ibm");
- } else {
- const stored = (localStorage.getItem("brand") as Brand) ?? "oss";
- applyBrand(stored);
- setBrandState(stored);
+ if (!isIbmAuthMode) {
+ const stored = resolveBrand(localStorage.getItem("brand") ?? undefined);
+ localStorage.setItem("brand", stored);
+ setStoredBrandState(stored);
}
}, [isIbmAuthMode]);
+ useEffect(() => {
+ applyBrand(brand);
+ }, [brand]);
+
function setBrand(newBrand: Brand) {
+ if (isIbmAuthMode) return;
localStorage.setItem("brand", newBrand);
- applyBrand(newBrand);
- setBrandState(newBrand);
+ setStoredBrandState(newBrand);
}
return (
@@ -53,4 +63,7 @@ export function BrandProvider({ children }: { children: React.ReactNode }) {
export const useBrand = () => useContext(BrandContext);
-export const useIsCloudBrand = () => useContext(BrandContext).brand === "ibm";
+export const useIsCloudBrand = () => {
+ const { brand } = useContext(BrandContext);
+ return isCloudBrand(brand);
+};
diff --git a/frontend/hooks/use-permissions.ts b/frontend/hooks/use-permissions.ts
index 7db28fea1..f43fa6631 100644
--- a/frontend/hooks/use-permissions.ts
+++ b/frontend/hooks/use-permissions.ts
@@ -1,6 +1,11 @@
"use client";
import { useAuth } from "@/contexts/auth-context";
+import { useBrand } from "@/contexts/brand-context";
+import {
+ buildSettingsTabAccess,
+ type SettingsTabAccessContext,
+} from "@/lib/brand";
export interface UsePermissionsResult {
/** All permission strings granted to the current user. */
@@ -60,3 +65,23 @@ export function usePermissions(): UsePermissionsResult {
rbacEnforced,
};
}
+
+/** Settings nav + tab guards — bundles auth, brand, and permissions. */
+export function useSettingsTabAccess(): SettingsTabAccessContext {
+ const {
+ isNoAuthMode,
+ isIbmAuthMode,
+ cloudContext,
+ permissions,
+ rbacEnforced,
+ } = useAuth();
+ const { brand } = useBrand();
+ return buildSettingsTabAccess({
+ isIbmAuthMode,
+ cloudContext,
+ isNoAuthMode,
+ rbacEnforced,
+ permissions,
+ brand,
+ });
+}
diff --git a/frontend/lib/brand.ts b/frontend/lib/brand.ts
new file mode 100644
index 000000000..d05947f04
--- /dev/null
+++ b/frontend/lib/brand.ts
@@ -0,0 +1,156 @@
+/** Brand preference, SaaS policy context, and settings tab visibility. */
+
+export type Brand = "oss" | "ibm";
+
+export const IBM_THEME_DEV = process.env.NEXT_PUBLIC_IBM_THEME_DEV === "true";
+
+/** Default when no localStorage — must match `BrandProvider` initial state. */
+export const DEFAULT_BRAND: Brand = IBM_THEME_DEV ? "ibm" : "oss";
+
+/** Normalize stored brand value; unknown/missing uses `DEFAULT_BRAND`. */
+export function resolveBrand(brand: Brand | string | undefined): Brand {
+ if (brand === "ibm" || brand === "oss") return brand;
+ return DEFAULT_BRAND;
+}
+
+/** IBM/SaaS UI styling from context brand only (see `BrandProvider`). */
+export function isCloudBrand(brand: Brand | string | undefined): boolean {
+ if (!IBM_THEME_DEV) return resolveBrand(brand) === "ibm";
+ return resolveBrand(brand) !== "oss";
+}
+
+/**
+ * SaaS policy context (connector access tab, RBAC-gated settings).
+ * Production: IBM auth or backend `cloud_context`.
+ * Local: IBM theme dev + IBM brand mirrors SaaS settings UX (client brand only).
+ */
+export function isSaasPolicyContext({
+ isIbmAuthMode,
+ cloudContext = false,
+ brand,
+ /** RSC cannot read localStorage — skip dev brand toggle on server guards. */
+ skipDevBrand = false,
+}: {
+ isIbmAuthMode: boolean;
+ cloudContext?: boolean;
+ brand?: Brand | string | undefined;
+ skipDevBrand?: boolean;
+}): boolean {
+ if (isIbmAuthMode || cloudContext) return true;
+ if (!IBM_THEME_DEV) return false;
+ // RSC cannot read localStorage — mirror BrandProvider's default brand.
+ const effectiveBrand = skipDevBrand ? DEFAULT_BRAND : resolveBrand(brand);
+ return effectiveBrand !== "oss";
+}
+
+/** False when the admin explicitly disabled this connector for the workspace. */
+export function isConnectorAllowedByWorkspace(
+ type: string,
+ storedAccess: Record<string, boolean>,
+): boolean {
+ return storedAccess[type] !== false;
+}
+
+/**
+ * Connectors tab visibility: workspace policy first, then deployment rules.
+ * Explicit `storedAccess[type] === true` (saved in Connectors Permission) overrides
+ * deployment filters so admins can re-enable types like OneDrive on cloud brand.
+ */
+export function isConnectorShownInWorkspace(
+ type: string,
+ storedAccess: Record<string, boolean>,
+ {
+ isCloudBrand: cloudBrand,
+ isIbmAuthMode,
+ }: { isCloudBrand: boolean; isIbmAuthMode: boolean },
+): boolean {
+ if (!isConnectorAllowedByWorkspace(type, storedAccess)) return false;
+ if (storedAccess[type] === true) return true;
+ return isConnectorTypeVisible(type, {
+ isCloudBrand: cloudBrand,
+ isIbmAuthMode,
+ });
+}
+
+/** Deployment filter shared by Connectors tab, permission admin, and upload menus. */
+export function isConnectorTypeVisible(
+ type: string,
+ {
+ isCloudBrand: cloudBrand,
+ isIbmAuthMode,
+ }: { isCloudBrand: boolean; isIbmAuthMode: boolean },
+): boolean {
+ if (type === "ibm_cos" || type === "aws_s3") return isIbmAuthMode;
+ if (cloudBrand && type === "onedrive") return false;
+ return true;
+}
+
+// --- Settings tab access (nav, RSC guards, auth-context `can()`) ---
+
+export type SettingsTabAccessContext = {
+ isSaasPolicy: boolean;
+ isNoAuthMode: boolean;
+ rbacEnforced: boolean;
+ permissions: Set<string>;
+};
+
+export function buildSettingsTabAccess({
+ isIbmAuthMode,
+ cloudContext,
+ isNoAuthMode,
+ permissions,
+ rbacEnforced,
+ brand = DEFAULT_BRAND,
+ useClientBrandPolicy = true,
+}: {
+ isIbmAuthMode: boolean;
+ cloudContext: boolean;
+ isNoAuthMode: boolean;
+ permissions: Set<string>;
+ rbacEnforced: boolean;
+ brand?: Brand | string;
+ /** False on RSC tab guards — brand lives in localStorage, not on the server. */
+ useClientBrandPolicy?: boolean;
+}): SettingsTabAccessContext {
+ return {
+ isSaasPolicy: isSaasPolicyContext({
+ isIbmAuthMode,
+ cloudContext,
+ brand,
+ skipDevBrand: !useClientBrandPolicy,
+ }),
+ isNoAuthMode,
+ rbacEnforced,
+ permissions,
+ };
+}
+
+export function hasRbacPermission(
+ perm: string,
+ {
+ isNoAuthMode,
+ rbacEnforced,
+ permissions,
+ }: Pick<
+ SettingsTabAccessContext,
+ "isNoAuthMode" | "rbacEnforced" | "permissions"
+ >,
+): boolean {
+ if (isNoAuthMode || !rbacEnforced) return true;
+ return permissions.has(perm);
+}
+
+/** RBAC applies in SaaS policy context only; OSS shows all standard tabs. */
+export function canShowRbacGatedSettingsTab(
+ perm: string,
+ ctx: SettingsTabAccessContext,
+): boolean {
+ if (!ctx.isSaasPolicy) return true;
+ return hasRbacPermission(perm, ctx);
+}
+
+export function canAccessConnectorAccessTab(
+ ctx: SettingsTabAccessContext,
+): boolean {
+ return ctx.isSaasPolicy && hasRbacPermission("connectors:manage:access", ctx);
+}
diff --git a/src/api/auth.py b/src/api/auth.py
index 22d3bb0fa..e514ad327 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -1,12 +1,18 @@
from fastapi import Depends, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
+from sqlalchemy.ext.asyncio import AsyncSession
from dependencies import (
get_auth_service,
get_current_user,
+ get_db_session,
get_optional_user,
)
+from services.connector_access_service import (
+ CONNECTOR_TYPES,
+ is_connector_allowed_for_request,
+)
from session_manager import User
from utils.logging_config import get_logger
from utils.telemetry import Category, MessageId, TelemetryClient
@@ -37,9 +43,20 @@ async def auth_init(
request: Request,
auth_service=Depends(get_auth_service),
user: User | None = Depends(get_optional_user),
+ session: AsyncSession = Depends(get_db_session),
):
"""Initialize OAuth flow for authentication or data source connection"""
try:
+ if (
+ body.purpose == "data_source"
+ and body.connector_type in CONNECTOR_TYPES
+ and not await is_connector_allowed_for_request(session, body.connector_type)
+ ):
+ return JSONResponse(
+ {"error": f"Connector not available: {body.connector_type}"},
+ status_code=403,
+ )
+
connection_name = body.name or f"{body.connector_type}_{body.purpose}"
user_id = user.user_id if user else None
diff --git a/src/api/connectors.py b/src/api/connectors.py
index 3babd660c..87bc740da 100644
--- a/src/api/connectors.py
+++ b/src/api/connectors.py
@@ -3,15 +3,26 @@ from typing import Any
from fastapi import Depends, Request
from fastapi.responses import JSONResponse, PlainTextResponse
from pydantic import BaseModel
+from sqlalchemy.ext.asyncio import AsyncSession
from config.settings import get_index_name
from connectors.sharepoint.utils import is_valid_sharepoint_url
from dependencies import (
get_connector_service,
get_current_user,
+ get_db_session,
get_session_manager,
require_permission,
)
+from services.connector_access_service import (
+ CONNECTOR_TYPES,
+ filter_connectors_for_user,
+ get_access_map,
+ is_connector_access_policy_enforced,
+ is_connector_allowed_for_request,
+ list_access_for_admin,
+ set_connector_access_bulk,
+)
from session_manager import User
from utils.logging_config import get_logger
from utils.telemetry import Category, MessageId, TelemetryClient
@@ -19,6 +30,36 @@ from utils.telemetry import Category, MessageId, TelemetryClient
logger = get_logger(__name__)
+async def _connector_access_denied(
+ request: Request,
+ session: AsyncSession,
+ connector_type: str,
+) -> JSONResponse | None:
+ """Return 403 when workspace policy blocks this connector type."""
+ if connector_type not in CONNECTOR_TYPES:
+ return None
+ if not is_connector_access_policy_enforced():
+ return None
+ if await is_connector_allowed_for_request(session, connector_type):
+ return None
+ return JSONResponse(
+ {"error": f"Connector not available: {connector_type}"},
+ status_code=403,
+ )
+
+
+async def _allowed_connector_types_for_request(
+ request: Request,
+ session: AsyncSession,
+ connector_types: list[str],
+) -> list[str]:
+ """Drop connector types blocked by workspace policy (sync-all style endpoints)."""
+ if not is_connector_access_policy_enforced():
+ return connector_types
+ access_map = await get_access_map(session)
+ return [t for t in connector_types if access_map.get(t, True)]
+
+
def _connector_sync_should_replace(connector_type: str) -> bool:
"""Return True for connector types where sync should replace existing indexed files."""
return connector_type in ["google_drive", "sharepoint", "onedrive"]
@@ -355,11 +396,16 @@ class ConnectorCheckDuplicatesBody(BaseModel):
async def connector_check_duplicates(
connector_type: str,
body: ConnectorCheckDuplicatesBody,
+ request: Request,
connector_service=Depends(get_connector_service),
session_manager=Depends(get_session_manager),
user: User = Depends(require_permission("connectors:use")),
+ session: AsyncSession = Depends(get_db_session),
):
"""Check if any of the selected files or folders contain files that already exist in the index"""
+ if denied := await _connector_access_denied(request, session, connector_type):
+ return denied
+
selected_files_raw = body.selected_files
if not selected_files_raw:
return JSONResponse({"duplicate_names": []})
@@ -498,28 +544,110 @@ async def connector_check_duplicates(
async def list_connectors(
+ request: Request,
connector_service=Depends(get_connector_service),
user: User = Depends(get_current_user),
+ session: AsyncSession = Depends(get_db_session),
):
"""List available connector types with metadata"""
try:
connector_types = connector_service.connection_manager.get_available_connector_types(
user_id=user.user_id
)
+ if is_connector_access_policy_enforced():
+ access_map = await get_access_map(session)
+ connector_types = filter_connectors_for_user(connector_types, access_map)
return JSONResponse({"connectors": connector_types})
except Exception as e:
logger.error("[CONNECTOR] Error listing connectors", error=str(e))
return JSONResponse({"connectors": []})
+class UpdateConnectorAccessBody(BaseModel):
+ access: dict[str, bool]
+
+
+def _connector_access_client_error(exc: ValueError) -> str:
+ """Safe client message for set_connector_access_bulk validation failures."""
+ detail = str(exc)
+ if detail.startswith("Unknown connector type:"):
+ return "Unknown connector type"
+ return "Invalid request data"
+
+
+async def get_connector_workspace_policy(
+ user: User = Depends(get_current_user),
+ session: AsyncSession = Depends(get_db_session),
+):
+ """Read-only stored workspace connector overrides for Connectors tab filtering.
+
+ Returns only explicit admin saves (missing types default to allowed server-side
+ but still follow deployment visibility rules on the client).
+ """
+ from db.repositories import WorkspaceConfigRepo
+ from services.connector_access_service import CONNECTOR_ACCESS_SECTION
+
+ stored = await WorkspaceConfigRepo(session).get_section(CONNECTOR_ACCESS_SECTION) or {}
+ return JSONResponse({"access": stored})
+
+
+async def get_connector_user_access(
+ connector_service=Depends(get_connector_service),
+ user: User = Depends(require_permission("connectors:manage:access")),
+ session: AsyncSession = Depends(get_db_session),
+):
+ """List connector types and whether they are enabled for this workspace."""
+ metadata = connector_service.connection_manager.get_available_connector_types(
+ user_id=user.user_id
+ )
+ connectors = await list_access_for_admin(session, metadata)
+ return JSONResponse({"connectors": connectors})
+
+
+async def update_connector_user_access(
+ body: UpdateConnectorAccessBody,
+ user: User = Depends(require_permission("connectors:manage:access")),
+ session: AsyncSession = Depends(get_db_session),
+ connector_service=Depends(get_connector_service),
+):
+ """Save workspace connector availability policy."""
+ try:
+ await set_connector_access_bulk(
+ session,
+ body.access,
+ user.db_user_id or user.user_id,
+ )
+ await session.commit()
+ except ValueError as e:
+ logger.error(
+ "[CONNECTOR] Invalid connector access update",
+ error=str(e),
+ )
+ return JSONResponse(
+ {"error": _connector_access_client_error(e)},
+ status_code=400,
+ )
+
+ metadata = connector_service.connection_manager.get_available_connector_types(
+ user_id=user.user_id
+ )
+ connectors = await list_access_for_admin(session, metadata)
+ return JSONResponse({"connectors": connectors})
+
+
async def connector_sync(
connector_type: str,
body: ConnectorSyncBody,
+ request: Request,
connector_service=Depends(get_connector_service),
session_manager=Depends(get_session_manager),
user: User = Depends(require_permission("connectors:use")),
+ session: AsyncSession = Depends(get_db_session),
):
"""Sync files from all active connections of a connector type"""
+ if denied := await _connector_access_denied(request, session, connector_type):
+ return denied
+
max_files = body.max_files
selected_files_raw = body.selected_files
selected_files = None
@@ -764,10 +892,14 @@ async def connector_sync(
async def connector_status(
connector_type: str,
+ request: Request,
connector_service=Depends(get_connector_service),
user: User = Depends(get_current_user),
+ session: AsyncSession = Depends(get_db_session),
):
"""Get connector status for authenticated user"""
+ if denied := await _connector_access_denied(request, session, connector_type):
+ return denied
# Get connections for this connector type and user
connections = await connector_service.connection_manager.list_connections(
@@ -862,9 +994,13 @@ async def connector_webhook(
request: Request,
connector_service=Depends(get_connector_service),
session_manager=Depends(get_session_manager),
+ session: AsyncSession = Depends(get_db_session),
):
"""Handle webhook notifications from any connector type"""
+ if denied := await _connector_access_denied(request, session, connector_type):
+ return denied
+
# Handle webhook validation (connector-specific)
temp_config = {"token_file": "temp.json"}
from connectors.connection_manager import ConnectionConfig
@@ -1015,10 +1151,14 @@ async def connector_webhook(
async def connector_disconnect(
connector_type: str,
+ request: Request,
connector_service=Depends(get_connector_service),
user: User = Depends(require_permission("connectors:delete:own")),
+ session: AsyncSession = Depends(get_db_session),
):
"""Disconnect a connector by deleting its connection"""
+ if denied := await _connector_access_denied(request, session, connector_type):
+ return denied
try:
# Get connections for this connector type and user
@@ -1094,9 +1234,11 @@ async def connector_disconnect(
async def sync_all_connectors(
+ request: Request,
connector_service=Depends(get_connector_service),
session_manager=Depends(get_session_manager),
user: User = Depends(require_permission("connectors:use")),
+ session: AsyncSession = Depends(get_db_session),
):
"""
Sync files from all active cloud connector connections.
@@ -1107,16 +1249,16 @@ async def sync_all_connectors(
)
jwt_token = user.jwt_token
- # Cloud connector types to sync
- cloud_connector_types = _cloud_connector_types()
-
all_task_ids = []
synced_connectors = []
skipped_connectors = []
deleted_only_connectors = []
errors = []
- for connector_type in cloud_connector_types:
+ connector_types = await _allowed_connector_types_for_request(
+ request, session, _cloud_connector_types()
+ )
+ for connector_type in connector_types:
try:
# First, get existing file IDs/filenames from OpenSearch for this connector type
(
@@ -1346,14 +1488,19 @@ async def _preview_orphans_for_connector_type(
async def connector_sync_preview(
connector_type: str,
+ request: Request,
connector_service=Depends(get_connector_service),
session_manager=Depends(get_session_manager),
user: User = Depends(require_permission("connectors:use")),
+ session: AsyncSession = Depends(get_db_session),
):
"""Preview the impact of syncing a connector type without performing any
deletion or ingest. Returns the list of orphan files (present in OpenSearch
but no longer at the source) by filename, plus the total synced count.
"""
+ if denied := await _connector_access_denied(request, session, connector_type):
+ return denied
+
try:
orphans, synced_count = await _preview_orphans_for_connector_type(
connector_type=connector_type,
@@ -1377,9 +1524,11 @@ async def connector_sync_preview(
async def connectors_sync_all_preview(
+ request: Request,
connector_service=Depends(get_connector_service),
session_manager=Depends(get_session_manager),
user: User = Depends(require_permission("connectors:use")),
+ session: AsyncSession = Depends(get_db_session),
):
"""Preview the impact of sync-all-connectors across every cloud connector
type. Returns orphan filenames grouped by connector_type plus a per-type
@@ -1390,7 +1539,10 @@ async def connectors_sync_all_preview(
synced_count_by_type: dict[str, int] = {}
orphans_available_by_type: dict[str, bool] = {}
- for connector_type in _cloud_connector_types():
+ connector_types = await _allowed_connector_types_for_request(
+ request, session, _cloud_connector_types()
+ )
+ for connector_type in connector_types:
try:
orphans, synced_count = await _preview_orphans_for_connector_type(
connector_type=connector_type,
@@ -1434,8 +1586,12 @@ async def connector_token(
request: Request,
connector_service=Depends(get_connector_service),
user: User = Depends(get_current_user),
+ session: AsyncSession = Depends(get_db_session),
):
"""Get access token for connector API calls (e.g., Pickers)."""
+ if denied := await _connector_access_denied(request, session, connector_type):
+ return denied
+
url_connector_type = connector_type
try:
@@ -1550,9 +1706,11 @@ async def connector_token(
async def browse_connection_files(
connector_type: str,
connection_id: str,
+ request: Request,
connector_service=Depends(get_connector_service),
session_manager=Depends(get_session_manager),
user: User = Depends(get_current_user),
+ session: AsyncSession = Depends(get_db_session),
bucket: str | None = None,
search: str | None = None,
page_token: str | None = None,
@@ -1564,6 +1722,9 @@ async def browse_connection_files(
Lists files from the remote source (e.g., S3 bucket) and marks each
as ingested or not by cross-referencing with OpenSearch.
"""
+ if denied := await _connector_access_denied(request, session, connector_type):
+ return denied
+
try:
connector = await connector_service.get_connector(connection_id)
if not connector:
diff --git a/src/api/users.py b/src/api/users.py
index 6c565673e..4f115c351 100644
--- a/src/api/users.py
+++ b/src/api/users.py
@@ -4,14 +4,25 @@ GET /api/users/me -> profile of the current user
GET /api/users/me/permissions -> list of permission strings
"""
-from fastapi import APIRouter, Depends
+from fastapi import APIRouter, Depends, HTTPException
+from fastapi.responses import JSONResponse
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
+from config.settings import is_cloud_context, is_dev_role_toggle_enabled
from db.repositories import PermissionRepo, RoleRepo, UserRepo
-from dependencies import get_current_user, get_db_session, get_rbac_service
+from dependencies import (
+ get_current_user,
+ get_db_session,
+ get_rbac_service,
+ invalidate_user_ensured_cache,
+)
+from services.dev_role_toggle import set_dev_role
from services.rbac_service import is_rbac_enforced
from session_manager import User
+from utils.logging_config import get_logger
+
+logger = get_logger(__name__)
async def _effective_permissions(rbac, db_id: str, session: AsyncSession) -> set[str]:
@@ -46,6 +57,8 @@ class MeResponse(BaseModel):
# sections (Users & Roles, Audit log, role pills) when the
# operator has the kill switch off.
rbac_enforced: bool
+ # SaaS/cloud context — connector policy and gated settings tabs.
+ cloud_context: bool
@router.get("/me", response_model=MeResponse)
@@ -75,6 +88,7 @@ async def get_me(
roles=[r.name for r in roles],
permissions=sorted(perms),
rbac_enforced=is_rbac_enforced(),
+ cloud_context=is_cloud_context(),
)
@@ -96,3 +110,57 @@ async def get_my_permissions(
perms = await _effective_permissions(rbac, db_id, session)
return PermissionsResponse(permissions=sorted(perms))
+
+
+class DevRoleBody(BaseModel):
+ role: str
+
+
+def _dev_role_client_error(exc: ValueError) -> str:
+ detail = str(exc)
+ if detail == "User not found in database":
+ return "User account not found"
+ if detail.startswith("Role not found:"):
+ return "Role not available"
+ if detail.startswith("Unsupported dev role:"):
+ return "Invalid role"
+ return "Invalid request"
+
+
[email protected]("/me/dev-role")
+async def set_my_dev_role(
+ body: DevRoleBody,
+ user: User = Depends(get_current_user),
+ session: AsyncSession = Depends(get_db_session),
+ rbac=Depends(get_rbac_service),
+):
+ """Swap the current user to any built-in role (local dev only)."""
+ if not is_dev_role_toggle_enabled():
+ raise HTTPException(status_code=404, detail="Not found")
+
+ try:
+ roles = await set_dev_role(session, user, body.role)
+ await session.commit()
+ except ValueError as e:
+ logger.error("[USERS] Invalid dev role update", error=str(e))
+ return JSONResponse(
+ {"error": _dev_role_client_error(e)},
+ status_code=400,
+ )
+
+ invalidate_user_ensured_cache(user.provider, user.user_id)
+
+ db_user = await UserRepo(session).get_by_oauth(user.provider or "unknown", user.user_id)
+ if db_user is None:
+ db_user = await UserRepo(session).get_by_id(user.user_id)
+ db_id = db_user.id if db_user else user.user_id
+ rbac.invalidate(db_id)
+ perms = await _effective_permissions(rbac, db_id, session)
+
+ return JSONResponse(
+ {
+ "roles": roles,
+ "role": body.role,
+ "permissions": sorted(perms),
+ }
+ )
diff --git a/src/app/routes/internal.py b/src/app/routes/internal.py
index a9557eafc..ee84c46b5 100644
--- a/src/app/routes/internal.py
+++ b/src/app/routes/internal.py
@@ -208,6 +208,24 @@ def register_internal_routes(app: FastAPI):
# Connector endpoints
app.add_api_route("/connectors", connectors.list_connectors, methods=["GET"], tags=["internal"])
+ app.add_api_route(
+ "/connectors/workspace-policy",
+ connectors.get_connector_workspace_policy,
+ methods=["GET"],
+ tags=["internal"],
+ )
+ app.add_api_route(
+ "/connectors/user-access",
+ connectors.get_connector_user_access,
+ methods=["GET"],
+ tags=["internal"],
+ )
+ app.add_api_route(
+ "/connectors/user-access",
+ connectors.update_connector_user_access,
+ methods=["PUT"],
+ 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.py
index 1516d430b..a77e20e82 100644
--- a/src/config/settings.py
+++ b/src/config/settings.py
@@ -197,6 +197,28 @@ def get_role_claim_viewer() -> str | None:
return os.getenv("OPENRAG_ROLE_CLAIM_VIEWER")
+def is_dev_role_toggle_enabled() -> bool:
+ """Allow POST /users/me/dev-role for local RBAC UI testing.
+
+ Requires ``OPENRAG_DEV_ROLE_TOGGLE=true``. Never enable in production.
+ """
+ raw = os.getenv("OPENRAG_DEV_ROLE_TOGGLE", "false").strip().lower()
+ return raw in ("true", "1", "yes", "on")
+
+
+def is_dev_connector_policy_enabled() -> bool:
+ """Local OSS dev: enforce workspace connector policy (pair with IBM theme dev UI)."""
+ raw = os.getenv("OPENRAG_DEV_CONNECTOR_POLICY", "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_saas
+
+ return IBM_AUTH_ENABLED or is_run_mode_saas() or is_dev_connector_policy_enabled()
+
+
def get_default_user_role() -> str:
"""Built-in role assigned to new users when JWT role sync is off."""
return os.getenv("OPENRAG_DEFAULT_ROLE", "user")
diff --git a/src/db/migrations_runtime.py b/src/db/migrations_runtime.py
index b4877c99a..03126156d 100644
--- a/src/db/migrations_runtime.py
+++ b/src/db/migrations_runtime.py
@@ -1,8 +1,9 @@
-"""One-shot runtime migrations from JSON state to the SQL DB.
+"""Runtime migrations from legacy JSON state and the RBAC catalog.
-These run on application startup AFTER Alembic upgrade. Idempotency is
-recorded in the `migration_status` table so the migration only ever
-inserts once per install.
+These run on application startup AFTER Alembic upgrade. Legacy JSON
+migrations are one-shot; idempotency is recorded in `migration_status`.
+RBAC catalog sync (`db.seed.seed_roles_and_permissions`) runs every boot
+and is additive-only.
Phase 1 only migrates *user identity* — connections.json, conversations.json,
and config.yaml are left in place. The legacy users get a placeholder row
@@ -16,15 +17,15 @@ from __future__ import annotations
import json
import os
-import uuid
+from collections.abc import Iterable
from datetime import datetime
-from typing import Iterable
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from config.paths import get_data_file
-from db.models import MigrationStatus, User as UserRow
+from db.models import MigrationStatus
+from db.models import User as UserRow
from db.repositories._helpers import email_lookup_hash
from utils.encryption import read_encrypted_file
from utils.logging_config import get_logger
@@ -52,9 +53,7 @@ async def _already_done(session: AsyncSession, name: str) -> bool:
async def _mark_done(session: AsyncSession, name: str, notes: str = "") -> None:
- session.add(
- MigrationStatus(name=name, completed_at=datetime.utcnow(), notes=notes)
- )
+ session.add(MigrationStatus(name=name, completed_at=datetime.utcnow(), notes=notes))
await session.flush()
@@ -157,7 +156,6 @@ async def migrate_config_yaml_to_db(session: AsyncSession) -> int:
workspace has no config.yaml yet (fresh install) and the table will
fill up the first time an admin completes onboarding.
"""
- from sqlalchemy.ext.asyncio import async_sessionmaker
from db.repositories import WorkspaceConfigRepo
from utils.encryption import encrypt_secret
@@ -165,6 +163,7 @@ async def migrate_config_yaml_to_db(session: AsyncSession) -> int:
# ConfigManager does (decrypts api_keys, applies env overrides, etc.).
try:
from config.config_manager import config_manager
+
config = config_manager.load_config()
except Exception as exc: # noqa: BLE001
logger.warning("config_yaml_to_db_v1: load_config() failed; skipping", error=str(exc))
@@ -217,9 +216,7 @@ async def migrate_chat_history_json_to_db(session: AsyncSession) -> dict[str, in
continue
try:
created = (
- datetime.fromisoformat(data["created_at"])
- if data.get("created_at")
- else None
+ datetime.fromisoformat(data["created_at"]) if data.get("created_at") else None
)
except Exception: # noqa: BLE001
created = None
@@ -302,9 +299,7 @@ async def run(session: AsyncSession) -> None:
except Exception as exc: # noqa: BLE001
logger.error("config_yaml_to_db_v1 failed; aborting startup", error=str(exc))
raise RuntimeMigrationError(f"{CONFIG_YAML_TO_DB_V1} failed") from exc
- await _mark_done(
- session, CONFIG_YAML_TO_DB_V1, notes=f"sections_written={written}"
- )
+ await _mark_done(session, CONFIG_YAML_TO_DB_V1, notes=f"sections_written={written}")
logger.info("config_yaml_to_db_v1 completed", sections_written=written)
if not await _already_done(session, CHAT_HISTORY_JSON_TO_DB_V1):
@@ -317,17 +312,25 @@ async def run(session: AsyncSession) -> None:
)
raise RuntimeMigrationError(f"{CHAT_HISTORY_JSON_TO_DB_V1} failed") from exc
notes = (
- f"sessions={stats['sessions_inserted']},"
- f"conversations={stats['conversations_inserted']}"
+ f"sessions={stats['sessions_inserted']},conversations={stats['conversations_inserted']}"
)
await _mark_done(session, CHAT_HISTORY_JSON_TO_DB_V1, notes=notes)
logger.info("chat_history_json_to_db_v1 completed", **stats)
+ try:
+ from db.seed import seed_roles_and_permissions
+
+ await seed_roles_and_permissions(session)
+ except Exception as exc: # noqa: BLE001
+ logger.error("RBAC catalog sync failed; aborting startup", error=str(exc))
+ raise RuntimeMigrationError("rbac_catalog_sync failed") from exc
+
# ---------------------------------------------------------------------------
# Alembic upgrade — programmatic invocation
# ---------------------------------------------------------------------------
+
def run_alembic_upgrade(target: str = "head") -> None:
"""Run `alembic upgrade <target>` programmatically.
@@ -335,10 +338,12 @@ def run_alembic_upgrade(target: str = "head") -> None:
function MUST NOT be invoked from inside an already-running event
loop. Async callers should use `run_alembic_upgrade_async` instead.
"""
- from alembic import command
- from alembic.config import Config
from pathlib import Path
+ from alembic.config import Config
+
+ from alembic import command
+
root = Path(__file__).resolve().parent.parent.parent
cfg_path = root / "alembic.ini"
if not cfg_path.exists():
diff --git a/src/db/seed.py b/src/db/seed.py
index 5633a6069..5e5d2b115 100644
--- a/src/db/seed.py
+++ b/src/db/seed.py
@@ -1,8 +1,13 @@
"""Idempotent seed for built-in roles and permissions.
-The full permission catalog and the role-permission default mapping live here
-so adding a permission or a role is a one-file change followed by an Alembic
-data migration. See plan §1.2 / §1.3 / §10.
+The full permission catalog and the role-permission default mapping live here.
+To add a permission, role, or default role grant: edit this file only —
+``seed_roles_and_permissions`` runs on application startup (after Alembic)
+and backfills missing rows on existing installs.
+
+To revoke a permission from a role on existing installs, add an explicit
+Alembic data migration (see ``0006_revoke_provider_override_nonadmin``);
+the seeder is additive-only and never removes rows.
Built-in role IDs are stable, deterministic strings so cross-environment
references (e.g. tests, docs) do not depend on UUIDs.
@@ -46,6 +51,7 @@ PERMISSIONS: list[tuple[str, str, str]] = [
("connectors", "delete:own", "Delete own connectors"),
("connectors", "delete:any", "Delete any connector"),
("connectors", "use", "Use connector OAuth and browse"),
+ ("connectors", "manage:access", "Manage workspace connector availability"),
# Knowledge
("knowledge", "upload", "Upload documents"),
("knowledge", "delete:own", "Delete own documents"),
@@ -174,8 +180,8 @@ ROLE_PERMISSION_MAP: dict[str, set[str]] = {
async def seed_roles_and_permissions(session: AsyncSession) -> None:
"""Insert any missing roles/permissions/role_permissions. Safe to call repeatedly.
- Used by the second Alembic data migration AND from tests against an
- in-memory SQLite. Does not commit — caller commits.
+ Alembic ``0002`` bootstraps greenfield installs; startup and tests call
+ this for additive catalog sync. Does not commit — caller commits.
"""
# Permissions
diff --git a/src/dependencies.py b/src/dependencies.py
index b2b8574df..3c8ea6747 100644
--- a/src/dependencies.py
+++ b/src/dependencies.py
@@ -268,6 +268,10 @@ async def _attach_db_user_id(request: Request, user: User | None) -> User | None
request.state.user = None
return None
jwt_roles = getattr(request.state, "jwt_roles", None)
+ from config.settings import is_dev_role_toggle_enabled
+
+ if is_dev_role_toggle_enabled():
+ jwt_roles = None
db_user_id = await _resolve_db_user_id(user, jwt_roles=jwt_roles)
user_with_db_id = dataclasses.replace(user, db_user_id=db_user_id)
request.state.db_user_id = db_user_id
diff --git a/src/services/connector_access_service.py b/src/services/connector_access_service.py
new file mode 100644
index 000000000..7a64edb17
--- /dev/null
+++ b/src/services/connector_access_service.py
@@ -0,0 +1,98 @@
+"""Workspace-wide connector availability policy (admin Connectors Permission UI)."""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from connectors.registry import get_connector_classes
+from db.repositories import WorkspaceConfigRepo
+
+CONNECTOR_ACCESS_SECTION = "connector_access"
+
+# Derived from the connector registry so new connector types are governable
+# without touching this module.
+CONNECTOR_TYPES: tuple[str, ...] = tuple(cls.CONNECTOR_TYPE for cls in get_connector_classes())
+
+_BUCKET_CONNECTOR_TYPES = frozenset({"aws_s3", "ibm_cos"})
+
+
+def governable_connector_types() -> tuple[str, ...]:
+ """Types shown in admin Connectors Permission — independent of the live connectors list."""
+ from config.settings import IBM_AUTH_ENABLED, is_cloud_context
+
+ if is_cloud_context() and not IBM_AUTH_ENABLED:
+ return tuple(t for t in CONNECTOR_TYPES if t not in _BUCKET_CONNECTOR_TYPES)
+ return CONNECTOR_TYPES
+
+
+async def get_access_map(session: AsyncSession) -> dict[str, bool]:
+ stored = await WorkspaceConfigRepo(session).get_section(CONNECTOR_ACCESS_SECTION) or {}
+ return {
+ connector_type: bool(stored.get(connector_type, True)) for connector_type in CONNECTOR_TYPES
+ }
+
+
+async def set_connector_access_bulk(
+ session: AsyncSession,
+ access: dict[str, bool],
+ actor_user_id: str | None,
+) -> dict[str, bool]:
+ current = await get_access_map(session)
+ for connector_type, enabled in access.items():
+ if connector_type not in CONNECTOR_TYPES:
+ raise ValueError(f"Unknown connector type: {connector_type}")
+ current[connector_type] = enabled
+ repo = WorkspaceConfigRepo(session)
+ await repo.upsert(CONNECTOR_ACCESS_SECTION, current, actor_user_id=actor_user_id)
+ return current
+
+
+def is_connector_access_policy_enforced() -> bool:
+ """Workspace connector policy applies in SaaS/cloud context only."""
+ from config.settings import is_cloud_context
+
+ return is_cloud_context()
+
+
+async def is_connector_allowed(session: AsyncSession, connector_type: str) -> bool:
+ access = await get_access_map(session)
+ return access.get(connector_type, True)
+
+
+async def is_connector_allowed_for_request(
+ session: AsyncSession,
+ connector_type: str,
+) -> bool:
+ if not is_connector_access_policy_enforced():
+ return True
+ return await is_connector_allowed(session, connector_type)
+
+
+def filter_connectors_for_user(
+ connector_metadata: dict[str, dict],
+ access_map: dict[str, bool],
+) -> dict[str, dict]:
+ """Apply workspace policy to the connector list for every role."""
+ return {
+ connector_type: meta
+ for connector_type, meta in connector_metadata.items()
+ if access_map.get(connector_type, True)
+ }
+
+
+async def list_access_for_admin(
+ session: AsyncSession,
+ connector_metadata: dict[str, dict],
+) -> list[dict[str, str | bool]]:
+ access_map = await get_access_map(session)
+ items: list[dict[str, str | bool]] = []
+ for connector_type in governable_connector_types():
+ meta = connector_metadata.get(connector_type, {})
+ items.append(
+ {
+ "type": connector_type,
+ "name": str(meta.get("name", connector_type.replace("_", " ").title())),
+ "enabled": access_map.get(connector_type, True),
+ }
+ )
+ return items
diff --git a/src/services/dev_role_toggle.py b/src/services/dev_role_toggle.py
new file mode 100644
index 000000000..986eb0afd
--- /dev/null
+++ b/src/services/dev_role_toggle.py
@@ -0,0 +1,48 @@
+"""Dev-only helper to swap the current user between built-in roles."""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from db.repositories import RoleRepo, UserRepo
+from db.seed import BUILTIN_ROLES
+from session_manager import User
+
+_DEV_ROLES = frozenset(name for _id, name, _desc in BUILTIN_ROLES)
+
+
+async def _resolve_db_user_id(session: AsyncSession, user: User) -> str | None:
+ user_repo = UserRepo(session)
+ db_user = await user_repo.get_by_oauth(user.provider or "unknown", user.user_id)
+ if db_user is None:
+ db_user = await user_repo.get_by_id(user.user_id)
+ return db_user.id if db_user else None
+
+
+async def set_dev_role(
+ session: AsyncSession,
+ user: User,
+ role_name: str,
+) -> list[str]:
+ """Replace built-in role membership with a single built-in role. Returns new role names."""
+ if role_name not in _DEV_ROLES:
+ raise ValueError(f"Unsupported dev role: {role_name}")
+
+ db_user_id = await _resolve_db_user_id(session, user)
+ if db_user_id is None:
+ raise ValueError("User not found in database")
+
+ role_repo = RoleRepo(session)
+ target = await role_repo.get_by_name(role_name)
+ if target is None:
+ raise ValueError(f"Role not found: {role_name}")
+
+ for name in _DEV_ROLES:
+ role = await role_repo.get_by_name(name)
+ if role is not None:
+ await role_repo.revoke_role(db_user_id, role.id)
+
+ await role_repo.assign_role(db_user_id, target.id)
+
+ roles = await role_repo.list_user_roles(db_user_id)
+ return [r.name for r in roles]
diff --git a/tests/unit/api/test_auth_init_connector_access.py b/tests/unit/api/test_auth_init_connector_access.py
new file mode 100644
index 000000000..b5150b38e
--- /dev/null
+++ b/tests/unit/api/test_auth_init_connector_access.py
@@ -0,0 +1,97 @@
+"""auth_init must enforce workspace connector policy for all callers."""
+
+import json
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+import pytest_asyncio # noqa: E402
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine # noqa: E402
+from sqlmodel import SQLModel # noqa: E402
+
+import db.models # noqa: E402,F401
+from api.auth import AuthInitBody, auth_init # noqa: E402
+from db.repositories import WorkspaceConfigRepo # noqa: E402
+
+
+@pytest_asyncio.fixture
+async def session():
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ )
+ async with engine.begin() as conn:
+ await conn.run_sync(SQLModel.metadata.create_all)
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ yield session
+ await engine.dispose()
+
+
+class _FakeRequest:
+ headers: dict[str, str] = {}
+
+
+async def test_auth_init_blocks_disabled_connector_without_user(session, monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+
+ await WorkspaceConfigRepo(session).upsert(
+ "connector_access",
+ {"google_drive": False},
+ )
+ await session.commit()
+
+ auth_service = AsyncMock()
+ body = AuthInitBody(connector_type="google_drive", purpose="data_source")
+
+ response = await auth_init(
+ body,
+ _FakeRequest(),
+ auth_service=auth_service,
+ user=None,
+ session=session,
+ )
+
+ assert response.status_code == 403
+ assert "google_drive" in json.loads(response.body)["error"]
+ auth_service.init_oauth.assert_not_called()
+
+
+async def test_auth_init_allows_disabled_connector_when_policy_not_enforced(session, monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "oss")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+
+ await WorkspaceConfigRepo(session).upsert(
+ "connector_access",
+ {"google_drive": False},
+ )
+ await session.commit()
+
+ auth_service = AsyncMock()
+ auth_service.init_oauth = AsyncMock(return_value={"auth_url": "https://example.com"})
+ body = AuthInitBody(
+ connector_type="google_drive",
+ purpose="data_source",
+ redirect_uri="http://localhost/callback",
+ )
+
+ response = await auth_init(
+ body,
+ _FakeRequest(),
+ auth_service=auth_service,
+ user=None,
+ session=session,
+ )
+
+ assert response.status_code == 200
+ auth_service.init_oauth.assert_called_once()
diff --git a/tests/unit/api/test_connectors_connector_access.py b/tests/unit/api/test_connectors_connector_access.py
new file mode 100644
index 000000000..9850ecd8a
--- /dev/null
+++ b/tests/unit/api/test_connectors_connector_access.py
@@ -0,0 +1,191 @@
+"""Connector handlers must enforce workspace connector policy."""
+
+import json
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+import pytest_asyncio # noqa: E402
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine # noqa: E402
+from sqlmodel import SQLModel # noqa: E402
+
+import db.models # noqa: E402,F401
+from api.connectors import ( # noqa: E402
+ browse_connection_files,
+ connector_disconnect,
+ connector_sync_preview,
+ connector_token,
+ connector_webhook,
+)
+from db.repositories import WorkspaceConfigRepo # noqa: E402
+from session_manager import User # noqa: E402
+
+
+@pytest_asyncio.fixture
+async def session():
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ )
+ async with engine.begin() as conn:
+ await conn.run_sync(SQLModel.metadata.create_all)
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ yield session
+ await engine.dispose()
+
+
+class _FakeRequest:
+ def __init__(self) -> None:
+ self.headers: dict[str, str] = {}
+ self.query_params: dict[str, str] = {}
+
+
+class _FakeWebhookRequest:
+ def __init__(self) -> None:
+ self.method = "POST"
+ self.headers: dict[str, str] = {}
+ self.query_params = {"validationToken": "graph-validation-token"}
+
+
+def user():
+ return User(user_id="user-1", email="[email protected]", name="User", jwt_token="jwt")
+
+
+async def test_connector_disconnect_blocks_disabled_type(session, user, monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+
+ await WorkspaceConfigRepo(session).upsert(
+ "connector_access",
+ {"google_drive": False},
+ )
+ await session.commit()
+
+ connector_service = AsyncMock()
+ response = await connector_disconnect(
+ "google_drive",
+ _FakeRequest(),
+ connector_service=connector_service,
+ user=user,
+ session=session,
+ )
+
+ assert response.status_code == 403
+ assert "google_drive" in json.loads(response.body)["error"]
+ connector_service.connection_manager.list_connections.assert_not_called()
+
+
+async def test_connector_token_blocks_disabled_type(session, user, monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+
+ await WorkspaceConfigRepo(session).upsert(
+ "connector_access",
+ {"google_drive": False},
+ )
+ await session.commit()
+
+ connector_service = AsyncMock()
+ response = await connector_token(
+ "google_drive",
+ "conn-1",
+ _FakeRequest(),
+ connector_service=connector_service,
+ user=user,
+ session=session,
+ )
+
+ assert response.status_code == 403
+ connector_service.connection_manager.get_connection.assert_not_called()
+
+
+async def test_connector_sync_preview_blocks_disabled_type(session, user, monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+
+ await WorkspaceConfigRepo(session).upsert(
+ "connector_access",
+ {"sharepoint": False},
+ )
+ await session.commit()
+
+ response = await connector_sync_preview(
+ "sharepoint",
+ _FakeRequest(),
+ connector_service=AsyncMock(),
+ session_manager=AsyncMock(),
+ user=user,
+ session=session,
+ )
+
+ assert response.status_code == 403
+ assert "sharepoint" in json.loads(response.body)["error"]
+
+
+async def test_browse_connection_files_blocks_disabled_type(session, user, monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+
+ await WorkspaceConfigRepo(session).upsert(
+ "connector_access",
+ {"aws_s3": False},
+ )
+ await session.commit()
+
+ connector_service = AsyncMock()
+ response = await browse_connection_files(
+ "aws_s3",
+ "conn-1",
+ _FakeRequest(),
+ connector_service=connector_service,
+ session_manager=AsyncMock(),
+ user=user,
+ session=session,
+ )
+
+ assert response.status_code == 403
+ connector_service.get_connector.assert_not_called()
+
+
+async def test_connector_webhook_blocks_disabled_type_before_validation(session, monkeypatch):
+ """Policy must run before validation handshakes for disabled connector types."""
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+
+ await WorkspaceConfigRepo(session).upsert(
+ "connector_access",
+ {"sharepoint": False},
+ )
+ await session.commit()
+
+ mock_connector = MagicMock()
+ mock_connector.handle_webhook_validation.return_value = "graph-validation-token"
+ connector_service = AsyncMock()
+ connector_service.connection_manager._create_connector.return_value = mock_connector
+
+ response = await connector_webhook(
+ "sharepoint",
+ _FakeWebhookRequest(),
+ connector_service=connector_service,
+ session_manager=AsyncMock(),
+ session=session,
+ )
+
+ assert response.status_code == 403
+ assert "sharepoint" in json.loads(response.body)["error"]
+ mock_connector.handle_webhook_validation.assert_not_called()
+ connector_service.connection_manager._create_connector.assert_not_called()
diff --git a/tests/unit/db/migrations/test_rbac_catalog_sync.py b/tests/unit/db/migrations/test_rbac_catalog_sync.py
new file mode 100644
index 000000000..2de0748ef
--- /dev/null
+++ b/tests/unit/db/migrations/test_rbac_catalog_sync.py
@@ -0,0 +1,109 @@
+"""migrations_runtime.run — RBAC catalog sync on startup."""
+
+import sys
+from pathlib import Path
+
+import pytest
+import pytest_asyncio
+from sqlalchemy import delete, select
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlmodel import SQLModel
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+import db.models # noqa: E402,F401
+from db.migrations_runtime import ( # noqa: E402
+ CHAT_HISTORY_JSON_TO_DB_V1,
+ CONFIG_YAML_TO_DB_V1,
+ JSON_TO_DB_V1,
+ _already_done,
+ _mark_done,
+ run,
+)
+from db.models import Permission, Role, RolePermission # noqa: E402
+from db.seed import ( # noqa: E402
+ permission_name,
+ seed_roles_and_permissions,
+)
+
+_MANAGE_ACCESS = permission_name("connectors", "manage:access")
+
+
+@pytest_asyncio.fixture
+async def session():
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ )
+ async with engine.begin() as conn:
+ await conn.run_sync(SQLModel.metadata.create_all)
+ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
+ async with SessionLocal() as s:
+ yield s
+ await engine.dispose()
+
+
+async def _skip_legacy_runtime_migrations(session) -> None:
+ for name in (JSON_TO_DB_V1, CONFIG_YAML_TO_DB_V1, CHAT_HISTORY_JSON_TO_DB_V1):
+ if not await _already_done(session, name):
+ await _mark_done(session, name)
+
+
+async def _remove_manage_access(session) -> None:
+ perm = (
+ await session.execute(select(Permission).where(Permission.name == _MANAGE_ACCESS))
+ ).scalar_one()
+ await session.execute(delete(RolePermission).where(RolePermission.permission_id == perm.id))
+ await session.execute(delete(Permission).where(Permission.id == perm.id))
+ await session.flush()
+
+
+async def test_run_backfills_missing_manage_access_permission(session):
+ await seed_roles_and_permissions(session)
+ await _remove_manage_access(session)
+ await session.commit()
+
+ assert (
+ await session.execute(select(Permission).where(Permission.name == _MANAGE_ACCESS))
+ ).scalar_one_or_none() is None
+
+ await _skip_legacy_runtime_migrations(session)
+ await run(session)
+ await session.commit()
+
+ perm = (
+ await session.execute(select(Permission).where(Permission.name == _MANAGE_ACCESS))
+ ).scalar_one()
+ admin = (await session.execute(select(Role).where(Role.name == "admin"))).scalar_one()
+ grant = (
+ await session.execute(
+ select(RolePermission).where(
+ RolePermission.role_id == admin.id,
+ RolePermission.permission_id == perm.id,
+ )
+ )
+ ).scalar_one_or_none()
+ assert grant is not None
+
+
+async def test_run_rbac_catalog_sync_is_idempotent(session):
+ await seed_roles_and_permissions(session)
+ await _remove_manage_access(session)
+ await session.commit()
+
+ perm_count = len((await session.execute(select(Permission))).scalars().all())
+ rp_count = len((await session.execute(select(RolePermission))).scalars().all())
+
+ await _skip_legacy_runtime_migrations(session)
+ await run(session)
+ await session.commit()
+ await run(session)
+ await session.commit()
+
+ assert len((await session.execute(select(Permission))).scalars().all()) == perm_count + 1
+ assert len((await session.execute(select(RolePermission))).scalars().all()) == rp_count + 1
diff --git a/tests/unit/services/test_connector_access_service.py b/tests/unit/services/test_connector_access_service.py
new file mode 100644
index 000000000..89d6e438a
--- /dev/null
+++ b/tests/unit/services/test_connector_access_service.py
@@ -0,0 +1,174 @@
+"""Connector access policy helpers."""
+
+import sys
+from pathlib import Path
+
+import pytest
+import pytest_asyncio
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlmodel import SQLModel
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+import db.models # noqa: E402,F401
+from db.repositories import WorkspaceConfigRepo # noqa: E402
+from services.connector_access_service import ( # noqa: E402
+ CONNECTOR_TYPES,
+ filter_connectors_for_user,
+ get_access_map,
+ governable_connector_types,
+ is_connector_access_policy_enforced,
+ is_connector_allowed,
+ list_access_for_admin,
+ set_connector_access_bulk,
+)
+
+
+@pytest_asyncio.fixture
+async def session():
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ )
+ async with engine.begin() as conn:
+ await conn.run_sync(SQLModel.metadata.create_all)
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ yield session
+ await engine.dispose()
+
+
+async def test_filter_connectors_applies_workspace_policy_to_all_roles(session):
+ metadata = {
+ "google_drive": {"name": "Google Drive"},
+ "sharepoint": {"name": "SharePoint"},
+ "onedrive": {"name": "OneDrive"},
+ }
+ access_map = {
+ "google_drive": False,
+ "sharepoint": True,
+ "onedrive": False,
+ }
+
+ filtered = filter_connectors_for_user(metadata, access_map)
+
+ assert set(filtered.keys()) == {"sharepoint"}
+
+
+async def test_filter_connectors_admin_subject_to_same_policy(session):
+ metadata = {
+ "google_drive": {"name": "Google Drive"},
+ "sharepoint": {"name": "SharePoint"},
+ }
+ access_map = {"google_drive": False, "sharepoint": True}
+
+ filtered = filter_connectors_for_user(metadata, access_map)
+
+ assert set(filtered.keys()) == {"sharepoint"}
+
+
+async def test_is_connector_allowed_reads_workspace_config(session):
+ await WorkspaceConfigRepo(session).upsert(
+ "connector_access",
+ {"google_drive": False, "sharepoint": True},
+ )
+ await session.commit()
+
+ access = await get_access_map(session)
+ assert access["google_drive"] is False
+ assert await is_connector_allowed(session, "sharepoint") is True
+ assert await is_connector_allowed(session, "google_drive") is False
+
+
+async def test_connector_types_derived_from_registry(session):
+ from connectors.registry import get_connector_classes
+
+ registry_types = tuple(cls.CONNECTOR_TYPE for cls in get_connector_classes())
+ assert CONNECTOR_TYPES == registry_types
+ assert "google_drive" in CONNECTOR_TYPES
+
+
+async def test_set_connector_access_bulk_persists(session):
+ await set_connector_access_bulk(session, {"google_drive": False}, actor_user_id="u1")
+ await session.commit()
+
+ assert await is_connector_allowed(session, "google_drive") is False
+ # Untouched types stay enabled by default.
+ assert await is_connector_allowed(session, "sharepoint") is True
+
+
+async def test_set_connector_access_bulk_rejects_unknown_type(session):
+ with pytest.raises(ValueError, match="Unknown connector type"):
+ await set_connector_access_bulk(session, {"not_a_connector": True}, actor_user_id="u1")
+
+
+def test_connector_access_policy_enforced_in_saas_run_mode(monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+ assert is_connector_access_policy_enforced() is True
+
+
+def test_connector_access_policy_enforced_with_ibm_auth(monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "oss")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", True)
+ assert is_connector_access_policy_enforced() is True
+
+
+def test_connector_access_policy_not_enforced_in_oss_run_mode(monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "oss")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+ monkeypatch.delenv("OPENRAG_DEV_CONNECTOR_POLICY", raising=False)
+ assert is_connector_access_policy_enforced() is False
+
+
+def test_connector_access_policy_enforced_with_dev_connector_policy(monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "oss")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+ monkeypatch.setenv("OPENRAG_DEV_CONNECTOR_POLICY", "true")
+ assert is_connector_access_policy_enforced() is True
+
+
+def test_governable_connector_types_excludes_buckets_in_saas(monkeypatch):
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+
+ governable = governable_connector_types()
+
+ assert "google_drive" in governable
+ assert "sharepoint" in governable
+ assert "aws_s3" not in governable
+ assert "ibm_cos" not in governable
+
+
+async def test_list_access_for_admin_includes_disabled_types(session, monkeypatch):
+ """Admin permission list is independent of the filtered connectors tab."""
+ monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
+ monkeypatch.setattr("config.settings.IBM_AUTH_ENABLED", False)
+
+ await set_connector_access_bulk(
+ session,
+ {"google_drive": False, "sharepoint": False},
+ actor_user_id="admin",
+ )
+ await session.commit()
+
+ metadata = {
+ "google_drive": {"name": "Google Drive"},
+ "sharepoint": {"name": "SharePoint"},
+ }
+ items = await list_access_for_admin(session, metadata)
+ by_type = {item["type"]: item for item in items}
+
+ assert by_type["google_drive"]["enabled"] is False
+ assert by_type["sharepoint"]["enabled"] is False
+ assert by_type["google_drive"]["name"] == "Google Drive"
diff --git a/tests/unit/services/test_dev_role_toggle.py b/tests/unit/services/test_dev_role_toggle.py
new file mode 100644
index 000000000..922f19af5
--- /dev/null
+++ b/tests/unit/services/test_dev_role_toggle.py
@@ -0,0 +1,71 @@
+"""dev_role_toggle — generic built-in role switching (testing-only feature)."""
+
+import sys
+from pathlib import Path
+
+import pytest
+import pytest_asyncio
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlmodel import SQLModel
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+import db.models # noqa: E402,F401
+from db.repositories import RoleRepo # noqa: E402
+from db.seed import BUILTIN_ROLES, seed_roles_and_permissions # noqa: E402
+from services.dev_role_toggle import _DEV_ROLES, set_dev_role # noqa: E402
+from services.user_service import ensure_user_row # noqa: E402
+from session_manager import User # noqa: E402
+
+_TEST_USER = User(user_id="dev-sub", email="[email protected]", name="D", provider="google")
+
+
+@pytest_asyncio.fixture
+async def setup():
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ )
+ async with engine.begin() as conn:
+ await conn.run_sync(SQLModel.metadata.create_all)
+ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
+
+ async with SessionLocal() as s:
+ await seed_roles_and_permissions(s)
+ db_user = await ensure_user_row(s, _TEST_USER)
+ role_repo = RoleRepo(s)
+ user_role = await role_repo.get_by_name("user")
+ await role_repo.assign_role(db_user.id, user_role.id)
+ await s.commit()
+
+ yield SessionLocal
+ await engine.dispose()
+
+
+def test_dev_roles_covers_every_builtin_role():
+ assert _DEV_ROLES == frozenset(name for _id, name, _desc in BUILTIN_ROLES)
+ assert {"admin", "developer", "user", "viewer"} <= _DEV_ROLES
+
+
[email protected]("target", ["admin", "developer", "viewer"])
+async def test_switch_to_any_builtin_role(setup, target):
+ SessionLocal = setup
+
+ async with SessionLocal() as s:
+ roles = await set_dev_role(s, _TEST_USER, target)
+ await s.commit()
+
+ assert roles == [target]
+
+
+async def test_invalid_role_rejected(setup):
+ SessionLocal = setup
+
+ async with SessionLocal() as s:
+ with pytest.raises(ValueError, match="Unsupported dev role"):
+ await set_dev_role(s, _TEST_USER, "superuser")
diff --git a/tests/unit/services/test_rbac_service.py b/tests/unit/services/test_rbac_service.py
index 65d9fda9a..13c3b7791 100644
--- a/tests/unit/services/test_rbac_service.py
+++ b/tests/unit/services/test_rbac_service.py
@@ -22,7 +22,8 @@ from session_manager import User # noqa: E402
@pytest_asyncio.fixture
-async def setup():
+async def setup(monkeypatch):
+ monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "user")
engine = create_async_engine(
"sqlite+aiosqlite:///:memory:",
connect_args={"check_same_thread": False},
@@ -59,6 +60,28 @@ async def test_admin_has_all_perms(setup):
assert "config:write" in perms
assert "users:list" in perms
assert "agent:prompt:global" in perms
+ assert "connectors:manage:access" in perms
+
+
+async def test_connectors_manage_access_is_admin_only(setup):
+ SessionLocal, _, user_id = setup
+ rbac = RBACService(SessionLocal)
+
+ # Default "user" role lacks it.
+ user_perms = await rbac.get_user_permissions(user_id)
+ assert "connectors:manage:access" not in user_perms
+
+ # developer and viewer lack it too (checked via role override).
+ async with SessionLocal() as s:
+ role_repo = RoleRepo(s)
+ developer_role = await role_repo.get_by_name("developer")
+ viewer_role = await role_repo.get_by_name("viewer")
+
+ dev_perms = await rbac.get_user_permissions(user_id, role_override=[developer_role.id])
+ viewer_perms = await rbac.get_user_permissions(user_id, role_override=[viewer_role.id])
+ assert "connectors:manage:access" not in dev_perms
+ assert "connectors:manage:access" not in viewer_perms
@pytest.mark.asyncio