Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Keep User Access state within its current reader

pulse-triage[bot]bc3c637d55cc
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 287828b909..6a999add39 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -13578,3 +13578,14 @@ earlier raw object; that current-read object remains usable for the same live
ID. A later full read, context withdrawal or deletion invalidates the old
confirmation. The registered sequential scope-edit/revoke consumer regression
and earlier-read rejection test cover both sides without ID-only admission.
+
+### User Access requests retain their confirmed context
+
+RBAC directory/role reads, saved-permission reads and user assignment/removal
+operations accept client-only `RBACAdminRequestOptions`. User Access supplies an
+abort signal, exact expected organisation and `retry: false` to the canonical
+API client, including its CSRF preparation boundary. A withdrawn confirmation
+must not dispatch into the default or a new organisation or automatically replay
+a refusal. Endpoint paths, encoded principal keys, JSON payloads, authentication
+and server permission checks are unchanged. `api/__tests__/rbac.test.ts` and
+`UserAccessReaderLifetime.test.tsx` pin forwarding and the consuming lifecycle.
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 5c347fdeae..2ddf03f2f0 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -11129,3 +11129,15 @@ literal date evidence and the browser-reproduced focus repair. The 15% threshold
all other per-chunk baselines, total JS/CSS and preload/SRI checks stay unchanged.
This is a narrowly declared intentional UI/accessibility cost, not suppression
of the retained failed budget runs or permission to omit browser verification.
+
+### User Access reader projection
+
+The canonical settings panel registry supplies User Access with the effective
+authenticated principal and explicit `settingsCapabilities.users` value from
+the shared security status, just as the existing SSO surface receives its
+reader. Primitive value changes, not a containing status-object refresh, retire
+that reader. Missing authority is denied; registry navigation gating alone is
+not a lifetime guard for mounted directory reads, dialogs or pending writes.
+`settingsPanelRegistryContext.test.ts`, `settingsArchitecture.test.ts` and the
+registered User Access lifetime tests cover this projection without introducing
+a new route or an alternative permission model.
diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md
index 47a89e2adf..f4faa0a306 100644
--- a/docs/release-control/v6/internal/subsystems/organization-settings.md
+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md
@@ -522,3 +522,20 @@ settings page. The old `system-ai-assistant` tab id and
`/settings/pulse-intelligence/assistant` path redirect there, so saved links
keep working. Organization-scoped settings ownership, RBAC gating, and the
settings shell's organization presentation rules are unchanged.
+
+### User Access reader lifetime
+
+The existing User Access directory, role choices, saved-permission read, drafts
+and removal confirmations belong to one mounted authenticated reader and
+organisation. `useUserAssignmentsPanelState.ts` withdraws them on principal,
+users-capability, RBAC-entitlement or organisation changes and disposal, aborts
+pending requests and rejects obsolete completions even after leaving and
+returning to the same context. The next admitted reader loads a fresh directory.
+A failed or malformed directory/role list is unknown, not an empty configuration;
+Retry is read-only. Only current inventory rows may open a confirmation, and
+only one confirmed assignment/removal write may run. No obsolete completion may
+announce success, close a new reader's editor or reload old accounts. Server
+authorisation, IdP deprovisioning and existing self-modification protection remain
+unchanged. Registered reader-lifetime, paywall-panel and RBAC transport tests
+cover these rules; synthetic desktop/narrow browser proof is not installed
+administrator or native IdP recovery.
diff --git a/frontend-modern/src/api/__tests__/rbac.test.ts b/frontend-modern/src/api/__tests__/rbac.test.ts
index 94d119ae10..59f7db330c 100644
--- a/frontend-modern/src/api/__tests__/rbac.test.ts
+++ b/frontend-modern/src/api/__tests__/rbac.test.ts
@@ -213,4 +213,30 @@ describe('RBACAPI', () => {
},
);
});
+ it('forwards an exact abortable organisation and no-retry binding for User Access', async () => {
+ const controller = new AbortController();
+ const options = { signal: controller.signal, expectedOrgID: 'selected-org', retry: false };
+ vi.mocked(apiFetchJSON).mockResolvedValue([]);
+ await RBACAPI.getUsers(options);
+ await RBACAPI.getRoles(options);
+ await RBACAPI.getUserPermissions('sso:user/a', options);
+ await RBACAPI.updateUserRoles('sso:user/a', ['viewer'], options);
+ await RBACAPI.deleteUser('sso:user/a', options);
+ expect(apiFetchJSON).toHaveBeenNthCalledWith(1, '/api/admin/users', options);
+ expect(apiFetchJSON).toHaveBeenNthCalledWith(2, '/api/admin/roles', options);
+ expect(apiFetchJSON).toHaveBeenNthCalledWith(
+ 3,
+ '/api/admin/users/sso%3Auser%2Fa/permissions',
+ options,
+ );
+ expect(apiFetchJSON).toHaveBeenNthCalledWith(4, '/api/admin/users/sso%3Auser%2Fa/roles', {
+ ...options,
+ method: 'PUT',
+ body: JSON.stringify({ roleIds: ['viewer'] }),
+ });
+ expect(apiFetchJSON).toHaveBeenNthCalledWith(5, '/api/admin/users/sso%3Auser%2Fa', {
+ ...options,
+ method: 'DELETE',
+ });
+ });
});
diff --git a/frontend-modern/src/api/rbac.ts b/frontend-modern/src/api/rbac.ts
index 5d8ad15d0e..d4a69d599a 100644
--- a/frontend-modern/src/api/rbac.ts
+++ b/frontend-modern/src/api/rbac.ts
@@ -1,9 +1,13 @@
import { apiFetchJSON } from '@/utils/apiClient';
import type { Role, UserRoleAssignment, Permission } from '@/types/rbac';
+import type { RBACAdminRequestOptions } from '@/types/api';
+
+const readRBAC = <T>(url: string, options?: RBACAdminRequestOptions) =>
+ options === undefined ? apiFetchJSON<T>(url) : apiFetchJSON<T>(url, options);
export const RBACAPI = {
// Roles
- getRoles: () => apiFetchJSON<Role[]>('/api/admin/roles'),
+ getRoles: (options?: RBACAdminRequestOptions) => readRBAC<Role[]>('/api/admin/roles', options),
getRole: (id: string) => apiFetchJSON<Role>(`/api/admin/roles/${encodeURIComponent(id)}`),
saveRole: (role: Role) => {
const method = role.createdAt ? 'PUT' : 'POST';
@@ -18,20 +22,29 @@ export const RBACAPI = {
apiFetchJSON(`/api/admin/roles/${encodeURIComponent(id)}`, { method: 'DELETE' }),
// User Assignments
- getUsers: () => apiFetchJSON<UserRoleAssignment[]>('/api/admin/users'),
+ getUsers: (options?: RBACAdminRequestOptions) =>
+ readRBAC<UserRoleAssignment[]>('/api/admin/users', options),
getUserAssignment: (username: string) =>
apiFetchJSON<UserRoleAssignment>(`/api/admin/users/${encodeURIComponent(username)}/roles`),
- updateUserRoles: (username: string, roleIds: string[]) =>
+ updateUserRoles: (username: string, roleIds: string[], options?: RBACAdminRequestOptions) =>
apiFetchJSON(`/api/admin/users/${encodeURIComponent(username)}/roles`, {
+ ...options,
method: 'PUT',
body: JSON.stringify({ roleIds }),
}),
- deleteUser: (username: string) =>
- apiFetchJSON(`/api/admin/users/${encodeURIComponent(username)}`, { method: 'DELETE' }),
+ deleteUser: (username: string, options?: RBACAdminRequestOptions) =>
+ apiFetchJSON(`/api/admin/users/${encodeURIComponent(username)}`, {
+ ...options,
+ method: 'DELETE',
+ }),
- getUserPermissions: async (username: string): Promise<Permission[]> => {
- const permissions = await apiFetchJSON<unknown>(
+ getUserPermissions: async (
+ username: string,
+ options?: RBACAdminRequestOptions,
+ ): Promise<Permission[]> => {
+ const permissions = await readRBAC<unknown>(
`/api/admin/users/${encodeURIComponent(username)}/permissions`,
+ options,
);
if (
!Array.isArray(permissions) ||
diff --git a/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx
index cb6204c772..78dc0b408a 100644
--- a/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx
+++ b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx
@@ -4,6 +4,7 @@ import SettingsPanel from '@/components/shared/SettingsPanel';
import { RBACFeatureGateSection } from './RBACFeatureGateSection';
import { UserAssignmentsDialog } from './UserAssignmentsDialog';
import { useUserAssignmentsPanelState } from './useUserAssignmentsPanelState';
+import type { UserAssignmentsPanelProps } from './useUserAssignmentsPanelState';
import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
import Users from 'lucide-solid/icons/users';
import Shield from 'lucide-solid/icons/shield';
@@ -20,8 +21,8 @@ import { InlineNotice } from '@/components/shared/InlineNotice';
import TriangleAlert from 'lucide-solid/icons/triangle-alert';
import { Dialog } from '@/components/shared/Dialog';
-export const UserAssignmentsPanel: Component = () => {
- const state = useUserAssignmentsPanelState();
+export const UserAssignmentsPanel: Component<UserAssignmentsPanelProps> = (props) => {
+ const state = useUserAssignmentsPanelState(props);
const emptyStateCopy = () => getUserAssignmentsEmptyStateCopy();
let searchInputRef: HTMLInputElement | undefined;
@@ -37,7 +38,7 @@ export const UserAssignmentsPanel: Component = () => {
placeholder="Search users..."
value={state.searchQuery()}
onChange={state.setSearchQuery}
- disabled={!state.featureGate.rbacEnabled() || Boolean(state.loadError())}
+ disabled={!state.canEdit()}
class="min-w-60"
inputClass="min-h-10 sm:min-h-9 py-2.5"
/>
@@ -59,7 +60,13 @@ export const UserAssignmentsPanel: Component = () => {
</div>
</Show>
- <Show when={!state.loading() && state.featureGate.rbacEnabled() && state.loadError()}>
+ <Show when={!state.loading() && state.featureGate.rbacEnabled() && !state.accessAllowed()}>
+ <InlineNotice tone="warning" role="status">
+ User access is unavailable for this session.
+ </InlineNotice>
+ </Show>
+
+ <Show when={!state.loading() && state.accessAllowed() && state.loadError()}>
{(message) => (
<InlineNotice
role="alert"
@@ -78,7 +85,7 @@ export const UserAssignmentsPanel: Component = () => {
<Show
when={
!state.loading() &&
- state.featureGate.rbacEnabled() &&
+ state.accessAllowed() &&
!state.loadError() &&
state.filteredAssignments().length === 0
}
@@ -101,7 +108,7 @@ export const UserAssignmentsPanel: Component = () => {
<Show
when={
!state.loading() &&
- state.featureGate.rbacEnabled() &&
+ state.accessAllowed() &&
!state.loadError() &&
state.filteredAssignments().length > 0
}
@@ -167,6 +174,7 @@ export const UserAssignmentsPanel: Component = () => {
class="min-h-11 min-w-11 gap-2 px-2 sm:min-h-9 sm:min-w-0"
aria-label={`Manage access for ${getUserIdentityDisplayName(assignment)}`}
title="Manage access"
+ disabled={!state.canEdit()}
onClick={() => state.openManageAccess(assignment)}
>
<Pencil class="w-4 h-4" />
@@ -178,6 +186,7 @@ export const UserAssignmentsPanel: Component = () => {
class="min-h-11 min-w-11 gap-2 px-2 text-red-600 hover:text-red-700 sm:min-h-9 sm:min-w-0"
aria-label={`Remove ${getUserIdentityDisplayName(assignment)}`}
title="Remove user access"
+ disabled={!state.canEdit()}
onClick={() => state.openDeleteUser(assignment)}
>
<Trash2 class="w-4 h-4" />
diff --git a/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx b/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx
index e70e878a96..2009cae79f 100644
--- a/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx
@@ -333,7 +333,17 @@ describe('RBAC paywall settings panels', () => {
expect(deleteUserMock).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole('button', { name: 'Save Changes' }));
- await waitFor(() => expect(updateUserRolesMock).toHaveBeenCalledWith('alice', ['viewer']));
+ await waitFor(() =>
+ expect(updateUserRolesMock).toHaveBeenCalledWith(
+ 'alice',
+ ['viewer'],
+ expect.objectContaining({
+ expectedOrgID: 'default',
+ retry: false,
+ signal: expect.any(AbortSignal),
+ }),
+ ),
+ );
expect(updateUserRolesMock).toHaveBeenCalledTimes(1);
});
@@ -461,7 +471,14 @@ describe('RBAC paywall settings panels', () => {
fireEvent.click(screen.getByRole('button', { name: 'Remove User Access' }));
await waitFor(() => {
- expect(deleteUserMock).toHaveBeenCalledWith('sso:oidc:okta:opaque_subject');
+ expect(deleteUserMock).toHaveBeenCalledWith(
+ 'sso:oidc:okta:opaque_subject',
+ expect.objectContaining({
+ expectedOrgID: 'default',
+ retry: false,
+ signal: expect.any(AbortSignal),
+ }),
+ );
});
expect(notificationSuccessMock).toHaveBeenCalledWith('User access removed for Alice Example');
await waitFor(() => {
@@ -534,7 +551,15 @@ describe('RBAC paywall settings panels', () => {
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
await waitFor(() => {
- expect(updateUserRolesMock).toHaveBeenCalledWith('alice', ['admin']);
+ expect(updateUserRolesMock).toHaveBeenCalledWith(
+ 'alice',
+ ['admin'],
+ expect.objectContaining({
+ expectedOrgID: 'default',
+ retry: false,
+ signal: expect.any(AbortSignal),
+ }),
+ );
});
expect(notificationErrorMock).toHaveBeenCalledWith('Failed to update user roles');
expect(notificationSuccessMock).not.toHaveBeenCalled();
diff --git a/frontend-modern/src/components/Settings/__tests__/UserAccessReaderLifetime.test.tsx b/frontend-modern/src/components/Settings/__tests__/UserAccessReaderLifetime.test.tsx
new file mode 100644
index 0000000000..9515a3c4d3
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/UserAccessReaderLifetime.test.tsx
@@ -0,0 +1,380 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, render, waitFor } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { eventBus } from '@/stores/events';
+import { useUserAssignmentsPanelState } from '../useUserAssignmentsPanelState';
+import type { Permission, Role, UserRoleAssignment } from '@/types/rbac';
+
+const mocks = vi.hoisted(() => ({
+ org: 'north',
+ getUsers: vi.fn(),
+ getRoles: vi.fn(),
+ getUserPermissions: vi.fn(),
+ updateUserRoles: vi.fn(),
+ deleteUser: vi.fn(),
+ success: vi.fn(),
+ error: vi.fn(),
+ log: vi.fn(),
+}));
+vi.mock('@/utils/apiClient', () => ({ getOrgID: () => mocks.org }));
+vi.mock('@/api/rbac', () => ({ RBACAPI: mocks }));
+vi.mock('@/stores/notifications', () => ({
+ notificationStore: { success: mocks.success, error: mocks.error },
+}));
+vi.mock('@/utils/logger', () => ({ logger: { error: mocks.log } }));
+vi.mock('../useRBACFeatureGateState', () => ({
+ useRBACFeatureGateState: () => ({ licenseReady: () => true, rbacEnabled: () => true }),
+}));
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+const alice: UserRoleAssignment = {
+ username: 'old-principal',
+ displayName: 'North private user',
+ email: '[email protected]',
+ roleIds: ['reader'],
+};
+const bob: UserRoleAssignment = {
+ username: 'new-principal',
+ displayName: 'South user',
+ roleIds: ['reader'],
+};
+const roles: Role[] = [
+ { id: 'reader', name: 'Reader', description: 'Read monitoring', permissions: [] },
+];
+const pause = () => new Promise((resolve) => setTimeout(resolve, 0));
+function mount() {
+ const [user, setUser] = createSignal<string | undefined>('operator-a');
+ const [allowed, setAllowed] = createSignal(true);
+ let state!: ReturnType<typeof useUserAssignmentsPanelState>;
+ const view = render(() => {
+ state = useUserAssignmentsPanelState({
+ get currentUser() {
+ return user();
+ },
+ get canManage() {
+ return allowed();
+ },
+ });
+ return <div />;
+ });
+ return { state, setUser, setAllowed, view };
+}
+async function loaded(state: ReturnType<typeof useUserAssignmentsPanelState>) {
+ await waitFor(() => expect(state.loading()).toBe(false));
+}
+function switchOrg() {
+ mocks.org = 'south';
+ eventBus.emit('org_switched', 'south');
+}
+
+describe('User Access reader lifetime', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.org = 'north';
+ mocks.getUsers.mockReset().mockResolvedValue([alice]);
+ mocks.getRoles.mockReset().mockResolvedValue(roles);
+ mocks.getUserPermissions
+ .mockReset()
+ .mockResolvedValue([{ action: 'read', resource: 'north-private' }]);
+ mocks.updateUserRoles.mockReset().mockResolvedValue(undefined);
+ mocks.deleteUser.mockReset().mockResolvedValue(undefined);
+ });
+ afterEach(cleanup);
+
+ it('withdraws the account directory, draft, permissions and removal confirmation on org switch', async () => {
+ const { state } = mount();
+ await loaded(state);
+ await state.openManageAccess(alice);
+ state.setSearchQuery('private');
+ state.openDeleteUser(alice);
+ const next = deferred<UserRoleAssignment[]>();
+ mocks.getUsers.mockReturnValueOnce(next.promise);
+ switchOrg();
+ await pause();
+ expect(state.filteredAssignments()).toEqual([]);
+ expect(state.editingUser()).toBeNull();
+ expect(state.formRoleIds()).toEqual([]);
+ expect(state.userPermissions()).toBeNull();
+ expect(state.userPendingDeletion()).toBeNull();
+ expect(state.searchQuery()).toBe('');
+ next.resolve([bob]);
+ await loaded(state);
+ expect(state.filteredAssignments()).toEqual([bob]);
+ });
+
+ it('ignores an old directory response after a new organisation read has completed', async () => {
+ const old = deferred<UserRoleAssignment[]>();
+ mocks.getUsers.mockReturnValueOnce(old.promise);
+ const { state } = mount();
+ await pause();
+ mocks.getUsers.mockResolvedValueOnce([bob]);
+ switchOrg();
+ await pause();
+ old.resolve([alice]);
+ await pause();
+ expect(state.filteredAssignments()).toEqual([bob]);
+ });
+
+ it('does not import an old permissions response into a same-principal new reader', async () => {
+ const old = deferred<Permission[]>();
+ mocks.getUserPermissions.mockReturnValueOnce(old.promise);
+ const { state, setUser } = mount();
+ await loaded(state);
+ const pending = state.openManageAccess(alice);
+ await pause();
+ setUser('operator-b');
+ await pause();
+ expect(state.showModal()).toBe(false);
+ old.resolve([{ action: 'read', resource: 'private-from-old-reader' }]);
+ await pending;
+ expect(state.userPermissions()).toBeNull();
+ expect(state.editingUser()).toBeNull();
+ });
+
+ it('withdraws all account state and refuses actions when administration is revoked', async () => {
+ const { state, setAllowed } = mount();
+ await loaded(state);
+ await state.openManageAccess(alice);
+ setAllowed(false);
+ await pause();
+ expect(state.filteredAssignments()).toEqual([]);
+ expect(state.showModal()).toBe(false);
+ await state.openManageAccess(alice);
+ state.openDeleteUser(alice);
+ await state.handleSaveAssignments();
+ await state.handleDeleteUser();
+ expect(mocks.updateUserRoles).not.toHaveBeenCalled();
+ expect(mocks.deleteUser).not.toHaveBeenCalled();
+ });
+
+ it('does not announce an obsolete save or reload its account into the new organisation', async () => {
+ const old = deferred<void>();
+ mocks.updateUserRoles.mockReturnValueOnce(old.promise);
+ const { state } = mount();
+ await loaded(state);
+ await state.openManageAccess(alice);
+ const saving = state.handleSaveAssignments();
+ await pause();
+ mocks.getUsers.mockResolvedValueOnce([bob]);
+ switchOrg();
+ await pause();
+ old.resolve();
+ await saving;
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(state.filteredAssignments()).toEqual([bob]);
+ });
+
+ it('releases a pending directory read on disposal without notification or retained accounts', async () => {
+ const old = deferred<UserRoleAssignment[]>();
+ mocks.getUsers.mockReturnValueOnce(old.promise);
+ const { state, view } = mount();
+ await pause();
+ view.unmount();
+ old.resolve([alice]);
+ await pause();
+ expect(state.filteredAssignments()).toEqual([]);
+ expect(mocks.error).not.toHaveBeenCalled();
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+ it('recovers a fresh inventory after administration is restored, without restoring the old draft', async () => {
+ const { state, setAllowed } = mount();
+ await loaded(state);
+ await state.openManageAccess(alice);
+ setAllowed(false);
+ await pause();
+ mocks.getUsers.mockResolvedValueOnce([bob]);
+ setAllowed(true);
+ await loaded(state);
+ expect(state.filteredAssignments()).toEqual([bob]);
+ expect(state.editingUser()).toBeNull();
+ expect(state.canEdit()).toBe(true);
+ });
+
+ it('refuses a stale row even when its principal also exists in the refreshed inventory', async () => {
+ const { state } = mount();
+ await loaded(state);
+ const fresh = { ...alice, displayName: 'Fresh account' };
+ mocks.getUsers.mockResolvedValueOnce([fresh]);
+ await state.loadData();
+ await state.openManageAccess(alice);
+ state.openDeleteUser(alice);
+ expect(state.showModal()).toBe(false);
+ expect(state.userPendingDeletion()).toBeNull();
+ await state.openManageAccess(fresh);
+ expect(state.showModal()).toBe(true);
+ });
+
+ it('refuses a retained action before the org-switch event is delivered', async () => {
+ const { state } = mount();
+ await loaded(state);
+ await state.openManageAccess(alice);
+ mocks.org = 'south';
+ await state.handleSaveAssignments();
+ state.openDeleteUser(alice);
+ await state.handleDeleteUser();
+ expect(mocks.updateUserRoles).not.toHaveBeenCalled();
+ expect(mocks.deleteUser).not.toHaveBeenCalled();
+ });
+
+ it('binds every read and write to an abortable, no-retry organisation request', async () => {
+ const { state } = mount();
+ await loaded(state);
+ await state.openManageAccess(alice);
+ const options = expect.objectContaining({
+ expectedOrgID: 'north',
+ retry: false,
+ signal: expect.any(AbortSignal),
+ });
+ expect(mocks.getUsers).toHaveBeenCalledWith(options);
+ expect(mocks.getRoles).toHaveBeenCalledWith(options);
+ expect(mocks.getUserPermissions).toHaveBeenCalledWith(alice.username, options);
+ await state.handleSaveAssignments();
+ expect(mocks.updateUserRoles).toHaveBeenCalledWith(alice.username, ['reader'], options);
+ state.openDeleteUser(alice);
+ await state.handleDeleteUser();
+ expect(mocks.deleteUser).toHaveBeenCalledWith(alice.username, options);
+ });
+
+ it('allows only one mutation and holds its confirmed role selection while it is pending', async () => {
+ const pending = deferred<void>();
+ mocks.updateUserRoles.mockReturnValueOnce(pending.promise);
+ const { state } = mount();
+ await loaded(state);
+ await state.openManageAccess(alice);
+ const save = state.handleSaveAssignments();
+ state.toggleRole('reader');
+ state.closeModal();
+ await state.handleSaveAssignments();
+ state.openDeleteUser(alice);
+ await state.handleDeleteUser();
+ expect(mocks.updateUserRoles).toHaveBeenCalledTimes(1);
+ expect(mocks.deleteUser).not.toHaveBeenCalled();
+ expect(state.formRoleIds()).toEqual(['reader']);
+ expect(state.showModal()).toBe(true);
+ pending.resolve();
+ await save;
+ expect(state.saving()).toBe(false);
+ expect(state.showModal()).toBe(false);
+ });
+
+ it('preserves the current draft on a refused save without logging the private response', async () => {
+ mocks.updateUserRoles.mockRejectedValueOnce(new Error('private response canary'));
+ const { state } = mount();
+ await loaded(state);
+ await state.openManageAccess(alice);
+ state.toggleRole('reader');
+ await state.handleSaveAssignments();
+ expect(state.showModal()).toBe(true);
+ expect(state.formRoleIds()).toEqual([]);
+ expect(mocks.error).toHaveBeenCalledWith('Failed to update user roles');
+ expect(JSON.stringify(mocks.log.mock.calls)).not.toContain('private response canary');
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+
+ it.each(['success', 'failure'])(
+ 'ignores obsolete deletion %s without closing the new reader editor',
+ async (outcome) => {
+ const old = deferred<void>();
+ mocks.deleteUser.mockReturnValueOnce(old.promise);
+ const { state } = mount();
+ await loaded(state);
+ state.openDeleteUser(alice);
+ const deletion = state.handleDeleteUser();
+ await pause();
+ mocks.getUsers.mockResolvedValueOnce([bob]);
+ switchOrg();
+ await loaded(state);
+ await state.openManageAccess(bob);
+ if (outcome === 'success') old.resolve();
+ else old.reject(new Error('private old failure'));
+ await deletion;
+ expect(state.showModal()).toBe(true);
+ expect(state.editingUser()).toEqual(bob);
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ },
+ );
+
+ it('aborts the previous directory and permission reads on withdrawal', async () => {
+ const { state, setAllowed } = mount();
+ await loaded(state);
+ const permission = deferred<Permission[]>();
+ mocks.getUserPermissions.mockReturnValueOnce(permission.promise);
+ const reading = state.openManageAccess(alice);
+ await pause();
+ const permissionOptions = mocks.getUserPermissions.mock.calls.at(-1)![1];
+ setAllowed(false);
+ await pause();
+ expect(permissionOptions.signal.aborted).toBe(true);
+ permission.reject(new Error('old private failure'));
+ await reading;
+ expect(mocks.log).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ });
+
+ it('does not reuse a response after leaving and returning to the same organisation', async () => {
+ const old = deferred<UserRoleAssignment[]>();
+ mocks.getUsers.mockReturnValueOnce(old.promise);
+ const { state } = mount();
+ await pause();
+ switchOrg();
+ await loaded(state);
+ mocks.getUsers.mockResolvedValueOnce([bob]);
+ mocks.org = 'north';
+ eventBus.emit('org_switched', 'north');
+ await loaded(state);
+ old.resolve([alice]);
+ await pause();
+ expect(state.filteredAssignments()).toEqual([bob]);
+ });
+
+ it.each([null, {}, [null], [{ ...alice, roleIds: null }], [alice, alice]])(
+ 'reports a malformed user inventory as unknown: %j',
+ async (value) => {
+ mocks.getUsers.mockResolvedValueOnce(value);
+ const { state } = mount();
+ await loaded(state);
+ expect(state.loadError()).toBe('Failed to load user assignments');
+ expect(state.canEdit()).toBe(false);
+ expect(state.filteredAssignments()).toEqual([]);
+ expect(state.roles()).toEqual([]);
+ },
+ );
+
+ it.each([null, {}, [null], [roles[0], roles[0]]])(
+ 'reports a malformed role inventory as unknown: %j',
+ async (value) => {
+ mocks.getRoles.mockResolvedValueOnce(value);
+ const { state } = mount();
+ await loaded(state);
+ expect(state.loadError()).toBe('Failed to load user assignments');
+ expect(state.canEdit()).toBe(false);
+ expect(state.filteredAssignments()).toEqual([]);
+ },
+ );
+
+ it('distinguishes a healthy empty directory from a failed one and serialises Retry', async () => {
+ mocks.getUsers.mockRejectedValueOnce(new Error('private directory failure'));
+ const { state } = mount();
+ await loaded(state);
+ expect(state.loadError()).not.toBeNull();
+ expect(JSON.stringify(mocks.log.mock.calls)).not.toContain('private directory failure');
+ const retry = deferred<UserRoleAssignment[]>();
+ mocks.getUsers.mockReturnValueOnce(retry.promise);
+ const read = state.loadData();
+ await state.loadData();
+ expect(mocks.getUsers).toHaveBeenCalledTimes(2);
+ retry.resolve([]);
+ await read;
+ expect(state.loadError()).toBeNull();
+ expect(state.canEdit()).toBe(true);
+ expect(state.filteredAssignments()).toEqual([]);
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 1e49cd4723..0e373d075d 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -2280,3 +2280,16 @@ describe('ordinary uninstall copy surfaces', () => {
);
});
});
+
+describe('User Access reader projection', () => {
+ it('supplies live reader props through the canonical registry instead of an unscoped mount', async () => {
+ const { default: registry } = await import('../settingsPanelRegistry.ts?raw');
+ const { default: context } = await import('../settingsPanelRegistryContext.tsx?raw');
+ expect(registry).toMatch(
+ /'security-users':\s*\{[^}]*getProps: context.getUserAssignmentsPanelProps/s,
+ );
+ expect(context).toMatch(
+ /getUserAssignmentsPanelProps: \(\) => \(\{\s*currentUser: currentUser\(\),\s*canManage: settingsCapabilities\(\)\?\.users === true/s,
+ );
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
index 46d8e2dcf6..703bbe2a3e 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
-import type { Setter } from 'solid-js';
+import { createSignal, type Setter } from 'solid-js';
import type { SecurityStatus } from '@/types/config';
import type { SettingsSystemPanels } from '../useSettingsSystemPanels';
import {
@@ -52,6 +52,7 @@ describe('buildSettingsPanelRegistryContext', () => {
expect(context.getOrganizationAccessPanelProps().currentUser).toBe('org-owner');
expect(context.getOrganizationOverviewPanelProps().currentUser).toBe('org-owner');
expect(context.getApiAccessPanelProps().currentUser).toBe('org-owner');
+ expect(context.getUserAssignmentsPanelProps().currentUser).toBe('org-owner');
});
it('does not replace an explicitly empty principal with the configured admin', () => {
@@ -148,4 +149,31 @@ describe('buildSettingsPanelRegistryContext', () => {
expect(context.getOrganizationSharingPanelProps()).toMatchObject({ currentUser: undefined });
expect(context.getApiAccessPanelProps()).toMatchObject({ currentUser: undefined });
});
+ it('binds User Access to the live principal and explicit users capability', () => {
+ const [status, setStatus] = createSignal<SecurityStatus | null>(null);
+ const context = buildSettingsPanelRegistryContext({
+ ...buildParams(null),
+ securityStatus: status,
+ });
+ expect(context.getUserAssignmentsPanelProps()).toEqual({
+ currentUser: undefined,
+ canManage: false,
+ });
+ setStatus({
+ currentUsername: 'reader-one',
+ settingsCapabilities: { users: true },
+ } as SecurityStatus);
+ expect(context.getUserAssignmentsPanelProps()).toEqual({
+ currentUser: 'reader-one',
+ canManage: true,
+ });
+ setStatus({
+ currentUsername: 'reader-two',
+ settingsCapabilities: { users: false },
+ } as SecurityStatus);
+ expect(context.getUserAssignmentsPanelProps()).toEqual({
+ currentUser: 'reader-two',
+ canManage: false,
+ });
+ });
});
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts b/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
index a6f6edbf61..b695b7b189 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
@@ -11,6 +11,7 @@ import type { SecurityOverviewPanel as SecurityOverviewPanelType } from './Secur
import type { SecurityAuthPanel as SecurityAuthPanelType } from './SecurityAuthPanel';
import type { RelaySettingsPanel as RelaySettingsPanelType } from './RelaySettingsPanel';
import type { AuditWebhookPanel as AuditWebhookPanelType } from './AuditWebhookPanel';
+import type { UserAssignmentsPanel as UserAssignmentsPanelType } from './UserAssignmentsPanel';
import type { InfrastructureWorkspace as InfrastructureWorkspaceType } from './InfrastructureWorkspace';
import type { SettingsTab } from './settingsNavigationModel';
import { SETTINGS_PANEL_REGISTRY_LOADERS } from './settingsPanelRegistryLoaders';
@@ -44,6 +45,7 @@ export interface SettingsPanelRegistryContext {
getSecurityAuthPanelProps: () => Parameters<typeof SecurityAuthPanelType>[0];
getRelayPanelProps: () => Parameters<typeof RelaySettingsPanelType>[0];
getAuditWebhookPanelProps: () => Parameters<typeof AuditWebhookPanelType>[0];
+ getUserAssignmentsPanelProps: () => Parameters<typeof UserAssignmentsPanelType>[0];
}
export const createSettingsPanelRegistry = (
@@ -138,6 +140,7 @@ export const createSettingsPanelRegistry = (
},
'security-users': {
component: SETTINGS_PANEL_REGISTRY_LOADERS.UserAssignmentsPanel,
+ getProps: context.getUserAssignmentsPanelProps,
},
'security-audit': {
component: SETTINGS_PANEL_REGISTRY_LOADERS.AuditLogPanel,
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
index d4469363ef..7c832cd89a 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
@@ -127,5 +127,9 @@ export function buildSettingsPanelRegistryContext(
getAuditWebhookPanelProps: () => ({
canManage: settingsCapabilities()?.auditWebhooksWrite === true,
}),
+ getUserAssignmentsPanelProps: () => ({
+ currentUser: currentUser(),
+ canManage: settingsCapabilities()?.users === true,
+ }),
};
}
diff --git a/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts b/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts
index 8b3ee05031..986db1de2f 100644
--- a/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts
+++ b/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts
@@ -1,5 +1,7 @@
-import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js';
+import { batch, createEffect, createMemo, createSignal, on, onCleanup } from 'solid-js';
import { RBACAPI } from '@/api/rbac';
+import { getOrgID } from '@/utils/apiClient';
+import { eventBus } from '@/stores/events';
import type { Permission, Role, UserRoleAssignment } from '@/types/rbac';
import { notificationStore } from '@/stores/notifications';
import { logger } from '@/utils/logger';
@@ -11,7 +13,12 @@ import {
} from '@/utils/rbacPresentation';
import { useRBACFeatureGateState } from './useRBACFeatureGateState';
-export function useUserAssignmentsPanelState() {
+export interface UserAssignmentsPanelProps {
+ currentUser?: string;
+ canManage?: boolean;
+}
+
+export function useUserAssignmentsPanelState(props: UserAssignmentsPanelProps = {}) {
const [assignments, setAssignments] = createSignal<UserRoleAssignment[]>([]);
const [roles, setRoles] = createSignal<Role[]>([]);
const [loading, setLoading] = createSignal(true);
@@ -22,67 +29,167 @@ export function useUserAssignmentsPanelState() {
const [userPermissions, setUserPermissions] = createSignal<Permission[] | null>(null);
const [loadingPermissions, setLoadingPermissions] = createSignal(false);
const [permissionsError, setPermissionsError] = createSignal<string | null>(null);
- let permissionsRequest = 0;
const [formRoleIds, setFormRoleIds] = createSignal<string[]>([]);
const [loadError, setLoadError] = createSignal<string | null>(null);
const [deletingUser, setDeletingUser] = createSignal(false);
const [userPendingDeletion, setUserPendingDeletion] = createSignal<UserRoleAssignment | null>(
null,
);
+ const [inventoryLoaded, setInventoryLoaded] = createSignal(false);
const featureGate = useRBACFeatureGateState({
kind: 'user-assignments',
loading,
paywallLocation: 'settings_user_assignments_panel',
});
+ const accessAllowed = () => featureGate.rbacEnabled() && props.canManage !== false;
+ const currentOrg = () => getOrgID() || 'default';
+ let context = { org: currentOrg(), user: props.currentUser, allowed: accessAllowed() };
+ let disposed = false;
+ let contextVersion = 0;
+ let editorVersion = 0;
+ let readController: AbortController | undefined;
+ let permissionsController: AbortController | undefined;
+ let mutationController: AbortController | undefined;
+ const contextIsCurrent = () =>
+ !disposed &&
+ context.org === currentOrg() &&
+ context.user === props.currentUser &&
+ context.allowed === accessAllowed();
+ const canEdit = () =>
+ contextIsCurrent() &&
+ accessAllowed() &&
+ inventoryLoaded() &&
+ !loading() &&
+ !loadError() &&
+ !saving() &&
+ !deletingUser();
+ const isCurrentUser = (user: UserRoleAssignment) => assignments().includes(user);
+ const requestOptions = (controller: AbortController) => ({
+ signal: controller.signal,
+ expectedOrgID: context.org,
+ retry: false,
+ });
+
+ const clearEditor = () => {
+ editorVersion += 1;
+ permissionsController?.abort();
+ permissionsController = undefined;
+ batch(() => {
+ setUserPermissions(null);
+ setPermissionsError(null);
+ setLoadingPermissions(false);
+ setShowModal(false);
+ setEditingUser(null);
+ setFormRoleIds([]);
+ });
+ };
+ const closeModal = () => {
+ if (!saving()) clearEditor();
+ };
const loadData = async () => {
- if (!featureGate.rbacEnabled()) {
+ if (!contextIsCurrent() || !accessAllowed() || readController || mutationController) return;
+ const version = contextVersion;
+ const controller = new AbortController();
+ const isCurrentRead = () =>
+ contextIsCurrent() && version === contextVersion && readController === controller;
+ readController = controller;
+ batch(() => {
+ clearEditor();
+ setUserPendingDeletion(null);
setAssignments([]);
setRoles([]);
+ setInventoryLoaded(false);
+ setLoading(true);
setLoadError(null);
- setLoading(false);
- return;
- }
-
- setLoading(true);
- setLoadError(null);
+ });
try {
- const [usersData, rolesData] = await Promise.all([RBACAPI.getUsers(), RBACAPI.getRoles()]);
- setAssignments(usersData || []);
- setRoles(rolesData || []);
- } catch (err) {
- if (err instanceof Error && /feature not included in license/i.test(err.message)) {
- setAssignments([]);
- setRoles([]);
- setLoadError(null);
- return;
- }
- setAssignments([]);
- setRoles([]);
+ const [usersData, rolesData] = await Promise.all([
+ RBACAPI.getUsers(requestOptions(controller)),
+ RBACAPI.getRoles(requestOptions(controller)),
+ ]);
+ if (!isCurrentRead()) return;
+ const users = new Set<string>();
+ const roleIds = new Set<string>();
+ // A failed or malformed read is unknown, not an empty account directory.
+ if (
+ !Array.isArray(usersData) ||
+ !Array.isArray(rolesData) ||
+ usersData.some((user) => {
+ if (
+ !user ||
+ typeof user.username !== 'string' ||
+ !user.username.trim() ||
+ users.has(user.username) ||
+ !Array.isArray(user.roleIds) ||
+ user.roleIds.some((id) => typeof id !== 'string' || !id.trim())
+ )
+ return true;
+ users.add(user.username);
+ return false;
+ }) ||
+ rolesData.some((role) => {
+ if (
+ !role ||
+ typeof role.id !== 'string' ||
+ !role.id.trim() ||
+ roleIds.has(role.id) ||
+ typeof role.name !== 'string' ||
+ typeof role.description !== 'string'
+ )
+ return true;
+ roleIds.add(role.id);
+ return false;
+ })
+ )
+ throw new Error('Invalid user access inventory');
+ batch(() => {
+ setAssignments(usersData);
+ setRoles(rolesData);
+ setInventoryLoaded(true);
+ });
+ } catch {
+ if (!isCurrentRead()) return;
setLoadError(getUserAssignmentsLoadErrorMessage());
- logger.error('Failed to load user assignments', err);
+ logger.error('Failed to load user assignments');
notificationStore.error(getUserAssignmentsLoadErrorMessage());
} finally {
- setLoading(false);
+ if (isCurrentRead()) {
+ readController = undefined;
+ setLoading(false);
+ }
}
};
- createEffect(() => {
- if (!featureGate.licenseReady()) {
- closeModal();
- setLoading(true);
- return;
- }
- if (!featureGate.rbacEnabled()) {
- closeModal();
+ const resetContext = () => {
+ contextVersion += 1;
+ readController?.abort();
+ mutationController?.abort();
+ readController = mutationController = undefined;
+ context = { org: currentOrg(), user: props.currentUser, allowed: accessAllowed() };
+ batch(() => {
+ clearEditor();
setAssignments([]);
setRoles([]);
+ setInventoryLoaded(false);
+ setSearchQuery('');
setLoadError(null);
- setLoading(false);
- return;
- }
- void loadData();
+ setUserPendingDeletion(null);
+ setSaving(false);
+ setDeletingUser(false);
+ setLoading(!featureGate.licenseReady() || accessAllowed());
+ });
+ if (!disposed) void loadData();
+ };
+ createEffect(
+ on([featureGate.licenseReady, accessAllowed, () => props.currentUser], resetContext),
+ );
+ const unsubscribeOrg = eventBus.on('org_switched', resetContext);
+ onCleanup(() => {
+ disposed = true;
+ unsubscribeOrg();
+ resetContext();
});
const filteredAssignments = createMemo(() => {
@@ -100,108 +207,130 @@ export function useUserAssignmentsPanelState() {
});
const loadUserPermissions = async () => {
- const username = editingUser()?.username;
- if (!username || !showModal() || !featureGate.rbacEnabled() || loadingPermissions()) return;
-
- const request = ++permissionsRequest;
+ const user = editingUser();
+ if (!user || !showModal() || !canEdit() || !isCurrentUser(user) || permissionsController)
+ return;
+ const version = contextVersion;
+ const editor = editorVersion;
+ const controller = new AbortController();
+ permissionsController = controller;
const isCurrentRead = () =>
- request === permissionsRequest &&
+ contextIsCurrent() &&
+ version === contextVersion &&
+ editor === editorVersion &&
+ permissionsController === controller &&
showModal() &&
- editingUser()?.username === username &&
- featureGate.rbacEnabled();
- setUserPermissions(null);
- setPermissionsError(null);
- setLoadingPermissions(true);
+ editingUser() === user;
+ batch(() => {
+ setUserPermissions(null);
+ setPermissionsError(null);
+ setLoadingPermissions(true);
+ });
try {
- const permissions = await RBACAPI.getUserPermissions(username);
+ const permissions = await RBACAPI.getUserPermissions(
+ user.username,
+ requestOptions(controller),
+ );
if (isCurrentRead()) setUserPermissions(permissions);
- } catch (err) {
+ } catch {
if (!isCurrentRead()) return;
setPermissionsError('Saved permissions could not be loaded. Access is unknown.');
- logger.error('Failed to load user permissions', err);
+ logger.error('Failed to load user permissions');
} finally {
- if (isCurrentRead()) setLoadingPermissions(false);
+ if (isCurrentRead()) {
+ permissionsController = undefined;
+ setLoadingPermissions(false);
+ }
}
};
- const closeModal = () => {
- permissionsRequest += 1;
- setUserPermissions(null);
- setPermissionsError(null);
- setLoadingPermissions(false);
- setShowModal(false);
- };
-
- onCleanup(() => {
- permissionsRequest += 1;
- });
-
const openManageAccess = async (assignment: UserRoleAssignment) => {
- closeModal();
+ if (!canEdit() || !isCurrentUser(assignment)) return;
+ clearEditor();
+ setUserPendingDeletion(null);
setEditingUser(assignment);
setFormRoleIds([...assignment.roleIds]);
setShowModal(true);
await loadUserPermissions();
};
-
const openDeleteUser = (assignment: UserRoleAssignment) => {
+ if (!canEdit() || !isCurrentUser(assignment)) return;
+ clearEditor();
setUserPendingDeletion(assignment);
};
-
const closeDeleteUser = () => {
if (!deletingUser()) setUserPendingDeletion(null);
};
- const handleDeleteUser = async () => {
- const user = userPendingDeletion();
- if (!user) return;
-
- setDeletingUser(true);
+ const mutateUser = async (user: UserRoleAssignment, kind: 'save' | 'delete') => {
+ if (!canEdit() || !isCurrentUser(user) || mutationController) return;
+ const version = contextVersion;
+ const controller = new AbortController();
+ const isCurrentMutation = () =>
+ contextIsCurrent() && version === contextVersion && mutationController === controller;
+ mutationController = controller;
+ if (kind === 'save') setSaving(true);
+ else setDeletingUser(true);
+ let saved = false;
try {
- await RBACAPI.deleteUser(user.username);
- notificationStore.success(`User access removed for ${getUserIdentityDisplayName(user)}`);
- if (editingUser()?.username === user.username) closeModal();
- setUserPendingDeletion(null);
- await loadData();
+ if (kind === 'save') {
+ await RBACAPI.updateUserRoles(
+ user.username,
+ [...formRoleIds()],
+ requestOptions(controller),
+ );
+ } else {
+ await RBACAPI.deleteUser(user.username, requestOptions(controller));
+ }
+ if (!isCurrentMutation()) return;
+ saved = true;
+ notificationStore.success(
+ kind === 'save'
+ ? `Roles updated for ${user.username}`
+ : `User access removed for ${getUserIdentityDisplayName(user)}`,
+ );
} catch (err) {
- logger.error('Failed to remove user access', err);
- notificationStore.error(getUserAssignmentsDeleteErrorMessage(err));
+ if (!isCurrentMutation()) return;
+ logger.error(
+ kind === 'save' ? 'Failed to update user roles' : 'Failed to remove user access',
+ );
+ notificationStore.error(
+ kind === 'save'
+ ? getUserAssignmentsUpdateErrorMessage()
+ : getUserAssignmentsDeleteErrorMessage(err),
+ );
} finally {
- setDeletingUser(false);
+ if (isCurrentMutation()) {
+ mutationController = undefined;
+ setSaving(false);
+ setDeletingUser(false);
+ if (saved) await loadData();
+ }
}
};
-
+ const handleDeleteUser = async () => {
+ const user = userPendingDeletion();
+ if (user) await mutateUser(user, 'delete');
+ };
const handleSaveAssignments = async () => {
const user = editingUser();
- if (!user) return;
-
- setSaving(true);
- try {
- await RBACAPI.updateUserRoles(user.username, formRoleIds());
- notificationStore.success(`Roles updated for ${user.username}`);
- closeModal();
- await loadData();
- } catch (err) {
- logger.error('Failed to update user roles', err);
- notificationStore.error(getUserAssignmentsUpdateErrorMessage());
- } finally {
- setSaving(false);
- }
+ if (showModal() && user) await mutateUser(user, 'save');
};
-
const toggleRole = (roleId: string) => {
+ if (!showModal() || !canEdit() || !roles().some((role) => role.id === roleId)) return;
const currentRoleIds = formRoleIds();
- if (currentRoleIds.includes(roleId)) {
- setFormRoleIds(currentRoleIds.filter((id) => id !== roleId));
- return;
- }
- setFormRoleIds([...currentRoleIds, roleId]);
+ setFormRoleIds(
+ currentRoleIds.includes(roleId)
+ ? currentRoleIds.filter((id) => id !== roleId)
+ : [...currentRoleIds, roleId],
+ );
};
-
const getRoleName = (roleId: string) =>
roles().find((role) => role.id === roleId)?.name || roleId;
return {
+ accessAllowed,
+ canEdit,
closeDeleteUser,
closeModal,
deletingUser,
diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.ts
index c07940ef8a..44860da9d0 100644
--- a/frontend-modern/src/types/api.ts
+++ b/frontend-modern/src/types/api.ts
@@ -3,6 +3,13 @@
import type { Resource, ResourceCapability, ResourcePolicy, ResourceChange } from './resource';
import type { EvidenceEnvelope, LifecycleTransition, OperationalRecord } from './operationalTrust';
+/** Client-only binding for RBAC administration; these are not JSON payload fields. */
+export interface RBACAdminRequestOptions {
+ signal?: AbortSignal;
+ expectedOrgID?: string;
+ retry?: boolean;
+}
+
export interface ResourceListFacetsPayload {
byType?: Partial<Record<string, number>>;
incidentCount?: number;