Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(web-studio): add resource permission management (#5329)
yufeng54dcc6987217
diff --git a/web-studio/src/components/account-acl-settings.test.tsx b/web-studio/src/components/account-acl-settings.test.tsxnew file mode 100644index 000000000..f00975336--- /dev/null+++ b/web-studio/src/components/account-acl-settings.test.tsx@@ -0,0 +1,79 @@+// @vitest-environment jsdom+import { beforeEach, afterEach, expect, it, vi } from 'vitest'+import { cleanup, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { AccountAclSettings } from './account-acl-settings'++const mocks = vi.hoisted(() => ({+ update: vi.fn(),+ enabled: false,+ allowed: true,+}))+vi.mock('#/hooks/use-acl-management', () => ({+ useAclManagement: () => ({+ allowed: mocks.allowed,+ api: { setEnabled: mocks.update },+ settingsKey: ['account-acl', 'acme'],+ connection: { accountId: 'acme' },+ settings: { data: mocks.enabled, isSuccess: true, isFetching: false },+ }),+}))+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}))+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))+beforeEach(() => {+ vi.resetAllMocks()+ mocks.enabled = false+ mocks.allowed = true+ mocks.update.mockResolvedValue(true)+})+afterEach(cleanup)+function mount() {+ const client = new QueryClient()+ render(+ <QueryClientProvider client={client}>+ <AccountAclSettings />+ </QueryClientProvider>,+ )+ return userEvent.setup()+}+it('requires confirmation before enabling account ACL', async () => {+ const user = mount()+ await user.click(screen.getByRole('button', { name: 'acl.enableAction' }))+ expect(screen.getByText('acl.enableWarning')).toBeTruthy()+ expect(mocks.update).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: 'acl.confirm' }))+ await waitFor(() => expect(mocks.update).toHaveBeenCalledWith(true))+})+it('explains expanded access on disable and cancellation leaves settings unchanged', async () => {+ mocks.enabled = true+ const user = mount()+ await user.click(screen.getByRole('button', { name: 'acl.disableAction' }))+ expect(screen.getByText('acl.disableWarning')).toBeTruthy()+ await user.click(screen.getByRole('button', { name: 'actions.cancel' }))+ expect(mocks.update).not.toHaveBeenCalled()+})+it('does not show account controls to non-administrators', () => {+ mocks.allowed = false+ mount()+ expect(screen.queryByRole('button', { name: 'acl.enableAction' })).toBeNull()+})+it('opens advanced controls on hover and keeps confirmation available after leaving', async () => {+ mocks.enabled = true+ const client = new QueryClient()+ const user = userEvent.setup()+ render(+ <QueryClientProvider client={client}>+ <AccountAclSettings inPopover />+ </QueryClientProvider>,+ )+ const trigger = screen.getByRole('button', { name: 'acl.page.advanced' })+ await user.hover(trigger)+ await user.click(+ await screen.findByRole('button', { name: 'acl.disableAction' }),+ )+ await user.unhover(trigger)+ expect(screen.getByRole('button', { name: 'acl.confirm' })).toBeTruthy()+})diff --git a/web-studio/src/components/account-acl-settings.tsx b/web-studio/src/components/account-acl-settings.tsxnew file mode 100644index 000000000..a16d5aec6--- /dev/null+++ b/web-studio/src/components/account-acl-settings.tsx@@ -0,0 +1,166 @@+import { useState } from 'react'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { Settings2Icon } from 'lucide-react'+import { useAclManagement } from '#/hooks/use-acl-management'+import { Button } from '#/components/ui/button'+import { Alert, AlertTitle, AlertDescription } from '#/components/ui/alert'+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogCancel,+ AlertDialogAction,+} from '#/components/ui/alert-dialog'+import { getErrorMessage } from '#/routes/users/-lib/error'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '#/components/ui/popover'++export function AccountAclSettings({+ inPopover = false,+}: {+ inPopover?: boolean+}) {+ const state = useAclManagement()+ if (!state.allowed) return null+ return (+ <AccountAclControl+ key={JSON.stringify(state.settingsKey)}+ state={state}+ inPopover={inPopover}+ />+ )+}+function AccountAclControl({+ state,+ inPopover,+}: {+ state: ReturnType<typeof useAclManagement>+ inPopover: boolean+}) {+ const { t } = useTranslation('settings')+ const client = useQueryClient()+ const [next, setNext] = useState<boolean | null>(null)+ const update = useMutation({+ mutationFn: (enabled: boolean) => state.api.setEnabled(enabled),+ onSuccess: async (enabled) => {+ client.setQueryData(state.settingsKey, enabled)+ setNext(null)+ toast.success(t('acl.saved'))+ await client.invalidateQueries()+ },+ onError: (error) =>+ toast.error(t('acl.failed'), { description: getErrorMessage(error) }),+ })+ const controls = (+ <>+ <p>{t('acl.accountHint')}</p>+ {state.settings.isError ? (+ <>+ <p role="alert">+ {t('acl.failed')}: {getErrorMessage(state.settings.error)}+ </p>+ <Button+ variant="outline"+ onClick={() => void state.settings.refetch()}+ >+ {t('actions.refresh')}+ </Button>+ </>+ ) : (+ <Button+ variant={state.settings.data ? 'outline' : 'default'}+ size="sm"+ disabled={+ !state.settings.isSuccess ||+ state.settings.isFetching ||+ update.isPending+ }+ onClick={() => setNext(!state.settings.data)}+ >+ {state.settings.isPending+ ? t('loading')+ : t(state.settings.data ? 'acl.disableAction' : 'acl.enableAction')}+ </Button>+ )}+ </>+ )+ return (+ <>+ {inPopover ? (+ <Popover>+ <PopoverTrigger+ openOnHover+ delay={150}+ closeDelay={150}+ render={<Button variant="ghost" size="sm" />}+ >+ <Settings2Icon data-icon="inline-start" />+ {t('acl.page.advanced')}+ </PopoverTrigger>+ <PopoverContent+ align="end"+ sideOffset={8}+ className="w-[min(22rem,calc(100vw-2rem))] gap-3"+ >+ <div className="font-medium">+ {t('acl.accountTitle', { account: state.connection.accountId })}+ </div>+ <div className="flex flex-col items-start gap-3 text-xs text-muted-foreground">+ {controls}+ </div>+ </PopoverContent>+ </Popover>+ ) : (+ <Alert className="bg-transparent">+ <AlertTitle>+ {t('acl.accountTitle', { account: state.connection.accountId })}+ </AlertTitle>+ <AlertDescription className="flex flex-col items-start gap-3">+ {controls}+ </AlertDescription>+ </Alert>+ )}+ <AlertDialog+ open={next !== null}+ onOpenChange={(open) => {+ if (!open && !update.isPending) setNext(null)+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t(next ? 'acl.enableTitle' : 'acl.disableTitle')}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t(next ? 'acl.enableWarning' : 'acl.disableWarning', {+ account: state.connection.accountId,+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={update.isPending}>+ {t('actions.cancel')}+ </AlertDialogCancel>+ <AlertDialogAction+ disabled={update.isPending}+ onClick={(event) => {+ event.preventDefault()+ if (next !== null) update.mutate(next)+ }}+ >+ {update.isPending ? t('loading') : t('acl.confirm')}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ )+}diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsxindex c38504465..90dab39fd 100644--- a/web-studio/src/components/app-shell.tsx+++ b/web-studio/src/components/app-shell.tsx@@ -314,7 +314,7 @@ function AppShellInner({ children }: { children: React.ReactNode }) {const { connection, connectionRole, isConnectionRoleLoading, serverMode } =useAppConnection()const settingsActive = pathname === '/settings'- const usersActive = pathname === '/users'+ const usersActive = pathname === '/users' || pathname.startsWith('/users/')const { canManageUsers } = resolveStudioManagementCapabilities({hasControlCredential: Boolean(connection.adminApiKey.trim()),isRoleLoading: isConnectionRoleLoading,diff --git a/web-studio/src/components/resource-acl-identity-recovery.tsx b/web-studio/src/components/resource-acl-identity-recovery.tsxnew file mode 100644index 000000000..810126aa4--- /dev/null+++ b/web-studio/src/components/resource-acl-identity-recovery.tsx@@ -0,0 +1,172 @@+import { useState } from 'react'+import { Link } from '@tanstack/react-router'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { useAclManagement } from '#/hooks/use-acl-management'+import { fetchAdminUsers } from '#/lib/admin'+import { Button } from '#/components/ui/button'+import { Input } from '#/components/ui/input'+import { Field, FieldLabel } from '#/components/ui/field'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '#/components/ui/select'+import { getErrorMessage } from '#/routes/users/-lib/error'++export function ResourceAclIdentityRecovery({+ onRetry,+ error,+}: {+ onRetry?: () => void+ error?: string+} = {}) {+ const { t } = useTranslation('settings')+ const state = useAclManagement(false)+ const [selectedId, setSelectedId] = useState('')+ const [apiKey, setApiKey] = useState('')+ const [switching, setSwitching] = useState(false)+ const users = useQuery({+ queryKey: ['acl-admin-identities', state.identityScopeKey],+ queryFn: () =>+ fetchAdminUsers(state.adminConnection, state.connection.accountId),+ enabled: state.allowed,+ retry: false,+ })+ const admins = users.data?.filter((user) => user.role === 'admin') ?? []+ const effectiveSelectedId = selectedId || admins[0]?.userId || ''+ const selected = admins.find((user) => user.userId === effectiveSelectedId)+ const trusted = state.serverMode === 'trusted'+ const switchSupported = trusted || state.serverMode === 'api_key'+ const needsKey = selected && !trusted && !selected.apiKey++ async function switchUser() {+ if (!selected || !switchSupported) return+ setSwitching(true)+ try {+ await state.switchIdentity({+ accountId: state.connection.accountId,+ userId: selected.userId,+ apiKey: trusted ? '' : selected.apiKey || apiKey.trim(),+ allowLegacyIdentityFallback: true,+ })+ setApiKey('')+ toast.success(t('acl.recovery.switched'))+ } catch (switchError) {+ toast.error(t('acl.recovery.switchFailed'), {+ description: getErrorMessage(switchError),+ })+ } finally {+ setSwitching(false)+ }+ }++ return (+ <section className="mx-auto flex max-w-lg flex-col gap-3 py-8">+ <h2 className="font-medium">{t('acl.recovery.title')}</h2>+ <p className="text-sm text-muted-foreground">+ {t('acl.recovery.description')}+ </p>+ <details className="text-xs text-muted-foreground">+ <summary className="cursor-pointer">+ {t('acl.recovery.scopeTitle')}+ </summary>+ <p className="mt-1">{t('acl.recovery.scope')}</p>+ </details>+ {!switchSupported ? (+ <p className="text-sm">{t('acl.recovery.unsupported')}</p>+ ) : users.isPending ? (+ <p role="status">{t('loading')}</p>+ ) : users.isError ? (+ <>+ <p role="alert">{t('acl.recovery.loadFailed')}</p>+ <details className="text-sm text-muted-foreground">+ <summary>{t('acl.recovery.details')}</summary>+ <p className="mt-2 break-all">{getErrorMessage(users.error)}</p>+ </details>+ <Button variant="outline" onClick={() => void users.refetch()}>+ {t('actions.refresh')}+ </Button>+ </>+ ) : admins.length === 0 ? (+ <p className="text-sm">{t('acl.recovery.noAdmins')}</p>+ ) : (+ <>+ <Field>+ <FieldLabel>{t('acl.recovery.admin')}</FieldLabel>+ <Select+ value={effectiveSelectedId}+ onValueChange={(value) => {+ setSelectedId(value ?? '')+ setApiKey('')+ }}+ >+ <SelectTrigger+ disabled={switching}+ aria-label={t('acl.recovery.admin')}+ >+ <SelectValue placeholder={t('acl.recovery.selectAdmin')}>+ {effectiveSelectedId || t('acl.recovery.selectAdmin')}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {admins.map((admin) => (+ <SelectItem key={admin.userId} value={admin.userId}>+ {admin.userId}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ {needsKey && (+ <Field>+ <FieldLabel htmlFor="acl-admin-key">+ {t('acl.recovery.key')}+ </FieldLabel>+ <Input+ id="acl-admin-key"+ type="password"+ autoComplete="off"+ value={apiKey}+ disabled={switching}+ onChange={(event) => setApiKey(event.target.value)}+ />+ <p className="text-sm text-muted-foreground">+ {t('acl.recovery.keyHint')}+ </p>+ </Field>+ )}+ <Button+ disabled={+ !selected || switching || Boolean(needsKey && !apiKey.trim())+ }+ onClick={() => void switchUser()}+ >+ {t(switching ? 'acl.recovery.switching' : 'acl.recovery.switch')}+ </Button>+ </>+ )}+ {admins.length === 0 && (+ <Link to="/users" className="text-sm underline">+ {t('acl.recovery.users')}+ </Link>+ )}+ {onRetry && (+ <Button variant="outline" onClick={onRetry}>+ {t('acl.recovery.retryAccess')}+ </Button>+ )}+ {error && (+ <details className="text-sm text-muted-foreground">+ <summary className="cursor-pointer">+ {t('acl.recovery.details')}+ </summary>+ <p className="mt-2 break-all">{error}</p>+ </details>+ )}+ </section>+ )+}diff --git a/web-studio/src/components/resource-permissions.test.tsx b/web-studio/src/components/resource-permissions.test.tsxnew file mode 100644index 000000000..f1fcd217d--- /dev/null+++ b/web-studio/src/components/resource-permissions.test.tsx@@ -0,0 +1,374 @@+// @vitest-environment jsdom+import { beforeEach, afterEach, expect, it, vi } from 'vitest'+import {+ cleanup,+ render,+ screen,+ waitFor,+ within,+} from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from '@tanstack/react-router'+import { ResourcePermissionsPanel } from './resource-permissions'+import { OvClientError } from '#/lib/ov-client'+import type { AclReport } from '#/lib/resource-acl'++const mocks = vi.hoisted(() => ({+ get: vi.fn(),+ change: vi.fn(),+ allowed: true,+ enabled: true,+ account: 'acme',+ identity: 'identity-acme',+ users: vi.fn(),+ groups: vi.fn(),+ admins: vi.fn(),+ switchIdentity: vi.fn(),+ serverMode: 'api_key',+}))+vi.mock('#/hooks/use-acl-management', () => ({+ useAclManagement: () => ({+ api: { get: mocks.get, change: mocks.change },+ serverMode: mocks.serverMode,+ switchIdentity: mocks.switchIdentity,+ allowed: mocks.allowed,+ settings: { data: mocks.enabled, isSuccess: true, isFetching: false },+ settingsKey: ['account-acl', mocks.account],+ connection: {+ userId: 'alice',+ accountId: mocks.account,+ baseUrl: 'http://localhost',+ adminApiKey: 'admin',+ },+ adminConnection: { accountId: mocks.account },+ identityScopeKey: mocks.identity,+ aclIdentityScopeKey: mocks.identity,+ useAccountAdminCredential: false,+ }),+}))+vi.mock('./account-acl-settings', () => ({ AccountAclSettings: () => null }))+vi.mock('#/lib/admin', () => ({+ fetchAdminUsersPage: mocks.users,+ fetchAdminUsers: mocks.admins,+ fetchAdminGroups: mocks.groups,+}))+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { count?: number; level?: string }) =>+ key === 'acl.confirmGrant'+ ? `${key}:${options?.count}:${options?.level}`+ : key === 'acl.confirmEveryoneGrant'+ ? `${key}:${options?.level}`+ : key,+ }),+}))+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))+const uri = 'viking://resources/project'+let report: AclReport+beforeEach(() => {+ vi.resetAllMocks()+ mocks.allowed = true+ mocks.enabled = true+ mocks.account = 'acme'+ mocks.identity = 'identity-acme'+ mocks.serverMode = 'api_key'+ mocks.admins.mockResolvedValue([+ { userId: 'owner', role: 'admin', apiKey: 'user-key' },+ { userId: 'root', role: 'root' },+ ])+ report = {+ uri,+ acl_mode: 'inherit',+ direct_entries: [{ principal: 'user:bob', level: 'read' }],+ inherited_entries: [{ principal: 'group:engineering', level: 'write' }],+ effective_entries: [],+ }+ mocks.get.mockImplementation(async () => report)+ mocks.change.mockImplementation(async (_uri, change) => {+ report = {+ ...report,+ ...(change.kind === 'mode'+ ? { acl_mode: change.mode }+ : { direct_entries: [] }),+ }+ return report+ })+ mocks.users.mockResolvedValue({ users: [{ userId: 'bob' }], total: 1 })+ mocks.groups.mockResolvedValue([{ group_id: 'engineering', member_count: 1 }])+})+afterEach(cleanup)+function mount() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ const router = createRouter({+ basepath: '/studio',+ history: createMemoryHistory({ initialEntries: ['/studio/'] }),+ routeTree: createRootRoute({+ component: () => (+ <QueryClientProvider client={client}>+ <ResourcePermissionsPanel uri={uri} />+ </QueryClientProvider>+ ),+ }),+ })+ const view = render(<RouterProvider router={router} />)+ return { ...view, client, user: userEvent.setup() }+}+it('keeps the no-admin recovery link inside the Studio base path', async () => {+ mocks.admins.mockResolvedValue([])+ mocks.get.mockRejectedValue(+ new OvClientError({+ code: 'PERMISSION_DENIED',+ message: 'Denied',+ statusCode: 403,+ }),+ )+ mount()+ const link = await screen.findByRole('link', { name: 'acl.recovery.users' })+ expect(link.getAttribute('href')).toBe('/studio/users')+})+it('shows current access and source of each grant without explanatory panels', async () => {+ mount()+ await screen.findByText('bob')+ expect(screen.getByText(/acl.subjects.user/)).toBeTruthy()+ expect(screen.getByText('acl.levels.read')).toBeTruthy()+ expect(screen.getByText('acl.peopleWithAccess')).toBeTruthy()+ expect(screen.getByText('engineering')).toBeTruthy()+ expect(screen.getByText(/acl.inheritedSource/)).toBeTruthy()+ expect(screen.queryByText('acl.page.grantScope')).toBeNull()+})+it('shows default sharing as the effective access when no ACL is configured', async () => {+ report = {+ ...report,+ acl_mode: 'none',+ direct_entries: [],+ inherited_entries: [],+ }+ mount()+ await screen.findByText('acl.everyone')+ expect(screen.getByText('acl.defaultRule')).toBeTruthy()+ expect(screen.queryByText('acl.onlyAdmins')).toBeNull()+ expect(screen.queryByRole('button', { name: 'acl.addGrant' })).toBeNull()+ expect(screen.getByRole('button', { name: 'acl.limitAccess' })).toBeTruthy()+})+it('confirms direct removal and preserves inherited permissions in the display', async () => {+ const { user } = mount()+ await screen.findByText('bob')+ await user.click(screen.getByRole('button', { name: 'acl.remove' }))+ expect(mocks.change).not.toHaveBeenCalled()+ await user.click(+ within(screen.getByRole('alertdialog')).getByRole('button', {+ name: 'acl.confirm',+ }),+ )+ await waitFor(() =>+ expect(mocks.change).toHaveBeenCalledWith(uri, {+ kind: 'revoke',+ principal: 'user:bob',+ }),+ )+ expect(screen.getByText('engineering')).toBeTruthy()+})+it('keeps restricted grants without showing the parent-inheritance control', async () => {+ report = { ...report, acl_mode: 'restricted' }+ mount()+ await screen.findByText('bob')+ expect(screen.queryByText(/acl.parentGrantsLabel/)).toBeNull()+ expect(screen.queryByRole('button', { name: 'acl.includeParent' })).toBeNull()+ expect(screen.queryByRole('button', { name: 'acl.excludeParent' })).toBeNull()+ expect(screen.queryByText('engineering')).toBeNull()+})+it('does not permit editing when account ACL is disabled', async () => {+ mocks.enabled = false+ mount()+ await screen.findByText('bob')+ expect(+ screen.getByRole('button', { name: 'acl.remove' }).hasAttribute('disabled'),+ ).toBe(true)+ expect(+ screen+ .getByRole('button', { name: 'acl.addGrant' })+ .hasAttribute('disabled'),+ ).toBe(true)+ expect(mocks.users).not.toHaveBeenCalled()+})+it('shows a local request error and retries without affecting the resource page', async () => {+ mocks.get.mockRejectedValueOnce(new Error('Network unavailable'))+ const { user } = mount()+ await screen.findByText('Network unavailable')+ await user.click(screen.getByRole('button', { name: 'actions.refresh' }))+ await screen.findByText('bob')+})+it('grants edit permission to a selected account group', async () => {+ const { user } = mount()+ await screen.findByText('bob')+ await user.click(screen.getByRole('button', { name: 'acl.addGrant' }))+ await user.click(screen.getByRole('button', { name: 'acl.subjects.group' }))+ await waitFor(() => expect(mocks.groups).toHaveBeenCalled())+ await user.click(screen.getByRole('button', { name: 'engineering' }))+ await user.click(screen.getByRole('button', { name: 'acl.levels.write' }))+ await user.click(+ screen.getByRole('button', {+ name: 'acl.confirmGrant:1:acl.levels.write',+ }),+ )+ await waitFor(() =>+ expect(mocks.change).toHaveBeenCalledWith(uri, {+ kind: 'grant',+ principal: 'group:engineering',+ level: 'write',+ }),+ )+})+it('selects multiple users and grants the same level to each', async () => {+ mocks.users.mockResolvedValue({+ users: [{ userId: 'bob' }, { userId: 'carol' }],+ total: 2,+ })+ const { user } = mount()+ await screen.findByText('bob')+ await user.click(screen.getByRole('button', { name: 'acl.addGrant' }))+ await user.click(await screen.findByRole('button', { name: 'carol' }))+ await user.click(screen.getByRole('button', { name: 'bob' }))+ await user.click(screen.getByRole('button', { name: 'acl.levels.write' }))+ await user.click(+ screen.getByRole('button', {+ name: 'acl.confirmGrant:2:acl.levels.write',+ }),+ )+ await waitFor(() => expect(mocks.change).toHaveBeenCalledTimes(2))+ expect(mocks.change.mock.calls.map(([, change]) => change)).toEqual([+ { kind: 'grant', principal: 'user:carol', level: 'write' },+ { kind: 'grant', principal: 'user:bob', level: 'write' },+ ])+})+it('adds permissions within the same panel and returns to the grant list', async () => {+ const { user } = mount()+ await screen.findByText('bob')+ await user.click(screen.getByRole('button', { name: 'acl.addGrant' }))+ expect(screen.queryByRole('dialog')).toBeNull()+ expect(screen.getByRole('button', { name: 'acl.backToGrants' })).toBeTruthy()+ expect(screen.getByRole('group', { name: 'acl.level' })).toBeTruthy()+ await user.click(+ screen.getByRole('button', { name: 'acl.subjects.everyoneShort' }),+ )+ expect(screen.getByRole('group', { name: 'acl.level' })).toBeTruthy()+ await user.click(screen.getByRole('button', { name: 'acl.backToGrants' }))+ expect(screen.getByText('bob')).toBeTruthy()+ expect(screen.queryByRole('button', { name: /acl.confirmGrant/ })).toBeNull()+})+it('grants permission to all account users without selecting a candidate', async () => {+ const { user } = mount()+ await screen.findByText('bob')+ await user.click(screen.getByRole('button', { name: 'acl.addGrant' }))+ await user.click(+ screen.getByRole('button', { name: 'acl.subjects.everyoneShort' }),+ )+ expect(screen.queryByLabelText('acl.search')).toBeNull()+ await user.click(+ screen.getByRole('button', {+ name: 'acl.confirmEveryoneGrant:acl.levels.read',+ }),+ )+ await waitFor(() =>+ expect(mocks.change).toHaveBeenCalledWith(uri, {+ kind: 'grant',+ principal: 'user:*',+ level: 'read',+ }),+ )+})++it('offers an existing account admin after a 403 without changing grants', async () => {+ mocks.get.mockRejectedValue(+ new OvClientError({+ code: 'PERMISSION_DENIED',+ message: 'ACL management denied',+ statusCode: 403,+ }),+ )+ const { user } = mount()+ expect(+ await screen.findByRole('combobox', { name: 'acl.recovery.admin' }),+ ).toBeTruthy()+ expect(+ screen.getByRole('combobox', { name: 'acl.recovery.admin' }).textContent,+ ).toContain('owner')+ expect(screen.queryByRole('option', { name: 'root' })).toBeNull()+ expect(screen.queryByText('acl.loadFailed')).toBeNull()+ expect(mocks.switchIdentity).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: 'acl.recovery.switch' }))+ await waitFor(() =>+ expect(mocks.switchIdentity).toHaveBeenCalledWith({+ accountId: 'acme',+ userId: 'owner',+ apiKey: 'user-key',+ allowLegacyIdentityFallback: true,+ }),+ )+ expect(mocks.change).not.toHaveBeenCalled()+})+it('requires a user key when the admin key is unavailable', async () => {+ mocks.admins.mockResolvedValue([{ userId: 'owner', role: 'admin' }])+ mocks.get.mockRejectedValue(+ new OvClientError({+ code: 'PERMISSION_DENIED',+ message: 'Denied',+ statusCode: 403,+ }),+ )+ const { user } = mount()+ await screen.findByRole('combobox', { name: 'acl.recovery.admin' })+ const button = screen.getByRole('button', { name: 'acl.recovery.switch' })+ expect(button.hasAttribute('disabled')).toBe(true)+ await user.type(+ screen.getByLabelText('acl.recovery.key'),+ 'existing-user-key',+ )+ await user.click(button)+ await waitFor(() =>+ expect(mocks.switchIdentity).toHaveBeenCalledWith(+ expect.objectContaining({ apiKey: 'existing-user-key' }),+ ),+ )+})+it('does not suggest switching identities for a network error', async () => {+ mocks.get.mockRejectedValue(new Error('Network unavailable'))+ mount()+ await screen.findByText('Network unavailable')+ expect(screen.queryByText('acl.recovery.title')).toBeNull()+ expect(mocks.admins).not.toHaveBeenCalled()+})++it('clears hidden selections when switching from users to groups', async () => {+ const { user } = mount()+ await screen.findByText('bob')+ await user.click(screen.getByRole('button', { name: 'acl.addGrant' }))+ await user.click(await screen.findByRole('button', { name: 'bob' }))+ await user.click(screen.getByRole('button', { name: 'acl.subjects.group' }))+ expect(+ screen+ .getByRole('button', { name: 'acl.confirmGrant:0:acl.levels.read' })+ .hasAttribute('disabled'),+ ).toBe(true)+ await user.click(await screen.findByRole('button', { name: 'engineering' }))+ await user.click(screen.getByRole('button', { name: 'acl.levels.manage' }))+ await user.click(+ screen.getByRole('button', {+ name: 'acl.confirmGrant:1:acl.levels.manage',+ }),+ )+ await waitFor(() => expect(mocks.change).toHaveBeenCalledTimes(1))+ expect(mocks.change).toHaveBeenCalledWith(uri, {+ kind: 'grant',+ principal: 'group:engineering',+ level: 'manage',+ })+})diff --git a/web-studio/src/components/resource-permissions.tsx b/web-studio/src/components/resource-permissions.tsxnew file mode 100644index 000000000..ed20bffd5--- /dev/null+++ b/web-studio/src/components/resource-permissions.tsx@@ -0,0 +1,607 @@+import { useState } from 'react'+import { ArrowLeftIcon, CheckIcon, PlusIcon, SearchIcon } from 'lucide-react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { useAclManagement } from '#/hooks/use-acl-management'+import { ResourceAclIdentityRecovery } from './resource-acl-identity-recovery'+import { isOvClientError } from '#/lib/ov-client'+import { Button } from '#/components/ui/button'+import { Badge } from '#/components/ui/badge'+import { Input } from '#/components/ui/input'+import { Field, FieldGroup, FieldLabel } from '#/components/ui/field'+import {+ Select,+ SelectTrigger,+ SelectValue,+ SelectContent,+ SelectGroup,+ SelectItem,+} from '#/components/ui/select'+import { Alert, AlertTitle, AlertDescription } from '#/components/ui/alert'+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogCancel,+ AlertDialogAction,+} from '#/components/ui/alert-dialog'+import { isSharedAclTarget } from '#/lib/resource-acl'+import type { AclChange, AclEntry, AclLevel } from '#/lib/resource-acl'+import { fetchAdminGroups, fetchAdminUsersPage } from '#/lib/admin'+import { getErrorMessage } from '#/routes/users/-lib/error'+import { useDebouncedValue } from '#/routes/resources/-hooks/viking-fm'++const subjectTypes = ['user', 'group', 'everyone'] as const+const levels: AclLevel[] = ['read', 'write', 'manage']+type PanelChange = AclChange | { kind: 'grantMany'; entries: AclEntry[] }++export function ResourcePermissionsPanel({ uri }: { uri: string }) {+ const state = useAclManagement()+ const { t } = useTranslation('settings')+ const client = useQueryClient()+ const [confirm, setConfirm] = useState<AclChange | null>(null)+ const [grantOpen, setGrantOpen] = useState(false)+ const key = ['resource-acl', state.aclIdentityScopeKey, uri]+ const report = useQuery({+ queryKey: key,+ queryFn: () => state.api.get(uri),+ enabled: state.allowed && isSharedAclTarget(uri),+ retry: false,+ })+ const mutation = useMutation({+ mutationFn: async (change: PanelChange) => {+ if (change.kind !== 'grantMany') return state.api.change(uri, change)+ let updated+ for (const entry of change.entries) {+ updated = await state.api.change(uri, { kind: 'grant', ...entry })+ }+ return updated+ },+ onSuccess: async (updated) => {+ client.setQueryData(key, updated)+ setConfirm(null)+ setGrantOpen(false)+ toast.success(t('acl.saved'))+ // Ancestor grants affect descendant reports and every cached resource listing/search.+ await client.invalidateQueries()+ },+ onError: async (error) => {+ toast.error(t('acl.failed'), { description: getErrorMessage(error) })+ // Earlier grants in a batch may already have succeeded.+ await client.invalidateQueries()+ },+ })+ const writable =+ state.allowed &&+ state.settings.data === true &&+ state.settings.isSuccess &&+ !state.settings.isFetching &&+ report.isSuccess &&+ !report.isFetching &&+ !mutation.isPending+ const permissionDenied =+ isOvClientError(report.error) &&+ (report.error.statusCode === 403 ||+ report.error.code === 'PERMISSION_DENIED')+ const restricted = report.data?.acl_mode === 'restricted'+ const defaultShared = report.data?.acl_mode === 'none'+ const modeChange = confirm?.kind === 'mode'+ return (+ <section className="min-w-0">+ <div className="flex flex-col gap-4">+ {report.isPending ? (+ <p role="status">{t('loading')}</p>+ ) : report.isError && permissionDenied ? (+ <ResourceAclIdentityRecovery+ onRetry={() => void report.refetch()}+ error={getErrorMessage(report.error)}+ />+ ) : report.isError ? (+ <>+ <Alert variant="destructive">+ <AlertTitle>{t('acl.loadFailed')}</AlertTitle>+ <AlertDescription>+ <p>{t('acl.retryHint')}</p>+ <p>{getErrorMessage(report.error)}</p>+ <Button variant="outline" onClick={() => void report.refetch()}>+ {t('actions.refresh')}+ </Button>+ </AlertDescription>+ </Alert>+ </>+ ) : grantOpen ? (+ <div className="space-y-5">+ <Button+ variant="ghost"+ size="sm"+ className="-ml-2"+ onClick={() => setGrantOpen(false)}+ >+ <ArrowLeftIcon data-icon="inline-start" />+ {t('acl.backToGrants')}+ </Button>+ <div className="border-b pb-3 text-sm font-medium">+ {t('acl.addGrant')}+ </div>+ <GrantForm+ state={state}+ disabled={!writable}+ onGrant={(entries) =>+ mutation.mutate({ kind: 'grantMany', entries })+ }+ />+ </div>+ ) : (+ <div className="space-y-4">+ <section className="min-w-0">+ <div className="flex flex-wrap items-center justify-between gap-3 border-b pb-3">+ <h2 className="text-sm font-medium">+ {t('acl.peopleWithAccess')}+ </h2>+ {!defaultShared && (+ <Button+ size="sm"+ disabled={!writable}+ onClick={() => setGrantOpen(true)}+ >+ <PlusIcon data-icon="inline-start" />+ {t('acl.addGrant')}+ </Button>+ )}+ </div>+ {defaultShared && (+ <div className="flex flex-wrap items-center justify-between gap-3 border-b py-4">+ <div className="min-w-0">+ <p className="text-sm font-medium">{t('acl.everyone')}</p>+ <p className="text-xs text-muted-foreground">+ {t('acl.defaultRule')}+ </p>+ </div>+ <Button+ variant="outline"+ size="sm"+ disabled={!writable}+ onClick={() =>+ setConfirm({ kind: 'mode', mode: 'restricted' })+ }+ >+ {t('acl.limitAccess')}+ </Button>+ </div>+ )}+ {!defaultShared &&+ report.data.direct_entries.length === 0 &&+ (restricted || report.data.inherited_entries.length === 0) && (+ <p className="py-6 text-sm text-muted-foreground">+ {t('acl.onlyAdmins')}+ </p>+ )}+ {report.data.direct_entries.map((entry) => (+ <div+ key={entry.principal}+ className="flex flex-wrap items-center gap-3 border-b py-3 last:border-b-0"+ >+ <div className="min-w-0 flex-1">+ <p className="break-all text-sm font-medium">+ {principalLabel(entry.principal, t('acl.everyone'))}+ </p>+ <p className="text-xs text-muted-foreground">+ {t('acl.directSource')} ·{' '}+ {t(`acl.subjects.${principalType(entry.principal)}`)}+ </p>+ </div>+ <LevelSelect+ value={entry.level}+ disabled={!writable}+ label={t('acl.levelFor', { principal: entry.principal })}+ onChange={(level) =>+ mutation.mutate({+ kind: 'grant',+ principal: entry.principal,+ level,+ })+ }+ />+ <Button+ variant="ghost"+ size="sm"+ disabled={!writable}+ onClick={() =>+ setConfirm({+ kind: 'revoke',+ principal: entry.principal,+ })+ }+ >+ {t('acl.remove')}+ </Button>+ </div>+ ))}+ {!restricted &&+ !defaultShared &&+ report.data.inherited_entries.map((entry) => (+ <div+ key={`parent:${entry.principal}`}+ className="flex items-center gap-3 border-b py-3 last:border-b-0"+ >+ <div className="min-w-0 flex-1">+ <p className="break-all text-sm font-medium">+ {principalLabel(entry.principal, t('acl.everyone'))}+ </p>+ <p className="text-xs text-muted-foreground">+ {t('acl.inheritedSource')} ·{' '}+ {t(`acl.subjects.${principalType(entry.principal)}`)}+ </p>+ </div>+ <Badge variant="outline">+ {t(`acl.levels.${entry.level}`)}+ </Badge>+ </div>+ ))}+ </section>+ </div>+ )}+ </div>+ <AlertDialog+ open={confirm !== null}+ onOpenChange={(open) => {+ if (!open && !mutation.isPending) setConfirm(null)+ }}+ >+ <AlertDialogContent onKeyDown={(event) => event.stopPropagation()}>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t(modeChange ? 'acl.limitTitle' : 'acl.remove')}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t(modeChange ? 'acl.limitWarning' : 'acl.removeWarning', {+ principal: confirm?.kind === 'revoke' ? confirm.principal : '',+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={mutation.isPending}>+ {t('actions.cancel')}+ </AlertDialogCancel>+ <AlertDialogAction+ disabled={!writable}+ onClick={(event) => {+ event.preventDefault()+ if (confirm) mutation.mutate(confirm)+ }}+ >+ {mutation.isPending ? t('loading') : t('acl.confirm')}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </section>+ )+}++function principalLabel(principal: string, everyone: string) {+ return principal === 'user:*'+ ? everyone+ : principal.replace(/^(user|group):/, '')+}+function principalType(principal: string) {+ return principal === 'user:*'+ ? 'everyone'+ : principal.startsWith('group:')+ ? 'group'+ : 'user'+}+function LevelSelect({+ value,+ disabled,+ label,+ onChange,+}: {+ value: AclLevel+ disabled: boolean+ label: string+ onChange: (level: AclLevel) => void+}) {+ const { t } = useTranslation('settings')+ return (+ <Select+ value={value}+ disabled={disabled}+ onValueChange={(level) => {+ if (levels.includes(level as AclLevel)) onChange(level as AclLevel)+ }}+ >+ <SelectTrigger aria-label={label} className="w-32">+ <SelectValue>{t(`acl.levels.${value}`)}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {levels.map((level) => (+ <SelectItem key={level} value={level}>+ {t(`acl.levels.${level}`)}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ )+}++function GrantForm({+ state,+ disabled,+ onGrant,+}: {+ state: ReturnType<typeof useAclManagement>+ disabled: boolean+ onGrant: (entries: AclEntry[]) => void+}) {+ const { t } = useTranslation('settings')+ const [kind, setKind] = useState('user')+ const [selectedPrincipals, setSelectedPrincipals] = useState<string[]>([])+ const [level, setLevel] = useState<AclLevel>('read')+ const [search, setSearch] = useState('')+ const query = useDebouncedValue(search, 250)+ const [page, setPage] = useState(1)+ const users = useQuery({+ queryKey: ['acl-users', state.identityScopeKey, query, page],+ queryFn: () =>+ fetchAdminUsersPage(state.adminConnection, state.connection.accountId, {+ search: query,+ page,+ pageSize: 20,+ }),+ enabled: !disabled && kind === 'user',+ retry: false,+ })+ const groups = useQuery({+ queryKey: [+ 'managed-groups',+ state.connection.baseUrl,+ state.connection.accountId,+ state.connection.adminApiKey,+ ],+ queryFn: () => fetchAdminGroups(state.adminConnection),+ enabled: !disabled && kind === 'group',+ retry: false,+ })+ const candidates =+ kind === 'group'+ ? (groups.data+ ?.filter((group) =>+ group.group_id.toLowerCase().includes(search.trim().toLowerCase()),+ )+ .map((group) => ({+ value: `group:${group.group_id}`,+ label: group.group_id,+ })) ?? [])+ : (users.data?.users.map((user) => ({+ value: `user:${user.userId}`,+ label: user.userId,+ })) ?? [])+ const list = kind === 'group' ? groups : users+ const selected = kind === 'everyone' ? ['user:*'] : selectedPrincipals+ const valid = selected.length > 0+ return (+ <form+ className="flex flex-col gap-5"+ onSubmit={(event) => {+ event.preventDefault()+ if (!disabled && valid)+ onGrant(selected.map((principal) => ({ principal, level })))+ }}+ >+ <FieldGroup className="gap-4">+ <Field>+ <FieldLabel>{t('acl.subjectType')}</FieldLabel>+ <div+ className="grid grid-cols-3 gap-1 rounded-md bg-muted/60 p-1"+ role="group"+ aria-label={t('acl.subjectType')}+ >+ {subjectTypes.map((value) => (+ <Button+ key={value}+ type="button"+ variant="ghost"+ size="sm"+ aria-pressed={kind === value}+ disabled={disabled}+ className={`min-w-0 px-1 text-xs ${+ kind === value+ ? 'bg-background shadow-xs hover:bg-background'+ : 'text-muted-foreground'+ }`}+ onClick={() => {+ setKind(value)+ if (value !== kind) setSelectedPrincipals([])+ setSearch('')+ setPage(1)+ }}+ >+ {t(+ value === 'everyone'+ ? 'acl.subjects.everyoneShort'+ : `acl.subjects.${value}`,+ )}+ </Button>+ ))}+ </div>+ </Field>+ {kind === 'everyone' ? (+ <Field className="min-h-[19rem]">+ <FieldLabel>{t('acl.subject')}</FieldLabel>+ <div className="h-44 rounded-md border p-1">+ <div className="flex items-center gap-2 rounded bg-muted px-3 py-2 text-sm font-medium">+ <CheckIcon className="size-4 shrink-0" />+ {t('acl.everyone')}+ </div>+ </div>+ </Field>+ ) : (+ <Field className="min-h-[19rem]">+ <FieldLabel htmlFor="acl-subject-search">+ {t('acl.search')}+ </FieldLabel>+ <div className="relative">+ <SearchIcon className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />+ <Input+ id="acl-subject-search"+ className="pl-9"+ disabled={disabled}+ value={search}+ onChange={(event) => {+ setSearch(event.target.value)+ setPage(1)+ }}+ />+ </div>+ {!disabled &&+ (list.isError ? (+ <Alert variant="destructive">+ <AlertTitle>{t('acl.candidatesFailed')}</AlertTitle>+ <AlertDescription>+ {getErrorMessage(list.error)}+ <Button+ type="button"+ variant="outline"+ onClick={() => void list.refetch()}+ >+ {t('actions.refresh')}+ </Button>+ </AlertDescription>+ </Alert>+ ) : (+ <>+ <div+ className="h-44 overflow-y-auto rounded-md border p-1"+ role="group"+ aria-label={t('acl.subject')}+ >+ {list.isPending || list.isFetching || query !== search ? (+ <p+ className="px-3 py-4 text-sm text-muted-foreground"+ role="status"+ >+ {t('loading')}+ </p>+ ) : candidates.length === 0 ? (+ <p className="px-3 py-4 text-sm text-muted-foreground">+ {t('acl.noCandidates')}+ </p>+ ) : (+ candidates.map((candidate) => (+ <button+ key={candidate.value}+ type="button"+ aria-pressed={selectedPrincipals.includes(+ candidate.value,+ )}+ className={`flex w-full items-center gap-3 rounded px-3 py-2 text-left text-sm hover:bg-muted ${selectedPrincipals.includes(candidate.value) ? 'bg-muted font-medium' : ''}`}+ onClick={() =>+ setSelectedPrincipals((current) =>+ current.includes(candidate.value)+ ? current.filter(+ (value) => value !== candidate.value,+ )+ : [...current, candidate.value],+ )+ }+ >+ <span className="flex size-4 shrink-0 items-center justify-center rounded border border-input">+ {selectedPrincipals.includes(candidate.value) && (+ <CheckIcon className="size-3" />+ )}+ </span>+ <span className="truncate">{candidate.label}</span>+ </button>+ ))+ )}+ </div>+ {kind === 'user' && (users.data?.total ?? 0) > 20 && (+ <div className="flex items-center justify-end gap-2 text-xs text-muted-foreground">+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={page <= 1 || users.isFetching}+ onClick={() => {+ setPage(page - 1)+ }}+ >+ {t('groups.previous')}+ </Button>+ <span>+ {t('groups.page', {+ page,+ pages: Math.max(+ 1,+ Math.ceil((users.data?.total ?? 0) / 20),+ ),+ })}+ </span>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={+ page * 20 >= (users.data?.total ?? 0) ||+ users.isFetching+ }+ onClick={() => {+ setPage(page + 1)+ }}+ >+ {t('groups.next')}+ </Button>+ </div>+ )}+ </>+ ))}+ </Field>+ )}+ <Field>+ <FieldLabel>{t('acl.level')}</FieldLabel>+ <div+ className="grid grid-cols-3 gap-1 rounded-md bg-muted/60 p-1"+ role="group"+ aria-label={t('acl.level')}+ >+ {levels.map((value) => (+ <Button+ key={value}+ type="button"+ variant="ghost"+ size="sm"+ aria-pressed={level === value}+ disabled={disabled}+ className={+ level === value+ ? 'bg-background shadow-xs hover:bg-background'+ : 'text-muted-foreground'+ }+ onClick={() => setLevel(value)}+ >+ {t(`acl.levels.${value}`)}+ </Button>+ ))}+ </div>+ </Field>+ </FieldGroup>+ <div className="flex justify-end">+ <Button type="submit" disabled={disabled || !valid}>+ {t(+ kind === 'everyone'+ ? 'acl.confirmEveryoneGrant'+ : 'acl.confirmGrant',+ { count: selected.length, level: t(`acl.levels.${level}`) },+ )}+ </Button>+ </div>+ </form>+ )+}diff --git a/web-studio/src/hooks/use-acl-management.ts b/web-studio/src/hooks/use-acl-management.tsnew file mode 100644index 000000000..9db3bf97e--- /dev/null+++ b/web-studio/src/hooks/use-acl-management.ts@@ -0,0 +1,71 @@+import { useMemo } from 'react'+import { useQuery } from '@tanstack/react-query'+import { useAppConnection } from './use-app-connection'+import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'+import { createResourceAclApi } from '#/lib/resource-acl'++export function useAclManagement(load = true) {+ const {+ connection,+ connectionRole,+ isConnectionRoleLoading,+ serverMode,+ identityScopeKey,+ switchIdentity,+ } = useAppConnection()+ const { canManageUsers } = resolveStudioManagementCapabilities({+ hasControlCredential: Boolean(connection.adminApiKey.trim()),+ isRoleLoading: isConnectionRoleLoading,+ role: connectionRole,+ serverMode,+ })+ const allowed =+ canManageUsers &&+ Boolean(connection.accountId) &&+ serverMode !== 'checking' &&+ serverMode !== 'offline'+ // An account admin's control key is also a valid tenant data credential.+ // Keep the regular browsing identity unchanged while managing ACLs.+ const useAccountAdminCredential =+ serverMode === 'api_key' && connectionRole === 'admin'+ const api = useMemo(+ () =>+ createResourceAclApi(+ connection,+ serverMode === 'trusted',+ useAccountAdminCredential,+ ),+ [connection, serverMode, useAccountAdminCredential],+ )+ const settingsKey = [+ 'account-acl',+ connection.baseUrl,+ connection.accountId,+ connection.adminApiKey,+ ]+ const settings = useQuery({+ queryKey: settingsKey,+ queryFn: () => api.getEnabled(),+ enabled: allowed && load,+ retry: false,+ })+ const adminConnection = {+ accountId: connection.accountId,+ userId: connection.userId,+ baseUrl: connection.baseUrl,+ apiKey: connection.adminApiKey,+ }+ return {+ api,+ serverMode,+ switchIdentity,+ allowed,+ settings,+ settingsKey,+ adminConnection,+ identityScopeKey,+ aclIdentityScopeKey: `${identityScopeKey}:${useAccountAdminCredential ? 'account-admin' : 'data-user'}`,+ useAccountAdminCredential,+ connection,+ }+}diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.tsindex b6981cfac..b723256b1 100644--- a/web-studio/src/i18n/locales/en/workspace.ts+++ b/web-studio/src/i18n/locales/en/workspace.ts@@ -6,7 +6,7 @@ const workspace = {docs: 'Documentation',github: 'GitHub',sdkApi: 'SDK & API',- users: 'User Management',+ users: 'Users & Permissions',},header: {currentUser: {@@ -779,12 +779,182 @@ const workspace = {},},settings: {+ acl: {+ page: {+ advanced: 'Advanced settings',+ aboutLevels: 'About permission levels',+ title: 'Resource permissions',+ description:+ 'Browse shared resource directories and manage access to each one.',+ path: 'Current directory',+ back: 'Go to parent directory',+ listFailed: 'Could not load directory',+ parentAclFailed:+ 'Could not load permissions for the current directory. Changes to subdirectory permissions are unavailable until you retry.',+ emptyDirectory: 'No subdirectories here.',+ nameColumn: 'Name',+ ruleColumn: 'Permission rule',+ granteesColumn: 'Grants on this directory',+ actionsColumn: 'Actions',+ unreadable: 'Unable to load',+ noGrantees: 'No direct grants',+ editAction: 'Edit permissions',+ manageAction: 'Manage permissions',+ limitFor: 'Restrict access to {{directory}}',+ restoreInheritanceTitle: 'Inherit permissions from the parent again?',+ restoreInheritanceWarning:+ 'Parent directory grants will apply again. Grants added on this directory will remain.',+ disableLimitTitle: 'Turn off restricted access for this directory?',+ disableLimitWarning:+ 'Grants added here will be removed and default sharing restored. Separate permissions on child directories remain.',+ editDirectory: 'Who can access {{directory}}',+ whoCanAccess: 'Grant access to these users or groups',+ grantScope:+ 'Permissions set here apply to this directory and its descendants by default. A child directory can have different rules.',+ advancedRules: 'Parent permissions and other settings',+ parentAccess: 'Parent directory grants',+ parentGrantsActive:+ '{{count}} additional parent grants apply here. Open “Parent permissions and other settings” to review them.',+ parentGrantsInactive:+ '{{count}} parent grants exist, but this directory has stopped inheriting them.',+ unavailable:+ 'This page requires account administrator or Root management credentials. Check connection settings.',+ },+ title: 'Access permissions',+ accountTitle: 'Resource access control · {{account}}',+ accountHint:+ 'Account-wide setting for shared resources. Existing resources without ACL remain shared under the original rules.',+ enableAction: 'Enable access control',+ disableAction: 'Disable access control',+ enabled: 'Enabled',+ disabled: 'Disabled — resource ACL grants are not enforced',+ enableTitle: 'Enable resource access control?',+ disableTitle: 'Disable resource access control?',+ enableWarning:+ 'Enable ACL for Account {{account}}? New shared resources grant their creator management access and inherit parent permissions. Existing resources without ACL remain shared; previously configured ACLs take effect again.',+ disableWarning:+ 'Disable ACL for Account {{account}}? All configured resource ACLs stop being enforced. Resources follow the original sharing rules, which may expand access. Stored grants are retained.',+ saved: 'Permissions updated',+ failed: 'Could not update permissions',+ confirm: 'Confirm',+ parentGrantsLabel: 'Parent directory grants',+ parentIncluded: 'Includes parent grants',+ parentExcluded: 'Excludes parent grants',+ includeParent: 'Include parent grants',+ excludeParent: 'Exclude parent grants',+ limitAccess: 'Restrict access',+ limitTitle: 'Restrict access to this directory?',+ limitWarning:+ 'This directory will stop inheriting parent grants. Existing direct grants, including Everyone grants, remain active. Review these grants after switching. Account administrators retain access.',+ peopleWithAccess: 'People and groups with access',+ defaultRule: 'Shared by default',+ onlyAdmins: 'No grants yet; account administrators can still access',+ directSource: 'Granted here',+ inheritedSource: 'From parent',+ adminCredentialIdentity:+ 'Permission management uses the account administrator credential for {{account}}. Resource browsing still uses the current user.',+ identity:+ 'Resource operations use the current data identity: {{account}} / {{user}}.',+ loadFailed: 'Could not load resource permissions',+ accessHint:+ 'The current data identity needs resource management access. In API Key mode, use an Account Admin user key, not a Root key.',+ retryHint:+ 'The request failed. Retry, or inspect the error details if it persists.',+ recovery: {+ loadFailed: 'Failed to load account administrators.',+ switchFailed: 'Failed to switch user.',+ title: 'Switch to a user with permission',+ description:+ 'This panel manages access to the current resource. Your user cannot read its grants. Switch to an account administrator to add users or groups with read, write, or manage access.',+ scope:+ 'Switching also changes the user identity used throughout Web Studio to browse and operate on resources.',+ unsupported:+ 'This connection mode does not support switching users here. Check your connection settings.',+ noAdmins:+ 'No account administrators are available. Check user roles in Users & Permissions, or ask someone with resource management access to grant permission.',+ admin: 'Account administrator',+ selectAdmin: 'Select an account administrator',+ key: 'Administrator user API key',+ keyHint:+ 'The server did not return a key for this user. Enter their existing API key. A Root key cannot be used here.',+ switch: 'Switch user and load permissions',+ switching: 'Switching…',+ switched:+ 'User switched. Select a directory to continue managing permissions.',+ retryAccess: 'Check access again',+ details: 'Error details',+ scopeTitle: 'About switching identity',+ users: 'Go to Users & Permissions',+ },+ modes: {+ none: 'Shared by default',+ inherit: 'Inherited permissions',+ restricted: 'Custom permissions',+ },+ modeDescriptions: {+ none: 'This directory follows the default sharing rules. Grants added here apply to descendant directories and files by default.',+ inherit:+ 'Parent grants and grants added here both apply, including to descendant directories and files by default. A descendant can stop inheritance.',+ restricted:+ 'This directory does not use parent grants. Grants added here still apply to descendant directories and files unless a descendant stops inheritance.',+ },+ levels: {+ read: 'View',+ write: 'Edit',+ manage: 'Manage',+ },+ levelHint:+ 'View: read and search. Edit: create, modify, delete or move files. Manage: edit permissions and delete or move directories; directory operations also check the entire subtree.',+ direct: 'Grants added to this directory',+ inherited: 'Grants from parent directories',+ noDirect:+ 'No grants have been added here. Access may still come from a parent directory or default sharing rules.',+ noInherited: 'No inherited grants.',+ inheritedHint:+ 'These grants apply here and to descendant directories and files by default. Edit them in the parent directory.',+ inheritedInactive:+ 'These parent grants remain stored but do not apply here or to descendants through this directory.',+ inactive: 'Inactive',+ adminHint:+ 'Account administrators always retain management access, even when no grants are listed.',+ indexHint:+ 'Changing permissions requires an indexed resource. Wait for indexing to finish before configuring newly created resources.',+ levelFor: 'Permission for {{principal}}',+ remove: 'Remove grant',+ restoreInheritance: 'Restore parent permissions',+ restrict: 'Stop inheriting parent permissions',+ restrictTitle: 'Stop inheriting parent directory permissions?',+ restoreTitle: 'Restore parent directory permissions?',+ restrictWarning:+ 'Parent grants will stop applying to this directory and its contents. Only grants added here and account administrators will have access.',+ restoreWarning:+ 'Parent grants will apply to this directory and its contents again.',+ removeWarning:+ 'Remove the direct grant for {{principal}}? Access may remain through ancestors, groups, or the Account-wide grant. Removing the last grant may restore default sharing if inheritance is enabled and no ancestor is controlled.',+ subjectType: 'Grant to',+ subjects: {+ user: 'User',+ group: 'User group',+ everyoneShort: 'All users',+ everyone: 'Everyone in this Account',+ },+ everyone: 'Everyone in this Account',+ search: 'Search users or groups',+ subject: 'User or group',+ selectSubject: 'Select a user or group',+ noCandidates: 'No matching users or groups.',+ candidatesFailed: 'Could not load grant candidates',+ level: 'Permission level',+ addGrant: 'Add permission',+ backToGrants: 'Back to permissions',+ confirmGrant: 'Grant {{level}} access to {{count}} selected',+ confirmEveryoneGrant: 'Grant {{level}} access to all users',+ },groups: {- navigation: 'User management',+ navigation: 'Users & Permissions',usersTab: 'Users',title: 'User groups',- description:- 'Manage groups within Account {{account}}. Resource permissions are granted separately.',+ description: 'Manage groups and members in the current account.',id: 'Group ID',count: 'Members',actions: 'Actions',@@ -797,6 +967,7 @@ const workspace = {deleteDescription:'Delete {{group}}? Existing resource ACL references are not removed. Recreating this ID may reactivate those grants.',empty: 'No user groups yet.',+ notJoined: 'No groups',search: 'Search groups',members: 'Members of {{group}}',memberHint:@@ -855,14 +1026,14 @@ const workspace = {primary:'The Root/Admin API Key is mainly for management. The Playground and tenant data APIs require a User API Key bound to a user identity.',secondary:- 'Select or create a user in User Management, or regenerate its key, then use it as the User API Key.',+ 'Select or create a user in Users & Permissions, or regenerate its key, then use it as the User API Key.',title: 'A User API Key is still required',},empty: {primary:'Regular users should request a User API Key from their Account admin.',secondary:- 'Deployment admins can find the Root API Key at server.root_api_key in the server-side ov.conf. Add it here, then create or regenerate a User Key in User Management.',+ 'Deployment admins can find the Root API Key at server.root_api_key in the server-side ov.conf. Add it here, then create or regenerate a User Key in Users & Permissions.',title: 'No OpenViking API Key yet?',},learnMore: 'Learn how to get an API Key',@@ -990,7 +1161,7 @@ const workspace = {'User management requires a validated Root or Account Admin API key.',accessDeniedTitle: 'User management unavailable',currentAccountDescription:- 'Manage users and access credentials in the {{account}} workspace.',+ 'Manage users and access credentials in the current account.',description:'Review users and credentials for selected accounts, then add users or rotate keys from the web UI.',memberListDescription:@@ -1004,7 +1175,7 @@ const workspace = {noUsableKey:'This user has no plaintext API key available for data access.',openConnection: 'Open connection settings',- title: 'User management',+ title: 'Users',},page: {adminDescription:@@ -1046,6 +1217,7 @@ const workspace = {actions: 'Actions',apiKey: 'API key',role: 'Role',+ groups: 'Groups',user: 'User',},toast: {diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.tsindex 6c4a49cc9..1d5932296 100644--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts@@ -6,7 +6,7 @@ const workspace = {docs: '文档站',github: 'GitHub',sdkApi: 'SDK 与 API',- users: '用户管理',+ users: '用户与权限',},header: {currentUser: {@@ -746,12 +746,172 @@ const workspace = {},},settings: {+ acl: {+ page: {+ advanced: '高级设置',+ aboutLevels: '权限级别说明',+ title: '资源权限',+ description: '逐级浏览共享资源目录,查看和设置每个目录的访问权限。',+ path: '当前目录',+ back: '返回上一级目录',+ listFailed: '无法读取目录',+ parentAclFailed:+ '无法读取当前目录权限,暂时无法修改子目录权限,请重试。',+ emptyDirectory: '当前目录下没有子目录。',+ nameColumn: '名称',+ ruleColumn: '权限规则',+ granteesColumn: '本目录授权对象',+ actionsColumn: '操作',+ unreadable: '无法读取',+ noGrantees: '未单独授权',+ editAction: '编辑权限',+ manageAction: '管理权限',+ limitFor: '限制访问:{{directory}}',+ restoreInheritanceTitle: '恢复继承上级权限?',+ restoreInheritanceWarning:+ '上级目录的授权将重新生效,本目录已添加的授权会保留。',+ disableLimitTitle: '关闭此目录的限制访问?',+ disableLimitWarning:+ '本目录的授权将被清除,目录恢复默认共享;下级目录的独立权限设置会保留。',+ editDirectory: '谁可以访问 {{directory}}',+ whoCanAccess: '授权给以下用户或用户组',+ grantScope:+ '这里设置的权限默认适用于此目录及其下级目录和文件。下级目录单独设置后可能不同。',+ advancedRules: '上级目录权限与其他设置',+ parentAccess: '上级目录授权',+ parentGrantsActive:+ '此外,还有 {{count}} 条上级目录授权在此生效。展开“上级目录权限与其他设置”可查看。',+ parentGrantsInactive:+ '上级目录有 {{count}} 条授权,但当前目录已停止继承。',+ unavailable: '此页面需要账号管理员或 Root 管理凭证,请检查连接设置。',+ },+ title: '访问权限',+ accountTitle: '资源访问控制 · {{account}}',+ accountHint:+ '作用于当前 Account 的所有共享资源。已有且未配置 ACL 的资源仍按原规则共享。',+ enableAction: '启用访问控制',+ disableAction: '关闭访问控制',+ enabled: '已启用',+ disabled: '已关闭 — 资源 ACL 授权不参与鉴权',+ enableTitle: '启用资源访问控制?',+ disableTitle: '关闭资源访问控制?',+ enableWarning:+ '为 Account {{account}} 启用 ACL?新建共享资源会给创建者管理权,并继承父目录权限。已有未配置 ACL 的资源仍按原规则共享;此前配置的 ACL 会重新生效。',+ disableWarning:+ '关闭 Account {{account}} 的 ACL 后,所有资源授权将停止参与鉴权,资源恢复原有共享规则,可能扩大访问范围。已保存的授权不会被删除。',+ saved: '权限已更新',+ failed: '权限更新失败',+ confirm: '确认',+ parentGrantsLabel: '上级目录授权',+ parentIncluded: '包含上级目录授权',+ parentExcluded: '不含上级目录授权',+ includeParent: '使用上级授权',+ excludeParent: '排除上级授权',+ limitAccess: '限制访问',+ limitTitle: '限制这个目录的访问?',+ limitWarning:+ '此目录将停止继承上级授权。已有的直接授权(包括所有人授权)仍然生效,请在切换后检查这些授权。账号管理员仍可访问。',+ peopleWithAccess: '有权限的用户和用户组',+ defaultRule: '默认共享',+ onlyAdmins: '暂无授权对象,仅账号管理员可访问',+ directSource: '本目录授权',+ inheritedSource: '上级目录授权',+ adminCredentialIdentity:+ '权限管理使用 {{account}} 的账号管理员凭证;资源浏览仍使用当前用户。',+ identity: '资源操作使用当前数据身份:{{account}} / {{user}}。',+ loadFailed: '无法读取资源权限',+ accessHint:+ '当前数据身份需要对资源拥有管理权。API Key 模式下请使用 Account Admin 用户密钥,Root 密钥不能访问资源接口。',+ retryHint: '请求失败,请重试;若仍然失败,可展开错误详情排查。',+ recovery: {+ loadFailed: '加载账户管理员失败。',+ switchFailed: '切换用户失败。',+ title: '先切换到有权限的用户',+ description:+ '这里就是当前资源的权限管理面板。当前用户没有管理权,因此无法读取授权列表。切换到账号管理员后,可添加用户或用户组,并设置查看、编辑或管理权限。',+ scope: '切换会同时更改 Web Studio 浏览和操作资源所用的用户身份。',+ unsupported: '当前连接模式不支持在此切换用户,请先检查连接设置。',+ noAdmins:+ '当前账号没有可选的管理员。请前往“用户与权限”检查用户角色,或联系已有资源管理权的用户授权。',+ admin: '账号管理员',+ selectAdmin: '选择账号管理员',+ key: '管理员用户 API Key',+ keyHint:+ '服务端未返回该用户的密钥,请填写该用户已有的 API Key。Root 密钥不能用于此处。',+ switch: '切换身份并加载权限',+ switching: '正在切换…',+ switched: '已切换用户,请选择目录继续配置权限。',+ retryAccess: '重新检查当前权限',+ details: '错误详情',+ scopeTitle: '身份切换说明',+ users: '前往用户与权限',+ },+ modes: {+ none: '默认共享',+ inherit: '继承上级权限',+ restricted: '自定义权限',+ },+ modeDescriptions: {+ none: '当前目录沿用默认共享规则。在这里添加的授权默认适用于下级目录和文件。',+ inherit:+ '上级授权和本目录授权共同生效,并默认适用于下级目录和文件;下级节点可以单独关闭继承。',+ restricted:+ '当前目录不使用上级授权;本目录授权仍默认适用于下级目录和文件,除非下级节点关闭继承。',+ },+ levels: {+ read: '查看',+ write: '编辑',+ manage: '管理',+ },+ levelHint:+ '查看:读取、浏览、检索。编辑:创建、修改、删除或移动文件。管理:调整授权、删除或移动目录;目录操作还会检查整个子树。',+ direct: '本目录添加的授权',+ inherited: '来自上级目录的授权',+ noDirect:+ '还没有为本目录单独授权。用户仍可能通过上级目录或默认共享规则访问。',+ noInherited: '没有继承授权。',+ inheritedHint:+ '这些授权在当前目录生效,并默认适用于下级目录和文件;如需修改,请到上级目录操作。',+ inheritedInactive:+ '这些上级授权仍会保存,但不会在当前目录及其下级目录和文件生效。',+ inactive: '未生效',+ adminHint: 'Account 管理员始终拥有管理权限,即使授权列表为空。',+ indexHint: '修改权限需要资源已有索引记录;新建资源请等待索引完成后配置。',+ levelFor: '{{principal}} 的权限',+ remove: '移除授权',+ restoreInheritance: '恢复继承上级权限',+ restrict: '停止继承上级权限',+ restrictTitle: '停止继承上级目录的权限?',+ restoreTitle: '恢复继承上级目录的权限?',+ restrictWarning:+ '当前目录及下级内容将不再使用上级授权。只有本目录授权对象和账号管理员可以访问。',+ restoreWarning: '上级目录的授权将重新作用于当前目录及下级内容。',+ removeWarning:+ '移除 {{principal}} 的直接授权?该用户或组仍可能通过继承、组成员关系或全体用户授权访问。若继承已开启且上级未受控,移除最后一条授权可能恢复默认共享。',+ subjectType: '授权对象类型',+ subjects: {+ user: '用户',+ group: '用户组',+ everyoneShort: '所有用户',+ everyone: '当前 Account 全体用户',+ },+ everyone: '当前 Account 全体用户',+ search: '搜索用户或用户组',+ subject: '用户或用户组',+ selectSubject: '请选择用户或用户组',+ noCandidates: '没有匹配的用户或用户组。',+ candidatesFailed: '授权对象加载失败',+ level: '权限级别',+ addGrant: '添加授权',+ backToGrants: '返回授权列表',+ confirmGrant: '确认授予 {{count}} 个对象{{level}}权限',+ confirmEveryoneGrant: '确认授予所有用户{{level}}权限',+ },groups: {- navigation: '用户管理',+ navigation: '用户与权限',usersTab: '用户',title: '用户组',- description:- '管理 Account {{account}} 内的用户组。资源访问权限需要单独授予。',+ description: '管理当前账号的用户组及成员。',id: '用户组 ID',count: '成员数',actions: '操作',@@ -763,6 +923,7 @@ const workspace = {deleteDescription:'确定删除 {{group}}?资源中的 ACL 引用不会被清理,重新创建相同 ID 可能恢复原有授权。',empty: '暂无用户组。',+ notJoined: '未加入用户组',search: '搜索用户组',members: '{{group}} 的成员',memberHint:@@ -820,13 +981,13 @@ const workspace = {primary:'Root 或管理员 API 密钥主要用于管理操作;工作台和租户数据 API 需要绑定用户身份的用户 API 密钥。',secondary:- '请在“用户管理”中选择或创建用户,或者重新生成用户密钥,然后将其用作用户 API 密钥。',+ '请在“用户与权限”中选择或创建用户,或者重新生成用户密钥,然后将其用作用户 API 密钥。',title: '还缺少用户 API 密钥',},empty: {primary: '普通用户:请向当前账号管理员索取用户 API 密钥。',secondary:- '部署管理员:Root API 密钥位于服务端 ov.conf 的 server.root_api_key;填入后可在“用户管理”中创建或重新生成用户密钥。',+ '部署管理员:Root API 密钥位于服务端 ov.conf 的 server.root_api_key;填入后可在“用户与权限”中创建或重新生成用户密钥。',title: '还没有 OpenViking API 密钥?',},learnMore: '查看 API 密钥获取方式',@@ -950,7 +1111,7 @@ const workspace = {accessDeniedDescription:'只有配置并通过校验的 Root 或账号管理员 API 密钥才能管理用户。',accessDeniedTitle: '无用户管理权限',- currentAccountDescription: '管理 {{account}} 空间下的用户和访问凭证。',+ currentAccountDescription: '管理当前账号的用户和访问凭证。',description: '查看选中账号下的用户和凭证,并在网页端新增用户或轮换密钥。',memberListDescription:'“切换身份”会将该用户设为工作台、检索等数据页面的访问身份,不会改变当前 Root 或管理员凭证。',@@ -961,7 +1122,7 @@ const workspace = {cannotRemoveLastManager: '不能删除空间内最后一个管理员。',noUsableKey: '该用户没有可用于数据访问的明文 API 密钥。',openConnection: '打开连接设置',- title: '用户管理',+ title: '用户',},page: {adminDescription:@@ -1003,6 +1164,7 @@ const workspace = {actions: '操作',apiKey: 'API 密钥',role: '角色',+ groups: '所属用户组',user: '用户',},toast: {diff --git a/web-studio/src/lib/resource-acl.test.ts b/web-studio/src/lib/resource-acl.test.tsnew file mode 100644index 000000000..63e806f14--- /dev/null+++ b/web-studio/src/lib/resource-acl.test.ts@@ -0,0 +1,122 @@+import axios from 'axios'+import { afterEach, expect, it, vi } from 'vitest'+import { createResourceAclApi, isSharedAclTarget } from './resource-acl'+import type { InternalAxiosRequestConfig } from 'axios'++afterEach(() => vi.restoreAllMocks())+const connection = {+ baseUrl: 'http://localhost:1933',+ accountId: 'acme',+ userId: 'alice',+ adminApiKey: 'control-key',+ apiKey: 'user-key',+}+function transport(result: unknown) {+ const requests: InternalAxiosRequestConfig[] = []+ const instance = axios.create({+ adapter: async (config) => {+ requests.push(config)+ return {+ status: 200,+ statusText: 'OK',+ headers: {},+ config,+ data: { status: 'ok', result },+ }+ },+ })+ vi.spyOn(axios, 'create').mockReturnValue(instance)+ return requests+}+it('separates configuration credentials from resource data credentials and patches only ACL', async () => {+ const requests = transport({ settings: { acl: { enabled: true } } })+ const api = createResourceAclApi(connection, false)+ expect(await api.getEnabled()).toBe(true)+ await api.setEnabled(false)+ await api.get('viking://resources/project')+ expect(requests.map((request) => request.headers.get('X-API-Key'))).toEqual([+ 'control-key',+ 'control-key',+ 'user-key',+ ])+ expect(JSON.parse(requests[1].data)).toEqual({+ settings: { acl: { enabled: false } },+ })+ expect(requests[0].url).toContain('/accounts/acme/configuration')+ expect(requests[2].headers.get('X-OpenViking-User')).toBeUndefined()+})+it('uses an authenticated account-admin control key for ACL without changing the browsing identity', async () => {+ const requests = transport({})+ const api = createResourceAclApi(connection, false, true)+ await api.get('viking://resources/project')+ await api.listDirectory('viking://resources/project/')+ await api.change('viking://resources/project', {+ kind: 'grant',+ principal: 'user:bob',+ level: 'read',+ })+ expect(requests.map((request) => request.headers.get('X-API-Key'))).toEqual([+ 'control-key',+ 'control-key',+ 'control-key',+ ])+ expect(requests[0].headers.get('X-OpenViking-User')).toBeUndefined()+ expect(requests[1].url).toContain('/fs/ls')+})+it('preserves trusted identity and makes targeted grants without replacing other entries', async () => {+ const requests = transport({})+ const api = createResourceAclApi({ ...connection, apiKey: '' }, true)+ await api.change('viking://resources/project', {+ kind: 'grant',+ principal: 'group:engineering',+ level: 'write',+ })+ await api.change('viking://resources/project', {+ kind: 'revoke',+ principal: 'user:bob',+ })+ await api.change('viking://resources/project', {+ kind: 'mode',+ mode: 'restricted',+ })+ expect(requests[0].headers.get('X-OpenViking-User')).toBe('alice')+ expect(requests[0].headers.get('X-OpenViking-Account')).toBe('acme')+ expect(requests[0].url).toContain('/acl/grant')+ expect(JSON.parse(requests[0].data)).toEqual({+ uri: 'viking://resources/project',+ principal: 'group:engineering',+ level: 'write',+ })+ expect(requests[1].url).toContain('/acl/revoke')+ expect(JSON.parse(requests[2].data)).toEqual({+ uri: 'viking://resources/project',+ acl_mode: 'restricted',+ })+})+it('clears a directory ACL through the reset endpoint', async () => {+ const requests = transport({})+ const api = createResourceAclApi(connection, false, true)+ await api.change('viking://resources/project', { kind: 'reset' })+ expect(requests[0].method).toBe('delete')+ expect(requests[0].url).toContain('/api/v1/acl')+ expect(+ new URL(requests[0].url!, 'http://localhost').searchParams.get('uri'),+ ).toBe('viking://resources/project')+})+it('offers ACL only on concrete shared resources', () => {+ for (const uri of [+ 'viking://resources/a',+ 'viking://resources/a/file.md',+ 'viking://resources/a/',+ ])+ expect(isSharedAclTarget(uri)).toBe(true)+ for (const uri of [+ 'viking://resources',+ 'viking://resources/',+ 'viking://user/alice/resources/a',+ 'viking://resources/../user/alice',+ 'viking://resources//a',+ 'viking://',+ ])+ expect(isSharedAclTarget(uri)).toBe(false)+})diff --git a/web-studio/src/lib/resource-acl.ts b/web-studio/src/lib/resource-acl.tsnew file mode 100644index 000000000..f1c23c7dd--- /dev/null+++ b/web-studio/src/lib/resource-acl.ts@@ -0,0 +1,105 @@+import { createOvClient, getOvResult } from '#/lib/ov-client'+import type { ConnectionDraft } from '#/hooks/use-app-connection'+import type { FSListResult } from '@ov-server/api/v1/fs'++export type AclLevel = 'read' | 'write' | 'manage'+export type AclEntry = { principal: string; level: AclLevel }+export type AclReport = {+ uri: string+ acl_mode: 'none' | 'inherit' | 'restricted'+ direct_entries: AclEntry[]+ inherited_entries: AclEntry[]+ effective_entries: AclEntry[]+}+export type AclChange =+ | { kind: 'grant'; principal: string; level: AclLevel }+ | { kind: 'revoke'; principal: string }+ | { kind: 'mode'; mode: 'inherit' | 'restricted' }+ | { kind: 'reset' }++type AccountConfig = { settings: { acl?: { enabled?: boolean } } }++export function isSharedAclTarget(uri: string) {+ const parts = uri.replace(/\/+$/, '').split('/')+ return (+ uri.startsWith('viking://resources/') &&+ parts.length > 3 &&+ parts.slice(3).every((part) => part && part !== '.' && part !== '..')+ )+}++// Capture both identities so an in-flight operation never follows a later UI switch.+export function createResourceAclApi(+ connection: ConnectionDraft,+ trusted: boolean,+ useAccountAdminCredential = false,+) {+ const { client } = createOvClient({+ baseUrl: connection.baseUrl,+ connection: {+ ...connection,+ apiKey: useAccountAdminCredential+ ? connection.adminApiKey+ : connection.apiKey,+ identityHeaders: trusted,+ },+ })+ const configuration = '/api/v1/admin/accounts/{account_id}/configuration'+ const path = { account_id: connection.accountId }+ return {+ async getEnabled() {+ const result = await getOvResult<AccountConfig>(+ client.get({ url: configuration, path }),+ )+ return result.settings.acl?.enabled === true+ },+ async setEnabled(enabled: boolean) {+ const result = await getOvResult<AccountConfig>(+ client.patch({+ url: configuration,+ path,+ headers: { 'Content-Type': 'application/json' },+ body: { settings: { acl: { enabled } } },+ }),+ )+ return result.settings.acl?.enabled === true+ },+ get: (uri: string) =>+ getOvResult<AclReport>(+ client.get({ url: '/api/v1/acl', query: { uri } }),+ ),+ listDirectory: (uri: string) =>+ getOvResult<FSListResult>(+ client.get({+ url: '/api/v1/fs/ls',+ query: { uri, show_all_hidden: false },+ }),+ ),+ change(uri: string, change: AclChange) {+ const headers = { 'Content-Type': 'application/json' }+ if (change.kind === 'reset')+ return getOvResult<AclReport>(+ client.delete({ url: '/api/v1/acl', query: { uri } }),+ )+ if (change.kind === 'mode')+ return getOvResult<AclReport>(+ client.put({+ url: '/api/v1/acl',+ headers,+ body: { uri, acl_mode: change.mode },+ }),+ )+ return getOvResult<AclReport>(+ client.post({+ url: `/api/v1/acl/${change.kind}`,+ headers,+ body: {+ uri,+ principal: change.principal,+ ...(change.kind === 'grant' ? { level: change.level } : {}),+ },+ }),+ )+ },+ }+}diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.tsindex 51a5de85e..f8a37355c 100644--- a/web-studio/src/routeTree.gen.ts+++ b/web-studio/src/routeTree.gen.ts@@ -19,14 +19,18 @@ import { Route as SessionsRouteRouteImport } from './routes/sessions/route'import { Route as RetrievalRouteRouteImport } from './routes/retrieval/route'import { Route as RequestLogsRouteRouteImport } from './routes/request-logs/route'import { Route as PlaygroundRouteRouteImport } from './routes/playground/route'+import { Route as PermissionsRouteRouteImport } from './routes/permissions/route'import { Route as MonitoringRouteRouteImport } from './routes/monitoring/route'import { Route as HomeRouteRouteImport } from './routes/home/route'import { Route as AgentExperienceRouteRouteImport } from './routes/agent-experience/route'import { Route as IndexRouteImport } from './routes/index'import { Route as VikingbotIndexRouteImport } from './routes/vikingbot/index'+import { Route as UsersIndexRouteImport } from './routes/users/index'import { Route as SessionsIndexRouteImport } from './routes/sessions/index'import { Route as CompileIndexRouteImport } from './routes/compile/index'import { Route as AgentExperienceIndexRouteImport } from './routes/agent-experience/index'+import { Route as UsersPermissionsRouteImport } from './routes/users/permissions'+import { Route as UsersGroupsRouteImport } from './routes/users/groups'import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'import { Route as OauthConsentRouteImport } from './routes/oauth/consent'import { Route as CompileNewRouteImport } from './routes/compile/new'@@ -83,6 +87,11 @@ const PlaygroundRouteRoute = PlaygroundRouteRouteImport.update({path: '/playground',getParentRoute: () => rootRouteImport,} as any)+const PermissionsRouteRoute = PermissionsRouteRouteImport.update({+ id: '/permissions',+ path: '/permissions',+ getParentRoute: () => rootRouteImport,+} as any)const MonitoringRouteRoute = MonitoringRouteRouteImport.update({id: '/monitoring',path: '/monitoring',@@ -108,6 +117,11 @@ const VikingbotIndexRoute = VikingbotIndexRouteImport.update({path: '/',getParentRoute: () => VikingbotRouteRoute,} as any)+const UsersIndexRoute = UsersIndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => UsersRouteRoute,+} as any)const SessionsIndexRoute = SessionsIndexRouteImport.update({id: '/',path: '/',@@ -123,6 +137,16 @@ const AgentExperienceIndexRoute = AgentExperienceIndexRouteImport.update({path: '/',getParentRoute: () => AgentExperienceRouteRoute,} as any)+const UsersPermissionsRoute = UsersPermissionsRouteImport.update({+ id: '/permissions',+ path: '/permissions',+ getParentRoute: () => UsersRouteRoute,+} as any)+const UsersGroupsRoute = UsersGroupsRouteImport.update({+ id: '/groups',+ path: '/groups',+ getParentRoute: () => UsersRouteRoute,+} as any)const OauthVerifyRoute = OauthVerifyRouteImport.update({id: '/oauth/verify',path: '/oauth/verify',@@ -155,6 +179,7 @@ export interface FileRoutesByFullPath {'/agent-experience': typeof AgentExperienceRouteRouteWithChildren'/home': typeof HomeRouteRoute'/monitoring': typeof MonitoringRouteRoute+ '/permissions': typeof PermissionsRouteRoute'/playground': typeof PlaygroundRouteRoute'/request-logs': typeof RequestLogsRouteRoute'/retrieval': typeof RetrievalRouteRoute@@ -162,16 +187,19 @@ export interface FileRoutesByFullPath {'/settings': typeof SettingsRouteRoute'/skills': typeof SkillsRouteRoute'/tasks': typeof TasksRouteRoute- '/users': typeof UsersRouteRoute+ '/users': typeof UsersRouteRouteWithChildren'/vikingbot': typeof VikingbotRouteRouteWithChildren'/watches': typeof WatchesRouteRoute'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute'/compile/new': typeof CompileNewRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/verify': typeof OauthVerifyRoute+ '/users/groups': typeof UsersGroupsRoute+ '/users/permissions': typeof UsersPermissionsRoute'/agent-experience/': typeof AgentExperienceIndexRoute'/compile/': typeof CompileIndexRoute'/sessions/': typeof SessionsIndexRoute+ '/users/': typeof UsersIndexRoute'/vikingbot/': typeof VikingbotIndexRoute'/compile/tasks/$taskId': typeof CompileTasksTaskIdRoute}@@ -179,21 +207,24 @@ export interface FileRoutesByTo {'/': typeof IndexRoute'/home': typeof HomeRouteRoute'/monitoring': typeof MonitoringRouteRoute+ '/permissions': typeof PermissionsRouteRoute'/playground': typeof PlaygroundRouteRoute'/request-logs': typeof RequestLogsRouteRoute'/retrieval': typeof RetrievalRouteRoute'/settings': typeof SettingsRouteRoute'/skills': typeof SkillsRouteRoute'/tasks': typeof TasksRouteRoute- '/users': typeof UsersRouteRoute'/watches': typeof WatchesRouteRoute'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute'/compile/new': typeof CompileNewRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/verify': typeof OauthVerifyRoute+ '/users/groups': typeof UsersGroupsRoute+ '/users/permissions': typeof UsersPermissionsRoute'/agent-experience': typeof AgentExperienceIndexRoute'/compile': typeof CompileIndexRoute'/sessions': typeof SessionsIndexRoute+ '/users': typeof UsersIndexRoute'/vikingbot': typeof VikingbotIndexRoute'/compile/tasks/$taskId': typeof CompileTasksTaskIdRoute}@@ -203,6 +234,7 @@ export interface FileRoutesById {'/agent-experience': typeof AgentExperienceRouteRouteWithChildren'/home': typeof HomeRouteRoute'/monitoring': typeof MonitoringRouteRoute+ '/permissions': typeof PermissionsRouteRoute'/playground': typeof PlaygroundRouteRoute'/request-logs': typeof RequestLogsRouteRoute'/retrieval': typeof RetrievalRouteRoute@@ -210,16 +242,19 @@ export interface FileRoutesById {'/settings': typeof SettingsRouteRoute'/skills': typeof SkillsRouteRoute'/tasks': typeof TasksRouteRoute- '/users': typeof UsersRouteRoute+ '/users': typeof UsersRouteRouteWithChildren'/vikingbot': typeof VikingbotRouteRouteWithChildren'/watches': typeof WatchesRouteRoute'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute'/compile/new': typeof CompileNewRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/verify': typeof OauthVerifyRoute+ '/users/groups': typeof UsersGroupsRoute+ '/users/permissions': typeof UsersPermissionsRoute'/agent-experience/': typeof AgentExperienceIndexRoute'/compile/': typeof CompileIndexRoute'/sessions/': typeof SessionsIndexRoute+ '/users/': typeof UsersIndexRoute'/vikingbot/': typeof VikingbotIndexRoute'/compile/tasks/$taskId': typeof CompileTasksTaskIdRoute}@@ -230,6 +265,7 @@ export interface FileRouteTypes {| '/agent-experience'| '/home'| '/monitoring'+ | '/permissions'| '/playground'| '/request-logs'| '/retrieval'@@ -244,9 +280,12 @@ export interface FileRouteTypes {| '/compile/new'| '/oauth/consent'| '/oauth/verify'+ | '/users/groups'+ | '/users/permissions'| '/agent-experience/'| '/compile/'| '/sessions/'+ | '/users/'| '/vikingbot/'| '/compile/tasks/$taskId'fileRoutesByTo: FileRoutesByTo@@ -254,21 +293,24 @@ export interface FileRouteTypes {| '/'| '/home'| '/monitoring'+ | '/permissions'| '/playground'| '/request-logs'| '/retrieval'| '/settings'| '/skills'| '/tasks'- | '/users'| '/watches'| '/agent-experience/$experienceUri'| '/compile/new'| '/oauth/consent'| '/oauth/verify'+ | '/users/groups'+ | '/users/permissions'| '/agent-experience'| '/compile'| '/sessions'+ | '/users'| '/vikingbot'| '/compile/tasks/$taskId'id:@@ -277,6 +319,7 @@ export interface FileRouteTypes {| '/agent-experience'| '/home'| '/monitoring'+ | '/permissions'| '/playground'| '/request-logs'| '/retrieval'@@ -291,9 +334,12 @@ export interface FileRouteTypes {| '/compile/new'| '/oauth/consent'| '/oauth/verify'+ | '/users/groups'+ | '/users/permissions'| '/agent-experience/'| '/compile/'| '/sessions/'+ | '/users/'| '/vikingbot/'| '/compile/tasks/$taskId'fileRoutesById: FileRoutesById@@ -303,6 +349,7 @@ export interface RootRouteChildren {AgentExperienceRouteRoute: typeof AgentExperienceRouteRouteWithChildrenHomeRouteRoute: typeof HomeRouteRouteMonitoringRouteRoute: typeof MonitoringRouteRoute+ PermissionsRouteRoute: typeof PermissionsRouteRoutePlaygroundRouteRoute: typeof PlaygroundRouteRouteRequestLogsRouteRoute: typeof RequestLogsRouteRouteRetrievalRouteRoute: typeof RetrievalRouteRoute@@ -310,7 +357,7 @@ export interface RootRouteChildren {SettingsRouteRoute: typeof SettingsRouteRouteSkillsRouteRoute: typeof SkillsRouteRouteTasksRouteRoute: typeof TasksRouteRoute- UsersRouteRoute: typeof UsersRouteRoute+ UsersRouteRoute: typeof UsersRouteRouteWithChildrenVikingbotRouteRoute: typeof VikingbotRouteRouteWithChildrenWatchesRouteRoute: typeof WatchesRouteRouteCompileNewRoute: typeof CompileNewRoute@@ -392,6 +439,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof PlaygroundRouteRouteImportparentRoute: typeof rootRouteImport}+ '/permissions': {+ id: '/permissions'+ path: '/permissions'+ fullPath: '/permissions'+ preLoaderRoute: typeof PermissionsRouteRouteImport+ parentRoute: typeof rootRouteImport+ }'/monitoring': {id: '/monitoring'path: '/monitoring'@@ -427,6 +481,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof VikingbotIndexRouteImportparentRoute: typeof VikingbotRouteRoute}+ '/users/': {+ id: '/users/'+ path: '/'+ fullPath: '/users/'+ preLoaderRoute: typeof UsersIndexRouteImport+ parentRoute: typeof UsersRouteRoute+ }'/sessions/': {id: '/sessions/'path: '/'@@ -448,6 +509,20 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AgentExperienceIndexRouteImportparentRoute: typeof AgentExperienceRouteRoute}+ '/users/permissions': {+ id: '/users/permissions'+ path: '/permissions'+ fullPath: '/users/permissions'+ preLoaderRoute: typeof UsersPermissionsRouteImport+ parentRoute: typeof UsersRouteRoute+ }+ '/users/groups': {+ id: '/users/groups'+ path: '/groups'+ fullPath: '/users/groups'+ preLoaderRoute: typeof UsersGroupsRouteImport+ parentRoute: typeof UsersRouteRoute+ }'/oauth/verify': {id: '/oauth/verify'path: '/oauth/verify'@@ -511,6 +586,22 @@ const SessionsRouteRouteWithChildren = SessionsRouteRoute._addFileChildren(SessionsRouteRouteChildren,)+interface UsersRouteRouteChildren {+ UsersGroupsRoute: typeof UsersGroupsRoute+ UsersPermissionsRoute: typeof UsersPermissionsRoute+ UsersIndexRoute: typeof UsersIndexRoute+}++const UsersRouteRouteChildren: UsersRouteRouteChildren = {+ UsersGroupsRoute: UsersGroupsRoute,+ UsersPermissionsRoute: UsersPermissionsRoute,+ UsersIndexRoute: UsersIndexRoute,+}++const UsersRouteRouteWithChildren = UsersRouteRoute._addFileChildren(+ UsersRouteRouteChildren,+)+interface VikingbotRouteRouteChildren {VikingbotIndexRoute: typeof VikingbotIndexRoute}@@ -528,6 +619,7 @@ const rootRouteChildren: RootRouteChildren = {AgentExperienceRouteRoute: AgentExperienceRouteRouteWithChildren,HomeRouteRoute: HomeRouteRoute,MonitoringRouteRoute: MonitoringRouteRoute,+ PermissionsRouteRoute: PermissionsRouteRoute,PlaygroundRouteRoute: PlaygroundRouteRoute,RequestLogsRouteRoute: RequestLogsRouteRoute,RetrievalRouteRoute: RetrievalRouteRoute,@@ -535,7 +627,7 @@ const rootRouteChildren: RootRouteChildren = {SettingsRouteRoute: SettingsRouteRoute,SkillsRouteRoute: SkillsRouteRoute,TasksRouteRoute: TasksRouteRoute,- UsersRouteRoute: UsersRouteRoute,+ UsersRouteRoute: UsersRouteRouteWithChildren,VikingbotRouteRoute: VikingbotRouteRouteWithChildren,WatchesRouteRoute: WatchesRouteRoute,CompileNewRoute: CompileNewRoute,diff --git a/web-studio/src/routes/permissions/-components/permissions-page.tsx b/web-studio/src/routes/permissions/-components/permissions-page.tsxnew file mode 100644index 000000000..a7fba53af--- /dev/null+++ b/web-studio/src/routes/permissions/-components/permissions-page.tsx@@ -0,0 +1,520 @@+import { useEffect, useState } from 'react'+import {+ ArrowLeftIcon,+ ChevronRightIcon,+ FolderIcon,+ Globe2Icon,+ RotateCwIcon,+ UserRoundIcon,+ UsersRoundIcon,+} from 'lucide-react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { AccountAclSettings } from '#/components/account-acl-settings'+import { ResourcePermissionsPanel } from '#/components/resource-permissions'+import { ResourceAclIdentityRecovery } from '#/components/resource-acl-identity-recovery'+import { Badge } from '#/components/ui/badge'+import { Button } from '#/components/ui/button'+import { Switch } from '#/components/ui/switch'+import { Alert, AlertTitle, AlertDescription } from '#/components/ui/alert'+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from '#/components/ui/alert-dialog'+import {+ Sheet,+ SheetContent,+ SheetHeader,+ SheetTitle,+} from '#/components/ui/sheet'+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '#/components/ui/table'+import { useAclManagement } from '#/hooks/use-acl-management'+import { isSharedAclTarget } from '#/lib/resource-acl'+import {+ normalizeFsEntries,+ parentUri,+} from '#/routes/resources/-lib/normalize'+import { getErrorMessage } from '#/routes/users/-lib/error'+import { isOvClientError } from '#/lib/ov-client'+import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'++const root = 'viking://resources/'++export function PermissionsPage() {+ const state = useAclManagement()+ const { t } = useTranslation('settings')+ return (+ <main className="flex w-full min-w-0 flex-col gap-6">+ <header className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h1 className="text-2xl font-semibold tracking-tight">+ {t('acl.page.title')}+ </h1>+ <p className="mt-1 text-sm text-muted-foreground">+ {t('acl.page.description')}+ </p>+ </div>+ {state.allowed && state.settings.data === true && (+ <AccountAclSettings inPopover />+ )}+ </header>+ {state.allowed && state.settings.data !== true && <AccountAclSettings />}+ <DirectoryPermissions+ key={`${state.connection.baseUrl}:${state.connection.accountId}`}+ />+ </main>+ )+}++function DirectoryPermissions() {+ const client = useQueryClient()+ const state = useAclManagement()+ const { t } = useTranslation('settings')+ const [currentUri, setCurrentUri] = useState(root)+ const [editingUri, setEditingUri] = useState('')+ const directories = useQuery({+ queryKey: ['acl-directory-list', state.aclIdentityScopeKey, currentUri],+ queryFn: async () => {+ const result = await state.api.listDirectory(currentUri)+ return normalizeFsEntries(result, currentUri).filter(+ (entry: VikingFsEntry) =>+ entry.isDir &&+ isSharedAclTarget(entry.uri) &&+ parentUri(entry.uri) === currentUri,+ )+ },+ enabled: state.allowed,+ retry: false,+ })+ const parentReport = useQuery({+ queryKey: ['resource-acl', state.aclIdentityScopeKey, currentUri],+ queryFn: () => state.api.get(currentUri),+ enabled: state.allowed && currentUri !== root,+ retry: false,+ })+ const parentControlled =+ currentUri !== root &&+ parentReport.isSuccess &&+ parentReport.data.acl_mode !== 'none'+ const parentKnown =+ currentUri === root || (parentReport.isSuccess && !parentReport.isFetching)+ const pathParts = currentUri.slice(root.length).split('/').filter(Boolean)+ const breadcrumbs = [+ { label: 'resources', uri: root },+ ...pathParts.map((part, index) => ({+ label: part,+ uri: `${root}${pathParts.slice(0, index + 1).join('/')}/`,+ })),+ ]++ if (!state.allowed) return <p>{t('acl.page.unavailable')}</p>++ return (+ <section className="min-w-0 space-y-4">+ <div className="flex flex-wrap items-center gap-2">+ {currentUri !== root && (+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t('acl.page.back')}+ onClick={() => setCurrentUri(parentUri(currentUri))}+ >+ <ArrowLeftIcon />+ </Button>+ )}+ <nav+ aria-label={t('acl.page.path')}+ className="flex min-w-0 flex-1 flex-wrap items-center gap-1 text-sm"+ >+ {breadcrumbs.map((crumb, index) => (+ <span key={crumb.uri} className="flex items-center gap-1">+ {index > 0 && (+ <ChevronRightIcon className="size-4 text-muted-foreground" />+ )}+ <button+ type="button"+ className={`rounded px-1.5 py-1 hover:bg-muted ${+ index === breadcrumbs.length - 1+ ? 'font-medium'+ : 'text-muted-foreground'+ }`}+ aria-current={+ index === breadcrumbs.length - 1 ? 'page' : undefined+ }+ onClick={() => setCurrentUri(crumb.uri)}+ >+ {crumb.label}+ </button>+ </span>+ ))}+ </nav>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t('actions.refresh')}+ onClick={() => {+ void directories.refetch()+ void client.invalidateQueries({+ queryKey: ['resource-acl', state.aclIdentityScopeKey],+ })+ void client.invalidateQueries({ queryKey: state.settingsKey })+ }}+ >+ <RotateCwIcon />+ </Button>+ </div>+ {currentUri !== root && parentReport.isError && (+ <Alert variant="destructive">+ <AlertTitle>{t('acl.page.parentAclFailed')}</AlertTitle>+ <AlertDescription>+ <p>{getErrorMessage(parentReport.error)}</p>+ <Button+ variant="outline"+ onClick={() => void parentReport.refetch()}+ >+ {t('actions.refresh')}+ </Button>+ </AlertDescription>+ </Alert>+ )}+ <div className="rounded-lg border">+ <Table className="min-w-[900px] table-fixed">+ <TableHeader>+ <TableRow>+ <TableHead className="w-[24%] pl-4">+ {t('acl.page.nameColumn')}+ </TableHead>+ <TableHead>{t('acl.page.granteesColumn')}</TableHead>+ <TableHead className="w-44">{t('acl.page.ruleColumn')}</TableHead>+ <TableHead className="w-28 text-center">+ {t('acl.limitAccess')}+ </TableHead>+ <TableHead className="w-28 pr-4 text-right">+ {t('acl.page.actionsColumn')}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {directories.isPending ? (+ <TableRow>+ <TableCell+ colSpan={5}+ className="py-10 text-center text-muted-foreground"+ >+ {t('loading')}+ </TableCell>+ </TableRow>+ ) : directories.isError ? (+ <TableRow>+ <TableCell colSpan={5} className="py-8 text-center">+ {isOvClientError(directories.error) &&+ (directories.error.statusCode === 403 ||+ directories.error.code === 'PERMISSION_DENIED') ? (+ <ResourceAclIdentityRecovery+ onRetry={() => void directories.refetch()}+ error={getErrorMessage(directories.error)}+ />+ ) : (+ <>+ <p className="text-destructive">+ {t('acl.page.listFailed')}+ </p>+ <p className="mt-1 text-xs text-muted-foreground">+ {getErrorMessage(directories.error)}+ </p>+ <Button+ variant="outline"+ size="sm"+ className="mt-3"+ onClick={() => void directories.refetch()}+ >+ {t('actions.refresh')}+ </Button>+ </>+ )}+ </TableCell>+ </TableRow>+ ) : directories.data.length === 0 ? (+ <TableRow>+ <TableCell+ colSpan={5}+ className="py-10 text-center text-muted-foreground"+ >+ {t('acl.page.emptyDirectory')}+ </TableCell>+ </TableRow>+ ) : (+ directories.data.map((entry) => (+ <DirectoryRow+ key={entry.uri}+ entry={entry}+ accountEnabled={+ state.settings.data === true &&+ state.settings.isSuccess &&+ !state.settings.isFetching+ }+ parentControlled={parentControlled}+ parentKnown={parentKnown}+ onOpen={() => setCurrentUri(entry.uri)}+ onEdit={() => setEditingUri(entry.uri)}+ />+ ))+ )}+ </TableBody>+ </Table>+ </div>+ <Sheet+ open={Boolean(editingUri)}+ onOpenChange={(open) => !open && setEditingUri('')}+ >+ <SheetContent className="gap-0 data-[side=right]:sm:max-w-2xl">+ <SheetHeader className="border-b px-6 py-5">+ <SheetTitle className="pr-10 text-lg">+ {t('acl.page.editDirectory', {+ directory: editingUri.slice(root.length).replace(/\/$/, ''),+ })}+ </SheetTitle>+ </SheetHeader>+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">+ {editingUri && (+ <ResourcePermissionsPanel+ key={`${state.aclIdentityScopeKey}:${editingUri}`}+ uri={editingUri}+ />+ )}+ </div>+ </SheetContent>+ </Sheet>+ </section>+ )+}++function DirectoryRow({+ entry,+ accountEnabled,+ parentControlled,+ parentKnown,+ onOpen,+ onEdit,+}: {+ entry: VikingFsEntry+ accountEnabled: boolean+ parentControlled: boolean+ parentKnown: boolean+ onOpen: () => void+ onEdit: () => void+}) {+ const state = useAclManagement(false)+ const { t } = useTranslation('settings')+ const client = useQueryClient()+ const [next, setNext] = useState<boolean | null>(null)+ useEffect(() => {+ if (!accountEnabled) setNext(null)+ }, [accountEnabled])+ const uri = entry.uri+ const key = ['resource-acl', state.aclIdentityScopeKey, uri]+ const report = useQuery({+ queryKey: key,+ queryFn: () => state.api.get(uri),+ enabled: state.allowed,+ retry: false,+ })+ const name = entry.name+ const hasAcl = report.isSuccess && report.data.acl_mode !== 'none'+ const restricted = report.isSuccess && report.data.acl_mode === 'restricted'+ const grants =+ report.data?.direct_entries.map((grant) => {+ if (grant.principal === 'user:*') {+ return {+ principal: grant.principal,+ label: t('acl.subjects.everyoneShort'),+ level: grant.level,+ type: 'everyone',+ }+ }+ const type = grant.principal.startsWith('group:') ? 'group' : 'user'+ return {+ principal: grant.principal,+ label: grant.principal.slice(grant.principal.indexOf(':') + 1),+ level: grant.level,+ type,+ }+ }) || []+ const grantNames = grants.map(+ ({ label, level, type }) =>+ `${type === 'everyone' ? t('acl.everyone') : `${t(`acl.subjects.${type}`)} · ${label}`}: ${t(`acl.levels.${level}`)}`,+ )+ const writable =+ accountEnabled && report.isSuccess && !report.isFetching && parentKnown+ // The drawer contains identity recovery when this row's ACL report is denied.+ const canOpenEditor =+ report.isError || (writable && (hasAcl || parentControlled))+ const update = useMutation({+ mutationFn: (limit: boolean) =>+ state.api.change(+ uri,+ limit+ ? { kind: 'mode', mode: 'restricted' }+ : parentControlled+ ? { kind: 'mode', mode: 'inherit' }+ : { kind: 'reset' },+ ),+ onSuccess: async (updated) => {+ client.setQueryData(key, updated)+ setNext(null)+ toast.success(t('acl.saved'))+ await client.invalidateQueries()+ },+ onError: (error) =>+ toast.error(t('acl.failed'), { description: getErrorMessage(error) }),+ })+ return (+ <>+ <TableRow>+ <TableCell className="pl-4">+ <button+ type="button"+ className="flex max-w-full items-center gap-2 text-left font-medium hover:underline"+ onClick={onOpen}+ >+ <FolderIcon className="size-4 shrink-0 text-muted-foreground" />+ <span className="truncate" title={name}>+ {name}+ </span>+ </button>+ </TableCell>+ <TableCell+ className="min-w-0 overflow-hidden"+ title={grantNames.join(', ')}+ >+ {report.isSuccess ? (+ grants.length > 0 ? (+ <div className="flex min-w-0 items-center gap-1.5 overflow-hidden">+ {grants.slice(0, 3).map((grant) => (+ <Badge+ key={grant.principal}+ variant="secondary"+ className="max-w-44 min-w-0 gap-1 text-muted-foreground"+ title={`${grant.label}: ${t(`acl.levels.${grant.level}`)}`}+ >+ {grant.type === 'group' ? (+ <UsersRoundIcon className="shrink-0" />+ ) : grant.type === 'everyone' ? (+ <Globe2Icon className="shrink-0" />+ ) : (+ <UserRoundIcon className="shrink-0" />+ )}+ <span className="truncate">{grant.label}</span>+ <span aria-hidden="true">:</span>+ <span className="shrink-0 text-foreground">+ {t(`acl.levels.${grant.level}`)}+ </span>+ </Badge>+ ))}+ {grants.length > 3 && (+ <Badge variant="outline" className="text-muted-foreground">+ +{grants.length - 3}+ </Badge>+ )}+ </div>+ ) : (+ <span className="text-muted-foreground">+ {t('acl.page.noGrantees')}+ </span>+ )+ ) : (+ '—'+ )}+ </TableCell>+ <TableCell>+ <span className="text-muted-foreground">+ {report.isPending+ ? t('loading')+ : report.isError+ ? t('acl.page.unreadable')+ : t(`acl.modes.${report.data.acl_mode}`)}+ </span>+ </TableCell>+ <TableCell className="text-center">+ {report.isSuccess ? (+ <Switch+ checked={parentControlled ? restricted : hasAcl}+ disabled={!writable || update.isPending}+ aria-label={t('acl.page.limitFor', { directory: name })}+ onCheckedChange={setNext}+ />+ ) : (+ <span className="text-muted-foreground">—</span>+ )}+ </TableCell>+ <TableCell className="pr-4 text-right">+ <Button+ variant="ghost"+ size="sm"+ disabled={!canOpenEditor || update.isPending}+ onClick={onEdit}+ >+ {t('acl.page.manageAction')}+ </Button>+ </TableCell>+ </TableRow>+ <AlertDialog+ open={next !== null}+ onOpenChange={(open) => {+ if (!open && !update.isPending) setNext(null)+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t(+ next+ ? 'acl.limitTitle'+ : parentControlled+ ? 'acl.page.restoreInheritanceTitle'+ : 'acl.page.disableLimitTitle',+ )}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t(+ next+ ? 'acl.limitWarning'+ : parentControlled+ ? 'acl.page.restoreInheritanceWarning'+ : 'acl.page.disableLimitWarning',+ )}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={update.isPending}>+ {t('actions.cancel')}+ </AlertDialogCancel>+ <AlertDialogAction+ disabled={!writable || update.isPending}+ onClick={(event) => {+ event.preventDefault()+ if (writable && next !== null) update.mutate(next)+ }}+ >+ {update.isPending ? t('loading') : t('acl.confirm')}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ )+}diff --git a/web-studio/src/routes/permissions/route.test.tsx b/web-studio/src/routes/permissions/route.test.tsxnew file mode 100644index 000000000..aca1b2fa0--- /dev/null+++ b/web-studio/src/routes/permissions/route.test.tsx@@ -0,0 +1,404 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import {+ cleanup,+ render,+ screen,+ waitFor,+ within,+} from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { OvClientError } from '#/lib/ov-client'+import { PermissionsPage } from './-components/permissions-page'++const root = 'viking://resources/'+const mocks = vi.hoisted(() => ({+ accountId: 'acme',+ allowed: true,+ enabled: true,+ settingsFetching: false,+ modes: {} as Record<string, 'none' | 'inherit' | 'restricted'>,+ list: vi.fn(),+ change: vi.fn(),+ get: vi.fn(async (uri: string) => ({+ uri,+ acl_mode: mocks.modes[uri] ?? 'inherit',+ direct_entries: [{ principal: 'user:alice', level: 'read' }],+ inherited_entries: [],+ effective_entries: [],+ })),+}))+vi.mock('#/hooks/use-acl-management', () => ({+ useAclManagement: () => ({+ allowed: mocks.allowed,+ settings: {+ data: mocks.enabled,+ isSuccess: true,+ isFetching: mocks.settingsFetching,+ },+ settingsKey: ['account-acl', mocks.accountId],+ connection: { baseUrl: 'http://localhost', accountId: mocks.accountId },+ identityScopeKey: mocks.accountId,+ aclIdentityScopeKey: mocks.accountId,+ api: { get: mocks.get, listDirectory: mocks.list, change: mocks.change },+ }),+}))+vi.mock('#/components/account-acl-settings', () => ({+ AccountAclSettings: ({ inPopover }: { inPopover?: boolean }) => (+ <div data-testid={inPopover ? 'advanced-settings' : 'account-settings'} />+ ),+}))+vi.mock('#/components/resource-permissions', () => ({+ ResourcePermissionsPanel: ({ uri }: { uri: string }) => (+ <div data-testid="editor">{uri}</div>+ ),+}))+vi.mock('#/components/resource-acl-identity-recovery', () => ({+ ResourceAclIdentityRecovery: () => <div data-testid="identity-recovery" />,+}))+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}))+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))+beforeEach(() => {+ mocks.allowed = true+ mocks.enabled = true+ mocks.settingsFetching = false+ mocks.accountId = 'acme'+ mocks.modes = {}+ mocks.list.mockReset()+ mocks.get.mockReset()+ mocks.get.mockImplementation(async (uri: string) => ({+ uri,+ acl_mode: mocks.modes[uri] ?? 'inherit',+ direct_entries: [{ principal: 'user:alice', level: 'read' }],+ inherited_entries: [],+ effective_entries: [],+ }))+ mocks.change.mockReset()+ mocks.change.mockImplementation(async (uri, change) => {+ mocks.modes[uri] = change.kind === 'reset' ? 'none' : change.mode+ return mocks.get(uri)+ })+ mocks.list.mockImplementation(async (uri: string) => ({+ entries:+ uri === root+ ? ['im/', 'volcengine/']+ : uri === `${root}im/`+ ? ['feishu/']+ : [],+ }))+})+afterEach(cleanup)+function mount() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ const element = () => (+ <QueryClientProvider client={client}>+ <PermissionsPage />+ </QueryClientProvider>+ )+ const view = render(element())+ return {+ ...view,+ user: userEvent.setup(),+ refresh: () => view.rerender(element()),+ }+}+it('shows parent ACL errors and restores child controls after retry', async () => {+ const getReport = mocks.get.getMockImplementation()!+ let parentFails = true+ mocks.get.mockImplementation(async (uri) => {+ if (uri === `${root}im/` && parentFails) {+ throw new Error('Parent ACL request timed out')+ }+ return getReport(uri)+ })+ const { user } = mount()+ await user.click(await screen.findByRole('button', { name: 'im' }))+ const row = (await screen.findByRole('button', { name: 'feishu' })).closest(+ 'tr',+ )!+ const alert = await screen.findByRole('alert')+ expect(within(alert).getByText('acl.page.parentAclFailed')).toBeTruthy()+ expect(within(alert).getByText('Parent ACL request timed out')).toBeTruthy()+ const toggle = await within(row).findByRole('switch')+ const manager = within(row).getByRole('button', {+ name: 'acl.page.manageAction',+ })+ expect(toggle.hasAttribute('data-disabled')).toBe(true)+ expect(manager.hasAttribute('disabled')).toBe(true)+ parentFails = false+ await user.click(+ within(alert).getByRole('button', { name: 'actions.refresh' }),+ )+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull())+ expect(toggle.hasAttribute('data-disabled')).toBe(false)+ expect(manager.hasAttribute('disabled')).toBe(false)+})++it('discards an open confirmation when account ACL is disabled', async () => {+ const { user, refresh } = mount()+ const row = (await screen.findByRole('button', { name: 'im' })).closest('tr')!+ await user.click(await within(row).findByRole('switch'))+ expect(screen.getByRole('alertdialog')).toBeTruthy()+ mocks.enabled = false+ refresh()+ await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull())+ expect(within(row).getByRole('switch').hasAttribute('data-disabled')).toBe(+ true,+ )+ expect(mocks.change).not.toHaveBeenCalled()+ mocks.enabled = true+ refresh()+ expect(screen.queryByRole('alertdialog')).toBeNull()+})++it('blocks directory changes while account settings are refreshing', async () => {+ const { user, refresh } = mount()+ const row = (await screen.findByRole('button', { name: 'im' })).closest('tr')!+ const toggle = await within(row).findByRole('switch')+ mocks.settingsFetching = true+ refresh()+ expect(toggle.hasAttribute('data-disabled')).toBe(true)+ await user.click(toggle)+ expect(screen.queryByRole('alertdialog')).toBeNull()+ expect(mocks.change).not.toHaveBeenCalled()+ mocks.settingsFetching = false+ refresh()+ expect(toggle.hasAttribute('data-disabled')).toBe(false)+})++it('browses resources one directory at a time and edits permissions separately', async () => {+ const { user } = mount()+ expect(await screen.findByRole('button', { name: 'im' })).toBeTruthy()+ expect(screen.getByRole('button', { name: 'volcengine' })).toBeTruthy()+ expect(+ screen.queryByRole('button', { name: 'acl.page.addDirectory' }),+ ).toBeNull()+ await waitFor(() =>+ expect(+ screen.getAllByRole('button', { name: 'acl.page.manageAction' }),+ ).toHaveLength(2),+ )++ await user.click(screen.getByRole('button', { name: 'im' }))+ expect(await screen.findByRole('button', { name: 'feishu' })).toBeTruthy()+ expect(screen.queryByRole('button', { name: 'volcengine' })).toBeNull()+ await user.click(+ screen.getByRole('button', { name: 'acl.page.manageAction' }),+ )+ expect(+ within(screen.getByRole('dialog')).getByTestId('editor').textContent,+ ).toBe(`${root}im/feishu/`)+ await user.keyboard('{Escape}')+ await user.click(screen.getByRole('button', { name: 'acl.page.back' }))+ expect(await screen.findByRole('button', { name: 'volcengine' })).toBeTruthy()+})+it('shows recipient and permission level in a wider summary column', async () => {+ mocks.get.mockImplementation(async (uri: string) => ({+ uri,+ acl_mode: 'restricted',+ direct_entries: [+ { principal: 'group:fe-dev', level: 'read' },+ { principal: 'user:anonymous', level: 'write' },+ { principal: 'user:alice', level: 'manage' },+ { principal: 'user:bob', level: 'read' },+ ],+ inherited_entries: [],+ effective_entries: [],+ }))+ mount()+ const row = (await screen.findByRole('button', { name: 'im' })).closest('tr')!+ await waitFor(() => expect(within(row).getByText('+1')).toBeTruthy())+ expect(within(row).getByText('fe-dev')).toBeTruthy()+ expect(within(row).getByText('anonymous')).toBeTruthy()+ expect(within(row).getByText('alice')).toBeTruthy()+ expect(within(row).getByText('acl.levels.read')).toBeTruthy()+ expect(within(row).getByText('acl.levels.write')).toBeTruthy()+ expect(within(row).getByText('acl.levels.manage')).toBeTruthy()+ expect(within(row).queryByText('bob')).toBeNull()+ expect(within(row).getByText('+1').closest('td')?.getAttribute('title')).toBe(+ 'acl.subjects.group · fe-dev: acl.levels.read, acl.subjects.user · anonymous: acl.levels.write, acl.subjects.user · alice: acl.levels.manage, acl.subjects.user · bob: acl.levels.read',+ )+})+it('enables permission management only after restricted access is switched on', async () => {+ mocks.modes[`${root}im/`] = 'none'+ const { user } = mount()+ const row = (await screen.findByRole('button', { name: 'im' })).closest('tr')!+ const manager = within(row).getByRole('button', {+ name: 'acl.page.manageAction',+ })+ expect(manager.hasAttribute('disabled')).toBe(true)+ await user.click(await within(row).findByRole('switch'))+ expect(mocks.change).not.toHaveBeenCalled()+ await user.click(+ within(screen.getByRole('alertdialog')).getByRole('button', {+ name: 'acl.confirm',+ }),+ )+ await waitFor(() =>+ expect(mocks.change).toHaveBeenCalledWith(`${root}im/`, {+ kind: 'mode',+ mode: 'restricted',+ }),+ )+ await waitFor(() => expect(manager.hasAttribute('disabled')).toBe(false))+})+it('turns off an independent restriction and disables its management action', async () => {+ const { user } = mount()+ const row = (await screen.findByRole('button', { name: 'im' })).closest('tr')!+ await user.click(await within(row).findByRole('switch'))+ await user.click(+ within(screen.getByRole('alertdialog')).getByRole('button', {+ name: 'acl.confirm',+ }),+ )+ await waitFor(() =>+ expect(mocks.change).toHaveBeenCalledWith(`${root}im/`, { kind: 'reset' }),+ )+ await waitFor(() =>+ expect(+ within(row)+ .getByRole('button', { name: 'acl.page.manageAction' })+ .hasAttribute('disabled'),+ ).toBe(true),+ )+})+it('lets a child stop and restore inheritance without clearing its grants', async () => {+ const { user } = mount()+ await user.click(await screen.findByRole('button', { name: 'im' }))+ const row = (await screen.findByRole('button', { name: 'feishu' })).closest(+ 'tr',+ )!+ await waitFor(() => expect(within(row).getByRole('switch')).toBeTruthy())+ expect(within(row).getByText('acl.modes.inherit')).toBeTruthy()+ await user.click(within(row).getByRole('switch'))+ await user.click(+ within(screen.getByRole('alertdialog')).getByRole('button', {+ name: 'acl.confirm',+ }),+ )+ await waitFor(() =>+ expect(mocks.change).toHaveBeenCalledWith(`${root}im/feishu/`, {+ kind: 'mode',+ mode: 'restricted',+ }),+ )+ await user.click(within(row).getByRole('switch'))+ expect(+ within(screen.getByRole('alertdialog')).getByText(+ 'acl.page.restoreInheritanceWarning',+ ),+ ).toBeTruthy()+ await user.click(+ within(screen.getByRole('alertdialog')).getByRole('button', {+ name: 'acl.confirm',+ }),+ )+ await waitFor(() =>+ expect(mocks.change).toHaveBeenCalledWith(`${root}im/feishu/`, {+ kind: 'mode',+ mode: 'inherit',+ }),+ )+ expect(+ within(row)+ .getByRole('button', { name: 'acl.page.manageAction' })+ .hasAttribute('disabled'),+ ).toBe(false)+})+it('loads the tree from the server for each account, without a browser-maintained directory list', async () => {+ const view = mount()+ await screen.findByRole('button', { name: 'im' })+ await view.user.click(screen.getByRole('button', { name: 'im' }))+ await screen.findByRole('button', { name: 'feishu' })+ mocks.accountId = 'other'+ view.refresh()+ expect(await screen.findByRole('button', { name: 'volcengine' })).toBeTruthy()+ expect(mocks.list).toHaveBeenCalledWith(root)+})+it('shows a directory listing error with a retry action', async () => {+ mocks.list.mockRejectedValueOnce(new Error('Network unavailable'))+ const { user } = mount()+ expect(await screen.findByText('Network unavailable')).toBeTruthy()+ await user.click(+ screen.getAllByRole('button', { name: 'actions.refresh' })[1],+ )+ expect(await screen.findByRole('button', { name: 'im' })).toBeTruthy()+})+it('offers identity recovery when listing directories is denied', async () => {+ mocks.list.mockRejectedValueOnce(+ new OvClientError({+ code: 'PERMISSION_DENIED',+ message: 'Denied',+ statusCode: 403,+ }),+ )+ mount()+ expect(await screen.findByTestId('identity-recovery')).toBeTruthy()+})+it('opens the permission drawer when a row ACL report is denied', async () => {+ mocks.get.mockRejectedValueOnce(+ new OvClientError({+ code: 'PERMISSION_DENIED',+ message: 'Denied',+ statusCode: 403,+ }),+ )+ const { user } = mount()+ const row = (await screen.findByRole('button', { name: 'im' })).closest('tr')!+ const manager = within(row).getByRole('button', {+ name: 'acl.page.manageAction',+ })+ await waitFor(() => expect(manager.hasAttribute('disabled')).toBe(false))+ await user.click(manager)+ expect(within(screen.getByRole('dialog')).getByTestId('editor')).toBeTruthy()+})+it('keeps advanced account settings in the header and shows inline controls when disabled', () => {+ const { refresh } = mount()+ expect(screen.queryByTestId('account-settings')).toBeNull()+ expect(screen.getByTestId('advanced-settings')).toBeTruthy()+ mocks.enabled = false+ refresh()+ expect(screen.getByTestId('account-settings')).toBeTruthy()+ expect(screen.queryByTestId('advanced-settings')).toBeNull()+})++it('refreshes parent and child ACL reports even when directory entries are unchanged', async () => {+ const { user } = mount()+ await user.click(await screen.findByRole('button', { name: 'im' }))+ await screen.findByRole('button', { name: 'feishu' })+ await waitFor(() =>+ expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(false),+ )+ mocks.get.mockClear()+ mocks.modes[`${root}im/`] = 'none'+ mocks.get.mockImplementation(async (uri: string) => ({+ uri,+ acl_mode: mocks.modes[uri] ?? 'restricted',+ direct_entries: [{ principal: 'user:bob', level: 'manage' }],+ inherited_entries: [],+ effective_entries: [],+ }))+ await user.click(screen.getByRole('button', { name: 'actions.refresh' }))+ await waitFor(() => {+ expect(mocks.get).toHaveBeenCalledWith(`${root}im/`)+ expect(mocks.get).toHaveBeenCalledWith(`${root}im/feishu/`)+ expect(screen.getByText('bob')).toBeTruthy()+ expect(screen.getByText('acl.modes.restricted')).toBeTruthy()+ })+ await user.click(screen.getByRole('switch'))+ await user.click(+ within(screen.getByRole('alertdialog')).getByRole('button', {+ name: 'acl.confirm',+ }),+ )+ await waitFor(() =>+ expect(mocks.change).toHaveBeenCalledWith(`${root}im/feishu/`, {+ kind: 'reset',+ }),+ )+})diff --git a/web-studio/src/routes/permissions/route.tsx b/web-studio/src/routes/permissions/route.tsxnew file mode 100644index 000000000..c62e45a14--- /dev/null+++ b/web-studio/src/routes/permissions/route.tsx@@ -0,0 +1,5 @@+import { Navigate, createFileRoute } from '@tanstack/react-router'++export const Route = createFileRoute('/permissions')({+ component: () => <Navigate replace to="/users/permissions" />,+})diff --git a/web-studio/src/routes/users/-components/user-groups.tsx b/web-studio/src/routes/users/-components/user-groups.tsxindex d498fd70d..dd42eaeeb 100644--- a/web-studio/src/routes/users/-components/user-groups.tsx+++ b/web-studio/src/routes/users/-components/user-groups.tsx@@ -111,12 +111,9 @@ export function UserGroups({ connection }: { connection: AdminConnection }) {<div className="flex flex-col gap-5"><header className="flex flex-wrap items-center justify-between gap-3"><div className="flex flex-col gap-2">- <h1 className="text-2xl font-semibold">- {t('groups.title')}{' '}- <Badge variant="secondary">{connection.accountId}</Badge>- </h1>+ <h1 className="text-2xl font-semibold">{t('groups.title')}</h1><p className="text-sm text-muted-foreground">- {t('groups.description', { account: connection.accountId })}+ {t('groups.description')}</p></div><div className="flex gap-2">@@ -225,9 +222,7 @@ export function UserGroups({ connection }: { connection: AdminConnection }) {><DialogHeader><DialogTitle>{t('groups.create')}</DialogTitle>- <DialogDescription>- {t('groups.description', { account: connection.accountId })}- </DialogDescription>+ <DialogDescription>{t('groups.description')}</DialogDescription></DialogHeader><FieldGroup><Field>diff --git a/web-studio/src/routes/users/-lib/use-user-group-memberships.test.tsx b/web-studio/src/routes/users/-lib/use-user-group-memberships.test.tsxnew file mode 100644index 000000000..611423d0c--- /dev/null+++ b/web-studio/src/routes/users/-lib/use-user-group-memberships.test.tsx@@ -0,0 +1,87 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { cleanup, renderHook, waitFor } from '@testing-library/react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import type { ReactNode } from 'react'+import { useUserGroupMemberships } from './use-user-group-memberships'++const api = vi.hoisted(() => ({+ groups: vi.fn(),+ members: vi.fn(),+}))+vi.mock('#/lib/admin', () => ({+ fetchAdminGroups: api.groups,+ fetchAdminGroupMembers: api.members,+}))++const connection = {+ baseUrl: 'http://localhost:1933',+ accountId: 'acme',+ userId: 'admin',+ apiKey: 'admin-key',+}++beforeEach(() => {+ vi.resetAllMocks()+ api.groups.mockResolvedValue([+ { group_id: 'fe-dev', member_count: 2 },+ { group_id: 'reviewers', member_count: 1 },+ { group_id: 'empty', member_count: 0 },+ ])+ api.members.mockImplementation(async (_connection, groupId) => ({+ group_id: groupId,+ members: groupId === 'fe-dev' ? ['alice', 'bob'] : ['alice'],+ }))+})+afterEach(cleanup)++it('maps users to their groups and skips empty groups', async () => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )+ const { result } = renderHook(+ () => useUserGroupMemberships(connection, true),+ { wrapper },+ )+ await waitFor(() => expect(result.current.status).toBe('ready'))+ expect(result.current.byUser.get('alice')).toEqual(['fe-dev', 'reviewers'])+ expect(result.current.byUser.get('bob')).toEqual(['fe-dev'])+ expect(api.members).toHaveBeenCalledTimes(2)+})++it('reports incomplete membership data as an error', async () => {+ const error = new Error('Failed to load')+ api.members.mockRejectedValueOnce(error)+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )+ const { result } = renderHook(+ () => useUserGroupMemberships(connection, true),+ { wrapper },+ )+ await waitFor(() => expect(result.current.status).toBe('error'))+ expect(result.current.errors).toEqual([{ groupId: 'fe-dev', error }])+})++it('preserves the group-list request error for diagnosis', async () => {+ const error = new Error('Forbidden')+ api.groups.mockRejectedValue(error)+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )+ const { result } = renderHook(+ () => useUserGroupMemberships(connection, true),+ { wrapper },+ )+ await waitFor(() => expect(result.current.status).toBe('error'))+ expect(result.current.errors).toEqual([{ groupId: undefined, error }])+})diff --git a/web-studio/src/routes/users/-lib/use-user-group-memberships.ts b/web-studio/src/routes/users/-lib/use-user-group-memberships.tsnew file mode 100644index 000000000..8779ecb56--- /dev/null+++ b/web-studio/src/routes/users/-lib/use-user-group-memberships.ts@@ -0,0 +1,51 @@+import { useQueries, useQuery } from '@tanstack/react-query'+import { fetchAdminGroupMembers, fetchAdminGroups } from '#/lib/admin'+import type { AdminConnection } from '#/lib/admin'++export function useUserGroupMemberships(+ connection: AdminConnection,+ enabled: boolean,+) {+ const scope = [connection.baseUrl, connection.accountId, connection.apiKey]+ const groups = useQuery({+ queryKey: ['managed-groups', ...scope],+ queryFn: () => fetchAdminGroups(connection),+ enabled,+ retry: false,+ })+ const populatedGroups =+ groups.data?.filter((group) => group.member_count > 0) ?? []+ const members = useQueries({+ queries: populatedGroups.map((group) => ({+ queryKey: ['managed-group-members', ...scope, group.group_id],+ queryFn: () => fetchAdminGroupMembers(connection, group.group_id),+ enabled,+ retry: false,+ })),+ })+ const byUser = new Map<string, string[]>()+ members.forEach((query, index) => {+ query.data?.members.forEach((userId) => {+ const groupIds = byUser.get(userId) ?? []+ groupIds.push(populatedGroups[index].group_id)+ byUser.set(userId, groupIds)+ })+ })+ const status =+ groups.isError || members.some((query) => query.isError)+ ? 'error'+ : groups.isPending || members.some((query) => query.isPending)+ ? 'loading'+ : 'ready'++ const errors = [+ ...(groups.isError ? [{ groupId: undefined, error: groups.error }] : []),+ ...members.flatMap((query, index) =>+ query.isError+ ? [{ groupId: populatedGroups[index].group_id, error: query.error }]+ : [],+ ),+ ]++ return { byUser, status, errors }+}diff --git a/web-studio/src/routes/users/groups.tsx b/web-studio/src/routes/users/groups.tsxnew file mode 100644index 000000000..c45b47870--- /dev/null+++ b/web-studio/src/routes/users/groups.tsx@@ -0,0 +1,31 @@+import { createFileRoute } from '@tanstack/react-router'+import { useAppConnection } from '#/hooks/use-app-connection'+import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'+import { UserGroups } from './-components/user-groups'+import { UserManagementPanel } from './route'++export const Route = createFileRoute('/users/groups')({+ component: UserGroupsRoute,+})++function UserGroupsRoute() {+ const { connection, connectionRole, isConnectionRoleLoading, serverMode } =+ useAppConnection()+ const { canManageUsers } = resolveStudioManagementCapabilities({+ hasControlCredential: Boolean(connection.adminApiKey.trim()),+ isRoleLoading: isConnectionRoleLoading,+ role: connectionRole,+ serverMode,+ })+ if (!canManageUsers) return <UserManagementPanel />+ return (+ <UserGroups+ connection={{+ accountId: connection.accountId,+ apiKey: connection.adminApiKey,+ baseUrl: connection.baseUrl,+ userId: connection.userId,+ }}+ />+ )+}diff --git a/web-studio/src/routes/users/index.tsx b/web-studio/src/routes/users/index.tsxnew file mode 100644index 000000000..9e86bce93--- /dev/null+++ b/web-studio/src/routes/users/index.tsx@@ -0,0 +1,6 @@+import { createFileRoute } from '@tanstack/react-router'+import { UserManagementPanel } from './route'++export const Route = createFileRoute('/users/')({+ component: UserManagementPanel,+})diff --git a/web-studio/src/routes/users/permissions.tsx b/web-studio/src/routes/users/permissions.tsxnew file mode 100644index 000000000..468a5f95c--- /dev/null+++ b/web-studio/src/routes/users/permissions.tsx@@ -0,0 +1,6 @@+import { createFileRoute } from '@tanstack/react-router'+import { PermissionsPage } from '#/routes/permissions/-components/permissions-page'++export const Route = createFileRoute('/users/permissions')({+ component: PermissionsPage,+})diff --git a/web-studio/src/routes/users/route.test.ts b/web-studio/src/routes/users/route.test.tsnew file mode 100644index 000000000..fadb0005f--- /dev/null+++ b/web-studio/src/routes/users/route.test.ts@@ -0,0 +1,15 @@+import { createMemoryHistory, createRouter } from '@tanstack/react-router'+import { expect, it } from 'vitest'+import { routeTree } from '#/routeTree.gen'++it.each([+ ['/users', '/users/'],+ ['/users/groups', '/users/groups'],+ ['/users/permissions', '/users/permissions'],+])('matches the user and permissions tab at %s', (path, routeId) => {+ const router = createRouter({+ routeTree,+ history: createMemoryHistory({ initialEntries: [path] }),+ })+ expect(router.matchRoutes(path).at(-1)?.routeId).toBe(routeId)+})diff --git a/web-studio/src/routes/users/route.tsx b/web-studio/src/routes/users/route.tsxindex 5428435e0..c53262e25 100644--- a/web-studio/src/routes/users/route.tsx+++ b/web-studio/src/routes/users/route.tsx@@ -1,6 +1,12 @@import * as React from 'react'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { Link, createFileRoute } from '@tanstack/react-router'+import {+ Link,+ Outlet,+ createFileRoute,+ useNavigate,+ useRouterState,+} from '@tanstack/react-router'import {CheckIcon,CopyIcon,@@ -9,21 +15,23 @@ import {PlusIcon,RefreshCwIcon,RotateCwIcon,+ ShieldCheckIcon,ShieldAlertIcon,Trash2Icon,+ UserRoundIcon,UsersRoundIcon,} from 'lucide-react'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'import { Tabs, TabsList, TabsTrigger, TabsContent } from '#/components/ui/tabs'-import { UserGroups } from './-components/user-groups'import { Badge } from '#/components/ui/badge'import { Button } from '#/components/ui/button'import { Input } from '#/components/ui/input'import { UserPagination } from './-components/user-pagination'import { useUserList } from './-lib/use-user-list'+import { useUserGroupMemberships } from './-lib/use-user-group-memberships'import {Card,CardContent,@@ -90,6 +98,8 @@ export const Route = createFileRoute('/users')({})const USER_ROLE_OPTIONS: AdminUserRole[] = ['user', 'admin', 'root']+const managementTabClassName =+ 'h-12 flex-none rounded-none border-0 px-4 text-sm data-active:bg-transparent data-active:font-semibold dark:data-active:border-transparent dark:data-active:bg-transparent focus-visible:border-transparent focus-visible:bg-transparent focus-visible:ring-0 focus-visible:outline-none focus-visible:after:h-1 focus-visible:after:bg-ring focus-visible:after:opacity-100 after:bg-primary'function isAdminUserRole(role: string): role is AdminUserRole {return USER_ROLE_OPTIONS.includes(role as AdminUserRole)@@ -111,46 +121,64 @@ function resolveKeyLabel(user: AdminUser): string {function UserManagementRoute() {const { t } = useTranslation('settings')- const { connection, connectionRole, isConnectionRoleLoading, serverMode } =- useAppConnection()- const { canManageUsers } = resolveStudioManagementCapabilities({- hasControlCredential: Boolean(connection.adminApiKey.trim()),- isRoleLoading: isConnectionRoleLoading,- role: connectionRole,- serverMode,+ const navigate = useNavigate()+ const pathname = useRouterState({+ select: (state) => state.location.pathname,})- if (!canManageUsers) return <UserManagementPanel />- const adminConnection: AdminConnection = {- accountId: connection.accountId,- apiKey: connection.adminApiKey,- baseUrl: connection.baseUrl,- userId: connection.userId,- }+ const activeTab = pathname.startsWith('/users/permissions')+ ? 'permissions'+ : pathname.startsWith('/users/groups')+ ? 'groups'+ : 'users'return (<Tabs- key={JSON.stringify([- connection.baseUrl,- connection.accountId,- connection.adminApiKey,- ])}- defaultValue="users"+ value={activeTab}+ onValueChange={(value) => {+ const to =+ value === 'groups'+ ? '/users/groups'+ : value === 'permissions'+ ? '/users/permissions'+ : '/users'+ void navigate({ to })+ }}className="w-full min-w-0">- <TabsList aria-label={t('groups.navigation')}>- <TabsTrigger value="users">{t('groups.usersTab')}</TabsTrigger>- <TabsTrigger value="groups">{t('groups.title')}</TabsTrigger>+ <h1 className="mb-3 text-2xl font-semibold tracking-tight">+ {t('groups.navigation')}+ </h1>+ <TabsList+ variant="line"+ aria-label={t('groups.navigation')}+ className="w-full justify-start gap-1 border-b border-border p-0 group-data-horizontal/tabs:h-12"+ >+ <TabsTrigger value="users" className={managementTabClassName}>+ <UserRoundIcon />+ {t('groups.usersTab')}+ </TabsTrigger>+ <TabsTrigger value="groups" className={managementTabClassName}>+ <UsersRoundIcon />+ {t('groups.title')}+ </TabsTrigger>+ <TabsTrigger value="permissions" className={managementTabClassName}>+ <ShieldCheckIcon />+ {t('acl.page.title')}+ </TabsTrigger></TabsList>- <TabsContent value="users">- <UserManagementPanel />+ <TabsContent value="users" className="pt-5">+ {activeTab === 'users' && <Outlet />}</TabsContent>- <TabsContent value="groups">- <UserGroups connection={adminConnection} />+ <TabsContent value="groups" className="pt-5">+ {activeTab === 'groups' && <Outlet />}+ </TabsContent>+ <TabsContent value="permissions" className="pt-5">+ {activeTab === 'permissions' && <Outlet />}</TabsContent></Tabs>)}-function UserManagementPanel() {+export function UserManagementPanel() {const { t } = useTranslation('settings')const queryClient = useQueryClient()const {@@ -227,6 +255,10 @@ function UserManagementPanel() {],retry: false,})+ const memberships = useUserGroupMemberships(+ adminConnection,+ canManageUsers && Boolean(connection.accountId),+ )const users = usersQuery.data?.users ?? []const total = usersQuery.data?.total ?? 0const accountTotal = usersQuery.data?.accountTotal ?? 0@@ -386,18 +418,11 @@ function UserManagementPanel() {<div className="flex w-full min-w-0 flex-col gap-5"><header className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between"><div className="flex min-w-0 flex-col gap-2">- <div className="flex flex-wrap items-center gap-2">- <h1 className="text-2xl font-semibold tracking-tight">- {t('management.title')}- </h1>- <Badge variant="secondary" className="max-w-72 truncate font-mono">- {connection.accountId}- </Badge>- </div>+ <h1 className="text-2xl font-semibold tracking-tight">+ {t('management.title')}+ </h1><p className="max-w-3xl text-sm leading-6 text-muted-foreground">- {t('management.currentAccountDescription', {- account: connection.accountId,- })}+ {t('management.currentAccountDescription')}</p></div><div className="flex shrink-0 flex-wrap gap-2">@@ -412,6 +437,22 @@ function UserManagementPanel() {variant="outline"onClick={() => {void usersQuery.refetch()+ void queryClient.invalidateQueries({+ queryKey: [+ 'managed-groups',+ adminConnection.baseUrl,+ adminConnection.accountId,+ adminConnection.apiKey,+ ],+ })+ void queryClient.invalidateQueries({+ queryKey: [+ 'managed-group-members',+ adminConnection.baseUrl,+ adminConnection.accountId,+ adminConnection.apiKey,+ ],+ })void queryClient.invalidateQueries({queryKey: ['user-memory-settings',@@ -520,6 +561,7 @@ function UserManagementPanel() {<TableRow className="bg-muted/20 hover:bg-muted/20"><TableHead>{t('table.user')}</TableHead><TableHead>{t('table.role')}</TableHead>+ <TableHead>{t('table.groups')}</TableHead><TableHead>{t('memoryPolicy.title')}</TableHead><TableHead>{t('table.apiKey')}</TableHead><TableHead className="text-right">@@ -530,6 +572,7 @@ function UserManagementPanel() {<TableBody>{users.map((user) => {const identityKey = `${user.accountId}:${user.userId}`+ const userGroups = memberships.byUser.get(user.userId) ?? []const isCurrentIdentity =user.accountId === connection.accountId &&user.userId === connection.userId@@ -556,8 +599,8 @@ function UserManagementPanel() {}><TableCell className="font-medium">- <div className="flex items-center gap-2">- {user.userId}+ <div className="group/user flex items-center gap-2">+ <span className="truncate">{user.userId}</span>{isCurrentIdentity ? (<Badgevariant="secondary"@@ -567,6 +610,27 @@ function UserManagementPanel() {{t('actions.currentIdentity')}</Badge>) : null}+ {canSwitchIdentity ? (+ <Button+ type="button"+ variant="secondary"+ size="xs"+ disabled={Boolean(switchingIdentityKey)}+ className={+ isSwitching+ ? 'opacity-100'+ : 'opacity-0 transition-opacity group-hover/user:opacity-100 group-focus-within/user:opacity-100 [@media(hover:none)]:opacity-100'+ }+ onClick={() => void useUserIdentity(user)}+ >+ {isSwitching ? (+ <LoaderCircleIcon className="animate-spin" />+ ) : (+ <KeyRoundIcon />+ )}+ {t('actions.switchIdentity')}+ </Button>+ ) : null}</div></TableCell><TableCell>@@ -618,6 +682,52 @@ function UserManagementPanel() {</Badge>)}</TableCell>+ <TableCell>+ {memberships.status === 'loading' ? (+ <span className="text-muted-foreground">+ {t('loading')}+ </span>+ ) : memberships.status === 'error' ? (+ <details className="text-muted-foreground">+ <summary className="cursor-pointer">+ {t('groups.loadFailed')}+ </summary>+ {memberships.errors.map(({ groupId, error }) => (+ <p+ key={groupId ?? 'groups'}+ className="mt-1 break-all text-xs"+ >+ {groupId ? `${groupId}: ` : ''}+ {getErrorMessage(error)}+ </p>+ ))}+ </details>+ ) : userGroups.length === 0 ? (+ <span className="text-muted-foreground">+ {t('groups.notJoined')}+ </span>+ ) : (+ <div+ className="flex max-w-56 items-center gap-1.5"+ title={userGroups.join(', ')}+ >+ {userGroups.slice(0, 2).map((groupId) => (+ <Badge+ key={groupId}+ variant="secondary"+ className="max-w-24 min-w-0"+ >+ <span className="truncate">{groupId}</span>+ </Badge>+ ))}+ {userGroups.length > 2 && (+ <Badge variant="outline">+ +{userGroups.length - 2}+ </Badge>+ )}+ </div>+ )}+ </TableCell><TableCell><UserMemoryPolicyCellconnection={adminConnection}@@ -679,29 +789,6 @@ function UserManagementPanel() {</TableCell><TableCell><div className="flex items-center justify-end gap-1">- {canSwitchIdentity ? (- <Button- type="button"- variant="secondary"- size="sm"- disabled={Boolean(switchingIdentityKey)}- onClick={() => void useUserIdentity(user)}- >- {isSwitching ? (- <LoaderCircleIcon className="animate-spin" />- ) : (- <KeyRoundIcon />- )}- {t('actions.switchIdentity')}- </Button>- ) : isCurrentIdentity ? (- <span- aria-hidden="true"- className="px-3 text-muted-foreground/45"- >- —- </span>- ) : null}<Tooltip><TooltipTriggerrender={