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.

18.8 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
  apiFetch,
  apiClient,
  apiFetchJSON,
  clearApiToken,
  getApiToken,
  getOrgID,
  setApiToken,
  setOrgID,
} from '@/utils/apiClient';
import { ResourceActionsAPI } from '@/api/resourceActions';

const mockFetch = vi.fn();

describe('apiClient org context', () => {
  beforeEach(() => {
    vi.useRealTimers();
    mockFetch.mockReset();
    global.fetch = mockFetch as unknown as typeof fetch;
    window.sessionStorage.clear();
    window.localStorage.clear();
    document.cookie = 'pulse_csrf=; Path=/; Max-Age=0';
    clearApiToken();
    setOrgID(null);
  });

  afterEach(() => {
    clearApiToken();
    setOrgID(null);
  });

  it('propagates selected org via X-Pulse-Org-ID header', async () => {
    mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));

    setOrgID('acme');
    await apiFetch('/api/state');

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-Pulse-Org-ID']).toBe('acme');
    expect(getOrgID()).toBe('acme');
    expect(window.sessionStorage.getItem('pulse_org_id')).toBe('acme');
  });

  it.each([400, 403, 429])('does not replay a confirmed mutation after HTTP %i', async (status) => {
    setOrgID('tenant-a');
    document.cookie = 'pulse_csrf=synthetic-csrf; Path=/';
    mockFetch.mockResolvedValue(
      new Response(JSON.stringify({ error: 'invalid_org' }), {
        status,
        headers: { 'X-CSRF-Token': 'replacement-csrf', 'Retry-After': '1' },
      }),
    );
    const response = await apiFetch('/api/ai/patrol/suppressions/rule_one', {
      method: 'DELETE',
      retry: false,
      expectedOrgID: 'tenant-a',
    });
    expect(response.status).toBe(status);
    expect(mockFetch).toHaveBeenCalledTimes(1);
    expect(mockFetch.mock.calls[0][1].headers['X-Pulse-Org-ID']).toBe('tenant-a');
    expect(mockFetch.mock.calls[0][1].headers['X-CSRF-Token']).toBeTruthy();
    expect(mockFetch.mock.calls[0][1].credentials).toBe('include');
    expect(getOrgID()).toBe('tenant-a');
    expect(mockFetch.mock.calls[0][1]).not.toHaveProperty('retry');
    expect(mockFetch.mock.calls[0][1]).not.toHaveProperty('expectedOrgID');
  });

  it('binds default explicitly and stops stale confirmations or aborted dispatch', async () => {
    setOrgID('default');
    mockFetch.mockResolvedValue(new Response('[]'));
    await apiFetch('/api/ai/patrol/suppressions', { retry: false, expectedOrgID: 'default' });
    expect(mockFetch.mock.calls[0][1].headers['X-Pulse-Org-ID']).toBe('default');
    setOrgID('tenant-b');
    await expect(
      apiFetch('/api/ai/patrol/suppressions/rule_one', {
        method: 'DELETE',
        expectedOrgID: 'default',
        retry: false,
      }),
    ).rejects.toThrow('Organisation changed');
    const controller = new AbortController();
    controller.abort();
    await expect(
      apiFetch('/api/ai/patrol/suppressions', {
        expectedOrgID: 'tenant-b',
        retry: false,
        signal: controller.signal,
      }),
    ).rejects.toMatchObject({ name: 'AbortError' });
    expect(mockFetch).toHaveBeenCalledTimes(1);
  });

  it.each([{ retry: false }, { expectedOrgID: 'default' }])(
    'rejects aborted dispatch before fetch for either strict opt-in %j',
    async (options) => {
      const controller = new AbortController();
      controller.abort();
      await expect(
        apiFetch('/api/state', { ...options, signal: controller.signal }),
      ).rejects.toMatchObject({ name: 'AbortError' });
      expect(mockFetch).not.toHaveBeenCalled();
    },
  );

  it('does not fall back to another authentication method after a strict-session refusal', async () => {
    setApiToken('synthetic-token');
    setOrgID('tenant-a');
    mockFetch.mockResolvedValue(new Response('{}', { status: 401 }));
    const result = await apiFetch('/api/state', {
      preferSessionAuth: true,
      retry: false,
      expectedOrgID: 'tenant-a',
    });
    expect(result.status).toBe(401);
    expect(mockFetch).toHaveBeenCalledTimes(1);
    expect(mockFetch.mock.calls[0][1].headers['X-API-Token']).toBeUndefined();
  });

  it('checks the confirmed organisation again after asynchronous CSRF preparation', async () => {
    setOrgID('tenant-a');
    let finish!: (token: string) => void;
    const preparation = vi.spyOn(apiClient as any, 'ensureCSRFToken').mockReturnValueOnce(
      new Promise((resolve) => {
        finish = resolve;
      }),
    );
    const tokenRead = vi.spyOn(apiClient as any, 'loadCSRFToken').mockReturnValueOnce(null);
    try {
      const pending = apiFetch('/api/ai/patrol/suppressions/rule_one', {
        method: 'DELETE',
        retry: false,
        expectedOrgID: 'tenant-a',
      });
      setOrgID('tenant-b');
      finish('synthetic-csrf');
      await expect(pending).rejects.toThrow('Organisation changed');
      expect(mockFetch).not.toHaveBeenCalled();
    } finally {
      preparation.mockRestore();
      tokenRead.mockRestore();
    }
  });

  it('reuses a server-issued org cookie when storage is empty', async () => {
    document.cookie = 'pulse_org_id=tenant-1; Path=/; SameSite=Lax';
    mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));

    const modulePath = '@/utils/apiClient';
    vi.resetModules();
    const reloaded = await import(modulePath);

    await reloaded.apiFetch('/api/state');

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-Pulse-Org-ID']).toBe('tenant-1');
    expect(reloaded.getOrgID()).toBe('tenant-1');
    expect(window.sessionStorage.getItem('pulse_org_id')).toBe('tenant-1');
  });

  it('preserves hosted org context on monitored-system ledger requests', async () => {
    mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));

    setOrgID('tenant-ledger');
    await apiFetchJSON('/api/license/monitored-system-ledger');

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-Pulse-Org-ID']).toBe('tenant-ledger');
  });

  it('preserves authenticated organization context across durable action operations', async () => {
    mockFetch.mockImplementation(
      async () =>
        new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }),
    );

    setOrgID('tenant-actions');
    await ResourceActionsAPI.listActions('pending', 20);
    await ResourceActionsAPI.listActions('settled', 20);
    await ResourceActionsAPI.getAction('action/one');
    await ResourceActionsAPI.decideAction(
      'action/one',
      'approved',
      'sha256:reviewed-plan',
      'Reviewed by operator',
    );
    await ResourceActionsAPI.executeAction(
      'action/one',
      'sha256:reviewed-plan',
      'Execute the reviewed plan',
    );

    expect(mockFetch.mock.calls.map(([url]) => String(url))).toEqual([
      '/api/actions?view=pending&limit=20',
      '/api/actions?view=settled&limit=20',
      '/api/actions/action%2Fone',
      '/api/actions/action%2Fone/decision',
      '/api/actions/action%2Fone/execute',
    ]);
    for (const [, options] of mockFetch.mock.calls as [string, RequestInit][]) {
      const headers = options.headers as Record<string, string>;
      expect(headers['X-Pulse-Org-ID']).toBe('tenant-actions');
    }
    const mutationBodies = mockFetch.mock.calls
      .slice(3)
      .map(([, options]) => JSON.parse(String((options as RequestInit).body)));
    expect(mutationBodies).toEqual([
      {
        outcome: 'approved',
        planHash: 'sha256:reviewed-plan',
        reason: 'Reviewed by operator',
      },
      { planHash: 'sha256:reviewed-plan', reason: 'Execute the reviewed plan' },
    ]);
    expect(mutationBodies.every((body) => !('orgId' in body))).toBe(true);
  });

  it('preserves hosted org context on structured commercial errors', async () => {
    mockFetch.mockResolvedValue(
      new Response(
        JSON.stringify({
          error: 'license_required',
          message: 'Relay access requires a paid feature',
          feature: 'relay',
        }),
        {
          status: 402,
          headers: { 'Content-Type': 'application/json' },
        },
      ),
    );

    setOrgID('tenant-ledger');
    await expect(
      apiFetchJSON('/api/truenas/connections', { method: 'POST', body: '{}' }),
    ).rejects.toMatchObject({
      message: 'Relay access requires a paid feature',
      status: 402,
      feature: 'relay',
    });

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-Pulse-Org-ID']).toBe('tenant-ledger');
  });

  it('uses default org context when skipOrgContext is enabled', async () => {
    mockFetch.mockResolvedValue(new Response('[]', { status: 200 }));

    setOrgID('acme');
    await apiFetch('/api/orgs', { skipOrgContext: true });

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-Pulse-Org-ID']).toBe('default');
  });

  it('prefers a browser session over a stored API token when requested', async () => {
    mockFetch.mockResolvedValue(new Response('[]', { status: 200 }));
    setApiToken('stored-api-token');

    await apiFetch('/api/org-invitations', { preferSessionAuth: true });

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-API-Token']).toBeUndefined();
    expect(options.credentials).toBe('include');
  });

  it('falls back to a stored API token when no browser session is available', async () => {
    mockFetch
      .mockResolvedValueOnce(new Response('{}', { status: 401 }))
      .mockResolvedValueOnce(new Response('[]', { status: 200 }));
    setApiToken('stored-api-token');

    await apiFetch('/api/orgs', { preferSessionAuth: true });

    expect(mockFetch).toHaveBeenCalledTimes(2);
    const [, firstOptions] = mockFetch.mock.calls[0] as [string, RequestInit];
    const firstHeaders = firstOptions.headers as Record<string, string>;
    expect(firstHeaders['X-API-Token']).toBeUndefined();
    const [, retryOptions] = mockFetch.mock.calls[1] as [string, RequestInit];
    const retryHeaders = retryOptions.headers as Record<string, string>;
    expect(retryHeaders['X-API-Token']).toBe('stored-api-token');
  });

  it('does not treat intentional unauthenticated 401 responses as expired sessions', async () => {
    document.cookie = 'pulse_csrf=csrf-token; Path=/';
    mockFetch.mockResolvedValue(
      new Response(JSON.stringify({ success: false, message: 'Invalid username or password' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' },
      }),
    );

    const response = await apiFetch('/api/login', {
      method: 'POST',
      skipAuth: true,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: 'wrong', password: 'wrong' }),
    });

    expect(response.status).toBe(401);
    expect(window.localStorage.getItem('just_logged_out')).toBeNull();
  });

  it('rejects malformed org IDs from storage and does not forward them to headers', async () => {
    mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));
    window.sessionStorage.setItem('pulse_org_id', 'bad\norg');

    await apiFetch('/api/state');

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-Pulse-Org-ID']).toBeUndefined();
    expect(getOrgID()).toBeNull();
    expect(window.sessionStorage.getItem('pulse_org_id')).toBeNull();
  });

  it('rejects malformed API tokens before attaching auth headers', async () => {
    mockFetch.mockResolvedValue(new Response('{}', { status: 200 }));

    setApiToken('bad\ntoken');
    await apiFetch('/api/state');

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-API-Token']).toBeUndefined();
    expect(getApiToken()).toBeNull();
    expect(window.sessionStorage.getItem('pulse_auth')).toBeNull();
  });

  it('clears stale org context and retries when backend returns invalid_org', async () => {
    mockFetch
      .mockResolvedValueOnce(
        new Response(JSON.stringify({ error: 'invalid_org', message: 'Invalid Organization ID' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' },
        }),
      )
      .mockResolvedValueOnce(new Response('{}', { status: 200 }));

    setOrgID('missing-org');
    await apiFetch('/api/state');

    expect(mockFetch).toHaveBeenCalledTimes(2);

    const [, firstOptions] = mockFetch.mock.calls[0] as [string, RequestInit];
    const firstHeaders = firstOptions.headers as Record<string, string>;
    expect(firstHeaders['X-Pulse-Org-ID']).toBe('missing-org');

    const [, secondOptions] = mockFetch.mock.calls[1] as [string, RequestInit];
    const secondHeaders = secondOptions.headers as Record<string, string>;
    expect(secondHeaders['X-Pulse-Org-ID']).toBeUndefined();
    expect(getOrgID()).toBeNull();
  });

  it('clears a refused default selection and retries without org context', async () => {
    mockFetch
      .mockResolvedValueOnce(
        new Response(
          JSON.stringify({
            error: 'default_org_access_denied',
            message: 'User is not a member of the default organization',
          }),
          { status: 403, headers: { 'Content-Type': 'application/json' } },
        ),
      )
      .mockResolvedValueOnce(new Response('{}', { status: 200 }));

    setOrgID('default');
    const response = await apiFetch('/api/state/summary');

    expect(response.status).toBe(200);
    expect(mockFetch).toHaveBeenCalledTimes(2);
    const [, firstOptions] = mockFetch.mock.calls[0] as [string, RequestInit];
    expect((firstOptions.headers as Record<string, string>)['X-Pulse-Org-ID']).toBe('default');
    const [, secondOptions] = mockFetch.mock.calls[1] as [string, RequestInit];
    expect((secondOptions.headers as Record<string, string>)['X-Pulse-Org-ID']).toBeUndefined();
    expect(getOrgID()).toBeNull();
  });

  it('does not retarget a write refused in the default organization', async () => {
    mockFetch.mockImplementation(
      async () =>
        new Response(JSON.stringify({ error: 'default_org_access_denied', message: 'denied' }), {
          status: 403,
          headers: { 'Content-Type': 'application/json' },
        }),
    );

    setOrgID('default');
    document.cookie = 'pulse_csrf=synthetic-csrf; Path=/';
    const response = await apiFetch('/api/guests/metadata/vm-1', { method: 'PUT', body: '{}' });

    expect(response.status).toBe(403);
    // The write may be retried once with a refreshed CSRF token, but never
    // without its organization or against the one the server would pick.
    const writes = mockFetch.mock.calls.filter(([url]) => url === '/api/guests/metadata/vm-1');
    expect(writes.length).toBeGreaterThan(0);
    for (const [, options] of writes) {
      expect((options as RequestInit).headers as Record<string, string>).toHaveProperty(
        'X-Pulse-Org-ID',
        'default',
      );
    }
    expect(getOrgID()).toBe('default');
  });

  it('keeps the org selection for other 403 responses', async () => {
    mockFetch.mockResolvedValueOnce(
      new Response(JSON.stringify({ error: 'access_denied', message: 'denied' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' },
      }),
    );

    setOrgID('tenant-a');
    const response = await apiFetch('/api/state/summary');

    expect(response.status).toBe(403);
    expect(mockFetch).toHaveBeenCalledTimes(1);
    expect(getOrgID()).toBe('tenant-a');
  });

  it('honors HTTP-date Retry-After before retrying a 429 response', async () => {
    vi.useFakeTimers();
    const retryAfter = new Date(Date.now() + 5000).toUTCString();

    mockFetch
      .mockResolvedValueOnce(
        new Response('rate limited', { status: 429, headers: { 'Retry-After': retryAfter } }),
      )
      .mockResolvedValueOnce(new Response('{}', { status: 200 }));

    const pending = apiFetch('/api/state');
    expect(mockFetch).toHaveBeenCalledTimes(1);

    await vi.advanceTimersByTimeAsync(2500);
    expect(mockFetch).toHaveBeenCalledTimes(1);

    await vi.advanceTimersByTimeAsync(5000);
    await pending;
    expect(mockFetch).toHaveBeenCalledTimes(2);
  });

  it('preserves requiredScope on JSON missing_scope errors', async () => {
    mockFetch.mockResolvedValue(
      new Response(JSON.stringify({ error: 'missing_scope', requiredScope: 'settings:write' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' },
      }),
    );

    await expect(
      apiFetchJSON('/api/security/tokens', { method: 'POST', body: '{}' }),
    ).rejects.toMatchObject({
      message: 'missing_scope',
      status: 403,
      requiredScope: 'settings:write',
    });
  });

  it('preserves org context while extracting structured JSON errors', async () => {
    mockFetch.mockResolvedValue(
      new Response(JSON.stringify({ error: 'Catalog is unavailable right now' }), {
        status: 503,
        headers: { 'Content-Type': 'application/json' },
      }),
    );

    setOrgID('tenant-reporting');
    await expect(apiFetchJSON('/api/admin/reports/catalog')).rejects.toMatchObject({
      message: 'Catalog is unavailable right now',
      status: 503,
    });

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-Pulse-Org-ID']).toBe('tenant-reporting');
  });

  it('preserves canonical error code and details while retaining org context', async () => {
    mockFetch.mockResolvedValue(
      new Response(
        JSON.stringify({
          error: 'Failed to connect to VMware vCenter',
          code: 'vmware_connection_failed',
          details: {
            category: 'unsupported_version',
            error: 'VMware vCenter 6.7 is below the supported VI JSON release floor',
          },
        }),
        {
          status: 400,
          headers: { 'Content-Type': 'application/json' },
        },
      ),
    );

    setOrgID('tenant-vmware');
    await expect(
      apiFetchJSON('/api/vmware/connections/test', { method: 'POST', body: '{}' }),
    ).rejects.toMatchObject({
      message: 'Failed to connect to VMware vCenter',
      status: 400,
      code: 'vmware_connection_failed',
      details: {
        category: 'unsupported_version',
        error: 'VMware vCenter 6.7 is below the supported VI JSON release floor',
      },
    });

    const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
    const headers = options.headers as Record<string, string>;
    expect(headers['X-Pulse-Org-ID']).toBe('tenant-vmware');
  });
});