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.

9.6 KB
Raw Blame
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { apiFetchJSON } from '@/utils/apiClient';
import { TrueNASAPI, isRedactedTrueNASSecret } from '@/api/truenas';

vi.mock('@/utils/apiClient', () => ({
  apiFetchJSON: vi.fn(),
}));

describe('TrueNASAPI', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('normalizes listed connections from the API contract', async () => {
    vi.mocked(apiFetchJSON).mockResolvedValueOnce([
      {
        id: ' conn-1 ',
        name: ' tower ',
        host: ' truenas.local ',
        port: 443,
        apiKey: ' ******** ',
        username: ' pulse-readonly ',
        useHttps: true,
        insecureSkipVerify: false,
        enabled: true,
        pollIntervalSeconds: 120,
        poll: {
          intervalSeconds: 120,
          lastSuccessAt: ' 2026-03-30T12:00:00Z ',
          consecutiveFailures: 0,
        },
        observed: {
          host: ' tower ',
          resourceId: ' tower ',
          systems: 1,
          storagePools: 2,
          datasets: 12,
          apps: 4,
          vms: 2,
          shares: 3,
          disks: 8,
          recoveryArtifacts: 18,
        },
        transport: {
          mode: 'jsonrpc-websocket',
          endpoint: ' wss://truenas.local/api/current ',
          tls: true,
          connected: true,
          authMechanism: ' api-key-plain ',
          applianceVersion: ' TrueNAS-SCALE-25.10.4 ',
          reconnects: 1,
        },
      },
    ]);

    await expect(TrueNASAPI.listConnections()).resolves.toEqual([
      {
        id: 'conn-1',
        name: 'tower',
        host: 'truenas.local',
        port: 443,
        apiKey: '********',
        username: 'pulse-readonly',
        password: undefined,
        useHttps: true,
        insecureSkipVerify: false,
        fingerprint: undefined,
        enabled: true,
        pollIntervalSeconds: 120,
        poll: {
          intervalSeconds: 120,
          lastAttemptAt: undefined,
          lastSuccessAt: '2026-03-30T12:00:00Z',
          consecutiveFailures: 0,
          lastError: undefined,
        },
        observed: {
          host: 'tower',
          resourceId: 'tower',
          collectedAt: undefined,
          systems: 1,
          storagePools: 2,
          datasets: 12,
          apps: 4,
          vms: 2,
          shares: 3,
          disks: 8,
          recoveryArtifacts: 18,
        },
        transport: {
          mode: 'jsonrpc-websocket',
          endpoint: 'wss://truenas.local/api/current',
          tls: true,
          connected: true,
          authMechanism: 'api-key-plain',
          applianceVersion: 'TrueNAS-SCALE-25.10.4',
          legacyReason: undefined,
          reconnects: 1,
          lastError: undefined,
          lastConnectedAt: undefined,
        },
        monitorDatasets: false,
        monitorPools: false,
        monitorReplication: false,
      },
    ]);
  });

  it('round-trips per-surface monitor* flags through list and update payloads', async () => {
    vi.mocked(apiFetchJSON)
      .mockResolvedValueOnce([
        {
          id: 'conn-1',
          name: 'tower',
          host: 'truenas.local',
          useHttps: true,
          insecureSkipVerify: false,
          enabled: true,
          pollIntervalSeconds: 60,
          monitorDatasets: true,
          monitorPools: false,
          monitorReplication: true,
        },
      ])
      .mockResolvedValueOnce({
        id: 'conn-1',
        name: 'tower',
        host: 'truenas.local',
        useHttps: true,
        insecureSkipVerify: false,
        enabled: true,
        pollIntervalSeconds: 60,
        monitorDatasets: false,
        monitorPools: true,
        monitorReplication: false,
      });

    const connections = await TrueNASAPI.listConnections();
    expect(connections[0]).toMatchObject({
      monitorDatasets: true,
      monitorPools: false,
      monitorReplication: true,
    });

    await TrueNASAPI.updateConnection('conn-1', {
      host: 'truenas.local',
      useHttps: true,
      enabled: true,
      monitorDatasets: false,
      monitorPools: true,
      monitorReplication: false,
    });
    expect(apiFetchJSON).toHaveBeenLastCalledWith(
      '/api/truenas/connections/conn-1',
      expect.objectContaining({
        method: 'PUT',
        body: JSON.stringify({
          host: 'truenas.local',
          useHttps: true,
          enabled: true,
          monitorDatasets: false,
          monitorPools: true,
          monitorReplication: false,
        }),
      }),
    );
  });

  it('creates, updates, deletes, and tests connections through canonical routes', async () => {
    vi.mocked(apiFetchJSON)
      .mockResolvedValueOnce({
        id: 'conn-1',
        name: 'tower',
        host: 'truenas.local',
        useHttps: true,
        insecureSkipVerify: false,
        enabled: true,
      })
      .mockResolvedValueOnce({
        id: 'conn-1',
        name: 'tower',
        host: 'truenas.local',
        useHttps: false,
        insecureSkipVerify: true,
        enabled: false,
      })
      .mockResolvedValueOnce({ success: true, id: 'conn-1' })
      .mockResolvedValueOnce({ success: true })
      .mockResolvedValueOnce({ success: true });

    await TrueNASAPI.createConnection({
      name: 'tower',
      host: 'truenas.local',
      apiKey: 'secret',
      useHttps: true,
      enabled: true,
    });
    await TrueNASAPI.updateConnection('conn/1', {
      host: 'truenas.local',
      username: 'admin',
      password: '********',
      useHttps: false,
      insecureSkipVerify: true,
      enabled: false,
    });
    await TrueNASAPI.deleteConnection('conn/1');
    await expect(
      TrueNASAPI.testConnection({
        host: 'truenas.local',
        apiKey: 'secret',
      }),
    ).resolves.toEqual({ success: true });
    await expect(
      TrueNASAPI.testSavedConnection('conn/1', {
        host: 'truenas.local',
        apiKey: '********',
        useHttps: true,
      }),
    ).resolves.toEqual({ success: true });

    expect(apiFetchJSON).toHaveBeenNthCalledWith(
      1,
      '/api/truenas/connections',
      expect.objectContaining({
        method: 'POST',
        body: JSON.stringify({
          name: 'tower',
          host: 'truenas.local',
          apiKey: 'secret',
          useHttps: true,
          enabled: true,
        }),
      }),
    );
    expect(apiFetchJSON).toHaveBeenNthCalledWith(
      2,
      '/api/truenas/connections/conn%2F1',
      expect.objectContaining({
        method: 'PUT',
        body: JSON.stringify({
          host: 'truenas.local',
          username: 'admin',
          password: '********',
          useHttps: false,
          insecureSkipVerify: true,
          enabled: false,
        }),
      }),
    );
    expect(apiFetchJSON).toHaveBeenNthCalledWith(
      3,
      '/api/truenas/connections/conn%2F1',
      expect.objectContaining({ method: 'DELETE' }),
    );
    expect(apiFetchJSON).toHaveBeenNthCalledWith(
      4,
      '/api/truenas/connections/test',
      expect.objectContaining({
        method: 'POST',
        body: JSON.stringify({ host: 'truenas.local', apiKey: 'secret' }),
      }),
    );
    expect(apiFetchJSON).toHaveBeenNthCalledWith(
      5,
      '/api/truenas/connections/conn%2F1/test',
      expect.objectContaining({
        method: 'POST',
        body: JSON.stringify({
          host: 'truenas.local',
          apiKey: '********',
          useHttps: true,
        }),
      }),
    );
  });

  it('recognizes the masked-secret placeholder used for update preservation', () => {
    expect(isRedactedTrueNASSecret('********')).toBe(true);
    expect(isRedactedTrueNASSecret(' ******** ')).toBe(true);
    expect(isRedactedTrueNASSecret('secret')).toBe(false);
    expect(isRedactedTrueNASSecret(undefined)).toBe(false);
  });
});

describe('TrueNAS request context', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });
  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: 'nas.example.invalid',
      username: 'monitor',
      useHttps: true,
      insecureSkipVerify: false,
      fingerprint: 'SHA256:synthetic',
    };
    await TrueNASAPI.listConnections(options);
    await TrueNASAPI.createConnection(input, options);
    await TrueNASAPI.updateConnection('id/with slash', input, options);
    await TrueNASAPI.deleteConnection('id/with slash', options);
    await TrueNASAPI.testConnection(input, options);
    await TrueNASAPI.testSavedConnection('id/with slash', input, options);
    await TrueNASAPI.previewConnection(input, options);
    await TrueNASAPI.previewSavedConnection('id/with slash', input, options);
    const calls = vi.mocked(apiFetchJSON).mock.calls;
    expect(calls).toHaveLength(8);
    expect(calls.map(([url]) => url)).toEqual([
      '/api/truenas/connections',
      '/api/truenas/connections',
      '/api/truenas/connections/id%2Fwith%20slash',
      '/api/truenas/connections/id%2Fwith%20slash',
      '/api/truenas/connections/test',
      '/api/truenas/connections/id%2Fwith%20slash/test',
      '/api/truenas/connections/preview',
      '/api/truenas/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);
  });
});