Keep VMware settings requests with their admitted reader

Bind inventory, drafts and actions to the current organisation, user and infrastructure capability. Withdraw obsolete state and ignore late completions; preserve saved credentials, collection choices and TLS. Exercise the reader through unit, containing-hook and real API transport tests.

Contract-Neutral: Restores existing least-privilege reader ownership without changing routes, entitlements, transport trust or the saved connection schema.
Change-source: pulse-maintainer
This commit is contained in:
pulse-triage[bot]
2026-11-03 04:28:14 +00:00
parent baf35dcc0a
commit e1578ff76f
8 changed files with 1210 additions and 137 deletions

View File

@@ -334,4 +334,50 @@ describe('VMwareAPI', () => {
expect(isRedactedVMwareSecret('secret')).toBe(false);
expect(isRedactedVMwareSecret(undefined)).toBe(false);
});
it('carries reader scope, cancellation and retry policy through every canonical connection operation', async () => {
vi.mocked(apiFetchJSON).mockResolvedValue({ success: true });
const options = { expectedOrgID: 'team-a', signal: new AbortController().signal, retry: false };
const input = {
host: 'vc.example.invalid',
username: 'monitor',
password: '********',
monitorVms: false,
monitorHosts: true,
monitorDatastores: false,
insecureSkipVerify: false,
};
await VMwareAPI.listConnections(options);
await VMwareAPI.createConnection(input, options);
await VMwareAPI.updateConnection('id/with slash', input, options);
await VMwareAPI.deleteConnection('id/with slash', options);
await VMwareAPI.testConnection(input, options);
await VMwareAPI.testSavedConnection('id/with slash', input, options);
await VMwareAPI.previewConnection(input, options);
await VMwareAPI.previewSavedConnection('id/with slash', input, options);
const calls = vi.mocked(apiFetchJSON).mock.calls;
expect(calls).toHaveLength(8);
expect(calls.map(([url]) => url)).toEqual([
'/api/vmware/connections',
'/api/vmware/connections',
'/api/vmware/connections/id%2Fwith%20slash',
'/api/vmware/connections/id%2Fwith%20slash',
'/api/vmware/connections/test',
'/api/vmware/connections/id%2Fwith%20slash/test',
'/api/vmware/connections/preview',
'/api/vmware/connections/id%2Fwith%20slash/preview',
]);
expect(calls.map(([, request]) => request?.method ?? 'GET')).toEqual([
'GET',
'POST',
'PUT',
'DELETE',
'POST',
'POST',
'POST',
'POST',
]);
for (const [, request] of calls) expect(request).toMatchObject(options);
for (const [, request] of calls.filter(([, request]) => request?.body))
expect(JSON.parse(request!.body as string)).toEqual(input);
});
});

View File

@@ -1,4 +1,4 @@
import { apiFetchJSON } from '@/utils/apiClient';
import { apiFetchJSON, type APIContextOptions } from '@/utils/apiClient';
import {
normalizeMonitoredSystemLedgerPreviewResponse,
type MonitoredSystemLedgerPreviewResponse,
@@ -215,14 +215,20 @@ export const isRedactedVMwareSecret = (value: string | null | undefined) =>
(value || '').trim() === REDACTED_SECRET;
export class VMwareAPI {
static async listConnections(): Promise<VMwareConnection[]> {
const response = await apiFetchJSON<RawVMwareConnection[]>(VMWARE_CONNECTIONS_PATH);
static async listConnections(options?: APIContextOptions): Promise<VMwareConnection[]> {
const response = await (options === undefined
? apiFetchJSON<RawVMwareConnection[]>(VMWARE_CONNECTIONS_PATH)
: apiFetchJSON<RawVMwareConnection[]>(VMWARE_CONNECTIONS_PATH, options));
const list = arrayOrUndefined<RawVMwareConnection>(response) ?? [];
return list.map(normalizeVMwareConnection);
}
static async createConnection(input: VMwareConnectionInput): Promise<VMwareConnection> {
static async createConnection(
input: VMwareConnectionInput,
options?: APIContextOptions,
): Promise<VMwareConnection> {
const response = await apiFetchJSON<RawVMwareConnection>(VMWARE_CONNECTIONS_PATH, {
...options,
method: 'POST',
body: JSON.stringify(serializeVMwareConnectionInput(input)),
});
@@ -232,10 +238,12 @@ export class VMwareAPI {
static async updateConnection(
id: string,
input: VMwareConnectionInput,
options?: APIContextOptions,
): Promise<VMwareConnection> {
const response = await apiFetchJSON<RawVMwareConnection>(
`${VMWARE_CONNECTIONS_PATH}/${encodeURIComponent(id)}`,
{
...options,
method: 'PUT',
body: JSON.stringify(serializeVMwareConnectionInput(input)),
},
@@ -243,16 +251,24 @@ export class VMwareAPI {
return normalizeVMwareConnection(response);
}
static async deleteConnection(id: string): Promise<{ success: boolean; id: string }> {
static async deleteConnection(
id: string,
options?: APIContextOptions,
): Promise<{ success: boolean; id: string }> {
return apiFetchJSON(`${VMWARE_CONNECTIONS_PATH}/${encodeURIComponent(id)}`, {
...options,
method: 'DELETE',
});
}
static async testConnection(input: VMwareConnectionInput): Promise<VMwareConnectionTestResult> {
static async testConnection(
input: VMwareConnectionInput,
options?: APIContextOptions,
): Promise<VMwareConnectionTestResult> {
const response = await apiFetchJSON<Partial<VMwareConnectionTestResult>>(
`${VMWARE_CONNECTIONS_PATH}/test`,
{
...options,
method: 'POST',
body: JSON.stringify(serializeVMwareConnectionInput(input)),
},
@@ -263,10 +279,12 @@ export class VMwareAPI {
static async testSavedConnection(
id: string,
input?: VMwareConnectionInput,
options?: APIContextOptions,
): Promise<VMwareConnectionTestResult> {
const response = await apiFetchJSON<Partial<VMwareConnectionTestResult>>(
`${VMWARE_CONNECTIONS_PATH}/${encodeURIComponent(id)}/test`,
{
...options,
method: 'POST',
...(input !== undefined
? { body: JSON.stringify(serializeVMwareConnectionInput(input)) }
@@ -278,10 +296,12 @@ export class VMwareAPI {
static async previewConnection(
input: VMwareConnectionInput,
options?: APIContextOptions,
): Promise<MonitoredSystemLedgerPreviewResponse> {
const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
`${VMWARE_CONNECTIONS_PATH}/preview`,
{
...options,
method: 'POST',
body: JSON.stringify(serializeVMwareConnectionInput(input)),
},
@@ -292,10 +312,12 @@ export class VMwareAPI {
static async previewSavedConnection(
id: string,
input?: VMwareConnectionInput,
options?: APIContextOptions,
): Promise<MonitoredSystemLedgerPreviewResponse> {
const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
`${VMWARE_CONNECTIONS_PATH}/${encodeURIComponent(id)}/preview`,
{
...options,
method: 'POST',
...(input !== undefined
? { body: JSON.stringify(serializeVMwareConnectionInput(input)) }

View File

@@ -0,0 +1,107 @@
import { renderHook, waitFor } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { VMwareAPI, type VMwareConnection } from '@/api/vmware';
import { eventBus } from '@/stores/events';
import { useInfrastructureSettingsState } from '../useInfrastructureSettingsState';
// Keep the containing hook and VMware state real: a lower-level reader test
// cannot detect a missing currentUser at the production call site.
vi.mock('../useInfrastructureConfiguredNodesState', () => ({
useInfrastructureConfiguredNodesState: () => ({
nodes: () => [],
showNodeModal: () => false,
loadNodes: vi.fn().mockResolvedValue(undefined),
clearLoadNodesRetry: vi.fn(),
}),
}));
vi.mock('../useInfrastructureDiscoveryRuntimeState', () => ({
useInfrastructureDiscoveryRuntimeState: () => ({
loadDiscoveredNodes: vi.fn().mockResolvedValue(undefined),
}),
}));
vi.mock('../useTrueNASSettingsPanelState', () => ({ useTrueNASSettingsPanelState: () => ({}) }));
vi.mock('@/api/vmware', () => ({
VMwareAPI: { listConnections: vi.fn() },
isRedactedVMwareSecret: (value?: string) => value === '********',
}));
vi.mock('@/utils/apiClient', () => ({ getOrgID: () => 'team-a' }));
vi.mock('@/utils/logger', () => ({ logger: { error: vi.fn() } }));
const connection = (): VMwareConnection => ({
id: 'vc-1',
name: 'Synthetic vCenter',
host: 'vc.example.invalid',
password: '********',
insecureSkipVerify: false,
enabled: true,
monitorVms: true,
monitorHosts: false,
monitorDatastores: true,
});
describe('Infrastructure settings VMware reader wiring', () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(VMwareAPI.listConnections).mockImplementation(async () => [connection()]);
});
it('withdraws the actual VMware draft when the containing settings user changes', async () => {
const [currentUser, setUser] = createSignal<string | undefined>('reader-a');
const noop = () => undefined;
const { result } = renderHook(() => {
const [enabled, setEnabled] = createSignal(false);
const [text, setText] = createSignal('');
const [mode, setMode] = createSignal<'auto' | 'custom'>('auto');
return useInfrastructureSettingsState({
eventBus,
canReadInfrastructure: () => true,
currentUser,
discoveryEnabled: enabled,
setDiscoveryEnabled: setEnabled,
discoverySubnet: text,
discoveryMode: mode,
setDiscoveryMode: setMode,
discoverySubnetDraft: text,
setDiscoverySubnetDraft: setText,
lastCustomSubnet: text,
setLastCustomSubnet: setText,
setDiscoverySubnetError: noop,
savingDiscoverySettings: enabled,
setSavingDiscoverySettings: setEnabled,
envOverrides: () => ({}),
normalizeSubnetList: (value) => value,
isValidCIDR: () => false,
applySavedDiscoverySubnet: noop,
temperatureMonitoringEnabled: enabled,
savingTemperatureSetting: enabled,
setSavingTemperatureSetting: setEnabled,
loadSecurityStatus: async () => undefined,
initializeSystemSettingsState: async () => undefined,
});
});
await waitFor(() => expect(result.initialLoadComplete()).toBe(true));
const state = result.vmwareSettings;
const old = state.connections()[0];
state.openEditDialog(old);
state.updateForm({ password: 'synthetic-draft' });
const first = vi.mocked(VMwareAPI.listConnections).mock.calls[0][0]!;
setUser('reader-b');
await waitFor(() => expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(2));
expect(first.signal?.aborted).toBe(true);
expect(state.dialogOpen()).toBe(false);
expect(state.form().password).toBe('');
await waitFor(() => expect(state.loading()).toBe(false));
state.openEditDialog(old);
expect(state.dialogOpen()).toBe(false);
state.openEditDialog(state.connections()[0]);
expect(state.form()).toMatchObject({
hasStoredPassword: true,
password: '',
insecureSkipVerify: false,
monitorVms: true,
monitorHosts: false,
monitorDatastores: true,
});
});
});

View File

@@ -0,0 +1,485 @@
import { renderHook, waitFor } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { VMwareAPI, type VMwareConnection } from '@/api/vmware';
import { eventBus } from '@/stores/events';
import { notificationStore } from '@/stores/notifications';
import { logger } from '@/utils/logger';
import { useVMwareSettingsPanelState } from '../useVMwareSettingsPanelState';
const scope = vi.hoisted(() => ({ org: 'team-a' }));
vi.mock('@/utils/apiClient', () => ({ getOrgID: () => scope.org }));
vi.mock('@/api/vmware', () => ({
VMwareAPI: {
listConnections: vi.fn(),
createConnection: vi.fn(),
updateConnection: vi.fn(),
deleteConnection: vi.fn(),
previewConnection: vi.fn(),
previewSavedConnection: vi.fn(),
testConnection: vi.fn(),
testSavedConnection: vi.fn(),
},
isRedactedVMwareSecret: (value?: string) => value?.trim() === '********',
}));
vi.mock('@/stores/notifications', () => ({
notificationStore: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },
}));
vi.mock('@/utils/logger', () => ({ logger: { error: vi.fn() } }));
const connection = (): VMwareConnection => ({
id: 'same-id',
name: 'Synthetic vCenter',
host: 'vc.example.invalid',
username: 'monitor',
password: '********',
insecureSkipVerify: false,
enabled: true,
monitorVms: true,
monitorHosts: true,
monitorDatastores: true,
});
const deferred = <T,>() => {
let resolve!: (value: T) => void;
let reject!: (error: unknown) => void;
const promise = new Promise<T>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
};
const ready = async (state: ReturnType<typeof useVMwareSettingsPanelState>) =>
waitFor(() => {
expect(state.loading()).toBe(false);
expect(state.connections()).toHaveLength(1);
});
const openDraft = (state: ReturnType<typeof useVMwareSettingsPanelState>) => {
state.openEditDialog(state.connections()[0]);
state.updateForm({ password: 'synthetic-draft', name: 'Unconfirmed draft' });
};
describe('VMware reader lifetime', () => {
beforeEach(() => {
vi.resetAllMocks();
scope.org = 'team-a';
vi.mocked(VMwareAPI.listConnections).mockImplementation(async () => [connection()]);
});
it('withdraws accepted inventory, draft secrets and confirmations when access is revoked', async () => {
const [canLoad, setAllowed] = createSignal(true);
const { result } = renderHook(() => useVMwareSettingsPanelState({ canLoad }));
await ready(result);
openDraft(result);
const old = result.connections()[0];
setAllowed(false);
await waitFor(() => expect(result.connections()).toEqual([]));
expect(result.form().password).toBe('');
expect(result.dialogOpen()).toBe(false);
expect(result.editingConnection()).toBeNull();
expect(result.pendingDeleteConnection()).toBeNull();
result.openEditDialog(old);
result.openDeleteDialog(old);
result.openCreateDialog();
result.updateForm({ password: 'must-not-stick' });
await result.testCurrentForm();
await result.testSavedConnection(old);
await result.previewCurrentForm();
await result.saveCurrentForm();
await result.deletePendingConnection();
expect(result.dialogOpen()).toBe(false);
expect(result.deleteDialogOpen()).toBe(false);
expect(result.form().password).toBe('');
for (const [method, mock] of Object.entries(VMwareAPI))
if (method !== 'listConnections') expect(mock).not.toHaveBeenCalled();
await result.loadConnections();
expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(1);
setAllowed(true);
await ready(result);
expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(2);
});
it('aborts a pending inventory read and rejects its late result after revocation', async () => {
const pending = deferred<VMwareConnection[]>();
vi.mocked(VMwareAPI.listConnections).mockReturnValueOnce(pending.promise);
const [canLoad, setAllowed] = createSignal(true);
const { result } = renderHook(() => useVMwareSettingsPanelState({ canLoad }));
const options = vi.mocked(VMwareAPI.listConnections).mock.calls[0][0]!;
expect(options).toMatchObject({ expectedOrgID: 'team-a', retry: false });
setAllowed(false);
expect(options.signal?.aborted).toBe(true);
pending.resolve([connection()]);
await pending.promise;
await Promise.resolve();
expect(result.connections()).toEqual([]);
expect(result.loading()).toBe(false);
expect(result.loadingError()).toBeNull();
});
it('preserves a same-reader draft across copied status and duplicate org events', async () => {
const [status, setStatus] = createSignal({ user: 'reader-a', allowed: true });
const { result } = renderHook(() =>
useVMwareSettingsPanelState({
canLoad: () => status().allowed,
currentUser: () => status().user,
}),
);
await ready(result);
openDraft(result);
setStatus({ user: 'reader-a', allowed: true });
eventBus.emit('org_switched', 'team-a');
expect(result.form().password).toBe('synthetic-draft');
expect(result.dialogOpen()).toBe(true);
expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(1);
});
it('does not accept an A-to-B-to-A read or let its finally clear a later loading state', async () => {
const a = deferred<VMwareConnection[]>(),
b = deferred<VMwareConnection[]>(),
next = deferred<VMwareConnection[]>();
vi.mocked(VMwareAPI.listConnections)
.mockReturnValueOnce(a.promise)
.mockReturnValueOnce(b.promise)
.mockReturnValueOnce(next.promise);
const [currentUser, setUser] = createSignal('a');
const { result } = renderHook(() => useVMwareSettingsPanelState({ currentUser }));
setUser('b');
setUser('a');
a.resolve([connection()]);
b.reject(new Error('obsolete-private-detail'));
await Promise.allSettled([a.promise, b.promise]);
await Promise.resolve();
expect(result.loading()).toBe(true);
expect(result.connections()).toEqual([]);
expect(result.loadingError()).toBeNull();
expect(logger.error).not.toHaveBeenCalled();
next.resolve([connection()]);
await ready(result);
expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(3);
});
const actions = [
'test',
'saved-test',
'preview',
'saved-preview',
'create',
'update',
'delete',
] as const;
for (const action of actions)
for (const outcome of ['success', 'error'] as const) {
it(`ignores ${action} ${outcome} after an org switch, including notifications and follow-up reads`, async () => {
const pending = deferred<never>();
const method = {
test: 'testConnection',
'saved-test': 'testSavedConnection',
preview: 'previewConnection',
'saved-preview': 'previewSavedConnection',
create: 'createConnection',
update: 'updateConnection',
delete: 'deleteConnection',
}[action] as Exclude<keyof typeof VMwareAPI, 'prototype' | 'listConnections'>;
vi.mocked(VMwareAPI[method]).mockReturnValueOnce(pending.promise);
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
const old = result.connections()[0];
if (['test', 'preview', 'create'].includes(action)) {
result.openCreateDialog();
result.updateForm({
host: 'vc.example.invalid',
username: 'monitor',
password: 'synthetic-draft',
});
} else if (action === 'delete') result.openDeleteDialog(old);
else if (action !== 'saved-test') openDraft(result);
const task =
action === 'test'
? result.testCurrentForm()
: action === 'saved-test'
? result.testSavedConnection(old)
: ['preview', 'saved-preview'].includes(action)
? result.previewCurrentForm()
: action === 'delete'
? result.deletePendingConnection()
: result.saveCurrentForm();
expect(VMwareAPI[method]).toHaveBeenCalledTimes(1);
const call = vi.mocked(VMwareAPI[method]).mock.calls[0];
const options = call[call.length - 1] as {
signal: AbortSignal;
expectedOrgID: string;
retry: boolean;
};
expect(options).toMatchObject({ expectedOrgID: 'team-a', retry: false });
scope.org = 'team-b';
eventBus.emit('org_switched', 'team-b');
await ready(result);
expect(options.signal.aborted).toBe(true);
expect(result.form().password).toBe('');
expect(result.dialogOpen()).toBe(false);
openDraft(result); // The late completion must not close/clear this new draft.
if (outcome === 'success') pending.resolve({ success: true } as never);
else pending.reject(new Error('obsolete-private-detail'));
await task;
expect(result.form().password).toBe('synthetic-draft');
expect(result.dialogOpen()).toBe(true);
expect(result.monitoredSystemPreview()).toBeNull();
expect(result.monitoredSystemPreviewError()).toBeNull();
expect(notificationStore.success).not.toHaveBeenCalled();
expect(notificationStore.error).not.toHaveBeenCalled();
expect(logger.error).not.toHaveBeenCalled();
expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(2);
expect(
result.saving() || result.testing() || result.previewing() || result.deleting(),
).toBe(false);
await result.testSavedConnection(old);
result.openDeleteDialog(old);
expect(result.deleteDialogOpen()).toBe(false); // Same ID is not the newly admitted object.
});
}
for (const outcome of ['success', 'error'] as const)
it(`aborts on disposal and ignores late ${outcome}`, async () => {
const pending = deferred<never>();
vi.mocked(VMwareAPI.testSavedConnection).mockReturnValueOnce(pending.promise);
const { result, cleanup } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
const task = result.testSavedConnection(result.connections()[0]);
const options = vi.mocked(VMwareAPI.testSavedConnection).mock.calls[0][2]!;
cleanup();
expect(options.signal?.aborted).toBe(true);
if (outcome === 'success') pending.resolve({ success: true } as never);
else pending.reject(new Error('late'));
await task;
eventBus.emit('org_switched', 'team-b');
expect(notificationStore.success).not.toHaveBeenCalled();
expect(notificationStore.error).not.toHaveBeenCalled();
expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(1);
});
it('withdraws before a stale action when org storage changed without an event', async () => {
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
openDraft(result);
scope.org = 'team-b';
await result.saveCurrentForm();
await ready(result);
expect(VMwareAPI.updateConnection).not.toHaveBeenCalled();
expect(result.form().password).toBe('');
expect(vi.mocked(VMwareAPI.listConnections).mock.calls[1][0]?.expectedOrgID).toBe('team-b');
});
it('ignores a preview and Test result for an edited draft, without leaving controls busy', async () => {
const preview = deferred<never>(),
test = deferred<never>();
vi.mocked(VMwareAPI.previewSavedConnection).mockReturnValueOnce(preview.promise);
vi.mocked(VMwareAPI.testSavedConnection).mockReturnValueOnce(test.promise);
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
openDraft(result);
const a = result.previewCurrentForm();
result.updateForm({ host: 'changed.example.invalid' });
preview.resolve({ additional_count: 5 } as never);
expect(await a).toBeNull();
expect(result.monitoredSystemPreview()).toBeNull();
expect(result.previewing()).toBe(false);
const b = result.testCurrentForm();
result.updateForm({ host: 'newer.example.invalid' });
test.resolve({ success: true } as never);
expect(await b).toBe(false);
expect(result.testing()).toBe(false);
expect(notificationStore.success).not.toHaveBeenCalled();
});
for (const action of ['Test', 'Preview'] as const)
for (const status of [401, 403])
for (const saved of [true, false])
it(`withdraws edited ${saved ? 'saved' : 'new'} draft on ${action} HTTP ${status}, then recovers only by fresh read`, async () => {
const method =
action === 'Test'
? saved
? 'testSavedConnection'
: 'testConnection'
: saved
? 'previewSavedConnection'
: 'previewConnection';
const pending = deferred<never>();
vi.mocked(VMwareAPI[method]).mockReturnValueOnce(pending.promise);
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
const old = result.connections()[0];
if (saved) openDraft(result);
else {
result.openCreateDialog();
result.updateForm({
host: 'vc.example.invalid',
username: 'monitor',
password: 'synthetic-draft',
});
}
const task = action === 'Test' ? result.testCurrentForm() : result.previewCurrentForm();
expect(VMwareAPI[method]).toHaveBeenCalledTimes(1);
result.updateForm({ name: 'Name edited while request is pending' });
expect(result.form().name).toBe('Name edited while request is pending');
pending.reject({ status, message: 'private-provider-detail' });
await task;
expect(result.connections()).toEqual([]);
expect(result.dialogOpen()).toBe(false);
expect(result.form().password).toBe('');
expect(result.form().username).toBe('');
expect(result.monitoredSystemPreview()).toBeNull();
expect(result.monitoredSystemPreviewError()).toBeNull();
expect(result.loadingError()).toContain('access could not be verified');
expect(result.testing() || result.previewing()).toBe(false);
expect(notificationStore.success).not.toHaveBeenCalled();
expect(notificationStore.error).toHaveBeenCalledWith(result.loadingError());
expect(notificationStore.error).not.toHaveBeenCalledWith('private-provider-detail');
expect(logger.error).not.toHaveBeenCalled();
result.openEditDialog(old);
result.openCreateDialog();
expect(result.dialogOpen()).toBe(false);
expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(1);
expect(VMwareAPI[method]).toHaveBeenCalledTimes(1); // No replay on denial.
await result.loadConnections();
await ready(result);
result.openEditDialog(result.connections()[0]);
expect(result.form().password).toBe('');
expect(result.loadingError()).toBeNull();
vi.mocked(VMwareAPI.testSavedConnection).mockResolvedValueOnce({
success: true,
} as never);
expect(await result.testCurrentForm()).toBe(true);
expect(notificationStore.success).toHaveBeenCalledWith('VMware connection successful');
});
for (const action of ['Test', 'Preview'] as const)
for (const status of [401, 403])
it(`ignores old-reader ${action} HTTP ${status} after an A-to-B-to-A replacement`, async () => {
const method = action === 'Test' ? 'testSavedConnection' : 'previewSavedConnection';
const pending = deferred<never>();
vi.mocked(VMwareAPI[method]).mockReturnValueOnce(pending.promise);
const [currentUser, setUser] = createSignal('a');
const { result } = renderHook(() => useVMwareSettingsPanelState({ currentUser }));
await ready(result);
openDraft(result);
const task = action === 'Test' ? result.testCurrentForm() : result.previewCurrentForm();
const options = vi.mocked(VMwareAPI[method]).mock.calls[0][2]!;
result.updateForm({ name: 'Obsolete edited draft' });
setUser('b');
setUser('a');
await ready(result);
openDraft(result);
pending.reject({ status, message: 'obsolete-private-detail' });
await task;
expect(options.signal?.aborted).toBe(true);
expect(result.connections()).toHaveLength(1);
expect(result.dialogOpen()).toBe(true);
expect(result.form().password).toBe('synthetic-draft');
expect(result.loadingError()).toBeNull();
expect(result.testing() || result.previewing()).toBe(false);
expect(notificationStore.error).not.toHaveBeenCalled();
expect(notificationStore.success).not.toHaveBeenCalled();
expect(logger.error).not.toHaveBeenCalled();
expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(3);
});
for (const action of ['Test', 'Preview'] as const)
it(`ignores a stale-draft ${action} ordinary error without withdrawing the current reader`, async () => {
const method = action === 'Test' ? 'testSavedConnection' : 'previewSavedConnection';
const pending = deferred<never>();
vi.mocked(VMwareAPI[method]).mockReturnValueOnce(pending.promise);
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
openDraft(result);
const task = action === 'Test' ? result.testCurrentForm() : result.previewCurrentForm();
result.updateForm({ name: 'Keep this current draft' });
pending.reject({ status: 500, message: 'obsolete-provider-detail' });
await task;
expect(result.connections()).toHaveLength(1);
expect(result.dialogOpen()).toBe(true);
expect(result.form().name).toBe('Keep this current draft');
expect(result.form().password).toBe('synthetic-draft');
expect(result.loadingError()).toBeNull();
expect(result.monitoredSystemPreviewError()).toBeNull();
expect(result.testing() || result.previewing()).toBe(false);
expect(notificationStore.error).not.toHaveBeenCalled();
expect(logger.error).not.toHaveBeenCalled();
});
it('starts a single mutation and does not retarget it while busy', async () => {
const pending = deferred<never>();
vi.mocked(VMwareAPI.updateConnection).mockReturnValueOnce(pending.promise);
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
openDraft(result);
const task = result.saveCurrentForm();
await result.saveCurrentForm();
await result.previewCurrentForm();
result.openCreateDialog();
result.openDeleteDialog(result.connections()[0]);
expect(result.dialogOpen()).toBe(true);
expect(result.deleteDialogOpen()).toBe(false);
expect(VMwareAPI.updateConnection).toHaveBeenCalledTimes(1);
expect(VMwareAPI.previewSavedConnection).not.toHaveBeenCalled();
pending.resolve(connection() as never);
await task;
expect(notificationStore.success).toHaveBeenCalledWith('VMware connection updated');
expect(VMwareAPI.listConnections).toHaveBeenCalledTimes(2);
});
for (const status of [401, 403])
it(`withdraws on HTTP ${status} and requires a fresh read, not a stale confirmation`, async () => {
vi.mocked(VMwareAPI.updateConnection).mockRejectedValueOnce({
status,
message: 'private-provider-detail',
});
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
openDraft(result);
const old = result.connections()[0];
await result.saveCurrentForm();
expect(result.connections()).toEqual([]);
expect(result.form().password).toBe('');
expect(result.loadingError()).toContain('access could not be verified');
expect(notificationStore.error).not.toHaveBeenCalledWith('private-provider-detail');
await result.testSavedConnection(old);
result.openCreateDialog();
expect(result.dialogOpen()).toBe(false);
expect(VMwareAPI.testSavedConnection).not.toHaveBeenCalled();
await result.loadConnections();
await ready(result);
result.openCreateDialog();
expect(result.dialogOpen()).toBe(true);
expect(result.loadingError()).toBeNull();
});
it.each([500, 404, 'empty'] as const)(
'withdraws a draft on an unread or removed saved source (%s) without writing settings',
async (outcome) => {
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
openDraft(result);
if (outcome === 'empty') vi.mocked(VMwareAPI.listConnections).mockResolvedValueOnce([]);
else
vi.mocked(VMwareAPI.listConnections).mockRejectedValueOnce({
status: outcome,
message: 'read failed',
});
await result.loadConnections();
expect(result.connections()).toEqual([]);
expect(result.dialogOpen()).toBe(false);
expect(result.form().password).toBe('');
expect(result.form().hasStoredPassword).toBe(false);
expect(result.featureDisabled()).toBe(outcome === 404);
expect(result.loadingError() !== null).toBe(outcome === 500);
expect(VMwareAPI.updateConnection).not.toHaveBeenCalled();
expect(VMwareAPI.deleteConnection).not.toHaveBeenCalled();
await result.loadConnections();
await ready(result);
result.openEditDialog(result.connections()[0]);
expect(result.form()).toMatchObject({
password: '',
hasStoredPassword: true,
insecureSkipVerify: false,
});
},
);
});

View File

@@ -33,6 +33,13 @@ vi.mock('@/utils/logger', () => ({
},
}));
const context = () =>
expect.objectContaining({
expectedOrgID: 'default',
signal: expect.any(AbortSignal),
retry: false,
});
const safeVMwarePreview = () => ({
current_count: 1,
projected_count: 1,
@@ -150,6 +157,7 @@ describe('useVMwareSettingsPanelState', () => {
username: 'administrator@vsphere.local',
password: '********',
}),
context(),
);
expect(VMwareAPI.updateConnection).toHaveBeenCalledWith(
'conn-1',
@@ -161,6 +169,7 @@ describe('useVMwareSettingsPanelState', () => {
insecureSkipVerify: false,
enabled: true,
}),
context(),
);
expect(result.dialogOpen()).toBe(false);
expect(notificationStore.success).toHaveBeenCalledWith('VMware connection updated');
@@ -202,7 +211,7 @@ describe('useVMwareSettingsPanelState', () => {
await result.testSavedConnection(result.connections()[0]);
expect(VMwareAPI.testSavedConnection).toHaveBeenCalledWith('conn-1');
expect(VMwareAPI.testSavedConnection).toHaveBeenCalledWith('conn-1', undefined, context());
expect(VMwareAPI.testConnection).not.toHaveBeenCalled();
expect(notificationStore.success).toHaveBeenCalledWith(
'VMware connection successful for lab-vcenter',
@@ -243,6 +252,7 @@ describe('useVMwareSettingsPanelState', () => {
password: '********',
insecureSkipVerify: true,
}),
context(),
);
expect(VMwareAPI.testConnection).not.toHaveBeenCalled();
expect(notificationStore.success).toHaveBeenCalledWith('VMware connection successful');
@@ -325,6 +335,7 @@ describe('useVMwareSettingsPanelState', () => {
username: 'administrator@vsphere.local',
password: 'secret',
}),
context(),
);
expect(notificationStore.success).toHaveBeenCalledWith('VMware connection added');
});
@@ -537,6 +548,7 @@ describe('useVMwareSettingsPanelState', () => {
username: 'administrator@vsphere.local',
password: 'secret',
}),
context(),
);
expect(preview?.additional_count).toBe(2);
expect(result.monitoredSystemPreview()?.projected_count).toBe(3);

View File

@@ -0,0 +1,254 @@
import { cleanup, renderHook, waitFor } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { eventBus } from '@/stores/events';
import { clearAuth, getOrgID, setApiToken, setOrgID } from '@/utils/apiClient';
import { useVMwareSettingsPanelState } from '../useVMwareSettingsPanelState';
// Keep the hook, VMware adapter, JSON/error body reader and API client real.
// Mocking VMwareAPI alone cannot detect lost signal/context/retry options.
vi.mock('@/stores/notifications', () => ({
notificationStore: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },
}));
vi.mock('@/utils/logger', () => ({ logger: { error: vi.fn(), warn: vi.fn(), debug: vi.fn() } }));
const fetchMock = vi.fn<typeof fetch>();
const pendingBodies = new Set<() => void>();
const connection = (name = 'Original private source') => ({
id: 'same-source-id',
name,
host: 'vc.example.invalid',
username: 'monitor',
password: '********',
insecureSkipVerify: false,
enabled: true,
monitorVms: true,
monitorHosts: true,
monitorDatastores: true,
});
const json = (value: unknown, status = 200, headers: Record<string, string> = {}) =>
new Response(JSON.stringify(value), {
status,
headers: { 'Content-Type': 'application/json', ...headers },
});
// A real Response whose headers arrive before its body. The fetch fixture
// deliberately ignores abort, so authority must still be checked at completion.
const delayedBody = (status = 200) => {
let controller!: ReadableStreamDefaultController<Uint8Array>;
const body = new ReadableStream<Uint8Array>({
start(stream) {
controller = stream;
},
});
const response = new Response(body, { status });
const release = (value: unknown) => {
if (!pendingBodies.delete(discard)) return;
controller.enqueue(new TextEncoder().encode(JSON.stringify(value)));
controller.close();
};
const discard = () => release([]);
pendingBodies.add(discard);
return { response, release };
};
const ready = async (state: ReturnType<typeof useVMwareSettingsPanelState>) => {
await waitFor(() => {
expect(state.loading()).toBe(false);
expect(state.connections()).toHaveLength(1);
});
};
describe('VMware settings through the real API transport', () => {
beforeEach(() => {
vi.clearAllMocks();
fetchMock.mockReset().mockImplementation(async () => json([connection('Replacement source')]));
fetchMock.mockResolvedValueOnce(json([connection()]));
vi.stubGlobal('fetch', fetchMock);
sessionStorage.clear();
localStorage.clear();
document.cookie = 'pulse_csrf=; Max-Age=0; Path=/';
clearAuth();
setOrgID('north');
setApiToken('synthetic-settings-token');
});
afterEach(() => {
cleanup();
for (const discard of pendingBodies) discard();
for (const [url, options] of fetchMock.mock.calls) {
expect(String(url)).toMatch(/^\/api\/vmware\/connections(?:\/|$)/);
expect(new Headers(options?.headers).get('X-Pulse-Org-ID')).toBeTruthy();
}
clearAuth();
setOrgID(null);
vi.unstubAllGlobals();
});
it.each(['organisation', 'user round trip', 'capability', 'disposal'] as const)(
'ignores a delayed JSON body after %s withdrawal and aborts the actual fetch signal',
async (change) => {
const [canLoad, setAllowed] = createSignal(true);
const [currentUser, setUser] = createSignal('reader-a');
const { result, cleanup: unmount } = renderHook(() =>
useVMwareSettingsPanelState({ canLoad, currentUser }),
);
await ready(result);
const oldConnection = result.connections()[0];
result.openEditDialog(oldConnection);
result.updateForm({ password: 'synthetic-unsaved-key' });
const old = delayedBody();
fetchMock.mockResolvedValueOnce(old.response);
const reading = result.loadConnections();
await waitFor(() => expect(old.response.body?.locked).toBe(true));
const options = fetchMock.mock.calls[1][1]!;
expect(options.signal).toBeDefined();
expect(options.signal?.aborted).toBe(false);
expect(options.credentials).toBe('include');
expect(new Headers(options.headers).get('X-Pulse-Org-ID')).toBe('north');
expect(options).not.toHaveProperty('expectedOrgID');
expect(options).not.toHaveProperty('retry');
if (change === 'organisation') {
setOrgID('south');
eventBus.emit('org_switched', 'south');
await ready(result);
expect(new Headers(fetchMock.mock.calls[2][1]?.headers).get('X-Pulse-Org-ID')).toBe(
'south',
);
} else if (change === 'user round trip') {
setUser('reader-b');
await ready(result);
setUser('reader-a');
await ready(result);
} else if (change === 'capability') {
setAllowed(false);
} else {
unmount();
}
expect(options.signal?.aborted).toBe(true);
expect(result.dialogOpen()).toBe(false);
expect(result.form().password).toBe('');
old.release([connection('Obsolete private source')]);
await reading;
expect(result.connections().map((item) => item.name)).toEqual(
change === 'organisation' || change === 'user round trip' ? ['Replacement source'] : [],
);
expect(result.loadingError()).toBeNull();
// A same-ID connection from the previous reader is still not actionable.
const requests = fetchMock.mock.calls.length;
result.openEditDialog(oldConnection);
await result.testSavedConnection(oldConnection);
expect(result.dialogOpen()).toBe(false);
expect(fetchMock).toHaveBeenCalledTimes(requests);
},
);
it.each([
[400, { error: 'invalid_org' }, {}],
[403, { error: 'private-denial-detail' }, { 'X-CSRF-Token': 'synthetic-replacement' }],
[429, { error: 'rate_limited' }, { 'Retry-After': '1' }],
] as const)(
'does not replay a settings read or drop its organisation after HTTP %i',
async (status, body, headers) => {
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
fetchMock.mockResolvedValueOnce(json(body, status, headers));
await result.loadConnections();
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(getOrgID()).toBe('north');
expect(result.connections()).toEqual([]);
expect(result.loadingError()).toBeTruthy();
if (status === 403) {
expect(result.loadingError()).toContain('access could not be verified');
expect(result.loadingError()).not.toContain('private-denial-detail');
}
},
);
it('does not apply an old delayed denial to a new same-user reader', async () => {
const [currentUser, setUser] = createSignal('reader-a');
const { result } = renderHook(() => useVMwareSettingsPanelState({ currentUser }));
await ready(result);
const old = delayedBody(403);
fetchMock.mockResolvedValueOnce(old.response);
const reading = result.loadConnections();
await waitFor(() => expect(old.response.body?.locked).toBe(true));
setUser('reader-b');
await ready(result);
setUser('reader-a');
await ready(result);
result.openEditDialog(result.connections()[0]);
result.updateForm({ password: 'synthetic-new-reader-draft' });
old.release({ error: 'obsolete-private-denial' });
await reading;
expect(result.connections()[0].name).toBe('Replacement source');
expect(result.dialogOpen()).toBe(true);
expect(result.form().password).toBe('synthetic-new-reader-draft');
expect(result.loadingError()).toBeNull();
expect(fetchMock).toHaveBeenCalledTimes(4);
});
it.each([
'create',
'update',
'delete',
'test',
'saved-test',
'preview',
'saved-preview',
] as const)(
'binds the actual %s request, never replays a denial and requires a fresh read',
async (action) => {
const { result } = renderHook(() => useVMwareSettingsPanelState());
await ready(result);
const saved = result.connections()[0];
if (action === 'delete') result.openDeleteDialog(saved);
else if (action !== 'saved-test') {
if (['create', 'test', 'preview'].includes(action)) result.openCreateDialog();
else result.openEditDialog(saved);
result.updateForm({ host: saved.host, username: 'monitor', password: 'synthetic-draft' });
}
fetchMock.mockResolvedValueOnce(
json({ error: 'private-denial-detail' }, 403, { 'X-CSRF-Token': 'synthetic-replacement' }),
);
if (action === 'delete') await result.deletePendingConnection();
else if (action === 'saved-test') await result.testSavedConnection(saved);
else if (['test', 'saved-test'].includes(action)) await result.testCurrentForm();
else if (['preview', 'saved-preview'].includes(action)) await result.previewCurrentForm();
else await result.saveCurrentForm();
expect(fetchMock).toHaveBeenCalledTimes(2);
const [url, options] = fetchMock.mock.calls[1];
const suffix = {
create: '',
update: '/same-source-id',
delete: '/same-source-id',
test: '/test',
'saved-test': '/same-source-id/test',
preview: '/preview',
'saved-preview': '/same-source-id/preview',
}[action];
expect(url).toBe(`/api/vmware/connections${suffix}`);
expect(options?.method).toBe(
action === 'update' ? 'PUT' : action === 'delete' ? 'DELETE' : 'POST',
);
expect(new Headers(options?.headers).get('X-Pulse-Org-ID')).toBe('north');
expect(options?.signal?.aborted).toBe(true);
expect(result.connections()).toEqual([]);
expect(result.form().password).toBe('');
expect(result.dialogOpen() || result.deleteDialogOpen()).toBe(false);
expect(result.loadingError()).toContain('access could not be verified');
await result.testSavedConnection(saved);
await result.saveCurrentForm();
expect(fetchMock).toHaveBeenCalledTimes(2);
await result.loadConnections();
await ready(result);
result.openEditDialog(result.connections()[0]);
expect(result.dialogOpen()).toBe(true);
expect(result.form().hasStoredPassword).toBe(true);
},
);
});

View File

@@ -81,7 +81,10 @@ export function useInfrastructureSettingsState({
canLoad: canReadInfrastructure,
currentUser,
});
const vmwareSettings = useVMwareSettingsPanelState({ canLoad: canReadInfrastructure });
const vmwareSettings = useVMwareSettingsPanelState({
canLoad: canReadInfrastructure,
currentUser,
});
const discoveryRuntime = useInfrastructureDiscoveryRuntimeState({
eventBus,

View File

@@ -1,4 +1,7 @@
import { createEffect, createMemo, createSignal } from 'solid-js';
import { batch, createEffect, createMemo, createSignal, on, onCleanup } from 'solid-js';
import { unwrap } from 'solid-js/store';
import { getOrgID } from '@/utils/apiClient';
import { eventBus } from '@/stores/events';
import type { MonitoredSystemLedgerPreviewResponse } from '@/api/monitoredSystemLedger';
import {
VMwareAPI,
@@ -146,10 +149,15 @@ const buildConnectionInput = (form: VMwareConnectionFormState): VMwareConnection
};
};
// See useTrueNASSettingsPanelState: /api/vmware/connections is RequireAdmin and
// this hook is constructed for every settings tab, so the mount fetch has to be
// gated on the session's infrastructure capability.
export function useVMwareSettingsPanelState({ canLoad }: { canLoad?: () => boolean } = {}) {
// Settings constructs this hook for every tab. Keep both inventory and actions
// with the org/user/capability reader that admitted them, not just its first load.
export function useVMwareSettingsPanelState({
canLoad,
currentUser,
}: {
canLoad?: () => boolean;
currentUser?: () => string | undefined;
} = {}) {
const [connections, setConnections] = createSignal<VMwareConnection[]>([]);
const [loading, setLoading] = createSignal(true);
const [loadingError, setLoadingError] = createSignal<string | null>(null);
@@ -186,124 +194,238 @@ export function useVMwareSettingsPanelState({ canLoad }: { canLoad?: () => boole
() => connections().find((connection) => connection.id === editingConnectionId()) ?? null,
);
const loadConnections = async () => {
setLoading(true);
setLoadingError(null);
try {
const nextConnections = await VMwareAPI.listConnections();
setConnections(nextConnections);
setFeatureDisabled(false);
setFeatureDisabledMessage('');
} catch (error) {
if (apiErrorStatus(error) === 404) {
setFeatureDisabled(true);
setFeatureDisabledMessage(
getErrorMessage(error, 'VMware integration has been explicitly disabled'),
);
setConnections([]);
return;
}
const message = getErrorMessage(error, 'Failed to load VMware connections');
setLoadingError(message);
logger.error('[VMware Settings] Failed to load connections', error);
} finally {
setLoading(false);
}
};
// See useTrueNASSettingsPanelState: wait for the capability to resolve rather
// than sampling it once at mount.
let connectionsRequested = false;
createEffect(() => {
if (connectionsRequested) return;
if (canLoad && !canLoad()) {
setLoading(false);
return;
}
connectionsRequested = true;
void loadConnections();
const accessAllowed = () => canLoad?.() ?? true;
const currentOrg = () => getOrgID() || 'default';
const snapshot = () => ({
org: currentOrg(),
user: currentUser?.(),
allowed: accessAllowed(),
controller: new AbortController(),
});
const openCreateDialog = () => {
setEditingConnectionId(null);
setForm(createEmptyFormState());
setConnectionFailure(null);
setConnectionTestWarning(null);
const [reader, setReader] = createSignal(snapshot());
const [accessRejected, setAccessRejected] = createSignal(false);
let disposed = false;
let readController: AbortController | undefined;
let dialogVersion = 0;
const isCurrentReader = (accepted = reader()) =>
!disposed &&
accepted === reader() &&
!accepted.controller.signal.aborted &&
accepted.org === currentOrg() &&
accepted.user === currentUser?.() &&
accepted.allowed === accessAllowed();
const requestOptions = (accepted = reader(), signal = accepted.controller.signal) => ({
expectedOrgID: accepted.org,
signal,
retry: false,
});
const busy = () => saving() || testing() || deleting() || previewing();
const isCurrentConnection = (connection: VMwareConnection) =>
connections().some((current) => unwrap(current) === unwrap(connection));
const clearPreview = () => {
setMonitoredSystemPreview(null);
setMonitoredSystemPreviewUnavailableState(null);
setMonitoredSystemPreviewGenericError(null);
setDialogOpen(true);
};
const openEditDialog = (connection: VMwareConnection) => {
setEditingConnectionId(connection.id);
setForm(buildFormStateFromConnection(connection));
setConnectionFailure(null);
setConnectionTestWarning(null);
setMonitoredSystemPreview(null);
setMonitoredSystemPreviewUnavailableState(null);
setMonitoredSystemPreviewGenericError(null);
setDialogOpen(true);
};
const resetDialogState = () => {
dialogVersion += 1;
setDialogOpen(false);
setEditingConnectionId(null);
setForm(createEmptyFormState());
setConnectionFailure(null);
setConnectionTestWarning(null);
setMonitoredSystemPreview(null);
setMonitoredSystemPreviewUnavailableState(null);
setMonitoredSystemPreviewGenericError(null);
clearPreview();
};
const closeDialog = () => {
if (saving() || testing()) return;
resetDialogState();
};
const openDeleteDialog = (connection: VMwareConnection) => {
setPendingDeleteConnection(connection);
setDeleteDialogOpen(true);
};
const resetDeleteDialogState = () => {
setDeleteDialogOpen(false);
setPendingDeleteConnection(null);
};
const closeDeleteDialog = () => {
if (deleting()) return;
resetDeleteDialogState();
const resetReader = (reload = true) => {
reader().controller.abort();
readController?.abort();
readController = undefined;
batch(() => {
// A returned user/org name does not revive an earlier reader's promises.
setReader(snapshot());
resetDialogState();
resetDeleteDialogState();
setConnections([]);
setLoadingError(null);
setFeatureDisabled(false);
setFeatureDisabledMessage('');
setAccessRejected(false);
setSaving(false);
setTesting(false);
setDeleting(false);
setPreviewing(false);
setLoading(false);
});
if (!disposed && reload) void loadConnections();
};
const ensureReader = () => {
if (isCurrentReader()) return true;
if (!disposed) resetReader();
return false;
};
const canAct = () =>
ensureReader() && accessAllowed() && !accessRejected() && !featureDisabled() && !busy();
const withdrawOnDenial = (error: unknown) => {
if (![401, 403].includes(apiErrorStatus(error) ?? 0)) return false;
resetReader(false);
setAccessRejected(true);
setLoadingError('VMware settings access could not be verified. Reload before making changes.');
return true;
};
const loadConnections = async () => {
if (!ensureReader() || !accessAllowed() || readController || busy()) return;
const accepted = reader();
const controller = new AbortController();
readController = controller;
const isCurrent = () => isCurrentReader(accepted) && readController === controller;
batch(() => {
setLoading(true);
setLoadingError(null);
});
try {
const nextConnections = await VMwareAPI.listConnections(
requestOptions(accepted, controller.signal),
);
if (!isCurrent()) return;
batch(() => {
setConnections(nextConnections);
if (
editingConnectionId() &&
!nextConnections.some((connection) => connection.id === editingConnectionId())
)
resetDialogState();
if (
pendingDeleteConnection() &&
!nextConnections.some((connection) => connection.id === pendingDeleteConnection()?.id)
)
resetDeleteDialogState();
setAccessRejected(false);
setFeatureDisabled(false);
setFeatureDisabledMessage('');
});
} catch (error) {
if (!isCurrent()) return;
if (withdrawOnDenial(error)) return;
batch(() => {
setConnections([]);
resetDialogState();
resetDeleteDialogState();
});
if (apiErrorStatus(error) === 404) {
setFeatureDisabled(true);
setFeatureDisabledMessage(
getErrorMessage(error, 'VMware integration has been explicitly disabled'),
);
return;
}
setLoadingError(getErrorMessage(error, 'Failed to load VMware connections'));
logger.error('[VMware Settings] Failed to load connections', error);
} finally {
if (isCurrent()) {
readController = undefined;
setLoading(false);
}
}
};
createEffect(
on([accessAllowed, () => currentUser?.()], (current, previous) => {
if (!previous || current.some((value, index) => value !== previous[index])) resetReader();
}),
);
const unsubscribeOrg = eventBus.on('org_switched', () => {
if (!isCurrentReader()) resetReader();
});
onCleanup(() => {
disposed = true;
unsubscribeOrg();
resetReader(false);
});
const openCreateDialog = () => {
if (!canAct()) return;
batch(() => {
resetDialogState();
resetDeleteDialogState();
setDialogOpen(true);
});
};
const openEditDialog = (connection: VMwareConnection) => {
if (!canAct() || !isCurrentConnection(connection)) return;
batch(() => {
resetDialogState();
resetDeleteDialogState();
setEditingConnectionId(connection.id);
setForm(buildFormStateFromConnection(connection));
setDialogOpen(true);
});
};
const closeDialog = () => {
if (saving() || testing()) return;
batch(resetDialogState);
};
const openDeleteDialog = (connection: VMwareConnection) => {
if (!canAct() || !isCurrentConnection(connection)) return;
batch(() => {
resetDialogState();
setPendingDeleteConnection(connection);
setDeleteDialogOpen(true);
});
};
const closeDeleteDialog = () => {
if (!deleting()) resetDeleteDialogState();
};
const updateForm = (patch: Partial<VMwareConnectionFormState>) => {
setConnectionFailure(null);
setConnectionTestWarning(null);
setMonitoredSystemPreview(null);
setMonitoredSystemPreviewUnavailableState(null);
setMonitoredSystemPreviewGenericError(null);
setForm((current) => ({ ...current, ...patch }));
if (!ensureReader() || !accessAllowed() || accessRejected() || !dialogOpen() || saving())
return;
dialogVersion += 1;
batch(() => {
setConnectionFailure(null);
setConnectionTestWarning(null);
clearPreview();
setForm((current) => ({ ...current, ...patch }));
});
};
const notifyDenial = (error: unknown) => {
if (!withdrawOnDenial(error)) return false;
notificationStore.error(loadingError()!);
return true;
};
const testCurrentForm = async () => {
setTesting(true);
setConnectionFailure(null);
setConnectionTestWarning(null);
if (!canAct() || !dialogOpen()) return false;
const accepted = reader();
const version = dialogVersion;
const isCurrent = () => isCurrentReader(accepted) && version === dialogVersion;
batch(() => {
setTesting(true);
setConnectionFailure(null);
setConnectionTestWarning(null);
});
try {
const payload = buildConnectionInput(form());
const result = editingConnectionId()
? await VMwareAPI.testSavedConnection(editingConnectionId()!, payload)
: await VMwareAPI.testConnection(payload);
? await VMwareAPI.testSavedConnection(
editingConnectionId()!,
payload,
requestOptions(accepted),
)
: await VMwareAPI.testConnection(payload, requestOptions(accepted));
if (!isCurrent()) return false;
const warning = buildConnectionTestWarning(result);
setConnectionTestWarning(warning);
if (warning) {
notificationStore.warning(warning.message);
} else {
notificationStore.success('VMware connection successful');
}
if (warning) notificationStore.warning(warning.message);
else notificationStore.success('VMware connection successful');
return true;
} catch (error) {
if (!isCurrentReader(accepted)) return false;
// A changed draft obsoletes its test result, but not this reader's denial.
if (notifyDenial(error) || !isCurrent()) return false;
const failure = buildVMwareConnectionFailurePresentation({
code: apiErrorCode(error),
category: apiErrorDetailField(error, 'category'),
@@ -315,14 +437,21 @@ export function useVMwareSettingsPanelState({ canLoad }: { canLoad?: () => boole
logger.error('[VMware Settings] Connection test failed', error);
return false;
} finally {
setTesting(false);
if (isCurrentReader(accepted)) setTesting(false);
}
};
const testSavedConnection = async (connection: VMwareConnection) => {
if (!canAct() || !isCurrentConnection(connection)) return;
const accepted = reader();
setTesting(true);
try {
const result = await VMwareAPI.testSavedConnection(connection.id);
const result = await VMwareAPI.testSavedConnection(
connection.id,
undefined,
requestOptions(accepted),
);
if (!isCurrentReader(accepted)) return;
const warning = buildConnectionTestWarning(result);
if (warning) {
notificationStore.warning(
@@ -334,6 +463,7 @@ export function useVMwareSettingsPanelState({ canLoad }: { canLoad?: () => boole
);
}
} catch (error) {
if (!isCurrentReader(accepted) || notifyDenial(error)) return;
const failure = buildVMwareConnectionFailurePresentation({
code: apiErrorCode(error),
category: apiErrorDetailField(error, 'category'),
@@ -346,31 +476,41 @@ export function useVMwareSettingsPanelState({ canLoad }: { canLoad?: () => boole
notificationStore.error(failure.message);
logger.error('[VMware Settings] Saved connection test failed', error);
} finally {
setTesting(false);
await loadConnections();
if (isCurrentReader(accepted)) {
setTesting(false);
await loadConnections();
}
}
};
const previewCurrentForm = async () => {
setPreviewing(true);
setConnectionFailure(null);
setMonitoredSystemPreviewUnavailableState(null);
setMonitoredSystemPreviewGenericError(null);
if (!canAct() || !dialogOpen()) return null;
const accepted = reader();
const version = dialogVersion;
const isCurrent = () => isCurrentReader(accepted) && version === dialogVersion;
batch(() => {
setPreviewing(true);
setConnectionFailure(null);
clearPreview();
});
try {
const payload = buildConnectionInput(form());
const preview = editingConnectionId()
? await VMwareAPI.previewSavedConnection(editingConnectionId()!, payload)
: await VMwareAPI.previewConnection(payload);
? await VMwareAPI.previewSavedConnection(
editingConnectionId()!,
payload,
requestOptions(accepted),
)
: await VMwareAPI.previewConnection(payload, requestOptions(accepted));
if (!isCurrent()) return null;
setMonitoredSystemPreview(preview);
setMonitoredSystemPreviewUnavailableState(null);
setMonitoredSystemPreviewGenericError(null);
return preview;
} catch (error) {
if (!isCurrentReader(accepted)) return null;
if (notifyDenial(error) || !isCurrent()) return null;
const unavailableState = monitoredSystemImpactPreviewUnavailableStateFromError(error);
if (unavailableState) {
setMonitoredSystemPreview(null);
setMonitoredSystemPreviewUnavailableState(unavailableState);
setMonitoredSystemPreviewGenericError(null);
logger.error('[VMware Settings] Preview failed', error);
return null;
}
@@ -380,60 +520,64 @@ export function useVMwareSettingsPanelState({ canLoad }: { canLoad?: () => boole
message: getVMwareErrorMessage(error, 'Could not preview monitored-system impact'),
fallback: 'Could not preview monitored-system impact',
});
setMonitoredSystemPreview(null);
setMonitoredSystemPreviewUnavailableState(null);
setMonitoredSystemPreviewGenericError(failure.message);
if (
apiErrorCode(error) === 'vmware_connection_failed' ||
apiErrorCode(error) === 'vmware_invalid_config'
) {
)
setConnectionFailure(failure);
}
logger.error('[VMware Settings] Preview failed', error);
return null;
} finally {
setPreviewing(false);
if (isCurrentReader(accepted)) setPreviewing(false);
}
};
const saveCurrentForm = async () => {
if (!canAct() || !dialogOpen()) return;
const accepted = reader();
setSaving(true);
try {
const payload = buildConnectionInput(form());
if (editingConnectionId()) {
await VMwareAPI.updateConnection(editingConnectionId()!, payload);
notificationStore.success('VMware connection updated');
} else {
await VMwareAPI.createConnection(payload);
notificationStore.success('VMware connection added');
}
resetDialogState();
const editingID = editingConnectionId();
if (editingID) await VMwareAPI.updateConnection(editingID, payload, requestOptions(accepted));
else await VMwareAPI.createConnection(payload, requestOptions(accepted));
if (!isCurrentReader(accepted)) return;
notificationStore.success(
editingID ? 'VMware connection updated' : 'VMware connection added',
);
batch(resetDialogState);
setSaving(false);
await loadConnections();
} catch (error) {
if (!isCurrentReader(accepted) || notifyDenial(error)) return;
setMonitoredSystemPreviewUnavailableState(null);
const message = getErrorMessage(error, 'Failed to save VMware connection');
notificationStore.error(message);
notificationStore.error(getErrorMessage(error, 'Failed to save VMware connection'));
logger.error('[VMware Settings] Save failed', error);
} finally {
setSaving(false);
if (isCurrentReader(accepted)) setSaving(false);
}
};
const deletePendingConnection = async () => {
if (!canAct()) return;
const connection = pendingDeleteConnection();
if (!connection) return;
if (!connection || !isCurrentConnection(connection)) return;
const accepted = reader();
setDeleting(true);
try {
await VMwareAPI.deleteConnection(connection.id);
await VMwareAPI.deleteConnection(connection.id, requestOptions(accepted));
if (!isCurrentReader(accepted)) return;
notificationStore.success(`Removed ${connection.name || connection.host}`);
resetDeleteDialogState();
setDeleting(false);
await loadConnections();
} catch (error) {
const message = getErrorMessage(error, 'Failed to remove VMware connection');
notificationStore.error(message);
if (!isCurrentReader(accepted) || notifyDenial(error)) return;
notificationStore.error(getErrorMessage(error, 'Failed to remove VMware connection'));
logger.error('[VMware Settings] Delete failed', error);
} finally {
setDeleting(false);
if (isCurrentReader(accepted)) setDeleting(false);
}
};