diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md index eedba18443..98b3a3ecfb 100644 --- a/docs/release-control/v6/internal/subsystems/organization-settings.md +++ b/docs/release-control/v6/internal/subsystems/organization-settings.md @@ -1268,6 +1268,26 @@ Paired directory/role reads are aborted when their combined read settles so a failed sibling does not leave an unowned pending request. The registered reader-lifetime/paywall tests and actual App browser witness cover this bound. +While User Access is reading, an admitted reader can use **Restart loading** +without leaving the panel. It aborts both parts of the old inventory read and +starts one replacement pair in the same authenticated organization. Ordinary +overlapping reads still coalesce. A late result from a replaced request cannot +finish loading, publish rows or clear the warning for an unconfirmed write. +Only a complete valid current pair shows inventory or enables changes; no +role edit or removal is replayed. The existing inventory shape checks live +in the shared RBAC presentation module; a saved role ID need not be present +in the catalogue for the assignment to be readable. The control is not +available before the RBAC gate admits the reader. An explicit restart focuses +the stable User Access region before the control disappears, without moving +focus on response. + +`UserAccessInventoryRestart.transport.test.tsx` covers a stalled role read, +replacement/withdrawal, failed read and an unconfirmed write. +`RBACPaywallPanels.test.tsx` verifies capability withdrawal removes the +restart and aborts the pending pair. Desktop and phone browser proof +exercises the actual User Access route, scoped API reads and the existing +recovery and edit controls with synthetic data. + ### Unconfirmed user changes require a saved-access check A lost response, server failure or unreadable success after updating a user's diff --git a/frontend-modern/browser-verification/5c792e219f455e82.json b/frontend-modern/browser-verification/5c792e219f455e82.json new file mode 100644 index 0000000000..9dd44f7d61 --- /dev/null +++ b/frontend-modern/browser-verification/5c792e219f455e82.json @@ -0,0 +1,38 @@ +{ + "version": 1, + "base_sha": "a9d15ca9396a797bbf5302750bc5c22c5f9ca302", + "result": "passed", + "verified_at": "2026-11-19T02:45:14Z", + "changed_paths": [ + "frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx", + "frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts", + "frontend-modern/src/utils/rbacPresentation.ts" + ], + "content_sha256": { + "frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx": "95761990ad36badae503b326097a4c3dbb712cbf141ed8d8f26fa79bcef946a3", + "frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts": "59ebe57522c9c1fe002dff558d250fbcd866277865edd94d8b52070d9ff69e7c", + "frontend-modern/src/utils/rbacPresentation.ts": "7c15232336735d55defe11194f6d400bf38b80665a4dccf45c93da8af6708f86" + }, + "routes": [ + "/settings/security-users" + ], + "viewports": [ + { + "width": 1440, + "height": 900 + }, + { + "width": 390, + "height": 844 + } + ], + "states": [ + "App with isolated HTTP fixtures, Playwright 1.56.1, desktop Chromium 141 (light) and touch WebKit 26 (dark). 110 assertions and 32 inspected captures in sixteen pairs.", + "A successful user read with a held role catalogue used to render only a spinner. The label and Restart loading are visible in the new pending panel; no rows or write controls appear without both valid lists.", + "An unconfirmed save warning survives a restarted check and denial. Valid readback restores both exact principals, role IDs and controls. Search, genuine empty guidance and the exact-principal removal confirmation retain their content." + ], + "interactions": [ + "Restart via Enter on desktop and tap on phone. The old pending response is canceled and one same-organization GET pair replaces it. Focus stays in User Access; a late result cannot change the replacement.", + "Induce one synthetic unconfirmed save per check scenario, restart only the reads, and recover using Check saved access. Search stays local; open and cancel removal without a write." + ] +} diff --git a/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx index 28cb3da12e..c2685d5b47 100644 --- a/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx +++ b/frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx @@ -45,6 +45,12 @@ export const UserAssignmentsPanel: Component = (props ); onCleanup(() => window.clearTimeout(focusTimer)); + const restartRead = () => { + window.clearTimeout(focusTimer); + panel?.focus({ preventScroll: true }); + void state.restartRead(); + }; + const saveOrReload = async (reload = false) => { const reader = state.readerKey(); const username = reload @@ -151,8 +157,20 @@ export const UserAssignmentsPanel: Component = (props -
- +
+
+ + Loading user access… +
+ + +
diff --git a/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx b/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx index dfc3955a66..6d38141d56 100644 --- a/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/RBACPaywallPanels.test.tsx @@ -634,6 +634,28 @@ describe('RBAC paywall settings panels', () => { expect(screen.queryByRole('heading', { name: /No (matching )?users/ })).not.toBeInTheDocument(); }); + it('withdraws a pending User Access restart on loss of management capability', async () => { + const pending = deferred(); + getRolesMock.mockReturnValueOnce(pending.promise); + const [canManage, setCanManage] = createSignal(true); + render(() => ); + const restart = await screen.findByRole('button', { name: 'Restart loading' }); + const { signal } = getRolesMock.mock.calls[0][0]; + + setCanManage(false); + await screen.findByText('User access is unavailable for this session.'); + expect(restart).not.toBeInTheDocument(); + expect(signal.aborted).toBe(true); + fireEvent.click(restart); + pending.resolve([]); + await pending.promise; + expect(screen.queryByRole('button', { name: /Manage access for/ })).not.toBeInTheDocument(); + expect(getUsersMock).toHaveBeenCalledTimes(1); + expect(getRolesMock).toHaveBeenCalledTimes(1); + expect(updateUserRolesMock).not.toHaveBeenCalled(); + expect(deleteUserMock).not.toHaveBeenCalled(); + }); + it('clears the previous user permissions during a new read and reports failure as unknown', async () => { const pending = deferred<{ action: string; resource: string }[]>(); getUsersMock.mockResolvedValue([ diff --git a/frontend-modern/src/components/Settings/__tests__/UserAccessInventoryRestart.transport.test.tsx b/frontend-modern/src/components/Settings/__tests__/UserAccessInventoryRestart.transport.test.tsx new file mode 100644 index 0000000000..d8c239b4b2 --- /dev/null +++ b/frontend-modern/src/components/Settings/__tests__/UserAccessInventoryRestart.transport.test.tsx @@ -0,0 +1,197 @@ +import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { eventBus } from '@/stores/events'; +import type { Role, UserRoleAssignment } from '@/types/rbac'; +import { clearAuth, setApiToken, setOrgID } from '@/utils/apiClient'; +import { UserAssignmentsPanel } from '../UserAssignmentsPanel'; + +const gate = vi.hoisted(() => ({ ready: true })); +vi.mock('../useRBACFeatureGateState', () => ({ + useRBACFeatureGateState: () => ({ + licenseReady: () => gate.ready, + rbacEnabled: () => gate.ready, + paywallVisible: () => false, + }), +})); + +const USERS = '/api/admin/users'; +const ROLES = '/api/admin/roles'; +const savedRole: Role = { + id: 'reader', + name: 'Fleet Reader', + description: 'Read the fleet', + permissions: [], +}; +const extraRole: Role = { + id: 'operator', + name: 'Fleet Operator', + description: 'Operate the fleet', + permissions: [], +}; +const account: UserRoleAssignment = { username: 'north.reader', roleIds: [savedRole.id] }; +const json = (data: unknown, status = 200) => + new Response(JSON.stringify(data), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +const deferredResponse = () => { + let resolve!: (response: Response) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +}; + +const fetchMock = vi.fn(); +const organizationOf = (init?: RequestInit) => new Headers(init?.headers).get('X-Pulse-Org-ID'); +type Read = (attempt: number, org: string | null) => Response | Promise; +let usersRead: Read; +let rolesRead: Read; +let usersReads: number; +let rolesReads: number; +const inventory = () => screen.getByRole('region', { name: 'User Access' }); +const restart = () => screen.getByRole('button', { name: 'Restart loading' }); +const edit = (user = account.username) => + screen.getByRole('button', { name: `Manage access for ${user}` }); +const writes = () => + fetchMock.mock.calls.filter(([, init]) => !['GET', 'HEAD'].includes(init?.method ?? 'GET')); + +beforeEach(() => { + gate.ready = true; + clearAuth(); + sessionStorage.clear(); + setOrgID('north'); + setApiToken('synthetic-inventory-restart'); + document.cookie = 'pulse_csrf=synthetic-restart; Path=/'; + vi.stubEnv('MODE', 'production'); + usersReads = rolesReads = 0; + usersRead = () => json([account]); + rolesRead = () => json([savedRole, extraRole]); + fetchMock.mockReset().mockImplementation(async (input, init) => { + const path = String(input); + const method = init?.method ?? 'GET'; + if (method === 'GET' && path === USERS) return usersRead(++usersReads, organizationOf(init)); + if (method === 'GET' && path === ROLES) return rolesRead(++rolesReads, organizationOf(init)); + if (method === 'GET' && path === `${USERS}/${account.username}/permissions`) return json([]); + if (method === 'PUT' && path === `${USERS}/${account.username}/roles`) { + return json({ code: 'synthetic_write_indeterminate' }, 503); + } + throw new Error(`Unexpected fixture request: ${method} ${path}`); + }); + vi.stubGlobal('fetch', fetchMock); +}); + +afterEach(() => { + cleanup(); + clearAuth(); + setOrgID(null); + document.cookie = 'pulse_csrf=; Max-Age=0; Path=/'; + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +describe('User Access inventory restart', () => { + it('replaces a stalled catalogue read without retaining old rows or losing keyboard focus', async () => { + const stalledRoles = deferredResponse(); + const currentUsers = deferredResponse(); + rolesRead = (attempt) => (attempt === 1 ? stalledRoles.promise : json([savedRole])); + usersRead = (attempt) => + attempt === 1 + ? json([{ ...account, username: 'superseded.directory' }]) + : currentUsers.promise; + render(() => ); + await waitFor(() => expect(rolesReads).toBe(1)); + expect(screen.queryByText('superseded.directory')).not.toBeInTheDocument(); + expect(screen.queryByRole('status', { name: 'User search results' })).not.toBeInTheDocument(); + + const firstPair = fetchMock.mock.calls.slice(); + restart().focus(); + fireEvent.click(restart()); + await waitFor(() => expect(rolesReads).toBe(2)); + expect(inventory()).toHaveFocus(); + expect(firstPair).toHaveLength(2); + expect(firstPair.every(([, init]) => init?.signal?.aborted)).toBe(true); + expect(fetchMock.mock.calls.every(([, init]) => organizationOf(init) === 'north')).toBe(true); + + // The transport can still finish locally after cancellation. It must not + // publish the completed old pair or mark the replacement as finished. + stalledRoles.resolve(json([extraRole])); + await stalledRoles.promise; + expect(restart()).toBeEnabled(); + expect(screen.queryByText('superseded.directory')).not.toBeInTheDocument(); + currentUsers.resolve(json([account])); + await waitFor(() => expect(edit()).toBeEnabled()); + expect(screen.getByText('Fleet Reader')).toBeVisible(); + expect(screen.queryByRole('button', { name: 'Restart loading' })).not.toBeInTheDocument(); + expect(inventory()).toHaveFocus(); + expect(writes()).toEqual([]); + expect(usersReads).toBe(2); + expect(rolesReads).toBe(2); + }); + + it('does not revive a replacement that finishes after the organization is withdrawn', async () => { + const formerUsers = deferredResponse(); + const replacementUsers = deferredResponse(); + usersRead = (attempt, org) => + org === 'south' + ? json([{ ...account, username: 'south.reader' }]) + : attempt === 1 + ? formerUsers.promise + : replacementUsers.promise; + render(() => ); + fireEvent.click(await screen.findByRole('button', { name: 'Restart loading' })); + await waitFor(() => expect(usersReads).toBe(2)); + const replacement = fetchMock.mock.calls[2][1]?.signal; + setOrgID('south'); + eventBus.emit('org_switched', 'south'); + await waitFor(() => expect(edit('south.reader')).toBeEnabled()); + expect(replacement?.aborted).toBe(true); + replacementUsers.resolve(json([account])); + formerUsers.resolve(json([account])); + await Promise.all([replacementUsers.promise, formerUsers.promise]); + expect(screen.queryByText(account.username)).not.toBeInTheDocument(); + expect(edit('south.reader')).toBeEnabled(); + expect(writes()).toEqual([]); + }); + + it('keeps an unconfirmed change guarded after a restarted check is denied', async () => { + const stalledRoles = deferredResponse(); + rolesRead = (attempt) => { + if (attempt === 2) return stalledRoles.promise; + if (attempt === 3) return json({ code: 'forbidden' }, 403); + return json([savedRole, extraRole]); + }; + render(() => ); + await waitFor(() => expect(edit()).toBeEnabled()); + fireEvent.click(edit()); + const dialog = within(await screen.findByRole('dialog')); + fireEvent.click(dialog.getByRole('checkbox', { name: /Operate the fleet/ })); + fireEvent.click(dialog.getByRole('button', { name: 'Save Changes' })); + + fireEvent.click(await screen.findByRole('button', { name: 'Check saved access' })); + const pending = await screen.findByRole('button', { name: 'Restart loading' }); + fireEvent.click(pending); + const retry = await screen.findByRole('button', { name: 'Check saved access' }); + expect(screen.getByText(/role update.*could not be confirmed/)).toBeVisible(); + expect(screen.getByText('Failed to load user assignments')).toBeVisible(); + expect(screen.queryByText(account.username)).not.toBeInTheDocument(); + expect(writes()).toHaveLength(1); + + stalledRoles.resolve(json([savedRole])); + await stalledRoles.promise; + expect(retry).toBeEnabled(); + fireEvent.click(retry); + await waitFor(() => expect(edit()).toBeEnabled()); + expect(screen.queryByText(/role update.*could not be confirmed/)).not.toBeInTheDocument(); + expect(writes()).toHaveLength(1); + expect(rolesReads).toBe(4); + }); + + it('does not offer a restart while the RBAC gate is unresolved', () => { + gate.ready = false; + render(() => ); + expect(screen.getByRole('status', { name: 'Loading user access' })).toBeVisible(); + expect(screen.queryByRole('button', { name: 'Restart loading' })).not.toBeInTheDocument(); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts b/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts index 70c79680fb..41be37bce9 100644 --- a/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts +++ b/frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts @@ -9,6 +9,7 @@ import { getUserAssignmentsLoadErrorMessage, getUserAssignmentsUpdateErrorMessage, getUserIdentityLabel, + isCompleteUserAccessInventory, sameRoleIDs, } from '@/utils/rbacPresentation'; import { useRBACFeatureGateState } from './useRBACFeatureGateState'; @@ -92,13 +93,16 @@ export function useUserAssignmentsPanelState(props: UserAssignmentsPanelProps = if (!saving()) clearEditor(); }; - const loadData = async () => { - if (!contextIsCurrent() || !accessAllowed() || readController || mutationController) return; + const loadData = async (restart = false) => { + if (!contextIsCurrent() || !accessAllowed() || mutationController) return; + const previousRead = readController; + if (restart ? !previousRead : previousRead) return; const reader = context; const controller = new AbortController(); const isCurrentRead = () => contextIsCurrent() && reader === context && readController === controller; readController = controller; + previousRead?.abort(); batch(() => { clearEditor(); setUserPendingDeletion(null); @@ -114,39 +118,8 @@ export function useUserAssignmentsPanelState(props: UserAssignmentsPanelProps = RBACAPI.getRoles(requestOptions(controller)), ]); if (!isCurrentRead()) return; - const users = new Set(); - const roleIds = new Set(); // 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; - }) - ) + if (!isCompleteUserAccessInventory(usersData, rolesData)) throw new Error('Invalid user access inventory'); batch(() => { setAssignments(usersData); @@ -376,6 +349,7 @@ export function useUserAssignmentsPanelState(props: UserAssignmentsPanelProps = openManageAccess, openDeleteUser, permissionsError, + restartRead: () => loadData(true), roles, saving, searchQuery, diff --git a/frontend-modern/src/utils/rbacPresentation.ts b/frontend-modern/src/utils/rbacPresentation.ts index c490c4eb0f..27ea192c45 100644 --- a/frontend-modern/src/utils/rbacPresentation.ts +++ b/frontend-modern/src/utils/rbacPresentation.ts @@ -101,6 +101,41 @@ export function getUserAssignmentsLoadErrorMessage(): string { return 'Failed to load user assignments'; } +/** Require both lists before presenting saved User Access or opening its editor. */ +export function isCompleteUserAccessInventory(users: unknown, roles: unknown): boolean { + if (!Array.isArray(users) || !Array.isArray(roles)) return false; + const usernames = new Set(); + const roleIds = new Set(); + return ( + users.every((user) => { + if ( + !user || + typeof user.username !== 'string' || + !user.username.trim() || + usernames.has(user.username) || + !Array.isArray(user.roleIds) || + user.roleIds.some((id: unknown) => typeof id !== 'string' || !id.trim()) + ) + return false; + usernames.add(user.username); + return true; + }) && + roles.every((role) => { + if ( + !role || + typeof role.id !== 'string' || + !role.id.trim() || + roleIds.has(role.id) || + typeof role.name !== 'string' || + typeof role.description !== 'string' + ) + return false; + roleIds.add(role.id); + return true; + }) + ); +} + export function getUserAssignmentsUpdateErrorMessage(): string { return 'Failed to update user roles'; }