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.

Bind API token management to its active panel lifetime

pulse-triage[bot]ba780ba8ac9a
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 5292d733f4..3e64a5049e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -13485,3 +13485,21 @@ synthetic credentials and preserved live data. `log_bundle_test.go` covers
value grammars, detached projections, log fallbacks, runtime identity and race
ownership. Consuming browser evidence exercises the unchanged download control
with the exact synthetic native ZIP; it is not installed/customer recovery.
+
+### API token panel requests retain their confirmed context
+
+The existing API Access token inventory and create, rename, scope-edit and revoke
+calls accept an abort signal and expected organisation. They use the ordinary
+credentials, retain backend permission/scope/owner checks, and do not automatically
+retry a refusal or switch a confirmation to the default organisation. CSRF
+preparation must finish without dispatching an aborted or differently scoped
+write. The Relay/mobile issuer and token detail API are unchanged.
+
+The consuming panel rejects results after disposal, an organisation/user change
+or management-authority change, including leave-and-return cycles. Only one write
+runs at once; an inventory read interrupted by a write resumes as a new read,
+never an old snapshot. An unreadable inventory remains unknown and read-only
+accounts retain explicit inventory recovery. These guarantees are exercised by
+`security.transport.test.ts`, `security.test.ts`, `APITokenLifetimes.test.tsx`
+and the registered API token panel tests; browser proof covers the actual API
+Access consumer with synthetic responses, not installed administrator recovery.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 51b2b30c9b..03ed392724 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -3990,3 +3990,23 @@ synthetic credentials and preserved live data. `log_bundle_test.go` covers
value grammars, detached projections, log fallbacks, runtime identity and race
ownership. Consuming browser evidence exercises the unchanged download control
with the exact synthetic native ZIP; it is not installed/customer recovery.
+
+### Token values belong to the active API Access panel
+
+API Access binds token request completion to its organisation, authenticated
+username, current management permission and mounted lifetime. An obsolete
+create response cannot open the shared token-reveal dialog, change inventory,
+notify success or call its containing panel. Withdrawal/disposal clears the
+panel's retained raw token and kiosk link and dismisses only the exact reveal
+state it issued, never a newer reveal from another issuer. Editing dialogs and
+pending focus restoration do not survive that context boundary. Aborting is not
+server-side rollback: a dispatched change may have applied and must not replay.
+
+The primary-token hint is not an authenticated identity; the existing Settings
+username is passed through API Access instead. Token metadata visibility,
+least-privilege scope presets, deliberate wildcard selection and server-side
+scope/organisation containment remain unchanged. Registered
+`APITokenLifetimes.test.tsx` covers late successes/failures, authority/user/org
+cycles, single writes, obsolete rows and reveal ownership; native browser proof
+uses synthetic credentials and responses. No release or installed recovery is
+implied by source/component/browser proof.
diff --git a/frontend-modern/src/api/__tests__/security.test.ts b/frontend-modern/src/api/__tests__/security.test.ts
index 9a217959ba..99c3aead82 100644
--- a/frontend-modern/src/api/__tests__/security.test.ts
+++ b/frontend-modern/src/api/__tests__/security.test.ts
@@ -12,6 +12,20 @@ describe('SecurityAPI', () => {
vi.clearAllMocks();
});
+ it('forwards the confirmed organisation and cancellation without replaying token operations', async () => {
+ const options = { signal: new AbortController().signal, expectedOrgID: 'chosen-org' };
+ vi.mocked(apiFetchJSON).mockResolvedValue({ tokens: [], record: {} });
+ await SecurityAPI.listTokens(options);
+ await SecurityAPI.createToken('Name', ['monitoring:read'], options);
+ await SecurityAPI.updateTokenScopes('token/1', ['settings:read'], options);
+ await SecurityAPI.renameToken('token/1', 'Renamed', options);
+ await SecurityAPI.deleteToken('token/1', options);
+ expect(apiFetchJSON).toHaveBeenCalledTimes(5);
+ for (const [, request] of vi.mocked(apiFetchJSON).mock.calls) {
+ expect(request).toEqual(expect.objectContaining({ ...options, retry: false }));
+ }
+ });
+
describe('getStatus', () => {
it('fetches security status', async () => {
const mockStatus: SecurityStatus = {
@@ -76,7 +90,7 @@ describe('SecurityAPI', () => {
const result = await SecurityAPI.listTokens();
- expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/tokens');
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/tokens', { retry: false });
expect(result).toEqual(mockTokens);
});
@@ -272,6 +286,7 @@ describe('SecurityAPI', () => {
]);
expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/tokens/token%2F1', {
+ retry: false,
method: 'PATCH',
body: JSON.stringify({ scopes: ['monitoring:read', 'settings:read'] }),
});
@@ -317,6 +332,7 @@ describe('SecurityAPI', () => {
const result = await SecurityAPI.renameToken('token/1', 'PBS host');
expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/tokens/token%2F1', {
+ retry: false,
method: 'PATCH',
body: JSON.stringify({ name: 'PBS host' }),
});
diff --git a/frontend-modern/src/api/__tests__/security.transport.test.ts b/frontend-modern/src/api/__tests__/security.transport.test.ts
new file mode 100644
index 0000000000..bc733491a1
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/security.transport.test.ts
@@ -0,0 +1,55 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const fetchMock = vi.fn();
+let api: typeof import('../security');
+let client: typeof import('@/utils/apiClient');
+beforeEach(async () => {
+ vi.resetModules(); fetchMock.mockReset(); vi.stubGlobal('fetch', fetchMock);
+ sessionStorage.clear(); document.cookie = 'pulse_csrf=; Max-Age=0; Path=/';
+ client = await import('@/utils/apiClient'); api = await import('../security');
+ client.setOrgID('org-a'); client.setApiToken('synthetic-only-auth');
+});
+afterEach(() => { client.clearAuth(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
+const invoke = (operation: string, options: { signal?: AbortSignal; expectedOrgID?: string }) => {
+ if (operation === 'create') return api.SecurityAPI.createToken('Test', ['monitoring:read'], options);
+ if (operation === 'rename') return api.SecurityAPI.renameToken('token/1', 'Renamed', options);
+ if (operation === 'scope') return api.SecurityAPI.updateTokenScopes('token/1', ['monitoring:read'], options);
+ return api.SecurityAPI.deleteToken('token/1', options);
+};
+describe('API token real transport', () => {
+ it.each(['create', 'rename', 'scope', 'revoke'])('does not dispatch an aborted %s after CSRF preparation', async (operation) => {
+ vi.stubEnv('MODE', 'production');
+ let resolve!: (response: Response) => void;
+ fetchMock.mockImplementationOnce(() => new Promise<Response>((yes) => { resolve = yes; }));
+ const controller = new AbortController();
+ const writing = invoke(operation, { expectedOrgID: 'org-a', signal: controller.signal });
+ const result = expect(writing).rejects.toMatchObject({ name: 'AbortError' });
+ expect(fetchMock.mock.calls[0][0]).toBe('/api/health');
+ controller.abort(); resolve(new Response('{}', { status: 200 })); await result;
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not dispatch a confirmation into a different organisation after CSRF preparation', async () => {
+ vi.stubEnv('MODE', 'production');
+ let resolve!: (response: Response) => void;
+ fetchMock.mockImplementationOnce(() => new Promise<Response>((yes) => { resolve = yes; }));
+ const writing = invoke('create', { expectedOrgID: 'org-a' });
+ const result = expect(writing).rejects.toThrow('Organisation changed.');
+ client.setOrgID('org-b'); resolve(new Response('{}', { status: 200 })); await result;
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['create', 'rename', 'scope', 'revoke'].flatMap((operation) => [403, 429, 503].map((status) => ({ operation, status }))))('does not replay $operation after HTTP $status', async ({ operation, status }) => {
+ fetchMock.mockResolvedValueOnce(new Response('{}', { status, headers: { 'X-CSRF-Token': 'new-synthetic-csrf', 'Retry-After': '0' } }));
+ await expect(invoke(operation, { expectedOrgID: 'org-a' })).rejects.toMatchObject({ status });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0][1]).toMatchObject({ headers: { 'X-Pulse-Org-ID': 'org-a', 'X-API-Token': 'synthetic-only-auth' }, credentials: 'include' });
+ expect(client.getOrgID()).toBe('org-a');
+ });
+
+ it('keeps a refused inventory unavailable instead of silently falling back to default', async () => {
+ fetchMock.mockResolvedValueOnce(new Response('{"error":"invalid_org"}', { status: 400 }));
+ await expect(api.SecurityAPI.listTokens({ expectedOrgID: 'org-a' })).rejects.toMatchObject({ status: 400 });
+ expect(fetchMock).toHaveBeenCalledTimes(1); expect(client.getOrgID()).toBe('org-a');
+ });
+});
diff --git a/frontend-modern/src/api/security.ts b/frontend-modern/src/api/security.ts
index 98a7381095..8a65d46a46 100644
--- a/frontend-modern/src/api/security.ts
+++ b/frontend-modern/src/api/security.ts
@@ -21,6 +21,11 @@ function isTokenInventoryRecord(value: unknown): value is APITokenRecord {
);
}
+export interface APITokenRequestOptions {
+ signal?: AbortSignal;
+ expectedOrgID?: string;
+}
+
export interface CreateAPITokenResponse {
token: string;
record: APITokenRecord;
@@ -38,8 +43,11 @@ export class SecurityAPI {
return response.record;
}
- static async listTokens(): Promise<APITokenRecord[]> {
- const response = await apiFetchJSON<unknown>('/api/security/tokens');
+ static async listTokens(options?: APITokenRequestOptions): Promise<APITokenRecord[]> {
+ const response = await apiFetchJSON<unknown>('/api/security/tokens', {
+ ...options,
+ retry: false,
+ });
if (response && typeof response === 'object' && !Array.isArray(response)) {
const tokens = (response as { tokens?: unknown }).tokens;
// A legacy nil list is explicitly empty; a missing or malformed list is not.
@@ -52,7 +60,11 @@ export class SecurityAPI {
throw new Error('Invalid API token inventory.');
}
- static async createToken(name?: string, scopes?: string[]): Promise<CreateAPITokenResponse> {
+ static async createToken(
+ name?: string,
+ scopes?: string[],
+ options?: APITokenRequestOptions,
+ ): Promise<CreateAPITokenResponse> {
const payload: Record<string, unknown> = {};
if (name) {
payload.name = name;
@@ -62,6 +74,8 @@ export class SecurityAPI {
}
return apiFetchJSON<CreateAPITokenResponse>('/api/security/tokens', {
+ ...options,
+ retry: false,
method: 'POST',
body: JSON.stringify(payload),
});
@@ -74,10 +88,16 @@ export class SecurityAPI {
});
}
- static async updateTokenScopes(id: string, scopes: string[]): Promise<APITokenRecord> {
+ static async updateTokenScopes(
+ id: string,
+ scopes: string[],
+ options?: APITokenRequestOptions,
+ ): Promise<APITokenRecord> {
const response = await apiFetchJSON<{ record: APITokenRecord }>(
`/api/security/tokens/${encodeURIComponent(id)}`,
{
+ ...options,
+ retry: false,
method: 'PATCH',
body: JSON.stringify({ scopes }),
},
@@ -85,16 +105,24 @@ export class SecurityAPI {
return response.record;
}
- static async deleteToken(id: string): Promise<void> {
+ static async deleteToken(id: string, options?: APITokenRequestOptions): Promise<void> {
await apiFetchJSON(`/api/security/tokens/${encodeURIComponent(id)}`, {
+ ...options,
+ retry: false,
method: 'DELETE',
});
}
- static async renameToken(id: string, name: string): Promise<APITokenRecord> {
+ static async renameToken(
+ id: string,
+ name: string,
+ options?: APITokenRequestOptions,
+ ): Promise<APITokenRecord> {
const response = await apiFetchJSON<{ record: APITokenRecord }>(
`/api/security/tokens/${encodeURIComponent(id)}`,
{
+ ...options,
+ retry: false,
method: 'PATCH',
body: JSON.stringify({ name }),
},
diff --git a/frontend-modern/src/components/Settings/APIAccessPanel.tsx b/frontend-modern/src/components/Settings/APIAccessPanel.tsx
index 2f67227a7d..677835c587 100644
--- a/frontend-modern/src/components/Settings/APIAccessPanel.tsx
+++ b/frontend-modern/src/components/Settings/APIAccessPanel.tsx
@@ -7,6 +7,7 @@ import APITokenManager from './APITokenManager';
interface APIAccessPanelProps {
currentTokenHint?: string;
+ currentUser?: string;
onTokensChanged: () => void;
refreshing: boolean;
canManage: boolean;
@@ -35,6 +36,7 @@ export const APIAccessPanel: Component<APIAccessPanelProps> = (props) => {
<div data-testid="api-access-token-section">
<APITokenManager
currentTokenHint={props.currentTokenHint}
+ currentUser={props.currentUser}
onTokensChanged={props.onTokensChanged}
refreshing={props.refreshing}
canManage={props.canManage}
diff --git a/frontend-modern/src/components/Settings/APITokenManager.tsx b/frontend-modern/src/components/Settings/APITokenManager.tsx
index 59e61a43b3..b97c45e5dc 100644
--- a/frontend-modern/src/components/Settings/APITokenManager.tsx
+++ b/frontend-modern/src/components/Settings/APITokenManager.tsx
@@ -1,4 +1,4 @@
-import { Component, For, Show, createSignal, lazy } from 'solid-js';
+import { Component, For, Show, createEffect, createSignal, lazy, on, onCleanup } from 'solid-js';
import { Card } from '@/components/shared/Card';
import { ExternalTextLink } from '@/components/shared/ExternalTextLink';
import { SectionHeader } from '@/components/shared/SectionHeader';
@@ -20,6 +20,7 @@ import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
interface APITokenManagerProps {
currentTokenHint?: string;
+ currentUser?: string;
onTokensChanged?: () => void;
refreshing?: boolean;
canManage?: boolean;
@@ -39,6 +40,7 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
const [tokenToRename, setTokenToRename] = createSignal<APITokenRecord | null>(null);
const [renameInput, setRenameInput] = createSignal('');
let dialogTrigger: HTMLButtonElement | undefined;
+ let focusTimer: number | undefined;
const {
API_SCOPE_LABELS,
API_TOKEN_SCOPES_DOC_URL,
@@ -46,6 +48,8 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
applyFullAccessPreset,
applyScopePreset,
canManage,
+ contextVersion,
+ isMutating,
canGenerateToken,
clearScopes,
copyNewMonitoringKioskLink,
@@ -88,6 +92,18 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
presetMatchesSelection,
} = useAPITokenManagerState(props);
+ const clearDialogs = () => {
+ window.clearTimeout(focusTimer);
+ dialogTrigger = undefined;
+ setTokenToEdit(null);
+ setEditScopes([]);
+ setTokenToRevoke(null);
+ setTokenToRename(null);
+ setRenameInput('');
+ };
+ createEffect(on(contextVersion, clearDialogs, { defer: true }));
+ onCleanup(() => window.clearTimeout(focusTimer));
+
const effectiveScopes = (token: APITokenRecord) =>
token.scopes && token.scopes.length > 0 ? token.scopes : ['*'];
@@ -100,7 +116,9 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
const tokenId = trigger?.dataset.apiTokenId;
const action = trigger?.dataset.apiTokenAction;
dialogTrigger = undefined;
- window.setTimeout(() => {
+ const version = contextVersion();
+ focusTimer = window.setTimeout(() => {
+ if (version !== contextVersion() || !canManage()) return;
if (trigger?.isConnected && !trigger.disabled) {
trigger.focus();
return;
@@ -122,17 +140,20 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
};
const openScopeEditor = (token: APITokenRecord, trigger: HTMLButtonElement) => {
+ if (!canManage() || isMutating()) return;
rememberDialogTrigger(trigger);
setEditScopes([...effectiveScopes(token)]);
setTokenToEdit(token);
};
const openRevokeDialog = (token: APITokenRecord, trigger: HTMLButtonElement) => {
+ if (!canManage() || isMutating()) return;
rememberDialogTrigger(trigger);
setTokenToRevoke(token);
};
const openRenameDialog = (token: APITokenRecord, trigger: HTMLButtonElement) => {
+ if (!canManage() || isMutating()) return;
rememberDialogTrigger(trigger);
setRenameInput(token.name ?? '');
setTokenToRename(token);
@@ -293,7 +314,7 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
data-api-token-id={token.id}
data-api-token-action="edit-scopes"
onClick={(event) => openScopeEditor(token, event.currentTarget)}
- disabled={!canManage()}
+ disabled={!canManage() || isMutating()}
class={`inline-flex min-h-10 items-center justify-center rounded-md px-2.5 py-1.5 text-sm font-semibold text-blue-600 transition hover:bg-blue-50 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-60 dark:text-blue-300 dark:hover:bg-blue-900/25 dark:hover:text-blue-200 ${
compact ? 'flex-1 border border-blue-200 dark:border-blue-800' : 'sm:min-h-9'
}`}
@@ -305,7 +326,7 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
data-api-token-id={token.id}
data-api-token-action="rename"
onClick={(event) => openRenameDialog(token, event.currentTarget)}
- disabled={!canManage()}
+ disabled={!canManage() || isMutating()}
class={`inline-flex min-h-10 items-center justify-center rounded-md px-2.5 py-1.5 text-sm font-semibold text-blue-600 transition hover:bg-blue-50 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-60 dark:text-blue-300 dark:hover:bg-blue-900/25 dark:hover:text-blue-200 ${
compact ? 'flex-1 border border-blue-200 dark:border-blue-800' : 'sm:min-h-9'
}`}
@@ -317,7 +338,7 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
data-api-token-id={token.id}
data-api-token-action="revoke"
onClick={(event) => openRevokeDialog(token, event.currentTarget)}
- disabled={!canManage()}
+ disabled={!canManage() || isMutating()}
class={`inline-flex min-h-10 items-center justify-center rounded-md px-2.5 py-1.5 text-sm font-semibold text-red-600 transition hover:bg-red-50 hover:text-red-700 disabled:cursor-not-allowed disabled:opacity-60 dark:text-red-400 dark:hover:bg-red-900/25 dark:hover:text-red-300 ${
compact ? 'flex-1 border border-red-200 dark:border-red-900/25' : 'sm:min-h-9'
}`}
diff --git a/frontend-modern/src/components/Settings/__tests__/APITokenLifetimes.test.tsx b/frontend-modern/src/components/Settings/__tests__/APITokenLifetimes.test.tsx
new file mode 100644
index 0000000000..1becbb7ac5
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/APITokenLifetimes.test.tsx
@@ -0,0 +1,200 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createSignal, Show } from 'solid-js';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
+import { SecurityAPI, type APITokenRecord } from '@/api/security';
+import { eventBus } from '@/stores/events';
+import { notificationStore } from '@/stores/notifications';
+import { dismissTokenReveal, showTokenReveal, useTokenRevealState } from '@/stores/tokenReveal';
+import { setOrgID } from '@/utils/apiClient';
+import { APITokenManager } from '../APITokenManager';
+import { useAPITokenManagerState } from '../useAPITokenManagerState';
+
+vi.mock('@/api/security', () => ({
+ SecurityAPI: {
+ listTokens: vi.fn(), createToken: vi.fn(), deleteToken: vi.fn(),
+ renameToken: vi.fn(), updateTokenScopes: vi.fn(),
+ },
+}));
+vi.mock('@/api/agentCapabilities', () => ({ fetchAgentCapabilitiesManifest: () => Promise.resolve({ requiredScopes: [] }) }));
+vi.mock('@/contexts/appRuntime', () => ({ useWebSocket: () => ({ markDockerRuntimesTokenRevoked: vi.fn(), markAgentsTokenRevoked: vi.fn() }) }));
+vi.mock('@/hooks/useResources', () => ({ useResources: () => ({ byType: () => [], resources: () => [] }) }));
+vi.mock('@/stores/notifications', () => ({ notificationStore: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('@/utils/logger', () => ({ logger: { error: vi.fn(), debug: vi.fn() } }));
+
+const record: APITokenRecord = { id: 'token-1', name: 'Known token', prefix: 'test', suffix: '1234', createdAt: '2026-11-01T00:00:00Z', scopes: ['monitoring:read'] };
+const created = { token: 'synthetic-only-secret', record: { ...record, id: 'created', name: 'Created token' } };
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+};
+let state: ReturnType<typeof useAPITokenManagerState>;
+let setAllowed!: (allowed: boolean) => void;
+let setHint!: (hint: string) => void;
+let setMounted!: (mounted: boolean) => void;
+const changed = vi.fn();
+const Harness = () => {
+ const [allowed, allow] = createSignal(true);
+ const [hint, hintTo] = createSignal('initial');
+ const [mounted, mount] = createSignal(true);
+ setAllowed = allow; setHint = hintTo; setMounted = mount;
+ const Panel = () => {
+ state = useAPITokenManagerState({ get canManage() { return allowed(); }, get currentUser() { return hint(); }, onTokensChanged: changed });
+ return null;
+ };
+ return <Show when={mounted()}><Panel /></Show>;
+};
+const ready = async () => {
+ render(() => <Harness />);
+ await waitFor(() => expect(state.tokensLoaded()).toBe(true));
+ state.applyScopePreset(['monitoring:read']);
+};
+const reveal = useTokenRevealState();
+beforeEach(() => {
+ vi.resetAllMocks(); setOrgID('org-a'); dismissTokenReveal();
+ vi.mocked(SecurityAPI.listTokens).mockResolvedValue([record]);
+ vi.mocked(SecurityAPI.createToken).mockResolvedValue(created);
+ vi.mocked(SecurityAPI.renameToken).mockResolvedValue({ ...record, name: 'Renamed' });
+ vi.mocked(SecurityAPI.updateTokenScopes).mockResolvedValue({ ...record, scopes: ['settings:read'] });
+});
+afterEach(() => { cleanup(); dismissTokenReveal(); setOrgID(null); });
+
+describe('API token request lifetimes', () => {
+ it('ignores a late create after unmount instead of revealing its credential globally', async () => {
+ await ready();
+ const pending = deferred<typeof created>();
+ vi.mocked(SecurityAPI.createToken).mockReturnValueOnce(pending.promise);
+ const writing = state.handleGenerate();
+ const options = vi.mocked(SecurityAPI.createToken).mock.calls[0][2]!;
+ setMounted(false);
+ expect(options.signal?.aborted).toBe(true);
+ pending.resolve(created); await writing;
+ expect(reveal()).toBeNull(); expect(state.newTokenValue()).toBeNull();
+ expect(notificationStore.success).not.toHaveBeenCalled(); expect(changed).not.toHaveBeenCalled();
+ });
+
+ it.each(['permission', 'organisation', 'user identity'])(
+ 'withdraws a create across a %s change and never replays it on return', async (change) => {
+ await ready();
+ const pending = deferred<typeof created>();
+ vi.mocked(SecurityAPI.createToken).mockReturnValueOnce(pending.promise);
+ const writing = state.handleGenerate();
+ const signal = vi.mocked(SecurityAPI.createToken).mock.calls[0][2]!.signal!;
+ if (change === 'permission') { setAllowed(false); setAllowed(true); }
+ if (change === 'organisation') {
+ setOrgID('org-b'); eventBus.emit('org_switched', 'org-b');
+ setOrgID('org-a'); eventBus.emit('org_switched', 'org-a');
+ }
+ if (change === 'user identity') { setHint('other'); setHint('initial'); }
+ expect(signal.aborted).toBe(true);
+ pending.resolve(created); await writing;
+ expect(reveal()).toBeNull(); expect(changed).not.toHaveBeenCalled();
+ expect(notificationStore.success).not.toHaveBeenCalled();
+ expect(SecurityAPI.createToken).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(state.tokensLoaded()).toBe(true));
+ expect(state.sortedTokens()).toEqual([record]);
+ },
+ );
+
+ it.each(['success', 'failure'])('ignores a disposed inventory %s without claiming absence or notifying', async (result) => {
+ const pending = deferred<APITokenRecord[]>();
+ vi.mocked(SecurityAPI.listTokens).mockReturnValueOnce(pending.promise);
+ render(() => <Harness />);
+ const signal = vi.mocked(SecurityAPI.listTokens).mock.calls[0][0]!.signal!;
+ setMounted(false); expect(signal.aborted).toBe(true);
+ if (result === 'success') pending.resolve([]); else pending.reject(new Error('synthetic failure'));
+ await pending.promise.catch(() => {});
+ await Promise.resolve();
+ expect(state.tokensLoaded()).toBe(false);
+ expect(notificationStore.error).not.toHaveBeenCalled();
+ });
+
+ it('does not let an old organisation inventory replace the new accepted read', async () => {
+ const oldRead = deferred<APITokenRecord[]>();
+ vi.mocked(SecurityAPI.listTokens).mockReturnValueOnce(oldRead.promise);
+ render(() => <Harness />);
+ const oldSignal = vi.mocked(SecurityAPI.listTokens).mock.calls[0][0]!.signal!;
+ setOrgID('org-b'); eventBus.emit('org_switched', 'org-b');
+ await waitFor(() => expect(state.tokensLoaded()).toBe(true));
+ oldRead.resolve([]); await oldRead.promise; await Promise.resolve();
+ expect(oldSignal.aborted).toBe(true);
+ expect(state.sortedTokens()).toEqual([record]);
+ expect(SecurityAPI.listTokens).toHaveBeenLastCalledWith(expect.objectContaining({ expectedOrgID: 'org-b' }));
+ });
+
+ it.each(['rename', 'scope', 'revoke'] as const)('ignores a late %s success after withdrawal', async (operation) => {
+ await ready();
+ const pending = deferred<APITokenRecord>();
+ vi.mocked(SecurityAPI.renameToken).mockReturnValueOnce(pending.promise);
+ vi.mocked(SecurityAPI.updateTokenScopes).mockReturnValueOnce(pending.promise);
+ vi.mocked(SecurityAPI.deleteToken).mockReturnValueOnce(pending.promise.then(() => undefined));
+ const writing = operation === 'rename' ? state.handleRename(record, 'Renamed') : operation === 'scope' ? state.handleUpdateScopes(record, ['settings:read']) : state.handleDelete(record);
+ setAllowed(false);
+ pending.resolve({ ...record, name: 'Obsolete completion' }); await writing;
+ expect(notificationStore.success).not.toHaveBeenCalled(); expect(changed).not.toHaveBeenCalled();
+ expect(state.sortedTokens()).not.toContainEqual(expect.objectContaining({ name: 'Obsolete completion' }));
+ });
+
+ it('serialises all writes and resumes an interrupted inventory read without accepting its old snapshot', async () => {
+ const read = deferred<APITokenRecord[]>();
+ vi.mocked(SecurityAPI.listTokens).mockReturnValueOnce(read.promise).mockResolvedValueOnce([record, created.record]);
+ render(() => <Harness />); state.applyScopePreset(['monitoring:read']);
+ const pending = deferred<typeof created>();
+ vi.mocked(SecurityAPI.createToken).mockReturnValueOnce(pending.promise);
+ const writing = state.handleGenerate();
+ await state.handleGenerate(); await state.loadTokens();
+ expect(SecurityAPI.createToken).toHaveBeenCalledTimes(1);
+ expect(SecurityAPI.listTokens).toHaveBeenCalledTimes(1);
+ pending.resolve(created); await writing;
+ await waitFor(() => expect(state.tokensLoaded()).toBe(true));
+ read.resolve([]); await read.promise; await Promise.resolve();
+ expect(state.sortedTokens()).toHaveLength(2);
+ expect(reveal()?.token).toBe(created.token);
+ expect(SecurityAPI.listTokens).toHaveBeenCalledTimes(2);
+ expect(changed).toHaveBeenCalledTimes(1);
+ });
+
+ it('clears only its owned reveal and local credential when its authority is withdrawn', async () => {
+ await ready(); await state.handleGenerate();
+ expect(reveal()?.token).toBe(created.token);
+ setAllowed(false);
+ expect(reveal()).toBeNull(); expect(state.newTokenValue()).toBeNull();
+ state.reopenTokenDialog(); await state.copyNewMonitoringKioskLink();
+ expect(reveal()).toBeNull(); expect(state.newMonitoringKioskLink()).toBeNull();
+ });
+
+ it('does not dismiss a replacement token reveal owned by another issuer', async () => {
+ await ready(); await state.handleGenerate();
+ showTokenReveal({ token: 'other-synthetic-secret', source: 'agent-setup' });
+ const other = reveal(); setMounted(false);
+ expect(reveal()).toBe(other); expect(state.newTokenValue()).toBeNull();
+ });
+
+ it('rejects a row retained from an earlier accepted inventory', async () => {
+ await ready();
+ await state.loadTokens();
+ // Same ID, different accepted object is not the earlier confirmation.
+ const obsolete = { ...record };
+ expect(await state.handleRename(obsolete, 'Wrong')).toBe(false);
+ expect(await state.handleUpdateScopes(obsolete, ['*'])).toBe(false);
+ await state.handleDelete(obsolete);
+ expect(SecurityAPI.renameToken).not.toHaveBeenCalled();
+ expect(SecurityAPI.updateTokenScopes).not.toHaveBeenCalled();
+ expect(SecurityAPI.deleteToken).not.toHaveBeenCalled();
+ });
+
+ it('closes an open action dialog on withdrawal while keeping read-only inventory usable', async () => {
+ const [allowed, allow] = createSignal(true);
+ render(() => <APITokenManager canManage={allowed()} />);
+ await screen.findAllByText('Known token');
+ const row = screen.getByRole('article', { name: 'API token Known token' });
+ fireEvent.click(within(row).getByRole('button', { name: 'Rename' }));
+ await screen.findByRole('dialog', { name: 'Rename API token' });
+ allow(false);
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ await screen.findAllByText('Known token');
+ expect(within(screen.getByRole('article', { name: 'API token Known token' })).getByRole('button', { name: 'Rename' })).toBeDisabled();
+ expect(SecurityAPI.renameToken).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
index a605b2aeba..d0a02946a9 100644
--- a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
@@ -66,6 +66,7 @@ vi.mock('@/stores/notifications', () => ({
}));
vi.mock('@/stores/tokenReveal', () => ({
+ dismissTokenReveal: vi.fn(),
showTokenReveal: (...args: unknown[]) => showTokenRevealMock(...args),
useTokenRevealState: () => () => null,
}));
@@ -521,7 +522,7 @@ describe('APITokenManager', () => {
expect(createTokenMock).toHaveBeenCalledWith('Container automation', [
DOCKER_MANAGE_SCOPE,
DOCKER_REPORT_SCOPE,
- ]);
+ ], expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
expect(showTokenRevealMock).toHaveBeenCalledWith(
@@ -570,7 +571,7 @@ describe('APITokenManager', () => {
expect(createTokenMock).toHaveBeenCalledWith('Replacement agent token', [
AGENT_CONFIG_READ_SCOPE,
AGENT_REPORT_SCOPE,
- ]);
+ ], expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
});
@@ -667,7 +668,7 @@ describe('APITokenManager', () => {
MONITORING_WRITE_SCOPE,
SETTINGS_READ_SCOPE,
SETTINGS_WRITE_SCOPE,
- ]);
+ ], expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
expect(showTokenRevealMock).toHaveBeenCalledWith(
@@ -720,7 +721,7 @@ describe('APITokenManager', () => {
MONITORING_WRITE_SCOPE,
SETTINGS_READ_SCOPE,
SETTINGS_WRITE_SCOPE,
- ]);
+ ], expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
});
@@ -762,7 +763,7 @@ describe('APITokenManager', () => {
fireEvent.click(screen.getByRole('button', { name: 'Generate' }));
await waitFor(() => {
- expect(createTokenMock).toHaveBeenCalledWith('Audit export', [AUDIT_READ_SCOPE]);
+ expect(createTokenMock).toHaveBeenCalledWith('Audit export', [AUDIT_READ_SCOPE], expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
});
@@ -824,7 +825,7 @@ describe('APITokenManager', () => {
fireEvent.click(confirmBtn);
await waitFor(() => {
- expect(deleteTokenMock).toHaveBeenCalledWith('token-runtime');
+ expect(deleteTokenMock).toHaveBeenCalledWith('token-runtime', expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
expect(markDockerRuntimesTokenRevokedMock).toHaveBeenCalledWith('token-runtime', [
@@ -911,7 +912,7 @@ describe('APITokenManager', () => {
fireEvent.click(within(dialog).getByRole('button', { name: 'Save scopes' }));
await waitFor(() => {
- expect(updateTokenScopesMock).toHaveBeenCalledWith('token-edit', [MONITORING_READ_SCOPE]);
+ expect(updateTokenScopesMock).toHaveBeenCalledWith('token-edit', [MONITORING_READ_SCOPE], expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
expect(deleteTokenMock).not.toHaveBeenCalled();
expect(createTokenMock).not.toHaveBeenCalled();
@@ -997,7 +998,7 @@ describe('APITokenManager', () => {
await waitFor(() => {
expect(updateTokenScopesMock).toHaveBeenCalledWith('token-edit-failure', [
MONITORING_READ_SCOPE,
- ]);
+ ], expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
expect(notificationErrorMock).toHaveBeenCalledWith('Unable to update API token scopes.');
expect(screen.getByRole('dialog', { name: 'Edit API token scopes' })).toBeInTheDocument();
@@ -1067,7 +1068,7 @@ describe('APITokenManager', () => {
fireEvent.click(within(dialog).getByRole('button', { name: 'Save' }));
await waitFor(() => {
- expect(renameTokenMock).toHaveBeenCalledWith('token-pbs', 'PBS 01 telemetry');
+ expect(renameTokenMock).toHaveBeenCalledWith('token-pbs', 'PBS 01 telemetry', expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
expect(screen.getAllByText('PBS 01 telemetry').length).toBeGreaterThan(0);
expect(document.activeElement).toHaveTextContent('Rename');
});
@@ -1098,7 +1099,7 @@ describe('APITokenManager', () => {
fireEvent.click(screen.getByRole('button', { name: 'Generate' }));
await waitFor(() => {
- expect(createTokenMock).toHaveBeenCalledWith('Blocked token', ['monitoring:read']);
+ expect(createTokenMock).toHaveBeenCalledWith('Blocked token', ['monitoring:read'], expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
expect(notificationErrorMock).toHaveBeenCalledWith(
@@ -1129,7 +1130,7 @@ describe('APITokenManager', () => {
fireEvent.click(screen.getByRole('button', { name: 'Generate' }));
await waitFor(() => {
- expect(createTokenMock).toHaveBeenCalledWith('Needs settings scope', [DOCKER_REPORT_SCOPE]);
+ expect(createTokenMock).toHaveBeenCalledWith('Needs settings scope', [DOCKER_REPORT_SCOPE], expect.objectContaining({ expectedOrgID: 'default', signal: expect.any(AbortSignal) }));
});
expect(notificationErrorMock).toHaveBeenCalledWith(
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
index b37be0fb82..dc5aba8663 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
@@ -91,6 +91,7 @@ export function buildSettingsPanelRegistryContext(
guestUsage: params.organizationGuestUsage(),
}),
getApiAccessPanelProps: () => ({
+ currentUser: currentUser(),
currentTokenHint: params.securityStatus()?.apiTokenHint,
onTokensChanged: () => {
void params.loadSecurityStatus();
diff --git a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts b/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
index f94473d4b3..8b882f6171 100644
--- a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
+++ b/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
@@ -1,12 +1,15 @@
import {
+ batch,
createEffect,
createMemo,
createResource,
createSignal,
+ on,
onCleanup,
onMount,
} from 'solid-js';
import { fetchAgentCapabilitiesManifest } from '@/api/agentCapabilities';
+import { unwrap } from 'solid-js/store';
import type { APITokenRecord } from '@/api/security';
import { SecurityAPI } from '@/api/security';
import { useWebSocket } from '@/contexts/appRuntime';
@@ -17,7 +20,7 @@ import {
} from '@/routing/resourceLinks';
import { useResources } from '@/hooks/useResources';
import { notificationStore } from '@/stores/notifications';
-import { showTokenReveal, useTokenRevealState } from '@/stores/tokenReveal';
+import { dismissTokenReveal, showTokenReveal, useTokenRevealState } from '@/stores/tokenReveal';
import type { Resource } from '@/types/resource';
import { formatRelativeTime } from '@/utils/format';
import {
@@ -29,6 +32,8 @@ import {
getAPITokenUpdateErrorMessage,
} from '@/utils/apiTokenPresentation';
import { logger } from '@/utils/logger';
+import { eventBus } from '@/stores/events';
+import { getOrgID } from '@/utils/apiClient';
import { getPulseBaseUrl } from '@/utils/url';
import {
API_TOKEN_SCOPES_DOC_URL,
@@ -53,6 +58,7 @@ import {
interface APITokenManagerProps {
currentTokenHint?: string;
+ currentUser?: string;
onTokensChanged?: () => void;
refreshing?: boolean;
canManage?: boolean;
@@ -83,7 +89,74 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
const [selectedScopes, setSelectedScopes] = createSignal<string[]>([]);
const [agentCapabilitiesManifest] = createResource(fetchAgentCapabilitiesManifest);
const tokenRevealState = useTokenRevealState();
- const canManage = () => props.canManage !== false;
+ const currentOrg = () => getOrgID() || 'default';
+ const [selectedOrg, setSelectedOrg] = createSignal(currentOrg());
+ const [selectedUser, setSelectedUser] = createSignal(props.currentUser);
+ const [contextVersion, setContextVersion] = createSignal(0);
+ const [isMutating, setIsMutating] = createSignal(false);
+ let disposed = false;
+ let readController: AbortController | undefined;
+ let mutationController: AbortController | undefined;
+ let ownedReveal: ReturnType<typeof tokenRevealState> = null;
+ const contextIsCurrent = () =>
+ !disposed && selectedOrg() === currentOrg() && selectedUser() === props.currentUser;
+ const canManage = () => contextIsCurrent() && props.canManage !== false;
+ const isCurrentRecord = (record: APITokenRecord) =>
+ tokensLoaded() && tokens().includes(unwrap(record));
+
+ const clearTokenValue = () => {
+ // A different issuer may have replaced the global dialog. Never dismiss theirs.
+ if (ownedReveal && tokenRevealState() === ownedReveal) dismissTokenReveal();
+ ownedReveal = null;
+ setNewTokenValue(null);
+ setNewTokenRecord(null);
+ };
+
+ const invalidateRequests = () => {
+ setContextVersion((version) => version + 1);
+ readController?.abort();
+ readController = undefined;
+ mutationController?.abort();
+ mutationController = undefined;
+ batch(() => {
+ setIsMutating(false);
+ setIsGenerating(false);
+ setUpdatingTokenId(null);
+ setIsRenaming(false);
+ clearTokenValue();
+ });
+ };
+
+ const beginMutation = () => {
+ if (!canManage() || mutationController) return;
+ const controller = new AbortController();
+ const version = contextVersion();
+ const org = selectedOrg();
+ // A snapshot started before a write must not erase its accepted result or
+ // mark the newly issued credential revoked. Resume only this interrupted read.
+ const resumeRead = Boolean(readController);
+ readController?.abort();
+ readController = undefined;
+ mutationController = controller;
+ setIsMutating(true);
+ const isCurrent = () =>
+ mutationController === controller && version === contextVersion() && canManage();
+ return {
+ options: { signal: controller.signal, expectedOrgID: org },
+ isCurrent,
+ finish: () => {
+ if (mutationController !== controller) return;
+ mutationController = undefined;
+ batch(() => {
+ setIsMutating(false);
+ setIsGenerating(false);
+ setUpdatingTokenId(null);
+ setIsRenaming(false);
+ });
+ if (resumeRead && contextIsCurrent()) void loadTokens();
+ },
+ };
+ };
const sortedTokens = createMemo(() => sortAPITokensByCreatedAt(tokens()));
const totalTokens = createMemo(() => sortedTokens().length);
@@ -99,7 +172,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
);
const hasScopeSelection = () => selectedScopes().length > 0;
const isFullAccessSelected = () => selectedScopes().includes(API_TOKEN_WILDCARD_SCOPE);
- const canGenerateToken = () => canManage() && hasScopeSelection() && !isGenerating();
+ const canGenerateToken = () => canManage() && hasScopeSelection() && !isMutating();
let createSectionRef: HTMLDivElement | undefined;
const [createHighlight, setCreateHighlight] = createSignal(false);
@@ -138,7 +211,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
};
const focusCreateSection = () => {
- if (!createSectionRef) return;
+ if (!canManage() || !createSectionRef) return;
if (typeof createSectionRef.scrollIntoView === 'function') {
createSectionRef.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
@@ -161,27 +234,68 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
if (routeFocusTimer) window.clearTimeout(routeFocusTimer);
});
- let tokenReadInFlight = false;
const loadTokens = async () => {
- if (tokenReadInFlight) return;
- tokenReadInFlight = true;
+ if (!contextIsCurrent() || readController || mutationController) return;
+ const controller = new AbortController();
+ const version = contextVersion();
+ readController = controller;
+ const isCurrent = () =>
+ readController === controller && version === contextVersion() && contextIsCurrent();
setLoading(true);
setTokensLoaded(false);
setLoadError(null);
try {
- const list = await SecurityAPI.listTokens();
+ const list = await SecurityAPI.listTokens({
+ signal: controller.signal,
+ expectedOrgID: selectedOrg(),
+ });
+ if (!isCurrent()) return;
setTokens(list);
setTokensLoaded(true);
} catch (err) {
+ if (!isCurrent()) return;
setLoadError(getAPITokensLoadErrorMessage());
logger.error('Failed to load API tokens', err);
notificationStore.error(getAPITokensLoadErrorMessage());
} finally {
- tokenReadInFlight = false;
- setLoading(false);
+ if (isCurrent()) {
+ readController = undefined;
+ setLoading(false);
+ }
}
};
+ const resetContext = () => {
+ if (disposed) return;
+ const selectionChanged =
+ selectedOrg() !== currentOrg() || selectedUser() !== props.currentUser;
+ invalidateRequests();
+ batch(() => {
+ setSelectedOrg(currentOrg());
+ setSelectedUser(props.currentUser);
+ setTokens([]);
+ setTokensLoaded(false);
+ setLoadError(null);
+ if (selectionChanged) {
+ setNameInput('');
+ setSelectedScopes([]);
+ }
+ });
+ // Read-only accounts retain inventory recovery. Never replay an interrupted write.
+ void loadTokens();
+ };
+
+ createEffect(
+ on(() => [props.canManage, props.currentUser], resetContext, { defer: true }),
+ );
+ const unsubscribeOrg = eventBus.on('org_switched', resetContext);
+ onCleanup(() => {
+ disposed = true;
+ invalidateRequests();
+ unsubscribeOrg();
+ setTokens([]);
+ });
+
onMount(() => {
setRequestedTokenPreset(readRequestedTokenPreset());
const handleRoutePresetChange = () => {
@@ -243,7 +357,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
});
createEffect(() => {
- if (!tokensLoaded()) return;
+ if (!tokensLoaded() || !contextIsCurrent()) return;
const activeTokenIds = new Set(tokens().map((token) => token.id));
const pendingRuntimesByToken = new Map<string, string[]>();
@@ -308,12 +422,15 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
notificationStore.error('Choose a scope preset or custom scope before generating a token.');
return;
}
+ const mutation = beginMutation();
+ if (!mutation) return;
setIsGenerating(true);
try {
const trimmedName = nameInput().trim() || undefined;
const scopeSelection = [...selectedScopes()].sort();
const scopePayload = scopeSelection.length > 0 ? scopeSelection : undefined;
- const { token, record } = await SecurityAPI.createToken(trimmedName, scopePayload);
+ const { token, record } = await SecurityAPI.createToken(trimmedName, scopePayload, mutation.options);
+ if (!mutation.isCurrent()) return;
setTokens((previous) => [record, ...previous]);
setNewTokenRecord(record);
@@ -326,20 +443,24 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
source: 'security',
note: getAPITokenRevealSettingsNote(),
});
+ ownedReveal = tokenRevealState();
notificationStore.success(
'New API token generated. Copy it below while it is still visible.',
);
props.onTokensChanged?.();
} catch (err) {
+ if (!mutation.isCurrent()) return;
logger.error('Failed to generate API token', err);
notificationStore.error(getAPITokenGenerateErrorMessage(err));
} finally {
- setIsGenerating(false);
+ mutation.finish();
}
};
const handleDelete = async (record: APITokenRecord) => {
- if (!canManage()) return;
+ if (!isCurrentRecord(record)) return;
+ const mutation = beginMutation();
+ if (!mutation) return;
const dockerUsage = dockerTokenUsage().get(record.id);
const agentUsage = agentTokenUsage().get(record.id);
const displayName = getAPITokenDialogName(record);
@@ -376,7 +497,8 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
}
try {
- await SecurityAPI.deleteToken(record.id);
+ await SecurityAPI.deleteToken(record.id, mutation.options);
+ if (!mutation.isCurrent()) return;
setTokens((previous) => previous.filter((token) => token.id !== record.id));
notificationStore.success(
revokeMessage ? `Token revoked: ${revokeMessage}` : 'Token revoked',
@@ -392,21 +514,26 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
const current = newTokenRecord();
if (current && current.id === record.id) {
- setNewTokenValue(null);
- setNewTokenRecord(null);
+ clearTokenValue();
}
} catch (err) {
+ if (!mutation.isCurrent()) return;
logger.error('Failed to revoke API token', err);
notificationStore.error(getAPITokenRevokeErrorMessage());
+ } finally {
+ mutation.finish();
}
};
const handleUpdateScopes = async (record: APITokenRecord, scopes: string[]) => {
- if (!canManage() || scopes.length === 0 || updatingTokenId() !== null) return false;
+ if (scopes.length === 0 || !isCurrentRecord(record)) return false;
+ const mutation = beginMutation();
+ if (!mutation) return false;
setUpdatingTokenId(record.id);
try {
- const updated = await SecurityAPI.updateTokenScopes(record.id, [...scopes].sort());
+ const updated = await SecurityAPI.updateTokenScopes(record.id, [...scopes].sort(), mutation.options);
+ if (!mutation.isCurrent()) return false;
setTokens((previous) => previous.map((token) => (token.id === updated.id ? updated : token)));
if (newTokenRecord()?.id === updated.id) {
setNewTokenRecord(updated);
@@ -415,36 +542,41 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
props.onTokensChanged?.();
return true;
} catch (err) {
+ if (!mutation.isCurrent()) return false;
logger.error('Failed to update API token scopes', err);
notificationStore.error(getAPITokenUpdateErrorMessage(err));
return false;
} finally {
- setUpdatingTokenId(null);
+ mutation.finish();
}
};
const handleRename = async (record: APITokenRecord, name: string): Promise<boolean> => {
- if (!canManage() || isRenaming()) return false;
+ if (!canManage() || !isCurrentRecord(record) || isMutating()) return false;
const trimmedName = name.trim();
if (!trimmedName) {
notificationStore.error('Enter a token name.');
return false;
}
+ const mutation = beginMutation();
+ if (!mutation) return false;
setIsRenaming(true);
try {
- const updated = await SecurityAPI.renameToken(record.id, trimmedName);
+ const updated = await SecurityAPI.renameToken(record.id, trimmedName, mutation.options);
+ if (!mutation.isCurrent()) return false;
setTokens((previous) => previous.map((token) => (token.id === updated.id ? updated : token)));
setNewTokenRecord((current) => (current?.id === updated.id ? updated : current));
notificationStore.success('Token renamed');
props.onTokensChanged?.();
return true;
} catch (err) {
+ if (!mutation.isCurrent()) return false;
logger.error('Failed to rename API token', err);
notificationStore.error('Unable to rename the API token.');
return false;
} finally {
- setIsRenaming(false);
+ mutation.finish();
}
};
@@ -456,22 +588,23 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
const reopenTokenDialog = () => {
const token = newTokenValue();
const record = newTokenRecord();
- if (!token || !record) return;
+ if (!canManage() || !token || !record) return;
showTokenReveal({
token,
record,
source: 'security',
note: 'Copy this token now. Close the dialog once you have stored it safely.',
});
+ ownedReveal = tokenRevealState();
};
const dismissNewToken = () => {
- setNewTokenValue(null);
- setNewTokenRecord(null);
+ clearTokenValue();
};
const newMonitoringKioskLink = createMemo(() => {
if (
+ !canManage() ||
!newTokenValue() ||
newTokenRecord()?.scopes?.length !== 1 ||
newTokenRecord()?.scopes?.[0] !== MONITORING_READ_SCOPE
@@ -483,8 +616,10 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
const copyNewMonitoringKioskLink = async () => {
const link = newMonitoringKioskLink();
- if (!link) return;
+ if (!canManage() || !link) return;
+ const version = contextVersion();
await navigator.clipboard.writeText(link);
+ if (version !== contextVersion() || !canManage()) return;
notificationStore.success('Link copied to clipboard');
};
@@ -495,6 +630,8 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
applyFullAccessPreset,
applyScopePreset,
canManage,
+ contextVersion,
+ isMutating,
clearScopes,
copyNewMonitoringKioskLink,
createHighlight,