OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
feat: Add JWT role sync and RBAC UI feature flag (#1631)
Edwin Josea54bb62e6ef6
diff --git a/frontend/app/api/mutations/useAssignRoleMutation.ts b/frontend/app/api/mutations/useAssignRoleMutation.tsdeleted file mode 100644index ee26a4b13..000000000--- a/frontend/app/api/mutations/useAssignRoleMutation.ts+++ /dev/null@@ -1,28 +0,0 @@-import { useMutation, useQueryClient } from "@tanstack/react-query";--interface AssignRoleVariables {- user_id: string;- role_id: string;-}--export const useAssignRoleMutation = () => {- const queryClient = useQueryClient();-- return useMutation({- mutationFn: async ({ user_id, role_id }: AssignRoleVariables) => {- const response = await fetch(`/api/admin/users/${user_id}/roles`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ role_id }),- });- if (!response.ok) {- const err = await response.json().catch(() => ({}));- throw new Error(err?.detail?.error || "Failed to assign role");- }- return await response.json();- },- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ["admin-users"] });- },- });-};diff --git a/frontend/app/api/mutations/useRevokeRoleMutation.ts b/frontend/app/api/mutations/useRevokeRoleMutation.tsdeleted file mode 100644index 88a61c432..000000000--- a/frontend/app/api/mutations/useRevokeRoleMutation.ts+++ /dev/null@@ -1,27 +0,0 @@-import { useMutation, useQueryClient } from "@tanstack/react-query";--interface RevokeRoleVariables {- user_id: string;- role_id: string;-}--export const useRevokeRoleMutation = () => {- const queryClient = useQueryClient();-- return useMutation({- mutationFn: async ({ user_id, role_id }: RevokeRoleVariables) => {- const response = await fetch(- `/api/admin/users/${user_id}/roles/${role_id}`,- { method: "DELETE" },- );- if (!response.ok) {- const err = await response.json().catch(() => ({}));- throw new Error(err?.detail?.error || "Failed to revoke role");- }- return await response.json();- },- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ["admin-users"] });- },- });-};diff --git a/frontend/app/api/queries/useGetAdminPermissionsQuery.ts b/frontend/app/api/queries/useGetAdminPermissionsQuery.tsdeleted file mode 100644index bc121dc74..000000000--- a/frontend/app/api/queries/useGetAdminPermissionsQuery.ts+++ /dev/null@@ -1,26 +0,0 @@-import { type UseQueryOptions, useQuery } from "@tanstack/react-query";--export interface AdminPermission {- id: string;- name: string;- resource: string;- action: string;- description: string | null;-}--export const useGetAdminPermissionsQuery = (- options?: Omit<UseQueryOptions<AdminPermission[]>, "queryKey" | "queryFn">,-) => {- async function fetchPermissions(): Promise<AdminPermission[]> {- const response = await fetch("/api/admin/permissions");- if (response.ok) return await response.json();- if (response.status === 403) return [];- throw new Error(`Failed to fetch permissions (${response.status})`);- }-- return useQuery({- queryKey: ["admin-permissions"],- queryFn: fetchPermissions,- ...options,- });-};diff --git a/frontend/app/api/queries/useGetAdminRolesQuery.ts b/frontend/app/api/queries/useGetAdminRolesQuery.tsdeleted file mode 100644index 15516f28b..000000000--- a/frontend/app/api/queries/useGetAdminRolesQuery.ts+++ /dev/null@@ -1,26 +0,0 @@-import { type UseQueryOptions, useQuery } from "@tanstack/react-query";--export interface AdminRole {- id: string;- name: string;- description: string | null;- is_system: boolean;- permissions: string[];-}--export const useGetAdminRolesQuery = (- options?: Omit<UseQueryOptions<AdminRole[]>, "queryKey" | "queryFn">,-) => {- async function fetchRoles(): Promise<AdminRole[]> {- const response = await fetch("/api/admin/roles");- if (response.ok) return await response.json();- if (response.status === 403) return [];- throw new Error(`Failed to fetch roles (${response.status})`);- }-- return useQuery({- queryKey: ["admin-roles"],- queryFn: fetchRoles,- ...options,- });-};diff --git a/frontend/app/api/queries/useGetAdminUsersQuery.ts b/frontend/app/api/queries/useGetAdminUsersQuery.tsdeleted file mode 100644index 8622fa96d..000000000--- a/frontend/app/api/queries/useGetAdminUsersQuery.ts+++ /dev/null@@ -1,31 +0,0 @@-import { type UseQueryOptions, useQuery } from "@tanstack/react-query";--export interface AdminUser {- id: string;- oauth_provider: string;- oauth_subject: string;- email: string | null;- display_name: string | null;- picture_url: string | null;- is_active: boolean;- roles: string[];- created_at: string | null;- last_login: string | null;-}--export const useGetAdminUsersQuery = (- options?: Omit<UseQueryOptions<AdminUser[]>, "queryKey" | "queryFn">,-) => {- async function fetchUsers(): Promise<AdminUser[]> {- const response = await fetch("/api/admin/users");- if (response.ok) return await response.json();- if (response.status === 403) return [];- throw new Error(`Failed to fetch users (${response.status})`);- }-- return useQuery({- queryKey: ["admin-users"],- queryFn: fetchUsers,- ...options,- });-};diff --git a/frontend/app/api/queries/useGetAuditEventsQuery.ts b/frontend/app/api/queries/useGetAuditEventsQuery.tsdeleted file mode 100644index 8718b3a32..000000000--- a/frontend/app/api/queries/useGetAuditEventsQuery.ts+++ /dev/null@@ -1,40 +0,0 @@-import { type UseQueryOptions, useQuery } from "@tanstack/react-query";--export interface AuditEvent {- id: string;- ts: string;- actor_user_id: string | null;- event: string;- target_type: string | null;- target_id: string | null;- audit_metadata: Record<string, unknown> | null;-}--interface AuditQueryParams {- limit?: number;- offset?: number;-}--export const useGetAuditEventsQuery = (- params: AuditQueryParams = {},- options?: Omit<UseQueryOptions<AuditEvent[]>, "queryKey" | "queryFn">,-) => {- const { limit = 20, offset = 0 } = params;-- async function fetchAudit(): Promise<AuditEvent[]> {- const qs = new URLSearchParams({- limit: String(limit),- offset: String(offset),- });- const response = await fetch(`/api/admin/audit?${qs.toString()}`);- if (response.ok) return await response.json();- if (response.status === 403) return [];- throw new Error(`Failed to fetch audit log (${response.status})`);- }-- return useQuery({- queryKey: ["admin-audit", limit, offset],- queryFn: fetchAudit,- ...options,- });-};diff --git a/frontend/app/settings/[tab]/page.tsx b/frontend/app/settings/[tab]/page.tsxindex 11177f8a2..eebf471ad 100644--- a/frontend/app/settings/[tab]/page.tsx+++ b/frontend/app/settings/[tab]/page.tsx@@ -7,15 +7,8 @@ import { ApiKeysSection } from "../_components/api-keys-section";import { ConnectorsTab } from "../_components/connectors-tab";import { IngestSettingsSection } from "../_components/ingest-settings-section";import ModelProviders from "../_components/model-providers";-import { UsersAndRolesSection } from "../_components/users-and-roles-section";-const VALID_TABS = [- "connectors",- "providers",- "langflow",- "api-keys",- "roles",-] as const;+const VALID_TABS = ["connectors", "providers", "langflow", "api-keys"] as const;type Tab = (typeof VALID_TABS)[number];@@ -38,8 +31,6 @@ async function getTabAuthContext() {isNoAuthMode: Boolean(authData.no_auth_mode),isIbmAuthMode: Boolean(authData.ibm_auth_mode),isAuthenticated: Boolean(authData.authenticated),- rbacEnforced:- typeof meData.rbac_enforced === "boolean" ? meData.rbac_enforced : true,permissions: new Set<string>(Array.isArray(meData.permissions) ? meData.permissions : [],),@@ -57,21 +48,10 @@ export default async function SettingsTabPage({redirect("/settings/connectors");}- const {- isNoAuthMode,- isIbmAuthMode,- isAuthenticated,- rbacEnforced,- permissions,- } = await getTabAuthContext();+ const { isNoAuthMode, isIbmAuthMode, isAuthenticated, permissions } =+ await getTabAuthContext();// Mirror the visibility logic from settings-nav.tsx- if (- tab === "roles" &&- (!rbacEnforced || (!isNoAuthMode && !permissions.has("users:list")))- ) {- redirect("/settings/connectors");- }if (tab === "api-keys" &&(isIbmAuthMode || (!isAuthenticated && !isNoAuthMode))@@ -126,7 +106,6 @@ export default async function SettingsTabPage({</div>)}{tab === "api-keys" && <ApiKeysSection />}- {tab === "roles" && <UsersAndRolesSection />}</HydrationBoundary>);}diff --git a/frontend/app/settings/_components/audit-log-feed.tsx b/frontend/app/settings/_components/audit-log-feed.tsxdeleted file mode 100644index 1e0b01f1a..000000000--- a/frontend/app/settings/_components/audit-log-feed.tsx+++ /dev/null@@ -1,225 +0,0 @@-"use client";--import { Activity, Loader2, RefreshCw } from "lucide-react";-import { useMemo } from "react";--import { useGetAdminUsersQuery } from "@/app/api/queries/useGetAdminUsersQuery";-import {- type AuditEvent,- useGetAuditEventsQuery,-} from "@/app/api/queries/useGetAuditEventsQuery";-import { Button } from "@/components/ui/button";-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@/components/ui/card";-import { useIsCloudBrand } from "@/contexts/brand-context";-import { cn } from "@/lib/utils";--/** Colored dot + label for an event. No pill chrome — pills are reserved for roles. */-const EVENT_PRESENTATION: Record<string, { label: string; dot: string }> = {- // Greens — additive, healthy- "user.bootstrap_admin": {- label: "Bootstrap admin",- dot: "bg-emerald-500",- },- "user.created": { label: "User created", dot: "bg-emerald-500" },- "user.role.assigned": { label: "Role assigned", dot: "bg-emerald-500" },- "role.created": { label: "Role created", dot: "bg-emerald-500" },-- // Blues — informational, neutral mutations- "user.updated": { label: "User updated", dot: "bg-blue-500" },- "role.updated": { label: "Role updated", dot: "bg-blue-500" },- "user.merged_legacy": { label: "Merged legacy", dot: "bg-blue-500" },-- // Reds — destructive- "user.deleted": { label: "User deleted", dot: "bg-red-500" },- "user.role.revoked": { label: "Role revoked", dot: "bg-red-500" },- "role.deleted": { label: "Role deleted", dot: "bg-red-500" },-- // Amber — warnings / denials- "permission.denied": { label: "Permission denied", dot: "bg-amber-500" },-};--function formatHumanRelative(iso: string): string {- const ts = new Date(iso).getTime();- const diffMs = Date.now() - ts;- const sec = Math.round(diffMs / 1000);- if (sec < 5) return "just now";- if (sec < 60) return `${sec} seconds ago`;- const min = Math.round(sec / 60);- if (min === 1) return "a minute ago";- if (min < 60) return `${min} minutes ago`;- const hr = Math.round(min / 60);- if (hr === 1) return "an hour ago";- if (hr < 24) return `${hr} hours ago`;- const day = Math.round(hr / 24);- if (day === 1) return "yesterday";- if (day < 7) return `${day} days ago`;- return new Date(iso).toLocaleDateString(undefined, {- year: "numeric",- month: "short",- day: "numeric",- });-}--function summarizeMetadata(e: AuditEvent): string | null {- const m = e.audit_metadata;- if (!m) return null;- if (typeof m.role_name === "string") return m.role_name;- if (typeof m.role === "string") return m.role;- if (typeof m.required === "string") return m.required;- if (typeof m.name === "string") return m.name;- return null;-}--export function AuditLogFeed() {- const isCloudBrand = useIsCloudBrand();- const auditQuery = useGetAuditEventsQuery({ limit: 20 });- const usersQuery = useGetAdminUsersQuery();-- const events = auditQuery.data ?? [];- const users = usersQuery.data ?? [];-- // Build a map: db_user_id -> display label (name or email).- const userLabel = useMemo(() => {- const map = new Map<string, string>();- for (const u of users) {- const label = u.display_name || u.email || u.oauth_subject;- map.set(u.id, label);- // Also key by oauth_subject so legacy events whose actor_user_id is- // the OAuth sub still resolve.- if (u.oauth_subject) map.set(u.oauth_subject, label);- }- return map;- }, [users]);-- const labelFor = (id: string | null): string => {- if (!id) return "—";- return userLabel.get(id) ?? `${id.slice(0, 8)}…`;- };-- return (- <Card>- <CardHeader>- <div className="flex items-center justify-between mb-3">- <CardTitle- className={cn(- "text-lg flex items-center gap-2",- isCloudBrand && "ibm-settings-section-title",- )}- >- <Activity className="h-5 w-5" /> Recent Activity- </CardTitle>- <Button- variant="outline"- size="sm"- onClick={() => auditQuery.refetch()}- disabled={auditQuery.isFetching}- >- <RefreshCw- className={cn(- "h-4 w-4 mr-2",- auditQuery.isFetching && "animate-spin",- )}- />- Refresh- </Button>- </div>- <CardDescription>- Last 20 RBAC events. Backend writes one row per role assignment,- revocation, or permission denial.- </CardDescription>- </CardHeader>- <CardContent>- {auditQuery.isLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />- </div>- ) : auditQuery.isError ? (- <div className="text-sm text-destructive py-4">- Failed to load audit log: {(auditQuery.error as Error).message}- </div>- ) : events.length === 0 ? (- <div className="text-center py-8">- <Activity className="h-12 w-12 mx-auto text-muted-foreground/50 mb-4" />- <p className="text-muted-foreground text-sm">- No events yet, or you do not have{" "}- <code className="text-xs bg-muted px-1 py-0.5 rounded">- audit:read- </code>- .- </p>- </div>- ) : (- <div className="border rounded-lg overflow-hidden">- <table className="w-full">- <thead className="bg-muted/50">- <tr>- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3 w-[200px]">- Event- </th>- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">- Actor- </th>- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">- Target- </th>- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">- Detail- </th>- <th className="text-right text-sm font-medium text-muted-foreground px-4 py-3 w-[140px]">- When- </th>- </tr>- </thead>- <tbody>- {events.map((e) => {- const meta = EVENT_PRESENTATION[e.event] ?? {- label: e.event,- dot: "bg-muted-foreground",- };- const summary = summarizeMetadata(e);- return (- <tr key={e.id} className="border-t">- <td className="px-4 py-3">- <span className="inline-flex items-center gap-2 text-sm">- <span- className={cn(- "h-1.5 w-1.5 rounded-full shrink-0",- meta.dot,- )}- aria-hidden- />- <span>{meta.label}</span>- </span>- </td>- <td className="px-4 py-3 text-sm">- {labelFor(e.actor_user_id)}- </td>- <td className="px-4 py-3 text-sm">- {labelFor(e.target_id)}- </td>- <td className="px-4 py-3 text-sm text-muted-foreground capitalize">- {summary ?? "—"}- </td>- <td- className="px-4 py-3 text-sm text-muted-foreground text-right whitespace-nowrap"- title={new Date(e.ts).toLocaleString()}- >- {formatHumanRelative(e.ts)}- </td>- </tr>- );- })}- </tbody>- </table>- </div>- )}- </CardContent>- </Card>- );-}diff --git a/frontend/app/settings/_components/role-permissions-matrix.tsx b/frontend/app/settings/_components/role-permissions-matrix.tsxdeleted file mode 100644index df3361655..000000000--- a/frontend/app/settings/_components/role-permissions-matrix.tsx+++ /dev/null@@ -1,388 +0,0 @@-"use client";--import { Check, ChevronDown, Minus } from "lucide-react";-import { Fragment, useState } from "react";--import {- type AdminPermission,- useGetAdminPermissionsQuery,-} from "@/app/api/queries/useGetAdminPermissionsQuery";-import {- type AdminRole,- useGetAdminRolesQuery,-} from "@/app/api/queries/useGetAdminRolesQuery";-import { Button } from "@/components/ui/button";-import { getRolePillClass } from "@/lib/role-styles";-import { cn } from "@/lib/utils";--/**- * Friendly description mapping for what each permission *actually* gates- * in the live system. Curated alongside the backend `require_permission`- * sites and the frontend `<RequirePermission>` wrappers, so admins can- * see at a glance which permission unlocks which UI / API surface.- *- * Anything not in this map falls back to the backend's free-form- * `description` column from the permissions table — there's always a- * description, this just adds a "where it bites" hint for the built-ins.- */-const PERMISSION_GATES: Record<string, { ui: string; api: string }> = {- // Config / Infra- "config:read": {- ui: "Settings page reads",- api: "GET /settings",- },- "config:write": {- ui: "Knowledge Ingest, Onboarding, Docling preset",- api: "POST /settings, /onboarding, /onboarding/state, /onboarding/rollback, /settings/docling-preset",- },- "providers:read": {- ui: "Model Providers section (read)",- api: "GET /models, /providers",- },- "providers:write": {- ui: "Model Providers section (edit)",- api: "POST /settings (provider fields)",- },- "providers:override:self": {- ui: "Per-user provider key override (Phase 4)",- api: "PATCH /api/users/me/preferences",- },- "opensearch:admin": {- ui: "(internal)",- api: "OpenSearch security setup at startup",- },-- // Users / RBAC- "users:list": {- ui: "Users & Roles table",- api: "GET /api/admin/users",- },- "users:read": {- ui: "User detail",- api: "GET /api/admin/users/{id}",- },- "users:invite": {- ui: "Activate / deactivate user",- api: "PATCH /api/admin/users/{id}",- },- "users:delete": {- ui: "Delete user (admin)",- api: "DELETE /api/admin/users/{id}",- },- "roles:list": {- ui: "Available Roles + this matrix",- api: "GET /api/admin/roles, /api/admin/permissions",- },- "roles:assign": {- ui: "+ Assign role / × Revoke role",- api: "POST /api/admin/users/{id}/roles, DELETE /api/admin/users/{id}/roles/{role_id}",- },- "roles:create": {- ui: "Create custom role (planned)",- api: "POST /api/admin/roles",- },- "roles:edit": {- ui: "Edit role permissions (planned)",- api: "PATCH /api/admin/roles/{id}",- },- "roles:delete": {- ui: "Delete custom role (planned)",- api: "DELETE /api/admin/roles/{id}",- },- "audit:read": {- ui: "Recent Activity table",- api: "GET /api/admin/audit",- },-- // Connectors- "connectors:list:own": {- ui: "List own connectors",- api: "GET /connectors (filtered to user)",- },- "connectors:list:all": {- ui: "List all users' connectors (admin)",- api: "GET /connectors (no filter)",- },- "connectors:create": {- ui: "Connect / Configure buttons in Settings",- api: "POST /connectors/{type}/sync, OAuth init",- },- "connectors:delete:own": {- ui: "Disconnect button on own connector",- api: "DELETE /connectors/{type}/disconnect",- },- "connectors:delete:any": {- ui: "Disconnect any user's connector (admin)",- api: "DELETE /connectors/{type}/disconnect (any user)",- },- "connectors:use": {- ui: "Sync, browse buckets, OAuth callback",- api: "POST /connectors/{type}/sync, /connectors/sync-all",- },-- // Knowledge- "knowledge:upload": {- ui: "Add Knowledge dropdown, file picker, folder ingest",- api: "POST /upload, /upload_path, /upload_context, /upload_bucket",- },- "knowledge:delete:own": {- ui: "Delete own document (row + bulk)",- api: "POST /documents/delete-by-filename (own)",- },- "knowledge:delete:any": {- ui: "Delete any document (admin)",- api: "POST /documents/delete-by-filename (any)",- },- "knowledge:read:own": {- ui: "Knowledge tab visibility, browse own docs",- api: "GET /search, /knowledge/* (own scope)",- },- "knowledge:read:all": {- ui: "Browse all users' docs (admin)",- api: "GET /search, /knowledge/* (no scope)",- },- "kf:create": {- ui: "Create Filter button",- api: "POST /knowledge-filter",- },- "kf:edit:own": {- ui: "Edit/Delete own KF (Save/Update/Delete buttons)",- api: "PUT/DELETE /knowledge-filter/{id} (own)",- },- "kf:edit:any": {- ui: "Edit/Delete any KF (admin)",- api: "PUT/DELETE /knowledge-filter/{id} (any)",- },- "kf:share": {- ui: "Share KF (planned)",- api: "(planned)",- },-- // Chat / search- "chat:use": {- ui: "Chat tab + send message + New Conversation",- api: "POST /chat, /langflow",- },- "search:use": {- ui: "Search bar",- api: "POST /search",- },- "conversations:read:own": {- ui: "Own chat history",- api: "GET /chat/history, /langflow/history",- },- "conversations:read:all": {- ui: "All users' history (admin)",- api: "(planned)",- },- "conversations:delete:own": {- ui: "Delete conversation menu item",- api: "DELETE /sessions/{id} (own)",- },- "conversations:delete:any": {- ui: "Delete any conversation (admin)",- api: "DELETE /sessions/{id} (any)",- },-- // Flows / agent- "flows:read": {- ui: "View Langflow",- api: "GET /flows/*",- },- "flows:edit": {- ui: "Edit in Langflow + Restore flow buttons",- api: "POST /reset-flow/{type}",- },- "agent:prompt:override": {- ui: "Per-user agent prompt (Phase 4)",- api: "PATCH /api/users/me/preferences",- },- "agent:prompt:global": {- ui: "Workspace agent system prompt textarea",- api: "POST /settings (agent.system_prompt)",- },-- // API keys- "apikeys:create:self": {- ui: "Create Key button",- api: "POST /keys",- },- "apikeys:revoke:self": {- ui: "Revoke own key (trash icon)",- api: "DELETE /keys/{id}, /keys/{id}/permanent",- },- "apikeys:revoke:any": {- ui: "Revoke any user's key (admin)",- api: "(planned)",- },- "apikeys:list:any": {- ui: "List all users' keys (admin)",- api: "(planned)",- },-};--interface MatrixRowProps {- perm: AdminPermission;- roles: AdminRole[];-}--function MatrixRow({ perm, roles }: MatrixRowProps) {- const gate = PERMISSION_GATES[perm.name];- return (- <tr className="border-t hover:bg-muted/30">- <td className="px-4 py-2.5 align-top">- <div className="flex flex-col gap-0.5">- <code className="text-xs font-mono text-foreground">{perm.name}</code>- {perm.description && (- <span className="text-xs text-muted-foreground">- {perm.description}- </span>- )}- {gate && (- <div className="flex flex-col gap-0.5 mt-1">- <span className="text-[10px] uppercase tracking-wide text-muted-foreground">- UI:{" "}- <span className="normal-case text-muted-foreground/80">- {gate.ui}- </span>- </span>- <span className="text-[10px] uppercase tracking-wide text-muted-foreground">- API:{" "}- <code className="normal-case text-muted-foreground/80 font-mono">- {gate.api}- </code>- </span>- </div>- )}- </div>- </td>- {roles.map((r) => {- const has = r.permissions.includes(perm.name);- return (- <td key={r.id} className="px-3 py-2.5 text-center align-top">- {has ? (- <Check- className="h-4 w-4 mx-auto text-emerald-600 dark:text-emerald-400"- aria-label={`${r.name} has ${perm.name}`}- />- ) : (- <Minus- className="h-4 w-4 mx-auto text-muted-foreground/30"- aria-label={`${r.name} does not have ${perm.name}`}- />- )}- </td>- );- })}- </tr>- );-}--export function RolePermissionsMatrix() {- const [open, setOpen] = useState(false);- const rolesQuery = useGetAdminRolesQuery();- const permsQuery = useGetAdminPermissionsQuery({- enabled: open, // lazy fetch — only when the matrix is expanded- });-- const roles = rolesQuery.data ?? [];- const perms = permsQuery.data ?? [];-- // Group permissions by resource for readable section headers.- const groupedPerms = perms.reduce<Record<string, AdminPermission[]>>(- (acc, p) => {- if (!acc[p.resource]) acc[p.resource] = [];- acc[p.resource].push(p);- return acc;- },- {},- );- const sortedGroups = Object.entries(groupedPerms).sort(([a], [b]) =>- a.localeCompare(b),- );-- return (- <div className="border rounded-lg overflow-hidden">- <Button- type="button"- variant="ghost"- onClick={() => setOpen((v) => !v)}- className="w-full justify-between h-auto px-4 py-3 rounded-none hover:bg-muted/30"- >- <span className="flex items-center gap-2 text-sm font-medium">- Role × Permission matrix- <span className="text-xs text-muted-foreground">- ({perms.length || roles.length} permissions- {roles.length > 0 ? ` × ${roles.length} roles` : ""})- </span>- </span>- <ChevronDown- className={cn(- "h-4 w-4 text-muted-foreground transition-transform",- open && "rotate-180",- )}- />- </Button>-- {open && (- <div className="border-t">- {permsQuery.isLoading ? (- <div className="px-4 py-6 text-center text-sm text-muted-foreground">- Loading…- </div>- ) : permsQuery.isError ? (- <div className="px-4 py-6 text-sm text-destructive">- Failed to load permission catalog:{" "}- {(permsQuery.error as Error).message}- </div>- ) : perms.length === 0 ? (- <div className="px-4 py-6 text-center text-sm text-muted-foreground italic">- No permissions returned (need <code>roles:list</code>).- </div>- ) : (- <div className="overflow-x-auto">- <table className="w-full">- <thead className="bg-muted/50 sticky top-0">- <tr>- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">- Permission- </th>- {roles.map((r) => (- <th- key={r.id}- className="text-center text-sm font-medium px-3 py-3 min-w-[100px]"- >- <span className={getRolePillClass(r.name)}>- {r.name}- </span>- </th>- ))}- </tr>- </thead>- <tbody>- {sortedGroups.map(([resource, resourcePerms]) => (- <Fragment key={`group-${resource}`}>- <tr className="bg-muted/20">- <td- colSpan={1 + roles.length}- className="px-4 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground font-semibold"- >- {resource}- </td>- </tr>- {resourcePerms- .sort((a, b) => a.action.localeCompare(b.action))- .map((p) => (- <MatrixRow key={p.id} perm={p} roles={roles} />- ))}- </Fragment>- ))}- </tbody>- </table>- </div>- )}- </div>- )}- </div>- );-}diff --git a/frontend/app/settings/_components/settings-nav.tsx b/frontend/app/settings/_components/settings-nav.tsxindex a78383665..0dce0d53a 100644--- a/frontend/app/settings/_components/settings-nav.tsx+++ b/frontend/app/settings/_components/settings-nav.tsx@@ -12,15 +12,13 @@ const TABS = [{ value: "providers", label: "Providers", perm: "providers:write" },{ value: "langflow", label: "Langflow" },{ value: "api-keys", label: "API Keys", apiKeysTab: true },- { value: "roles", label: "Roles & Permissions", rbacPerm: "users:list" },] as const;export function SettingsNav() {const isCloudBrand = useIsCloudBrand();const pathname = usePathname();const router = useRouter();- const { isAuthenticated, isNoAuthMode, isIbmAuthMode, rbacEnforced } =- useAuth();+ const { isAuthenticated, isNoAuthMode, isIbmAuthMode } = useAuth();const { can } = usePermissions();const currentTab = pathname.split("/").pop() ?? "connectors";@@ -29,7 +27,6 @@ export function SettingsNav() {if ("perm" in tab) return can(tab.perm);if ("apiKeysTab" in tab)return (isAuthenticated || isNoAuthMode) && !isIbmAuthMode;- if ("rbacPerm" in tab) return rbacEnforced && can(tab.rbacPerm);return true;});diff --git a/frontend/app/settings/_components/users-and-roles-section.tsx b/frontend/app/settings/_components/users-and-roles-section.tsxdeleted file mode 100644index 6a09a9a39..000000000--- a/frontend/app/settings/_components/users-and-roles-section.tsx+++ /dev/null@@ -1,415 +0,0 @@-"use client";--import { Loader2, RefreshCw, Search, ShieldCheck, X } from "lucide-react";-import { useMemo, useState } from "react";-import { toast } from "sonner";-import { useAssignRoleMutation } from "@/app/api/mutations/useAssignRoleMutation";-import { useRevokeRoleMutation } from "@/app/api/mutations/useRevokeRoleMutation";-import {- type AdminRole,- useGetAdminRolesQuery,-} from "@/app/api/queries/useGetAdminRolesQuery";-import {- type AdminUser,- useGetAdminUsersQuery,-} from "@/app/api/queries/useGetAdminUsersQuery";-import { RolePermissionsPreview } from "@/components/role-permissions-preview";-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";-import { Badge } from "@/components/ui/badge";-import { Button } from "@/components/ui/button";-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@/components/ui/card";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import { useAuth } from "@/contexts/auth-context";-import { useIsCloudBrand } from "@/contexts/brand-context";-import { getRolePillClass } from "@/lib/role-styles";-import { cn } from "@/lib/utils";--import { AuditLogFeed } from "./audit-log-feed";-import { RolePermissionsMatrix } from "./role-permissions-matrix";--interface UserRowProps {- u: AdminUser;- roles: AdminRole[];- onAssign: (userId: string, roleId: string) => void;- onRevoke: (userId: string, roleId: string, roleName: string) => void;- pending: boolean;- selfDbId?: string;-}--function UserRow({- u,- roles,- onAssign,- onRevoke,- pending,- selfDbId,-}: UserRowProps) {- const [selectedRole, setSelectedRole] = useState<string>("");- const isSelf = selfDbId && selfDbId === u.id;- const availableRoles = roles.filter((r) => !u.roles.includes(r.name));-- return (- <tr className="border-t">- <td className="px-4 py-3">- <div className="flex items-center gap-3 min-w-0">- <Avatar className="rounded-md w-8 h-8 shrink-0">- {u.picture_url && (- <AvatarImage src={u.picture_url} alt={u.display_name ?? ""} />- )}- <AvatarFallback className="text-xs rounded-md">- {(u.display_name ?? u.email ?? "?").charAt(0).toUpperCase()}- </AvatarFallback>- </Avatar>- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2">- <p className="text-sm font-medium truncate">- {u.display_name ?? "(unnamed)"}- </p>- {isSelf && (- <Badge variant="outline" className="text-[10px] py-0 px-1.5">- you- </Badge>- )}- </div>- <p className="text-xs text-muted-foreground truncate">- {u.email ?? u.oauth_subject}- </p>- </div>- </div>- </td>- <td className="px-4 py-3">- <div className="flex flex-wrap items-center gap-1.5">- {u.roles.length === 0 ? (- <span className="text-xs text-muted-foreground italic">- no roles- </span>- ) : (- u.roles.map((r) => {- const role = roles.find((rr) => rr.name === r);- return (- <span key={r} className={getRolePillClass(r)}>- {r}- {role && (- <RolePermissionsPreview- name={role.name}- description={role.description}- permissions={role.permissions}- />- )}- {role && (- <button- type="button"- aria-label={`Remove ${r}`}- disabled={pending}- onClick={() => onRevoke(u.id, role.id, role.name)}- className="inline-flex h-5 w-5 items-center justify-center rounded-full hover:bg-foreground/10 transition-colors -mr-1 disabled:opacity-50"- >- <X className="h-3.5 w-3.5" />- </button>- )}- </span>- );- })- )}- </div>- </td>- <td className="px-4 py-3 text-right">- <Select- value={selectedRole}- onValueChange={(v) => {- setSelectedRole("");- const role = roles.find((rr) => rr.id === v);- if (role) onAssign(u.id, role.id);- }}- disabled={pending || availableRoles.length === 0}- >- <SelectTrigger className="h-9 w-[160px] text-sm ml-auto">- <SelectValue placeholder="+ Assign role" />- </SelectTrigger>- <SelectContent>- {availableRoles.map((r) => (- <SelectItem key={r.id} value={r.id} className="text-sm py-2">- <span className="capitalize font-medium">{r.name}</span>- </SelectItem>- ))}- </SelectContent>- </Select>- </td>- </tr>- );-}--export function UsersAndRolesSection() {- const isCloudBrand = useIsCloudBrand();- const { user: currentUser } = useAuth();- const usersQuery = useGetAdminUsersQuery();- const rolesQuery = useGetAdminRolesQuery();- const assignMutation = useAssignRoleMutation();- const revokeMutation = useRevokeRoleMutation();-- const [search, setSearch] = useState("");- const [filterRole, setFilterRole] = useState<string>("__all");-- const [pendingRevoke, setPendingRevoke] = useState<{- user_id: string;- role_id: string;- role_name: string;- } | null>(null);-- const onAssign = (user_id: string, role_id: string) => {- assignMutation.mutate(- { user_id, role_id },- {- onSuccess: () => toast.success("Role assigned"),- onError: (err: Error) => toast.error(err.message),- },- );- };-- const performRevoke = (user_id: string, role_id: string) => {- revokeMutation.mutate(- { user_id, role_id },- {- onSuccess: () => toast.success("Role revoked"),- onError: (err: Error) => toast.error(err.message),- },- );- };-- const onRevoke = (user_id: string, role_id: string, role_name: string) => {- if (role_name === "admin") {- setPendingRevoke({ user_id, role_id, role_name });- return;- }- performRevoke(user_id, role_id);- };-- const isLoading = usersQuery.isLoading || rolesQuery.isLoading;- const isMutating = assignMutation.isPending || revokeMutation.isPending;- const users = usersQuery.data ?? [];- const roles = rolesQuery.data ?? [];-- const filteredUsers = useMemo(() => {- const q = search.trim().toLowerCase();- return users.filter((u) => {- if (filterRole !== "__all" && !u.roles.includes(filterRole)) return false;- if (!q) return true;- const hay =- `${u.email ?? ""} ${u.display_name ?? ""} ${u.oauth_subject}`.toLowerCase();- return hay.includes(q);- });- }, [users, search, filterRole]);-- const selfDbId = useMemo(() => {- if (!currentUser) return undefined;- const match = users.find(- (u) =>- u.oauth_subject === currentUser.user_id || u.id === currentUser.user_id,- );- return match?.id;- }, [users, currentUser]);-- return (- <div className="space-y-6">- <Card>- <CardHeader>- <div className="flex items-center justify-between mb-3">- <CardTitle- className={cn(- "text-lg flex items-center gap-2",- isCloudBrand && "ibm-settings-section-title",- )}- >- <ShieldCheck className="h-5 w-5" /> Users & Roles- </CardTitle>- <Button- variant="outline"- size="sm"- onClick={() => {- usersQuery.refetch();- rolesQuery.refetch();- }}- disabled={usersQuery.isFetching || rolesQuery.isFetching}- >- <RefreshCw- className={cn(- "h-4 w-4 mr-2",- (usersQuery.isFetching || rolesQuery.isFetching) &&- "animate-spin",- )}- />- Refresh- </Button>- </div>- <CardDescription>- Assign or revoke roles for users in your workspace. Backend enforces- all permission checks; this UI mirrors the live state.- </CardDescription>- </CardHeader>- <CardContent className="space-y-4">- {/* Search + filter row — heights match Settings primitives (h-9) */}- <div className="flex items-center gap-2">- <div className="relative flex-1">- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />- <Input- placeholder="Search by name, email, or ID"- value={search}- onChange={(e) => setSearch(e.target.value)}- className="pl-9"- />- </div>- <Select value={filterRole} onValueChange={setFilterRole}>- <SelectTrigger className="w-[180px]">- <SelectValue placeholder="All roles" />- </SelectTrigger>- <SelectContent>- <SelectItem value="__all">All roles</SelectItem>- {roles.map((r) => (- <SelectItem key={r.id} value={r.name}>- <span className="capitalize">{r.name}</span>- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- {/* User table — matches API Keys table styling */}- {isLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />- </div>- ) : usersQuery.isError ? (- <div className="text-sm text-destructive py-4">- Failed to load users: {(usersQuery.error as Error).message}- </div>- ) : filteredUsers.length === 0 ? (- <div className="text-sm text-muted-foreground italic py-8 text-center">- {users.length === 0- ? "No users found, or you do not have permission to list users."- : "No users match your search."}- </div>- ) : (- <div className="border rounded-lg overflow-hidden">- <table className="w-full">- <thead className="bg-muted/50">- <tr>- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">- User- </th>- <th className="text-left text-sm font-medium text-muted-foreground px-4 py-3">- Roles- </th>- <th className="text-right text-sm font-medium text-muted-foreground px-4 py-3 w-[180px]">- Actions- </th>- </tr>- </thead>- <tbody>- {filteredUsers.map((u) => (- <UserRow- key={u.id}- u={u}- roles={roles}- onAssign={onAssign}- onRevoke={onRevoke}- pending={isMutating}- selfDbId={selfDbId}- />- ))}- </tbody>- </table>- </div>- )}-- {/* Available Roles strip + collapsible matrix */}- {roles.length > 0 && (- <div className="pt-2 space-y-3">- <div>- <p className="text-xs uppercase tracking-wide text-muted-foreground mb-2">- Available Roles- </p>- <div className="flex flex-wrap gap-1.5">- {roles.map((r) => (- <span key={r.id} className={getRolePillClass(r.name)}>- {r.name}- <RolePermissionsPreview- name={r.name}- description={r.description}- permissions={r.permissions}- />- </span>- ))}- </div>- </div>- <RolePermissionsMatrix />- </div>- )}- </CardContent>- </Card>-- <AuditLogFeed />-- <Dialog- open={pendingRevoke !== null}- onOpenChange={(open) => !open && setPendingRevoke(null)}- >- <DialogContent>- <DialogHeader>- <DialogTitle className="mb-4">Revoke admin role?</DialogTitle>- <DialogDescription className="text-left">- <span className="block mb-2">- You are about to remove the <strong>admin</strong> role from- this user. They will lose all admin permissions immediately.- </span>- <span className="block text-xs text-muted-foreground">- The backend prevents removing the last admin in the workspace.- </span>- </DialogDescription>- </DialogHeader>- <DialogFooter>- <Button- variant="ghost"- onClick={() => setPendingRevoke(null)}- size="sm"- >- Cancel- </Button>- <Button- variant="destructive"- onClick={() => {- if (pendingRevoke) {- performRevoke(pendingRevoke.user_id, pendingRevoke.role_id);- setPendingRevoke(null);- }- }}- size="sm"- >- Revoke admin- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </div>- );-}diff --git a/frontend/components/role-permissions-preview.tsx b/frontend/components/role-permissions-preview.tsxdeleted file mode 100644index b3517c7d5..000000000--- a/frontend/components/role-permissions-preview.tsx+++ /dev/null@@ -1,103 +0,0 @@-"use client";--import { ChevronDown, Info } from "lucide-react";-import { useState } from "react";--import { Badge } from "@/components/ui/badge";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/components/ui/popover";-import { ScrollArea } from "@/components/ui/scroll-area";-import { cn } from "@/lib/utils";--interface RolePermissionsPreviewProps {- /** Role name (display only). */- name: string;- /** Optional description shown above the permissions list. */- description?: string | null;- /** Full permission set granted by this role. */- permissions: string[];- /** Optional trigger override. Defaults to a small info icon. */- trigger?: React.ReactNode;- /** Visual size of the trigger icon. */- size?: "sm" | "md";-}--/**- * Hover/click-to-open popover showing every permission a role grants.- * Used inline next to a role badge or in the role-assign dropdown.- */-export function RolePermissionsPreview({- name,- description,- permissions,- trigger,- size = "sm",-}: RolePermissionsPreviewProps) {- const [open, setOpen] = useState(false);-- // Group permissions by resource for readability:- // connectors:create / connectors:list:own / kf:create / ...- const grouped = permissions.reduce<Record<string, string[]>>((acc, p) => {- const [resource] = p.split(":");- if (!acc[resource]) acc[resource] = [];- acc[resource].push(p);- return acc;- }, {});-- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- {trigger ?? (- <button- type="button"- aria-label={`Show permissions for ${name}`}- className={cn(- "inline-flex items-center justify-center rounded hover:bg-foreground/10 transition-colors -mr-0.5",- size === "sm" ? "h-5 w-5" : "h-6 w-6",- )}- >- <Info className={size === "sm" ? "h-3.5 w-3.5" : "h-4 w-4"} />- </button>- )}- </PopoverTrigger>- <PopoverContent className="w-80 p-0" align="end" sideOffset={4}>- <div className="px-3 pt-3 pb-2 border-b">- <p className="text-sm font-medium leading-none capitalize">{name}</p>- {description && (- <p className="text-xs text-muted-foreground mt-1">{description}</p>- )}- <p className="text-xs text-muted-foreground mt-1.5">- {permissions.length} permission{permissions.length === 1 ? "" : "s"}- </p>- </div>- <ScrollArea className="max-h-72">- <div className="px-3 py-2 space-y-3">- {Object.entries(grouped)- .sort(([a], [b]) => a.localeCompare(b))- .map(([resource, perms]) => (- <div key={resource}>- <p className="text-xs uppercase tracking-wide text-muted-foreground mb-1">- {resource}- </p>- <div className="flex flex-wrap gap-1">- {perms.sort().map((p) => (- <Badge- key={p}- variant="outline"- className="text-[10px] font-mono py-0 px-1.5 leading-4"- >- {p.split(":").slice(1).join(":")}- </Badge>- ))}- </div>- </div>- ))}- </div>- </ScrollArea>- </PopoverContent>- </Popover>- );-}diff --git a/frontend/lib/role-styles.ts b/frontend/lib/role-styles.tsdeleted file mode 100644index d63fe0b5f..000000000--- a/frontend/lib/role-styles.ts+++ /dev/null@@ -1,42 +0,0 @@-/**- * Single source of truth for role visuals.- *- * One pill SHAPE/SIZE — only the COLOR tint changes by role. The tint- * is applied as a TRANSPARENT overlay (`bg-{color}/10`,- * `border-{color}/30`) so the underlying card/page background shows- * through. No white is pre-mixed into the colors — that means the same- * classes work correctly on light AND dark themes:- * light theme: red-500 at 10% over white → soft pink- * dark theme: red-500 at 10% over slate → muted red ember- *- * Sizing matches the modern admin "chip" pattern (Vercel / Linear /- * Stripe / GitHub): `px-3 py-1 text-sm` ≈ 32px tall, big enough to read- * without competing with primary action buttons (h-9 / 36px).- *- * Industry-standard role colors:- * admin -> red (high privilege, danger zone — Discord, Auth0)- * developer -> blue (technical/builder — GitHub, VS Code)- * user -> neutral foreground (default, no special status)- * viewer -> emerald (read-only, safe — Slack guest)- * custom -> amber (visually distinguishable from built-ins)- */--export const ROLE_PILL_BASE =- "inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-sm font-medium capitalize transition-colors";--const ROLE_TINTS: Record<string, string> = {- admin: "bg-red-500/10 text-red-600 border-red-500/30 dark:text-red-400",- developer:- "bg-blue-500/10 text-blue-600 border-blue-500/30 dark:text-blue-400",- user: "bg-foreground/5 text-foreground/80 border-foreground/15",- viewer:- "bg-emerald-500/10 text-emerald-600 border-emerald-500/30 dark:text-emerald-400",-};--const CUSTOM_ROLE_TINT =- "bg-amber-500/10 text-amber-600 border-amber-500/30 dark:text-amber-400";--export function getRolePillClass(roleName: string): string {- const tint = ROLE_TINTS[roleName] ?? CUSTOM_ROLE_TINT;- return `${ROLE_PILL_BASE} ${tint}`;-}diff --git a/pyproject.toml b/pyproject.tomlindex 44ba46bcb..3540c7d6a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -115,6 +115,7 @@ extend-immutable-calls = ["fastapi.Form","fastapi.Security","dependencies.require_permission",+ "dependencies.require_all_permissions",]# `bootstrap` must be the first import in any module that uses itdiff --git a/src/api/admin/__init__.py b/src/api/admin/__init__.pydeleted file mode 100644index 6ee4a3e32..000000000--- a/src/api/admin/__init__.py+++ /dev/null@@ -1,5 +0,0 @@-"""Admin-only API surface (RBAC management).--Every endpoint in this package is gated by `require_permission(...)` and-writes an `audit_log` row in the same transaction as its mutation.-"""diff --git a/src/api/admin/rbac.py b/src/api/admin/rbac.pydeleted file mode 100644index 1ed3d8857..000000000--- a/src/api/admin/rbac.py+++ /dev/null@@ -1,568 +0,0 @@-"""Admin RBAC endpoints.--Owns:- GET /api/admin/users- GET /api/admin/users/{id}- PATCH /api/admin/users/{id}- DELETE /api/admin/users/{id}- POST /api/admin/users/{id}/roles body: {role_id}- DELETE /api/admin/users/{id}/roles/{role_id}-- GET /api/admin/roles- POST /api/admin/roles body: {name, description, permissions[]}- PATCH /api/admin/roles/{id} body: {description?, permissions?[]}- DELETE /api/admin/roles/{id}- GET /api/admin/permissions-- GET /api/admin/audit ?limit=100&offset=0--Every mutation writes an audit_log row inside the same DB transaction.-Cache invalidation: any role/permission mutation calls-`rbac.invalidate(user_id)` for the affected user (or `invalidate_all()`-for permission-catalog changes).-"""--from __future__ import annotations--import uuid-from typing import List, Optional--from fastapi import APIRouter, Depends, HTTPException, Request-from pydantic import BaseModel-from sqlalchemy import select, update-from sqlalchemy.ext.asyncio import AsyncSession--from db.models import (- AuditLog,- Permission,- Role,- RolePermission,- User as UserRow,- UserRole,-)-from db.repositories import (- AuditRepo,- PermissionRepo,- RoleRepo,- UserRepo,-)-from dependencies import (- get_current_user,- get_db_session,- get_rbac_service,- invalidate_user_ensured_cache,- require_permission,-)-from session_manager import User-from utils.logging_config import get_logger--logger = get_logger(__name__)--# See note in api/users.py — Next.js proxy strips /api before forwarding,-# so we mount under /admin and the frontend reaches us at /api/admin/...-router = APIRouter(prefix="/admin", tags=["admin"])---# ----------------------------------------------------------------------------# Pydantic shapes-# -----------------------------------------------------------------------------class UserOut(BaseModel):- id: str- oauth_provider: str- oauth_subject: str- email: Optional[str] = None- display_name: Optional[str] = None- picture_url: Optional[str] = None- is_active: bool- roles: List[str]- created_at: Optional[str] = None- last_login: Optional[str] = None---class UserPatch(BaseModel):- is_active: Optional[bool] = None---class AssignRoleBody(BaseModel):- role_id: str---class RoleOut(BaseModel):- id: str- name: str- description: Optional[str] = None- is_system: bool- permissions: List[str]---class RoleCreateBody(BaseModel):- name: str- description: Optional[str] = None- permissions: List[str] = []---class RolePatchBody(BaseModel):- description: Optional[str] = None- permissions: Optional[List[str]] = None---class PermissionOut(BaseModel):- id: str- name: str- resource: str- action: str- description: Optional[str] = None---class AuditOut(BaseModel):- id: str- ts: str- actor_user_id: Optional[str] = None- event: str- target_type: Optional[str] = None- target_id: Optional[str] = None- audit_metadata: Optional[dict] = None---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------async def _user_to_out(session: AsyncSession, row: UserRow) -> UserOut:- role_repo = RoleRepo(session)- roles = await role_repo.list_user_roles(row.id)- return UserOut(- id=row.id,- oauth_provider=row.oauth_provider,- oauth_subject=row.oauth_subject,- email=row.email,- display_name=row.display_name,- picture_url=row.picture_url,- is_active=row.is_active,- roles=[r.name for r in roles],- created_at=row.created_at.isoformat() if row.created_at else None,- last_login=row.last_login.isoformat() if row.last_login else None,- )---def _audit_to_out(row: AuditLog) -> AuditOut:- return AuditOut(- id=row.id,- ts=row.ts.isoformat() if row.ts else "",- actor_user_id=row.actor_user_id,- event=row.event,- target_type=row.target_type,- target_id=row.target_id,- audit_metadata=row.audit_metadata,- )---# ----------------------------------------------------------------------------# Users-# -----------------------------------------------------------------------------[email protected]("/users", response_model=List[UserOut])-async def list_users(- limit: int = 100,- offset: int = 0,- actor: User = Depends(require_permission("users:list")),- session: AsyncSession = Depends(get_db_session),-) -> List[UserOut]:- user_repo = UserRepo(session)- rows = await user_repo.list_all(limit=limit, offset=offset)- return [await _user_to_out(session, r) for r in rows]--[email protected]("/users/{user_id}", response_model=UserOut)-async def get_user(- user_id: str,- actor: User = Depends(require_permission("users:read")),- session: AsyncSession = Depends(get_db_session),-) -> UserOut:- row = await UserRepo(session).get_by_id(user_id)- if row is None:- raise HTTPException(404, {"error": "user_not_found"})- return await _user_to_out(session, row)--[email protected]("/users/{user_id}", response_model=UserOut)-async def update_user(- user_id: str,- body: UserPatch,- request: Request,- actor: User = Depends(require_permission("users:invite")),- session: AsyncSession = Depends(get_db_session),- rbac=Depends(get_rbac_service),-) -> UserOut:- row = await UserRepo(session).get_by_id(user_id)- if row is None:- raise HTTPException(404, {"error": "user_not_found"})-- # Don't let the operator deactivate the last active admin.- if body.is_active is False and row.is_active:- role_repo = RoleRepo(session)- roles = await role_repo.list_user_roles(user_id)- if any(r.name == "admin" for r in roles):- if await role_repo.count_admins() <= 1:- raise HTTPException(- 400, {"error": "cannot_deactivate_last_admin"}- )-- changed: dict = {}- if body.is_active is not None and body.is_active != row.is_active:- row.is_active = body.is_active- changed["is_active"] = body.is_active-- if changed:- session.add(row)- await AuditRepo(session).write(- event="user.updated",- actor_user_id=actor.user_id,- target_type="user",- target_id=row.id,- audit_metadata={"changes": changed},- ip=request.client.host if request.client else None,- )- await session.commit()- rbac.invalidate(row.id)- invalidate_user_ensured_cache(row.oauth_provider, row.oauth_subject)-- return await _user_to_out(session, row)--[email protected]("/users/{user_id}")-async def delete_user(- user_id: str,- request: Request,- actor: User = Depends(require_permission("users:delete")),- session: AsyncSession = Depends(get_db_session),- rbac=Depends(get_rbac_service),-):- if actor.user_id == user_id:- raise HTTPException(400, {"error": "cannot_delete_self"})-- row = await UserRepo(session).get_by_id(user_id)- if row is None:- raise HTTPException(404, {"error": "user_not_found"})-- # Capture identity for the post-commit cache invalidation; after- # session.delete(row) + commit the row is expunged and these- # attributes become unavailable.- deleted_provider = row.oauth_provider- deleted_subject = row.oauth_subject-- # Don't let the operator delete the last admin.- role_repo = RoleRepo(session)- roles = await role_repo.list_user_roles(user_id)- if any(r.name == "admin" for r in roles):- if await role_repo.count_admins() <= 1:- raise HTTPException(400, {"error": "cannot_delete_last_admin"})-- # Pre-null audit_log.actor_user_id so the audit row written below- # for the delete event survives even after the deleted user's other- # historical audit rows are nulled by the SET NULL FK policy. (The- # FK migration handles the cascade from the DB side; this explicit- # nulling is belt-and-suspenders for older deployments where the- # 0005_user_fk_ondelete migration hasn't run yet.)- await session.execute(- update(AuditLog)- .where(AuditLog.actor_user_id == user_id)- .values(actor_user_id=None)- )- # The 0005 migration sets ON DELETE CASCADE for user_roles and- # user_preferences and ON DELETE SET NULL for granted_by /- # workspace_config.updated_by, so a single delete of the user row- # propagates correctly. Keep the explicit deletes for the legacy- # path (deployments that haven't applied 0005 yet); they're no-ops- # under the new FK policy.- await session.execute(- UserRole.__table__.delete().where(UserRole.user_id == user_id)- )- from db.models import UserPreferences- await session.execute(- UserPreferences.__table__.delete().where(UserPreferences.user_id == user_id)- )- await session.delete(row)-- await AuditRepo(session).write(- event="user.deleted",- actor_user_id=actor.user_id,- target_type="user",- target_id=user_id,- ip=request.client.host if request.client else None,- )- await session.commit()- rbac.invalidate(user_id)- invalidate_user_ensured_cache(deleted_provider, deleted_subject)- return {"success": True}--[email protected]("/users/{user_id}/roles", response_model=UserOut)-async def assign_role(- user_id: str,- body: AssignRoleBody,- request: Request,- actor: User = Depends(require_permission("roles:assign")),- session: AsyncSession = Depends(get_db_session),- rbac=Depends(get_rbac_service),-) -> UserOut:- user_repo = UserRepo(session)- role_repo = RoleRepo(session)-- user = await user_repo.get_by_id(user_id)- if user is None:- raise HTTPException(404, {"error": "user_not_found"})- role = await role_repo.get_by_id(body.role_id)- if role is None:- raise HTTPException(404, {"error": "role_not_found"})-- await role_repo.assign_role(user_id, body.role_id, granted_by=actor.user_id)- await AuditRepo(session).write(- event="user.role.assigned",- actor_user_id=actor.user_id,- target_type="user",- target_id=user_id,- audit_metadata={"role_id": body.role_id, "role_name": role.name},- ip=request.client.host if request.client else None,- )- await session.commit()- rbac.invalidate(user_id)- return await _user_to_out(session, user)--[email protected]("/users/{user_id}/roles/{role_id}", response_model=UserOut)-async def revoke_role(- user_id: str,- role_id: str,- request: Request,- actor: User = Depends(require_permission("roles:assign")),- session: AsyncSession = Depends(get_db_session),- rbac=Depends(get_rbac_service),-) -> UserOut:- user_repo = UserRepo(session)- role_repo = RoleRepo(session)- user = await user_repo.get_by_id(user_id)- if user is None:- raise HTTPException(404, {"error": "user_not_found"})- role = await role_repo.get_by_id(role_id)-- # Don't let the operator strip the last admin.- if role and role.name == "admin":- admin_count = await role_repo.count_admins()- if admin_count <= 1:- raise HTTPException(400, {"error": "cannot_remove_last_admin"})-- await role_repo.revoke_role(user_id, role_id)- await AuditRepo(session).write(- event="user.role.revoked",- actor_user_id=actor.user_id,- target_type="user",- target_id=user_id,- audit_metadata={"role_id": role_id, "role_name": role.name if role else None},- ip=request.client.host if request.client else None,- )- await session.commit()- rbac.invalidate(user_id)- return await _user_to_out(session, user)---# ----------------------------------------------------------------------------# Roles-# ------------------------------------------------------------------------------async def _role_to_out(session: AsyncSession, role: Role) -> RoleOut:- perms = await RoleRepo(session).list_permissions_for_role(role.id)- return RoleOut(- id=role.id,- name=role.name,- description=role.description,- is_system=role.is_system,- permissions=[p.name for p in perms],- )--[email protected]("/roles", response_model=List[RoleOut])-async def list_roles(- actor: User = Depends(require_permission("roles:list")),- session: AsyncSession = Depends(get_db_session),-) -> List[RoleOut]:- roles = await RoleRepo(session).list_all()- return [await _role_to_out(session, r) for r in roles]--[email protected]("/roles", response_model=RoleOut)-async def create_role(- body: RoleCreateBody,- request: Request,- actor: User = Depends(require_permission("roles:create")),- session: AsyncSession = Depends(get_db_session),- rbac=Depends(get_rbac_service),-) -> RoleOut:- role_repo = RoleRepo(session)- perm_repo = PermissionRepo(session)-- if not body.name or len(body.name) > 64:- raise HTTPException(400, {"error": "invalid_role_name"})-- existing = await role_repo.get_by_name(body.name)- if existing is not None:- raise HTTPException(409, {"error": "role_exists"})-- role = Role(- id=str(uuid.uuid4()),- name=body.name,- description=body.description,- is_system=False,- )- session.add(role)- await session.flush()-- # Resolve permissions by name → id- if body.permissions:- for pname in body.permissions:- perm = await perm_repo.get_by_name(pname)- if perm is None:- raise HTTPException(400, {"error": "unknown_permission", "name": pname})- session.add(RolePermission(role_id=role.id, permission_id=perm.id))-- await AuditRepo(session).write(- event="role.created",- actor_user_id=actor.user_id,- target_type="role",- target_id=role.id,- audit_metadata={"name": role.name, "permissions": body.permissions},- ip=request.client.host if request.client else None,- )- await session.commit()- rbac.invalidate_all()- return await _role_to_out(session, role)--[email protected]("/roles/{role_id}", response_model=RoleOut)-async def update_role(- role_id: str,- body: RolePatchBody,- request: Request,- actor: User = Depends(require_permission("roles:edit")),- session: AsyncSession = Depends(get_db_session),- rbac=Depends(get_rbac_service),-) -> RoleOut:- role_repo = RoleRepo(session)- perm_repo = PermissionRepo(session)-- role = await role_repo.get_by_id(role_id)- if role is None:- raise HTTPException(404, {"error": "role_not_found"})-- changed: dict = {}- if body.description is not None and body.description != role.description:- role.description = body.description- changed["description"] = body.description- session.add(role)-- if body.permissions is not None:- # Resolve names; fail fast on any unknown.- new_perm_ids: list[str] = []- for pname in body.permissions:- perm = await perm_repo.get_by_name(pname)- if perm is None:- raise HTTPException(400, {"error": "unknown_permission", "name": pname})- new_perm_ids.append(perm.id)-- # Replace the role's permission set. For is_system roles we still- # allow this so admins can adjust defaults — they just can't rename- # or delete the role.- await session.execute(- RolePermission.__table__.delete().where(RolePermission.role_id == role.id)- )- for pid in new_perm_ids:- session.add(RolePermission(role_id=role.id, permission_id=pid))- changed["permissions"] = body.permissions-- if changed:- await AuditRepo(session).write(- event="role.updated",- actor_user_id=actor.user_id,- target_type="role",- target_id=role.id,- audit_metadata={"changes": changed},- ip=request.client.host if request.client else None,- )- await session.commit()- rbac.invalidate_all()- return await _role_to_out(session, role)--[email protected]("/roles/{role_id}")-async def delete_role(- role_id: str,- request: Request,- actor: User = Depends(require_permission("roles:delete")),- session: AsyncSession = Depends(get_db_session),- rbac=Depends(get_rbac_service),-):- role_repo = RoleRepo(session)- role = await role_repo.get_by_id(role_id)- if role is None:- raise HTTPException(404, {"error": "role_not_found"})- if role.is_system:- raise HTTPException(400, {"error": "cannot_delete_system_role"})-- await session.execute(- RolePermission.__table__.delete().where(RolePermission.role_id == role.id)- )- await session.execute(- UserRole.__table__.delete().where(UserRole.role_id == role.id)- )- await session.delete(role)- await AuditRepo(session).write(- event="role.deleted",- actor_user_id=actor.user_id,- target_type="role",- target_id=role.id,- audit_metadata={"name": role.name},- ip=request.client.host if request.client else None,- )- await session.commit()- rbac.invalidate_all()- return {"success": True}---# ----------------------------------------------------------------------------# Permissions-# -----------------------------------------------------------------------------[email protected]("/permissions", response_model=List[PermissionOut])-async def list_permissions(- actor: User = Depends(require_permission("roles:list")),- session: AsyncSession = Depends(get_db_session),-) -> List[PermissionOut]:- perms = await PermissionRepo(session).list_all()- return [- PermissionOut(- id=p.id, name=p.name, resource=p.resource, action=p.action,- description=p.description,- )- for p in perms- ]---# ----------------------------------------------------------------------------# Audit log-# -----------------------------------------------------------------------------[email protected]("/audit", response_model=List[AuditOut])-async def list_audit(- limit: int = 100,- offset: int = 0,- actor: User = Depends(require_permission("audit:read")),- session: AsyncSession = Depends(get_db_session),-) -> List[AuditOut]:- rows = await AuditRepo(session).list_recent(limit=limit, offset=offset)- return [_audit_to_out(r) for r in rows]diff --git a/src/api/users.py b/src/api/users.pyindex ed711acae..6c565673e 100644--- a/src/api/users.py+++ b/src/api/users.py@@ -4,16 +4,14 @@ GET /api/users/me -> profile of the current userGET /api/users/me/permissions -> list of permission strings"""-from typing import List-from fastapi import APIRouter, Dependsfrom pydantic import BaseModel+from sqlalchemy.ext.asyncio import AsyncSessionfrom db.repositories import PermissionRepo, RoleRepo, UserRepofrom dependencies import get_current_user, get_db_session, get_rbac_servicefrom services.rbac_service import is_rbac_enforcedfrom session_manager import User-from sqlalchemy.ext.asyncio import AsyncSessionasync def _effective_permissions(rbac, db_id: str, session: AsyncSession) -> set[str]:@@ -29,6 +27,7 @@ async def _effective_permissions(rbac, db_id: str, session: AsyncSession) -> setperms = await PermissionRepo(session).list_all()return {p.name for p in perms}+# Backend routes are mounted WITHOUT the /api prefix because the Next.js# proxy at frontend/app/api/[...path]/route.ts strips it before forwarding.# Frontend reaches these via /api/users/me, /api/users/me/permissions.@@ -41,8 +40,8 @@ class MeResponse(BaseModel):name: strpicture: str | None = Noneprovider: str- roles: List[str]- permissions: List[str]+ roles: list[str]+ permissions: list[str]# OPENRAG_RBAC_ENFORCE — surfaced so the UI can hide RBAC-only# sections (Users & Roles, Audit log, role pills) when the# operator has the kill switch off.@@ -80,7 +79,7 @@ async def get_me(class PermissionsResponse(BaseModel):- permissions: List[str]+ permissions: list[str]@router.get("/me/permissions", response_model=PermissionsResponse)diff --git a/src/app/routes/internal.py b/src/app/routes/internal.pyindex 86b13e80e..1b0a64f35 100644--- a/src/app/routes/internal.py+++ b/src/app/routes/internal.py@@ -418,13 +418,11 @@ def register_internal_routes(app: FastAPI):# Docling service proxyapp.add_api_route("/docling/health", docling.health, methods=["GET"], tags=["internal"])- # ===== Users / RBAC Endpoints (JWT auth) =====+ # ===== Users Endpoints (JWT auth) =====from api import config as config_apifrom api import users as users_api- from api.admin import rbac as admin_rbacapp.include_router(users_api.router)- app.include_router(admin_rbac.router)# Public — must work pre-auth so the onboarding wizard can render.app.include_router(config_api.router)diff --git a/src/auth/jwt_roles.py b/src/auth/jwt_roles.pynew file mode 100644index 000000000..32d0134ba--- /dev/null+++ b/src/auth/jwt_roles.py@@ -0,0 +1,91 @@+"""JWT-sourced role assignment.++Reads the role claim named by `OPENRAG_JWT_ROLES_CLAIM` from a decoded JWT+and maps each claim value to a built-in OpenRAG role via the+`OPENRAG_ROLE_CLAIM_*` settings.++Pure helper — no DB access. Config is read through the per-call accessors in+`config.settings` so test overrides (`monkeypatch.setenv`) take effect without+a process restart.+"""++from __future__ import annotations++from config.settings import (+ get_jwt_roles_claim,+ get_role_claim_admin,+ get_role_claim_developer,+ get_role_claim_user,+ get_role_claim_viewer,+)+from services.rbac_service import is_rbac_enforced+from utils.logging_config import get_logger++logger = get_logger(__name__)+++def _claim_to_role_map() -> dict[str, list[str]]:+ """Build a {jwt_claim_value: [openrag_role, ...]} map from current env.++ Constructed per call so test overrides are picked up. Skips unset+ mappings entirely.+ """+ pairs = (+ ("admin", get_role_claim_admin()),+ ("developer", get_role_claim_developer()),+ ("user", get_role_claim_user()),+ ("viewer", get_role_claim_viewer()),+ )+ mapping: dict[str, list[str]] = {}+ for openrag_role, claim_value in pairs:+ if not claim_value:+ continue+ mapping.setdefault(claim_value, []).append(openrag_role)+ return mapping+++def extract_jwt_role_names(claims: dict | None) -> list[str]:+ """Return the OpenRAG role names derived from a decoded JWT.++ Returns an empty list when the claim is missing, malformed, or contains+ no recognized role values. The returned list preserves the order of the+ JWT claim and is de-duplicated.+ """+ if not claims:+ return []++ claim_name = get_jwt_roles_claim()+ raw = claims.get(claim_name)+ if raw is None:+ return []++ if not isinstance(raw, list) or not all(isinstance(v, str) for v in raw):+ logger.warning(+ "JWT roles claim is not a list of strings; treating as no roles",+ claim_name=claim_name,+ value_type=type(raw).__name__,+ )+ return []++ mapping = _claim_to_role_map()+ seen: set[str] = set()+ result: list[str] = []+ for value in raw:+ openrag_roles = mapping.get(value)+ if not openrag_roles:+ logger.debug("Unknown JWT role claim value ignored", value=value)+ continue+ for role in openrag_roles:+ if role not in seen:+ seen.add(role)+ result.append(role)+ return result+++def jwt_roles_enabled() -> bool:+ """True when JWT-sourced role assignment is active.++ Tied to RBAC enforcement today; kept as its own predicate so the two+ can be decoupled later if needed.+ """+ return is_rbac_enforced()diff --git a/src/config/settings.py b/src/config/settings.pyindex e4471a640..e8f3aabee 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -70,6 +70,43 @@ PLATFORM_PASSWORD = os.getenv("PLATFORM_PASSWORD")IBM_JWT_PUBLIC_KEY_URL = os.getenv("IBM_JWT_PUBLIC_KEY_URL", "")IBM_SESSION_COOKIE_NAME = os.getenv("IBM_SESSION_COOKIE_NAME", "ibm-openrag-session")IBM_CREDENTIALS_HEADER = os.getenv("IBM_CREDENTIALS_HEADER", "X-IBM-LH-Credentials")++# ── JWT roles claim ─────────────────────────────────────────────+# These are exposed as functions (not module constants) so they are read+# per-call: auth/jwt_roles.py must pick up runtime overrides, and the unit+# tests drive them via monkeypatch.setenv. This mirrors is_rbac_enforced(),+# which reads OPENRAG_RBAC_ENFORCE the same way.+++def get_jwt_roles_claim() -> str:+ """Name of the JWT claim that carries the user's OpenRAG roles.++ The claim's value MUST be a JSON array of strings; anything else is+ treated as no roles and rejected (HTTP 401) when JWT-role sync is active.+ """+ return os.getenv("OPENRAG_JWT_ROLES_CLAIM", "openrag_roles")+++# Mapping from OpenRAG built-in role -> JWT claim value. When the JWT roles+# claim contains the returned value, the user is granted that OpenRAG role.+# A None return (viewer, unset by default) means the OpenRAG role cannot be+# assigned via JWT (e.g. when the IdP only ships 3 roles).+def get_role_claim_admin() -> str:+ return os.getenv("OPENRAG_ROLE_CLAIM_ADMIN", "admin")+++def get_role_claim_developer() -> str:+ return os.getenv("OPENRAG_ROLE_CLAIM_DEVELOPER", "manager")+++def get_role_claim_user() -> str:+ return os.getenv("OPENRAG_ROLE_CLAIM_USER", "user")+++def get_role_claim_viewer() -> str | None:+ return os.getenv("OPENRAG_ROLE_CLAIM_VIEWER")++DOCLING_OCR_ENGINE = os.getenv("DOCLING_OCR_ENGINE")SEGMENT_WRITE_KEY = os.getenv("SEGMENT_WRITE_KEY", "")ENVIRONMENT = os.getenv("ENVIRONMENT", "")diff --git a/src/db/repositories/audit_repo.py b/src/db/repositories/audit_repo.pyindex e7a3eddf4..5d380c2e0 100644--- a/src/db/repositories/audit_repo.py+++ b/src/db/repositories/audit_repo.py@@ -1,7 +1,5 @@import uuid-from typing import Optional-from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom db.models import AuditLog@@ -14,13 +12,13 @@ class AuditRepo:async def write(self,event: str,- actor_user_id: Optional[str] = None,- actor_api_key_id: Optional[str] = None,- target_type: Optional[str] = None,- target_id: Optional[str] = None,- audit_metadata: Optional[dict] = None,- ip: Optional[str] = None,- user_agent: Optional[str] = None,+ actor_user_id: str | None = None,+ actor_api_key_id: str | None = None,+ target_type: str | None = None,+ target_id: str | None = None,+ audit_metadata: dict | None = None,+ ip: str | None = None,+ user_agent: str | None = None,) -> AuditLog:row = AuditLog(id=str(uuid.uuid4()),@@ -36,9 +34,3 @@ class AuditRepo:self.session.add(row)await self.session.flush()return row-- async def list_recent(self, limit: int = 100, offset: int = 0) -> list[AuditLog]:- result = await self.session.execute(- select(AuditLog).order_by(AuditLog.ts.desc()).offset(offset).limit(limit)- )- return list(result.scalars().all())diff --git a/src/db/repositories/role_repo.py b/src/db/repositories/role_repo.pyindex 2c9c4313a..cb4b44d67 100644--- a/src/db/repositories/role_repo.py+++ b/src/db/repositories/role_repo.py@@ -1,7 +1,6 @@-from typing import Optional--from sqlalchemy import func, select+from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from sqlmodel import colfrom db.models import Permission, Role, RolePermission, UserRole@@ -10,63 +9,24 @@ class RoleRepo:def __init__(self, session: AsyncSession):self.session = session- async def get_by_name(self, name: str) -> Optional[Role]:- result = await self.session.execute(select(Role).where(Role.name == name))+ async def get_by_name(self, name: str) -> Role | None:+ result = await self.session.execute(select(Role).where(col(Role.name) == name))return result.scalar_one_or_none()- async def get_by_id(self, role_id: str) -> Optional[Role]:- return await self.session.get(Role, role_id)-- async def list_all(self) -> list[Role]:- result = await self.session.execute(select(Role).order_by(Role.name))- return list(result.scalars().all())-- async def count_admins(self) -> int:- result = await self.session.execute(- select(func.count())- .select_from(UserRole)- .join(Role, Role.id == UserRole.role_id)- .where(Role.name == "admin")- )- return int(result.scalar_one() or 0)-- async def list_admin_user_ids(self) -> list[str]:- """All user_ids that currently hold the admin role.-- Returned in lexicographic order so callers can use it as a- deterministic tie-breaker (e.g. bootstrap-race rollback in- ``user_service._assign_bootstrap_or_default``).- """- result = await self.session.execute(- select(UserRole.user_id)- .join(Role, Role.id == UserRole.role_id)- .where(Role.name == "admin")- .order_by(UserRole.user_id)- )- return list(result.scalars().all())-async def list_user_roles(self, user_id: str) -> list[Role]:result = await self.session.execute(select(Role)- .join(UserRole, UserRole.role_id == Role.id)- .where(UserRole.user_id == user_id)- )- return list(result.scalars().all())-- async def list_permissions_for_role(self, role_id: str) -> list[Permission]:- result = await self.session.execute(- select(Permission)- .join(RolePermission, RolePermission.permission_id == Permission.id)- .where(RolePermission.role_id == role_id)+ .join(UserRole, col(UserRole.role_id) == col(Role.id))+ .where(col(UserRole.user_id) == user_id))return list(result.scalars().all())async def list_permissions_for_user(self, user_id: str) -> set[str]:result = await self.session.execute(- select(Permission.name)- .join(RolePermission, RolePermission.permission_id == Permission.id)- .join(UserRole, UserRole.role_id == RolePermission.role_id)- .where(UserRole.user_id == user_id)+ select(col(Permission.name))+ .join(RolePermission, col(RolePermission.permission_id) == col(Permission.id))+ .join(UserRole, col(UserRole.role_id) == col(RolePermission.role_id))+ .where(col(UserRole.user_id) == user_id))return set(result.scalars().all())@@ -74,18 +34,18 @@ class RoleRepo:if not role_ids:return set()result = await self.session.execute(- select(Permission.name)- .join(RolePermission, RolePermission.permission_id == Permission.id)- .where(RolePermission.role_id.in_(role_ids))+ select(col(Permission.name))+ .join(RolePermission, col(RolePermission.permission_id) == col(Permission.id))+ .where(col(RolePermission.role_id).in_(role_ids)))return set(result.scalars().all())async def assign_role(- self, user_id: str, role_id: str, granted_by: Optional[str] = None+ self, user_id: str, role_id: str, granted_by: str | None = None) -> UserRole:existing = await self.session.execute(select(UserRole).where(- UserRole.user_id == user_id, UserRole.role_id == role_id+ col(UserRole.user_id) == user_id, col(UserRole.role_id) == role_id))row = existing.scalar_one_or_none()@@ -99,7 +59,7 @@ class RoleRepo:async def revoke_role(self, user_id: str, role_id: str) -> None:result = await self.session.execute(select(UserRole).where(- UserRole.user_id == user_id, UserRole.role_id == role_id+ col(UserRole.user_id) == user_id, col(UserRole.role_id) == role_id))row = result.scalar_one_or_none()diff --git a/src/dependencies.py b/src/dependencies.pyindex bb3c0e776..8f589b30b 100644--- a/src/dependencies.py+++ b/src/dependencies.py@@ -163,11 +163,16 @@ async def get_db_session() -> AsyncIterator[AsyncSession]:yield session-async def _ensure_db_user(user: User) -> str | None:+async def _ensure_db_user(user: User, jwt_roles: list[str] | None = None) -> str | None:"""Best-effort DB upsert for the authenticated user. Returns the SQL`users.id` for this user (so callers can cache the OAuth-sub → DB-idmapping). Returns None on failure.+ When ``jwt_roles`` is not None, the user's DB role assignments are+ reconciled against it on every call — the per-process cache short-+ circuits the user-row INSERT but not the role sync. Pass None to+ preserve pre-JWT-roles behavior.+No-ops for anonymous users in no-auth mode beyond the very first call(which does set up the synthetic anonymous row + role). Failures arelogged but never block the request.@@ -176,7 +181,7 @@ async def _ensure_db_user(user: User) -> str | None:return Nonecache_key = _user_cache_key(user)cached_db_id = _ENSURED_USER_IDS.get(cache_key)- if cached_db_id is not None:+ if cached_db_id is not None and jwt_roles is None:return cached_db_id# Serialize concurrent first-time ensures for the SAME identity so a@@ -185,14 +190,12 @@ async def _ensure_db_user(user: User) -> str | None:# subject) lock so unrelated users never block each other.lock = _ENSURE_LOCKS.setdefault(cache_key, asyncio.Lock())async with lock:- # Re-check the cache inside the lock; the previous holder may- # have just populated it.cached_db_id = _ENSURED_USER_IDS.get(cache_key)- if cached_db_id is not None:+ if cached_db_id is not None and jwt_roles is None:return cached_db_idtry:from db.engine import SessionLocal, init_engine- from services.user_service import ensure_user_row+ from services.user_service import ensure_user_row, sync_jwt_rolesif SessionLocal is None:init_engine()@@ -201,27 +204,39 @@ async def _ensure_db_user(user: User) -> str | None:if _SessionLocal is None:return Noneasync with _SessionLocal() as session:- db_row = await ensure_user_row(session, user)+ if cached_db_id is not None and jwt_roles is not None:+ # User row already exists in this process; just reconcile+ # roles from the JWT.+ await sync_jwt_roles(session, cached_db_id, jwt_roles)+ await session.commit()+ return cached_db_id+ db_row = await ensure_user_row(session, user, jwt_roles=jwt_roles)await session.commit()_ENSURED_USER_IDS[cache_key] = db_row.idreturn db_row.id+ except HTTPException:+ raiseexcept Exception as exc: # noqa: BLE001logger.warning("ensure_user_row failed", user_id=user.user_id, error=str(exc))return None-async def _resolve_db_user_id(user: User) -> str:+async def _resolve_db_user_id(user: User, jwt_roles: list[str] | None = None) -> str:"""Translate an authenticated `User` (which carries the JWT/OAuthsubject) to the SQL `users.id` used by the RBAC tables. Falls back to`user.user_id` if no DB row can be resolved (no-auth mode, transientDB error, etc.) so caller behavior degrades gracefully.++ When ``jwt_roles`` is not None, role sync runs on every call (the cache+ only short-circuits the INSERT, not the reconcile step)."""if not user or not user.user_id:return ""- cached = _ENSURED_USER_IDS.get(_user_cache_key(user))- if cached is not None:- return cached- resolved = await _ensure_db_user(user)+ if jwt_roles is None:+ cached = _ENSURED_USER_IDS.get(_user_cache_key(user))+ if cached is not None:+ return cached+ resolved = await _ensure_db_user(user, jwt_roles=jwt_roles)return resolved or user.user_id@@ -236,7 +251,8 @@ async def _attach_db_user_id(request: Request, user: User | None) -> User | Nonerequest.state.db_user_id = Nonerequest.state.user = Nonereturn None- db_user_id = await _resolve_db_user_id(user)+ jwt_roles = getattr(request.state, "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_idrequest.state.user = user_with_db_id@@ -362,6 +378,7 @@ async def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:"""import auth.ibm_auth as ibm_authfrom auth.ibm_auth import extract_ibm_credentials+ from auth.jwt_roles import extract_jwt_role_names, jwt_roles_enabledfrom config.settings import (IBM_CREDENTIALS_HEADER,IBM_SESSION_COOKIE_NAME,@@ -397,6 +414,7 @@ async def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:user_id = Noneemail = Nonename = None+ jwt_roles: list[str] | None = Noneif ibm_token:logger.debug("[AUTH] IBM JWT token found in request cookies")claims = ibm_auth.decode_ibm_jwt(ibm_token)@@ -411,6 +429,22 @@ async def _get_ibm_user(request: Request, required: bool) -> Optional["User"]:user_id = claims.get("username", sub)email = claims.get("username", sub)name = claims.get("display_name", claims.get("username", sub))+ # Only consume the roles claim when JWT-role sync is+ # active. When RBAC is off, leave jwt_roles as None so+ # the legacy bootstrap-or-default-role path runs and the+ # user's DB roles are NOT clobbered by an empty claim.+ if jwt_roles_enabled():+ jwt_roles = extract_jwt_role_names(claims)+ if not jwt_roles:+ logger.warning(+ "IBM JWT carries no recognized OpenRAG role claim",+ user_id=user_id,+ )+ raise HTTPException(+ status_code=401,+ detail="User has no OpenRAG roles assigned",+ )+ request.state.jwt_roles = jwt_rolesif lh_credentials and lh_credentials.strip() != "":logger.debug("[AUTH] IBM LH credentials found in request headers")diff --git a/src/services/user_service.py b/src/services/user_service.pyindex 1911c9db0..c8e8b8611 100644--- a/src/services/user_service.py+++ b/src/services/user_service.py@@ -34,12 +34,21 @@ def _noauth_role() -> str:return os.getenv("OPENRAG_NOAUTH_ROLE", "admin")-async def ensure_user_row(session: AsyncSession, user: User) -> UserRow:+async def ensure_user_row(+ session: AsyncSession,+ user: User,+ jwt_roles: list[str] | None = None,+) -> UserRow:"""Ensure the authenticated `user` exists in the SQL `users` table.- First-ever user gets the `admin` role. All subsequent users get the- role named in `OPENRAG_DEFAULT_ROLE` (default `user`). The synthetic- no-auth user is granted `OPENRAG_NOAUTH_ROLE` (default `admin`).+ Role assignment:++ * ``jwt_roles is None`` — env-default behavior (oss / RBAC-off). Every new+ user gets ``OPENRAG_DEFAULT_ROLE`` (default ``user``); the synthetic+ anonymous user gets ``OPENRAG_NOAUTH_ROLE`` (default ``admin``). There is+ no first-user-becomes-admin bootstrap.+ * ``jwt_roles is not None`` — JWT is authoritative (saas / on_prem). The+ user's DB role assignments are reconciled against the list every call.Returns the persisted UserRow. Caller commits."""@@ -57,6 +66,8 @@ async def ensure_user_row(session: AsyncSession, user: User) -> UserRow:existing = await user_repo.get_by_oauth(provider, subject)if existing:await user_repo.update_last_login(existing.id)+ if jwt_roles is not None:+ await _sync_jwt_roles(role_repo, audit_repo, existing.id, jwt_roles)return existing# Possible legacy row (oauth_provider='legacy', oauth_subject==user_id)@@ -83,8 +94,11 @@ async def ensure_user_row(session: AsyncSession, user: User) -> UserRow:target_id=merged.id,audit_metadata={"provider": provider},)- # Legacy rows had no role assignment — give them the default.- await _assign_bootstrap_or_default(session, role_repo, audit_repo, merged.id)+ if jwt_roles is not None:+ await _sync_jwt_roles(role_repo, audit_repo, merged.id, jwt_roles)+ else:+ # Legacy rows had no role assignment — give them the default.+ await _assign_default_role(session, role_repo, audit_repo, merged.id)return merged# Brand-new row.@@ -151,7 +165,10 @@ async def ensure_user_row(session: AsyncSession, user: User) -> UserRow:picture_url=user.picture,)await user_repo.add(row)- await _assign_bootstrap_or_default(session, role_repo, audit_repo, row.id)+ if jwt_roles is not None:+ await _sync_jwt_roles(role_repo, audit_repo, row.id, jwt_roles)+ else:+ await _assign_default_role(session, role_repo, audit_repo, row.id)return row# Case 3: pure PK collision (id==subject already occupied by a@@ -169,50 +186,91 @@ async def ensure_user_row(session: AsyncSession, user: User) -> UserRow:)await user_repo.add(row)- await _assign_bootstrap_or_default(session, role_repo, audit_repo, row.id)+ if jwt_roles is not None:+ await _sync_jwt_roles(role_repo, audit_repo, row.id, jwt_roles)+ else:+ await _assign_default_role(session, role_repo, audit_repo, row.id)return row-async def _assign_bootstrap_or_default(- session: AsyncSession,+async def sync_jwt_roles(session: AsyncSession, user_id: str, jwt_roles: list[str]) -> None:+ """Public entry point for re-syncing a user's roles from JWT claims.++ Used by the ensure-user cache fast path in ``dependencies.py``: when the+ user row is already in the per-process cache we skip ``ensure_user_row``+ but still need to reconcile roles each request. Caller commits.+ """+ role_repo = RoleRepo(session)+ audit_repo = AuditRepo(session)+ await _sync_jwt_roles(role_repo, audit_repo, user_id, jwt_roles)+++async def _sync_jwt_roles(role_repo: RoleRepo,audit_repo: AuditRepo,user_id: str,+ jwt_roles: list[str],) -> None:- admin_count = await role_repo.count_admins()- if admin_count == 0:- admin_role = await role_repo.get_by_name("admin")- if admin_role is None:- logger.warning("admin role not seeded; skipping bootstrap assignment")- return- await role_repo.assign_role(user_id, admin_role.id)- await session.flush()-- # Race-detect: a concurrent caller may have *also* observed- # admin_count == 0 and granted admin to a different user. Both- # writes succeeded (no DB-level mutex). Resolve by lexicographic- # tie-break — only the smallest user_id keeps admin; others- # demote and fall through to the default-role path. This is- # portable across SQLite and Postgres without advisory locks.- admins = await role_repo.list_admin_user_ids()- if len(admins) > 1 and min(admins) != user_id:- await role_repo.revoke_role(user_id, admin_role.id)- await session.flush()+ """Reconcile ``user_roles`` for ``user_id`` against the JWT-derived list.++ JWT is authoritative: roles missing from the JWT are revoked, new ones+ are added. Role names not present in the ``roles`` table are skipped+ (logged at WARNING). A single ``user.roles_synced`` audit row is written+ when the role set changes.+ """+ current = await role_repo.list_user_roles(user_id)+ current_by_name = {r.name: r for r in current}++ desired: dict[str, str] = {} # name -> role_id+ for name in jwt_roles:+ if name in desired:+ continue+ role = await role_repo.get_by_name(name)+ if role is None:logger.warning(- "bootstrap race detected; demoted to default role",+ "JWT role not present in roles table; skipping",+ role=name,user_id=user_id,- winner=min(admins),- )- # Fall through to the default-role assignment block below.- else:- await audit_repo.write(- event="user.bootstrap_admin",- actor_user_id=user_id,- target_type="user",- target_id=user_id,)- return+ continue+ desired[name] = role.id+ added: list[str] = []+ removed: list[str] = []++ for name, role_id in desired.items():+ if name not in current_by_name:+ await role_repo.assign_role(user_id, role_id)+ added.append(name)++ for name, role in current_by_name.items():+ if name not in desired:+ await role_repo.revoke_role(user_id, role.id)+ removed.append(name)++ if added or removed:+ await audit_repo.write(+ event="user.roles_synced",+ actor_user_id=user_id,+ target_type="user",+ target_id=user_id,+ audit_metadata={"added": added, "removed": removed, "source": "jwt"},+ )+++async def _assign_default_role(+ session: AsyncSession,+ role_repo: RoleRepo,+ audit_repo: AuditRepo,+ user_id: str,+) -> None:+ """Assign the configured default role to a freshly-created user.++ Role assignment is owned outside the app: saas/on_prem deployments sync+ roles from the JWT claim (see ``_sync_jwt_roles``), and everything else+ falls back here. There is no first-user-becomes-admin bootstrap — an oss+ operator who wants an admin sets ``OPENRAG_DEFAULT_ROLE=admin``.+ """# No-auth synthetic user -> configurable roleif user_id == "anonymous":target_name = _noauth_role()diff --git a/tests/unit/api/admin/__init__.py b/tests/unit/api/admin/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/tests/unit/api/admin/test_rbac_endpoints.py b/tests/unit/api/admin/test_rbac_endpoints.pydeleted file mode 100644index 4ce3236af..000000000--- a/tests/unit/api/admin/test_rbac_endpoints.py+++ /dev/null@@ -1,362 +0,0 @@-"""Phase 3: admin RBAC endpoints — happy paths + access control."""--import sys-from pathlib import Path--import httpx-import pytest-import pytest_asyncio-from fastapi import FastAPI, Request-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.repositories import RoleRepo # noqa: E402-from db.seed import seed_roles_and_permissions # noqa: E402-from dependencies import ( # noqa: E402- get_current_user,- get_db_session,- get_rbac_service,-)-from services.rbac_service import RBACService # noqa: E402-from services.user_service import ensure_user_row # noqa: E402-from session_manager import User # noqa: E402--PERSONAS: dict[str, User] = {}---@pytest_asyncio.fixture-async def app(monkeypatch):- monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "user")- 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)-- PERSONAS.clear()- async with SessionLocal() as s:- await seed_roles_and_permissions(s)- admin_db = await ensure_user_row(- s, User(user_id="admin-sub", email="[email protected]", name="A", provider="google")- )- user_db = await ensure_user_row(- s, User(user_id="user-sub", email="[email protected]", name="U", provider="google")- )- await s.commit()-- PERSONAS["admin"] = User(- user_id=admin_db.id, email="[email protected]", name="A", provider="google"- )- PERSONAS["user"] = User(- user_id=user_db.id, email="[email protected]", name="U", provider="google"- )-- rbac = RBACService(SessionLocal)-- fastapi_app = FastAPI()-- async def _stub_user(request: Request) -> User:- persona = request.headers.get("X-Test-Persona", "admin")- return PERSONAS[persona]-- async def _db_session():- async with SessionLocal() as s:- yield s-- fastapi_app.dependency_overrides[get_current_user] = _stub_user- fastapi_app.dependency_overrides[get_rbac_service] = lambda: rbac- fastapi_app.dependency_overrides[get_db_session] = _db_session-- from api.admin import rbac as admin_rbac- fastapi_app.include_router(admin_rbac.router)-- yield fastapi_app, SessionLocal, rbac- await engine.dispose()---def _admin_headers():- return {"X-Test-Persona": "admin"}---def _user_headers():- return {"X-Test-Persona": "user"}---async def test_admin_can_list_users(app):- fastapi_app, _, _ = app- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.get("/admin/users", headers=_admin_headers())- assert r.status_code == 200- assert len(r.json()) == 2---async def test_non_admin_cannot_list_users(app):- fastapi_app, _, _ = app- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.get("/admin/users", headers=_user_headers())- assert r.status_code == 403- assert r.json()["detail"]["required"] == "users:list"---async def test_admin_can_promote_user(app):- fastapi_app, SessionLocal, rbac = app- user_id = PERSONAS["user"].user_id-- async with SessionLocal() as s:- dev_role = await RoleRepo(s).get_by_name("developer")- role_id = dev_role.id-- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.post(- f"/admin/users/{user_id}/roles",- json={"role_id": role_id},- headers=_admin_headers(),- )- assert r.status_code == 200- body = r.json()- assert "developer" in body["roles"]---async def test_cannot_remove_last_admin(app):- fastapi_app, SessionLocal, _ = app- admin_id = PERSONAS["admin"].user_id-- async with SessionLocal() as s:- admin_role = await RoleRepo(s).get_by_name("admin")-- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.delete(- f"/admin/users/{admin_id}/roles/{admin_role.id}",- headers=_admin_headers(),- )- assert r.status_code == 400- assert r.json()["detail"]["error"] == "cannot_remove_last_admin"---async def test_admin_can_create_and_delete_custom_role(app):- fastapi_app, _, _ = app- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- # Create- r = await c.post(- "/admin/roles",- json={- "name": "reviewer",- "description": "Doc reviewer",- "permissions": ["chat:use", "search:use", "kf:edit:own"],- },- headers=_admin_headers(),- )- assert r.status_code == 200- role = r.json()- assert role["name"] == "reviewer"- assert role["is_system"] is False- assert set(role["permissions"]) == {"chat:use", "search:use", "kf:edit:own"}-- # List- r = await c.get("/admin/roles", headers=_admin_headers())- names = {row["name"] for row in r.json()}- assert "reviewer" in names-- # Delete- r = await c.delete(f"/admin/roles/{role['id']}", headers=_admin_headers())- assert r.status_code == 200---async def test_cannot_delete_system_role(app):- fastapi_app, SessionLocal, _ = app- async with SessionLocal() as s:- admin_role = await RoleRepo(s).get_by_name("admin")-- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.delete(- f"/admin/roles/{admin_role.id}", headers=_admin_headers()- )- assert r.status_code == 400- assert r.json()["detail"]["error"] == "cannot_delete_system_role"---async def test_role_edit_replaces_permissions_and_invalidates_cache(app):- fastapi_app, SessionLocal, rbac = app- async with SessionLocal() as s:- user_role = await RoleRepo(s).get_by_name("user")- user_id = PERSONAS["user"].user_id-- # Warm cache- perms_before = await rbac.get_user_permissions(user_id)- assert "chat:use" in perms_before-- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.patch(- f"/admin/roles/{user_role.id}",- json={"permissions": ["search:use"]},- headers=_admin_headers(),- )- assert r.status_code == 200-- perms_after = await rbac.get_user_permissions(user_id)- assert "chat:use" not in perms_after- assert "search:use" in perms_after---async def test_audit_log_records_role_assignment(app):- fastapi_app, SessionLocal, _ = app- user_id = PERSONAS["user"].user_id- async with SessionLocal() as s:- dev_role = await RoleRepo(s).get_by_name("developer")-- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- await c.post(- f"/admin/users/{user_id}/roles",- json={"role_id": dev_role.id},- headers=_admin_headers(),- )-- r = await c.get("/admin/audit?limit=50", headers=_admin_headers())- assert r.status_code == 200- events = [row["event"] for row in r.json()]- assert "user.role.assigned" in events---async def test_permissions_endpoint(app):- fastapi_app, _, _ = app- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.get("/admin/permissions", headers=_admin_headers())- assert r.status_code == 200- names = {p["name"] for p in r.json()}- # Sample known catalog members- assert {"config:write", "users:list", "chat:use", "kf:create"}.issubset(names)---async def test_cannot_delete_self(app):- fastapi_app, _, _ = app- admin_id = PERSONAS["admin"].user_id- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.delete(f"/admin/users/{admin_id}", headers=_admin_headers())- assert r.status_code == 400- assert r.json()["detail"]["error"] == "cannot_delete_self"---async def test_cannot_delete_last_admin(app):- """Single-admin DB. A non-admin actor with `users:delete` permission- tries to DELETE the sole admin → cannot_delete_last_admin (400).-- The cannot_delete_self guard runs first, so we use a non-admin actor- with a custom role granting `users:delete`. This isolates the- last-admin guard from the self-delete guard.- """- fastapi_app, SessionLocal, _ = app- admin_id = PERSONAS["admin"].user_id- user_id = PERSONAS["user"].user_id-- # Grant the `user` persona a custom role that includes users:delete- # without being an admin. This requires us to create the role and- # assign it via the admin endpoints.- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.post(- "/admin/roles",- json={"name": "user_deleter", "permissions": ["users:delete"]},- headers=_admin_headers(),- )- assert r.status_code == 200- deleter_role_id = r.json()["id"]- r = await c.post(- f"/admin/users/{user_id}/roles",- json={"role_id": deleter_role_id},- headers=_admin_headers(),- )- assert r.status_code == 200- # `user` (non-admin, has users:delete) tries to delete the sole admin.- r = await c.delete(- f"/admin/users/{admin_id}",- headers={"X-Test-Persona": "user"},- )- assert r.status_code == 400- assert r.json()["detail"]["error"] == "cannot_delete_last_admin"---async def test_can_delete_non_last_admin(app):- """Two-admin DB → deleting one admin leaves the other; should succeed."""- fastapi_app, SessionLocal, _ = app- user_id = PERSONAS["user"].user_id- async with SessionLocal() as s:- admin_role = await RoleRepo(s).get_by_name("admin")-- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- # Promote user to admin → now 2 admins.- r = await c.post(- f"/admin/users/{user_id}/roles",- json={"role_id": admin_role.id},- headers=_admin_headers(),- )- assert r.status_code == 200- # Admin (still admin) deletes the second admin → succeeds.- r = await c.delete(- f"/admin/users/{user_id}",- headers=_admin_headers(),- )- assert r.status_code == 200---async def test_cannot_deactivate_last_admin(app):- """PATCH /users/{admin_id} {is_active: False} on the only admin → 400."""- fastapi_app, SessionLocal, _ = app- admin_id = PERSONAS["admin"].user_id- async with SessionLocal() as s:- admin_role = await RoleRepo(s).get_by_name("admin")-- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.patch(- f"/admin/users/{admin_id}",- json={"is_active": False},- headers=_admin_headers(),- )- assert r.status_code == 400- assert r.json()["detail"]["error"] == "cannot_deactivate_last_admin"---async def test_unknown_permission_rejected_on_create_role(app):- fastapi_app, _, _ = app- transport = httpx.ASGITransport(app=fastapi_app)- async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:- r = await c.post(- "/admin/roles",- json={"name": "weird", "permissions": ["does:not:exist"]},- headers=_admin_headers(),- )- assert r.status_code == 400- assert r.json()["detail"]["error"] == "unknown_permission"diff --git a/tests/unit/dependencies/test_rbac_kill_switch.py b/tests/unit/dependencies/test_rbac_kill_switch.pyindex 21383c5ae..888da9ca3 100644--- a/tests/unit/dependencies/test_rbac_kill_switch.py+++ b/tests/unit/dependencies/test_rbac_kill_switch.py@@ -13,12 +13,12 @@ single-user OSS installs or emergency debugging.import sysfrom pathlib import Path-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import MagicMockimport httpximport pytestimport pytest_asyncio-from fastapi import FastAPI, Request+from fastapi import Depends, FastAPI, Requestfrom sqlalchemy.ext.asyncio import async_sessionmaker, create_async_enginefrom sqlmodel import SQLModel@@ -28,7 +28,6 @@ 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: E402from db.seed import seed_roles_and_permissions # noqa: E402from dependencies import ( # noqa: E402get_current_user,@@ -39,7 +38,6 @@ from services.rbac_service import RBACService, is_rbac_enforced # noqa: E402from services.user_service import ensure_user_row # noqa: E402from session_manager import User # noqa: E402-# ----------------------------------------------------------------------# is_rbac_enforced() resolver# ----------------------------------------------------------------------@@ -91,12 +89,8 @@ async def app(monkeypatch):s, User(user_id="user-sub", email="u@x", name="U", provider="google"))await s.commit()- personas["admin"] = User(- user_id=admin_db.id, email="a@x", name="A", provider="google"- )- personas["user"] = User(- user_id=user_db.id, email="u@x", name="U", provider="google"- )+ personas["admin"] = User(user_id=admin_db.id, email="a@x", name="A", provider="google")+ personas["user"] = User(user_id=user_db.id, email="u@x", name="U", provider="google")rbac = RBACService(SessionLocal)fastapi_app = FastAPI()@@ -113,9 +107,13 @@ async def app(monkeypatch):fastapi_app.dependency_overrides[get_rbac_service] = lambda: rbacfastapi_app.dependency_overrides[get_db_session] = _db_session- # Mount the admin router so we can hit a real require_permission gate.- from api.admin import rbac as admin_rbac- fastapi_app.include_router(admin_rbac.router)+ # Mount a minimal endpoint behind a real require_permission gate so the+ # kill switch can be exercised without depending on any specific router.+ from dependencies import require_permission++ @fastapi_app.get("/admin/users")+ async def _gated(_=Depends(require_permission("users:list"))):+ return []yield fastapi_app, SessionLocal, rbac, personasawait engine.dispose()@@ -126,7 +124,6 @@ async def test_kill_switch_bypasses_require_permission(app, monkeypatch):"""`user` persona has no admin role but DELETE /admin/users requires`users:delete`. Default = 403. With kill switch = 200/4xx-from-handler."""fastapi_app, _, _, personas = app- target_id = personas["admin"].user_id # arbitrary other idtransport = httpx.ASGITransport(app=fastapi_app)async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:@@ -192,6 +189,7 @@ async def test_me_returns_full_permission_catalog_when_disabled(app, monkeypatchmonkeypatch.setenv("OPENRAG_RBAC_ENFORCE", "false")from api import users as users_api+fastapi_app.include_router(users_api.router)transport = httpx.ASGITransport(app=fastapi_app)@@ -213,6 +211,7 @@ async def test_me_returns_only_user_perms_when_enforced(app, monkeypatch):monkeypatch.setenv("OPENRAG_RBAC_ENFORCE", "true")from api import users as users_api+fastapi_app.include_router(users_api.router)transport = httpx.ASGITransport(app=fastapi_app)diff --git a/tests/unit/dependencies/test_require_permission.py b/tests/unit/dependencies/test_require_permission.pyindex bb48deef0..719797f14 100644--- a/tests/unit/dependencies/test_require_permission.py+++ b/tests/unit/dependencies/test_require_permission.py@@ -39,7 +39,6 @@ from services.rbac_service import RBACService # noqa: E402from services.user_service import ensure_user_row # noqa: E402from session_manager import User # noqa: E402-# Map role-name -> User dataclass we hand to overridesPERSONAS: dict[str, User] = {}@@ -58,11 +57,11 @@ async def app(monkeypatch):PERSONAS.clear()async with SessionLocal() as s:await seed_roles_and_permissions(s)- # First user becomes admin (bootstrap rule)+ # Every user gets OPENRAG_DEFAULT_ROLE = "user"; promote personas+ # explicitly (no bootstrap-admin rule).admin_db = await ensure_user_row(s, User(user_id="admin-sub", email="[email protected]", name="A", provider="google"))- # Subsequent users get OPENRAG_DEFAULT_ROLE = "user"user_db = await ensure_user_row(s, User(user_id="user-sub", email="[email protected]", name="U", provider="google"))@@ -73,8 +72,12 @@ async def app(monkeypatch):)role_repo = RoleRepo(s)user_role = await role_repo.get_by_name("user")+ admin_role = await role_repo.get_by_name("admin")dev_role = await role_repo.get_by_name("developer")viewer_role = await role_repo.get_by_name("viewer")+ # Promote the admin persona from its default "user" role to "admin".+ await role_repo.revoke_role(admin_db.id, user_role.id)+ await role_repo.assign_role(admin_db.id, admin_role.id)await role_repo.revoke_role(dev_db.id, user_role.id)await role_repo.assign_role(dev_db.id, dev_role.id)@@ -102,12 +105,8 @@ async def app(monkeypatch):# require_permission's lookups via rbac.get_user_permissions(user.user_id)# resolve correctly. Note: User.user_id is the *DB id* here so the key# lookups (which use db_user.id) line up.- PERSONAS["admin"] = User(- user_id=admin_db.id, email="[email protected]", name="A", provider="google"- )- PERSONAS["user"] = User(- user_id=user_db.id, email="[email protected]", name="U", provider="google"- )+ PERSONAS["admin"] = User(user_id=admin_db.id, email="[email protected]", name="A", provider="google")+ PERSONAS["user"] = User(user_id=user_db.id, email="[email protected]", name="U", provider="google")PERSONAS["developer"] = User(user_id=dev_db.id, email="[email protected]", name="D", provider="google")@@ -155,7 +154,7 @@ async def app(monkeypatch):@app.post("/test/upload-context")async def upload_context_gate(- user=Depends(require_all_permissions(("knowledge:upload", "chat:use")))+ user=Depends(require_all_permissions(("knowledge:upload", "chat:use"))),):return JSONResponse({"user_id": user.user_id})diff --git a/tests/unit/services/test_jwt_roles.py b/tests/unit/services/test_jwt_roles.pynew file mode 100644index 000000000..dd357526a--- /dev/null+++ b/tests/unit/services/test_jwt_roles.py@@ -0,0 +1,100 @@+"""Unit tests for auth.jwt_roles.extract_jwt_role_names.++The helper is a pure function that reads env vars on each call, so we drive+it entirely with monkeypatch.setenv.+"""++import sys+from pathlib import Path++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))++from auth.jwt_roles import extract_jwt_role_names, jwt_roles_enabled # noqa: E402++[email protected](autouse=True)+def _default_role_env(monkeypatch):+ """Reset the role-claim mapping to a known shape for each test."""+ monkeypatch.setenv("OPENRAG_JWT_ROLES_CLAIM", "openrag_roles")+ monkeypatch.setenv("OPENRAG_ROLE_CLAIM_ADMIN", "admin")+ monkeypatch.setenv("OPENRAG_ROLE_CLAIM_DEVELOPER", "manager")+ monkeypatch.setenv("OPENRAG_ROLE_CLAIM_USER", "user")+ monkeypatch.delenv("OPENRAG_ROLE_CLAIM_VIEWER", raising=False)+++def test_empty_or_none_claims_returns_empty():+ assert extract_jwt_role_names(None) == []+ assert extract_jwt_role_names({}) == []+++def test_missing_claim_returns_empty():+ assert extract_jwt_role_names({"sub": "alice"}) == []+++def test_single_admin_role_mapped():+ assert extract_jwt_role_names({"openrag_roles": ["admin"]}) == ["admin"]+++def test_manager_claim_maps_to_developer_role():+ """The IdP sends "manager"; the operator maps that to OpenRAG developer."""+ assert extract_jwt_role_names({"openrag_roles": ["manager"]}) == ["developer"]+++def test_multiple_roles_preserve_order_and_dedup():+ result = extract_jwt_role_names({"openrag_roles": ["user", "admin", "user"]})+ assert result == ["user", "admin"]+++def test_unknown_claim_values_are_skipped(monkeypatch, caplog):+ result = extract_jwt_role_names({"openrag_roles": ["super-duper", "admin", "ghost"]})+ assert result == ["admin"]+++def test_string_value_is_rejected(caplog):+ """Strict shape: a string is NOT silently treated as a single role."""+ assert extract_jwt_role_names({"openrag_roles": "admin"}) == []+++def test_mixed_list_is_rejected():+ """If any element isn't a string, the whole claim is rejected."""+ assert extract_jwt_role_names({"openrag_roles": ["admin", 42]}) == []+++def test_dict_value_is_rejected():+ assert extract_jwt_role_names({"openrag_roles": {"role": "admin"}}) == []+++def test_empty_list_returns_empty():+ assert extract_jwt_role_names({"openrag_roles": []}) == []+++def test_custom_claim_name(monkeypatch):+ monkeypatch.setenv("OPENRAG_JWT_ROLES_CLAIM", "groups")+ assert extract_jwt_role_names({"groups": ["admin"], "openrag_roles": []}) == ["admin"]+++def test_one_claim_value_maps_to_two_openrag_roles(monkeypatch):+ """When the IdP only ships 3 role values, the operator can route a single+ claim value (here "user") to both the OpenRAG user and viewer roles."""+ monkeypatch.setenv("OPENRAG_ROLE_CLAIM_VIEWER", "user")+ result = extract_jwt_role_names({"openrag_roles": ["user"]})+ # Order: user comes first because admin/developer/user/viewer iteration+ # places user's bucket before viewer's.+ assert set(result) == {"user", "viewer"}+++def test_viewer_unmapped_means_unreachable():+ """Without OPENRAG_ROLE_CLAIM_VIEWER set, the JWT cannot grant viewer."""+ assert extract_jwt_role_names({"openrag_roles": ["viewer"]}) == []+++def test_jwt_roles_enabled_tracks_rbac_enforce(monkeypatch):+ monkeypatch.setenv("OPENRAG_RBAC_ENFORCE", "false")+ assert jwt_roles_enabled() is False+ monkeypatch.setenv("OPENRAG_RBAC_ENFORCE", "true")+ assert jwt_roles_enabled() is Truediff --git a/tests/unit/services/test_rbac_service.py b/tests/unit/services/test_rbac_service.pyindex 3b19b5651..65d9fda9a 100644--- a/tests/unit/services/test_rbac_service.py+++ b/tests/unit/services/test_rbac_service.py@@ -36,6 +36,10 @@ async def setup():admin_user = await ensure_user_row(s, User(user_id="admin-sub", email="[email protected]", name="A", provider="google"))+ # No bootstrap-admin anymore — grant admin explicitly.+ role_repo = RoleRepo(s)+ admin_role = await role_repo.get_by_name("admin")+ await role_repo.assign_role(admin_user.id, admin_role.id)end_user = await ensure_user_row(s, User(user_id="user-sub", email="[email protected]", name="U", provider="google"))diff --git a/tests/unit/services/test_user_service_bootstrap.py b/tests/unit/services/test_user_service_bootstrap.pyindex d2a357f78..079647f77 100644--- a/tests/unit/services/test_user_service_bootstrap.py+++ b/tests/unit/services/test_user_service_bootstrap.py@@ -1,4 +1,4 @@-"""ensure_user_row: first user becomes admin; subsequent users get default role."""+"""ensure_user_row: every user gets the env default role (no bootstrap-admin)."""import sysfrom pathlib import Path@@ -41,17 +41,19 @@ def _user(uid="u1", email="[email protected]", name="A", provider="google"):@pytest.mark.asyncio-async def test_first_user_becomes_admin(session):+async def test_first_user_gets_default_role(session, monkeypatch):+ """No bootstrap-admin: even the first user gets the env default role."""+ monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "user")row = await ensure_user_row(session, _user(uid="oauth-1"))await session.commit()role_repo = RoleRepo(session)roles = await role_repo.list_user_roles(row.id)- assert {r.name for r in roles} == {"admin"}+ assert {r.name for r in roles} == {"user"}@pytest.mark.asyncio-async def test_second_user_gets_default_role(session, monkeypatch):+async def test_all_users_get_default_role(session, monkeypatch):monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "user")first = await ensure_user_row(session, _user(uid="oauth-1", email="[email protected]"))second = await ensure_user_row(session, _user(uid="oauth-2", email="[email protected]"))@@ -60,12 +62,23 @@ async def test_second_user_gets_default_role(session, monkeypatch):role_repo = RoleRepo(session)first_roles = {r.name for r in await role_repo.list_user_roles(first.id)}second_roles = {r.name for r in await role_repo.list_user_roles(second.id)}- assert first_roles == {"admin"}+ assert first_roles == {"user"}assert second_roles == {"user"}@pytest.mark.asyncio-async def test_repeated_calls_are_idempotent(session):+async def test_default_role_is_configurable(session, monkeypatch):+ """An oss operator who wants an admin sets OPENRAG_DEFAULT_ROLE=admin."""+ monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "admin")+ row = await ensure_user_row(session, _user(uid="oauth-1"))+ await session.commit()+ roles = {r.name for r in await RoleRepo(session).list_user_roles(row.id)}+ assert roles == {"admin"}+++async def test_repeated_calls_are_idempotent(session, monkeypatch):+ monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "user")a = await ensure_user_row(session, _user(uid="oauth-1"))b = await ensure_user_row(session, _user(uid="oauth-1"))await session.commit()@@ -73,16 +86,14 @@ async def test_repeated_calls_are_idempotent(session):assert a.id == b.idrole_repo = RoleRepo(session)roles = await role_repo.list_user_roles(a.id)- assert {r.name for r in roles} == {"admin"}+ assert {r.name for r in roles} == {"user"}@pytest.mark.asyncioasync def test_new_user_id_matches_oauth_subject(session):"""Regression: the SQL users.id must equal the OAuth subject sorequire_permission can use the JWT sub directly (no extra lookup)."""- row = await ensure_user_row(- session, _user(uid="oauth-subject-xyz", email="[email protected]")- )+ row = await ensure_user_row(session, _user(uid="oauth-subject-xyz", email="[email protected]"))await session.commit()assert row.id == "oauth-subject-xyz"assert row.oauth_subject == "oauth-subject-xyz"@@ -91,13 +102,15 @@ async def test_new_user_id_matches_oauth_subject(session):@pytest.mark.asyncioasync def test_legacy_user_merges_on_real_signin(session, monkeypatch):monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "user")- # Pre-seed first admin so the legacy merge does NOT take admin.+ # Pre-seed an existing user; the legacy merge below should still get the+ # env default role, not anything special.await ensure_user_row(session, _user(uid="oauth-admin", email="[email protected]"))await session.commit()# Pretend a JSON migration inserted a legacy row keyed by a GA user_id.from db.models import User as UserRowfrom db.repositories._helpers import email_lookup_hash+legacy = UserRow(id="legacy-123",oauth_provider="legacy",diff --git a/tests/unit/services/test_user_service_jwt_roles.py b/tests/unit/services/test_user_service_jwt_roles.pynew file mode 100644index 000000000..f0198b900--- /dev/null+++ b/tests/unit/services/test_user_service_jwt_roles.py@@ -0,0 +1,163 @@+"""ensure_user_row with jwt_roles: JWT is authoritative.++Verifies:+* Brand-new user with jwt_roles=["admin"] becomes admin.+* Existing user re-syncs roles on subsequent calls: revokes roles the JWT+ no longer carries, adds new ones.+* jwt_roles=None falls back to the env default role (no bootstrap-admin);+ the anonymous user gets OPENRAG_NOAUTH_ROLE.+* Unknown role names in the JWT are skipped (logged, not assigned).+"""++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 seed_roles_and_permissions # noqa: E402+from services.user_service import ensure_user_row, sync_jwt_roles # 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)+ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)+ async with SessionLocal() as s:+ await seed_roles_and_permissions(s)+ await s.commit()+ yield s+ await engine.dispose()+++def _user(uid="u1", email="[email protected]", name="A", provider="ibm_ams"):+ return User(user_id=uid, email=email, name=name, provider=provider)+++async def test_new_user_with_jwt_roles_skips_bootstrap(session):+ """JWT-sourced role: first user gets exactly what the JWT says, not+ the bootstrap admin shortcut."""+ row = await ensure_user_row(session, _user(uid="oauth-1"), jwt_roles=["user"])+ await session.commit()++ roles = {r.name for r in await RoleRepo(session).list_user_roles(row.id)}+ assert roles == {"user"}, "bootstrap-admin must not fire when JWT roles supplied"+++async def test_new_user_with_jwt_admin_becomes_admin(session):+ row = await ensure_user_row(session, _user(uid="oauth-1"), jwt_roles=["admin"])+ await session.commit()+ roles = {r.name for r in await RoleRepo(session).list_user_roles(row.id)}+ assert roles == {"admin"}+++async def test_existing_user_role_set_reconciled_on_relogin(session):+ """Login 1: admin+user. Login 2: just user. Admin is revoked."""+ user = _user(uid="oauth-1")+ row = await ensure_user_row(session, user, jwt_roles=["admin", "user"])+ await session.commit()+ assert {r.name for r in await RoleRepo(session).list_user_roles(row.id)} == {+ "admin",+ "user",+ }++ # Second login — JWT now carries only "user"+ again = await ensure_user_row(session, user, jwt_roles=["user"])+ await session.commit()+ assert again.id == row.id+ assert {r.name for r in await RoleRepo(session).list_user_roles(row.id)} == {"user"}+++async def test_jwt_roles_none_assigns_default_role(session, monkeypatch):+ """When jwt_roles is None, the user gets OPENRAG_DEFAULT_ROLE — there is+ no first-user-becomes-admin bootstrap."""+ monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "user")+ row = await ensure_user_row(session, _user(uid="oauth-1"))+ await session.commit()+ roles = {r.name for r in await RoleRepo(session).list_user_roles(row.id)}+ assert roles == {"user"}+++async def test_anonymous_user_gets_noauth_role(session, monkeypatch):+ """The synthetic anonymous user gets OPENRAG_NOAUTH_ROLE (default admin)."""+ monkeypatch.setenv("OPENRAG_NOAUTH_ROLE", "admin")+ row = await ensure_user_row(+ session, _user(uid="anonymous", email="anonymous@localhost", provider="none")+ )+ await session.commit()+ roles = {r.name for r in await RoleRepo(session).list_user_roles(row.id)}+ assert roles == {"admin"}+++async def test_unknown_role_names_skipped(session):+ """JWT carrying a role that doesn't exist in the roles table is ignored."""+ row = await ensure_user_row(session, _user(uid="oauth-1"), jwt_roles=["admin", "nonexistent"])+ await session.commit()+ roles = {r.name for r in await RoleRepo(session).list_user_roles(row.id)}+ assert roles == {"admin"}+++async def test_sync_jwt_roles_standalone(session, monkeypatch):+ """The public sync_jwt_roles entry point reconciles without creating+ the user row — covers the dependency-cache fast path."""+ monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "user")+ # Pre-create a user with the env default role.+ row = await ensure_user_row(session, _user(uid="oauth-1"))+ await session.commit()+ assert {r.name for r in await RoleRepo(session).list_user_roles(row.id)} == {"user"}++ # Now reconcile to "admin" through the standalone helper.+ await sync_jwt_roles(session, row.id, ["admin"])+ await session.commit()+ assert {r.name for r in await RoleRepo(session).list_user_roles(row.id)} == {"admin"}+++async def test_rbac_off_with_no_claim_assigns_default_role(session, monkeypatch):+ """Regression: when RBAC is disabled and the IBM JWT carries no roles+ claim, ``_get_ibm_user`` leaves jwt_roles=None so ensure_user_row falls+ back to the env default role (no bootstrap-admin). Verified here by+ passing jwt_roles=None — what the auth handler sets when+ jwt_roles_enabled() returns False."""+ monkeypatch.setenv("OPENRAG_DEFAULT_ROLE", "user")+ row = await ensure_user_row(session, _user(uid="oauth-1"), jwt_roles=None)+ await session.commit()+ roles = {r.name for r in await RoleRepo(session).list_user_roles(row.id)}+ assert roles == {"user"}, "RBAC-off path assigns the env default role"+++async def test_empty_jwt_roles_list_revokes_all(session):+ """JWT-side decision: an explicit empty list (caller chose to pass it+ through) revokes every role. (In practice _get_ibm_user 401s before+ reaching this code path when the list is empty and RBAC is enforced.)"""+ user = _user(uid="oauth-1")+ row = await ensure_user_row(session, user, jwt_roles=["admin"])+ await session.commit()+ assert {r.name for r in await RoleRepo(session).list_user_roles(row.id)} == {"admin"}++ await ensure_user_row(session, user, jwt_roles=[])+ await session.commit()+ assert await RoleRepo(session).list_user_roles(row.id) == []