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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { SecurityAPI, type APITokenRecord, type CreateAPITokenResponse } from '../security';
import { apiFetchJSON } from '@/utils/apiClient';
import type { SecurityStatus } from '@/types/config';
vi.mock('@/utils/apiClient', () => ({
apiFetchJSON: vi.fn(),
}));
describe('SecurityAPI', () => {
beforeEach(() => {
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 = {
hasAuthentication: true,
apiTokenConfigured: true,
apiTokenHint: 'pmp_***',
requiresAuth: true,
credentialsEncrypted: true,
exportProtected: true,
hasAuditLogging: true,
configuredButPendingRestart: false,
sessionCapabilities: {
demoMode: false,
assistantEnabled: true,
},
};
vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockStatus);
const result = await SecurityAPI.getStatus();
expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/status');
expect(result).toEqual(mockStatus);
});
it('preserves assistant availability in session capabilities', async () => {
const mockStatus: SecurityStatus = {
hasAuthentication: true,
apiTokenConfigured: false,
apiTokenHint: '',
requiresAuth: true,
credentialsEncrypted: true,
exportProtected: true,
hasAuditLogging: false,
configuredButPendingRestart: false,
sessionCapabilities: {
demoMode: false,
assistantEnabled: true,
},
};
vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockStatus);
const result = await SecurityAPI.getStatus();
expect(result.sessionCapabilities?.assistantEnabled).toBe(true);
});
});
describe('listTokens', () => {
const record = { id: 't1', name: 'Known', prefix: 'pmp_', suffix: '1234', createdAt: '' };
it('fetches all tokens', async () => {
const mockTokens: APITokenRecord[] = [
{
id: 't1',
name: 'Token 1',
prefix: 'pmp_',
suffix: 'abc',
createdAt: '',
ownerUserId: '[email protected]',
},
];
vi.mocked(apiFetchJSON).mockResolvedValueOnce({ tokens: mockTokens });
const result = await SecurityAPI.listTokens();
expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/tokens', { retry: false });
expect(result).toEqual(mockTokens);
});
it('returns empty array when tokens is null', async () => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce({ tokens: null });
const result = await SecurityAPI.listTokens();
expect(result).toEqual([]);
});
it.each(
[
null,
[],
{},
{ tokens: 'bad' },
{ tokens: {} },
{ tokens: [null] },
{ tokens: [{ ...record, scopes: 'monitoring:read' }] },
{ tokens: [{ ...record, scopes: [null] }] },
{ tokens: [{ ...record, scopes: [''] }] },
{ tokens: [{ ...record, id: '' }] },
{ tokens: [{ ...record, name: {} }] },
{ tokens: [record, record] },
].map((response) => ({ response })),
)('rejects an unreadable inventory instead of inventing absence (%j)', async ({ response }) => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce(response);
await expect(SecurityAPI.listTokens()).rejects.toThrow('Invalid API token inventory.');
expect(apiFetchJSON).toHaveBeenCalledTimes(1);
});
it('rejects a partial inventory instead of dropping its unreadable member', async () => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce({
tokens: [
{
id: 't1',
name: 'Known',
prefix: 'pmp_',
suffix: '1234',
createdAt: '',
scopes: ['monitoring:read'],
},
null,
],
});
await expect(SecurityAPI.listTokens()).rejects.toThrow('Invalid API token inventory.');
});
it.each([undefined, null, [], ['*'], ['future:scope']].map((scopes) => ({ scopes })))(
'preserves supported and legacy scopes (%j)',
async ({ scopes }) => {
const token = { id: 't1', name: '', prefix: 'pmp_', suffix: '1234', createdAt: '', scopes };
vi.mocked(apiFetchJSON).mockResolvedValueOnce({ tokens: [token] });
await expect(SecurityAPI.listTokens()).resolves.toEqual([token]);
},
);
it('preserves an explicitly empty inventory', async () => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce({ tokens: [] });
await expect(SecurityAPI.listTokens()).resolves.toEqual([]);
});
});
describe('getToken', () => {
it('fetches a single token record', async () => {
const mockRecord: APITokenRecord = {
id: 't1',
name: 'Token 1',
prefix: 'pmp_',
suffix: 'abc',
createdAt: '',
lastUsedAt: '2026-03-24T12:00:00Z',
expiresAt: '2026-03-25T12:00:00Z',
ownerUserId: '[email protected]',
};
vi.mocked(apiFetchJSON).mockResolvedValueOnce({ record: mockRecord });
const result = await SecurityAPI.getToken('token/1');
expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/tokens/token%2F1');
expect(result).toEqual(mockRecord);
});
});
describe('createToken', () => {
it('creates token with name and scopes', async () => {
const mockResponse: CreateAPITokenResponse = {
token: 'pmp_xxx',
record: {
id: 't1',
name: 'Token',
prefix: 'pmp_',
suffix: 'xxx',
createdAt: '',
ownerUserId: '[email protected]',
},
};
vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockResponse);
const result = await SecurityAPI.createToken('My Token', ['read', 'write']);
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/security/tokens',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ name: 'My Token', scopes: ['read', 'write'] }),
}),
);
expect(result).toEqual(mockResponse);
});
it('preserves owner user binding from the API response', async () => {
const mockResponse: CreateAPITokenResponse = {
token: 'pmp_xxx',
record: {
id: 't1',
name: 'Token',
prefix: 'pmp_',
suffix: 'xxx',
createdAt: '',
ownerUserId: '[email protected]',
},
};
vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockResponse);
const result = await SecurityAPI.createToken('My Token', ['read']);
expect(result.record.ownerUserId).toBe('[email protected]');
});
it('creates token without optional params', async () => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce({
token: 'pmp_xxx',
record: {},
} as CreateAPITokenResponse);
await SecurityAPI.createToken();
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/security/tokens',
expect.objectContaining({
body: JSON.stringify({}),
}),
);
});
});
describe('createRelayMobileAccessToken', () => {
it('creates a server-owned relay mobile runtime token', async () => {
const mockResponse: CreateAPITokenResponse = {
token: 'pmp_mobile',
record: {
id: 'relay-mobile-1',
name: 'Pulse Mobile relay access 2026-03-24T23:30:00Z',
prefix: 'pmp_',
suffix: 'bile',
createdAt: '',
scopes: ['relay:mobile:access'],
ownerUserId: '[email protected]',
},
};
vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockResponse);
const result = await SecurityAPI.createRelayMobileAccessToken();
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/security/tokens/relay-mobile',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({}),
}),
);
expect(result).toEqual(mockResponse);
});
});
describe('updateTokenScopes', () => {
it('patches an encoded token id and returns the updated record', async () => {
const updated: APITokenRecord = {
id: 'token/1',
name: 'Automation',
prefix: 'pulse',
suffix: '1234',
createdAt: '2026-07-30T10:00:00Z',
scopes: ['monitoring:read', 'settings:read'],
};
vi.mocked(apiFetchJSON).mockResolvedValueOnce({ record: updated });
const result = await SecurityAPI.updateTokenScopes('token/1', [
'monitoring:read',
'settings:read',
]);
expect(apiFetchJSON).toHaveBeenCalledWith('/api/security/tokens/token%2F1', {
retry: false,
method: 'PATCH',
body: JSON.stringify({ scopes: ['monitoring:read', 'settings:read'] }),
});
expect(result).toEqual(updated);
});
});
describe('deleteToken', () => {
it('deletes a token', async () => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce(undefined);
await SecurityAPI.deleteToken('token-1');
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/security/tokens/token-1',
expect.objectContaining({ method: 'DELETE' }),
);
});
it('encodes special characters in token id', async () => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce(undefined);
await SecurityAPI.deleteToken('token/1');
expect(apiFetchJSON).toHaveBeenCalledWith(
'/api/security/tokens/token%2F1',
expect.objectContaining({ method: 'DELETE' }),
);
});
});
describe('renameToken', () => {
it('renames a token without rotating it', async () => {
const record: APITokenRecord = {
id: 'token/1',
name: 'PBS host',
prefix: 'pulse',
suffix: '1234',
createdAt: '',
};
vi.mocked(apiFetchJSON).mockResolvedValueOnce({ record });
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' }),
});
expect(result).toEqual(record);
});
});
});