Files
rust-discovery/tests/browser/customer-management.spec.ts
T
2026-11-18 22:57:05 +01:00

371 lines
22 KiB
TypeScript

import { test, expect } from '../../web/node_modules/@playwright/test/index.js';
import { createServer, type ViteDevServer } from '../../web/node_modules/vite/dist/node/index.js';
import { resolve } from 'node:path';
let server: ViteDevServer;
let origin: string;
test.beforeAll(async () => {
server = await createServer({
root: resolve(__dirname, '../../web'),
configFile: false,
server: { host: '127.0.0.1', port: 0 },
logLevel: 'silent'
});
await server.listen();
const address = server.httpServer!.address();
if (!address || typeof address === 'string') throw new Error('Missing local fixture address');
origin = `http://127.0.0.1:${address.port}`;
});
test.afterAll(async () => { await server?.close(); });
test('creates and renames a customer, opens its inventory, and hides editing for a reader', async ({ page }) => {
const home = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'Testzentrale' };
const customerId = '22222222-2222-4222-8222-222222222222';
const customers = [home];
const csrf = 'local-customer-test';
let canManage = true;
const mutations: { method: string; path: string; body: unknown }[] = [];
const listing = (items: unknown[]) => ({
items, next_cursor: null, truncated: false, completeness: 'complete', as_of: '2026-11-17T12:00:00Z'
});
await page.route(`${origin}/auth/config`, route => route.fulfill({
json: { local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false }
}));
await page.route(`${origin}/auth/session`, route => route.fulfill({
json: {
principal: canManage ? 'customer-admin-fixture' : 'inventory-reader-fixture',
testsimulation: false,
tenant_id: route.request().headers()['x-rmm-tenant'] ?? home.tenant_id,
csrf_token: csrf,
permissions: ['inventory:read']
}
}));
await page.route(`${origin}/api/v1/**`, async route => {
const request = route.request();
const path = new URL(request.url()).pathname;
const method = request.method();
const collection = '/api/v1/tenants';
if (method === 'GET' && path === collection) {
return route.fulfill({ json: { ...listing(customers), can_manage_customers: canManage } });
}
if (method === 'GET' && path === `${collection}/${customerId}/devices`) {
const customer = customers.find(c => c.tenant_id === customerId);
if (!customer) throw new Error('Kunde fehlt im Testbestand');
return route.fulfill({ json: listing([{
tenant_id: customerId, customer_name: customer.name, asset_id: 'device-1', agent_id: 'agent-1',
lifecycle: 'current', status: 'online', hostname: 'NORD-PC', device_type: 'hypervisor', os: 'Proxmox VE',
ram_available_bytes: 6 * 2 ** 30, ram_total_bytes: 16 * 2 ** 30, cpu_usage_percent: 0,
disk_free_bytes: 24 * 2 ** 30, disk_total_bytes: 32 * 2 ** 30
}]) });
}
if (method === 'POST' || method === 'PATCH') {
const body = request.postDataJSON();
mutations.push({ method, path, body });
expect(canManage).toBe(true);
expect(request.headers()['x-csrf-token']).toBe(csrf);
if (method === 'POST' && path === collection) {
const created = { tenant_id: customerId, name: body.name };
customers.push(created);
return route.fulfill({ status: 201, json: created });
}
if (method === 'PATCH' && path === `${collection}/${customerId}`) {
expect(request.headers()['x-rmm-tenant']).toBe(customerId);
const customer = customers.find(c => c.tenant_id === customerId);
if (!customer) throw new Error('Unbekannter Testkunde');
customer.name = body.name;
return route.fulfill({ json: customer });
}
}
return route.fulfill({ status: 404, json: { code: 'UNEXPECTED_FIXTURE_REQUEST', message: path } });
});
await page.goto(`${origin}/#kunden`);
await page.getByRole('button', { name: 'Kunde anlegen' }).click();
await page.getByLabel('Kundenname').fill('Nord');
await page.getByRole('button', { name: 'Speichern' }).click();
await expect(page.getByRole('status')).toHaveText('Kunde „Nord“ angelegt.');
await page.getByRole('button', { name: 'Nord umbenennen' }).click();
await expect(page.getByLabel('Kundenname')).toHaveValue('Nord');
await page.getByLabel('Kundenname').fill('Nord GmbH');
await page.getByRole('button', { name: 'Speichern' }).click();
await expect(page.getByRole('status')).toHaveText('Kundenname in „Nord GmbH“ geändert.');
await expect(page.getByRole('cell', { name: 'Nord', exact: true })).toHaveCount(0);
canManage = false;
await page.reload();
await expect(page.getByRole('row', { name: /Nord GmbH/ })).toBeVisible();
await expect(page.getByRole('button', { name: 'Kunde anlegen' })).toHaveCount(0);
await expect(page.getByRole('button', { name: /umbenennen/i })).toHaveCount(0);
await page.getByRole('button', { name: 'Geräte von Nord GmbH anzeigen' }).click();
await expect(page.getByRole('heading', { name: 'Geräte', exact: true })).toBeVisible();
await expect(page.getByRole('combobox', { name: 'Kunde', exact: true })).toHaveValue(customerId);
await expect(page.getByRole('combobox', { name: 'Kunde im Gerätebestand', exact: true })).toHaveValue(customerId);
const device = page.getByRole('row').filter({ hasText: 'NORD-PC' });
await expect(device).toContainText('Nord GmbH');
const headers = page.locator('.fleet-table thead th[scope="col"]');
await expect(headers.nth(0)).toHaveText('Hostname');
await expect(headers.nth(1)).toHaveText('Type');
await expect(device.getByRole('cell').nth(2)).toHaveText('hypervisor');
await expect(device.getByRole('cell').nth(3)).toHaveText('Proxmox VE');
const memory = device.locator('[data-label="RAM frei / gesamt"]');
await expect(memory).toHaveText('6 / 16 GiB');
await expect(memory.locator('.capacity-track')).toHaveAttribute('title', '37,5 % frei');
await expect(memory.locator('.capacity-track i')).toHaveAttribute('style', 'width: 62.5%;');
await expect(device.locator('[data-label="Speicher frei / gesamt"] .capacity-track i'))
.toHaveAttribute('style', 'width: 25%;');
await expect(device.getByText('Auslastung 0 %', { exact: true })).toBeVisible();
const navigation = page.getByRole('navigation', { name: 'Hauptnavigation' });
await navigation.getByRole('link', { name: 'Aufträge', exact: true }).click();
await expect(page.getByRole('combobox', { name: 'Kunde', exact: true })).toHaveValue(customerId);
await navigation.getByRole('link', { name: 'Skripte', exact: true }).click();
await expect(page.getByRole('combobox', { name: 'Kunde', exact: true })).toHaveValue(customerId);
await navigation.getByRole('link', { name: 'Genehmigungen', exact: true }).click();
await expect(page.locator('header').getByText('Nord GmbH')).toBeVisible();
await navigation.getByRole('link', { name: 'Geräte', exact: true }).click();
await expect(page.getByRole('combobox', { name: 'Kunde im Gerätebestand', exact: true })).toHaveValue(customerId);
expect(mutations).toEqual([
{ method: 'POST', path: '/api/v1/tenants', body: { name: 'Nord' } },
{ method: 'PATCH', path: `/api/v1/tenants/${customerId}`, body: { name: 'Nord GmbH' } }
]);
});
test('removes the confirmed historical installation and keeps its successor', async ({ page }) => {
const customer = { tenant_id: '22222222-2222-4222-8222-222222222222', name: 'Nord GmbH' };
const asset = '33333333-3333-4333-8333-333333333333';
const old = '44444444-4444-4444-8444-444444444444';
const active = '55555555-5555-4555-8555-555555555555';
const path = '/api/v1/tenants/' + customer.tenant_id + '/devices/' + asset;
const device = { tenant_id: customer.tenant_id, customer_name: customer.name, asset_id: asset,
hostname: 'NORD-PC', os: 'Windows', recent_jobs: [], volumes: [] };
const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false,
completeness: 'complete', as_of: new Date().toISOString() });
let attempts = 0, revoked = false, deleted = false, canManage = true;
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false
} }));
await page.route(origin + '/auth/session', r => r.fulfill({ json: {
principal: 'operator', tenant_id: customer.tenant_id, csrf_token: 'fixture-csrf', testsimulation: false,
permissions: canManage ? ['inventory:read', 'devices:revoke'] : ['inventory:read']
} }));
await page.route(origin + '/api/v1/**', async r => {
const req = r.request(), url = new URL(req.url());
const historical = { ...device, agent_id: old, lifecycle: revoked ? 'revoked' : 'replaced', status: 'offline' };
const successor = { ...device, agent_id: active, lifecycle: 'current', status: 'online', source_id: 'windows.base',
capabilities: ['windows.base/1', 'rmm.sync.v1', 'run_script', 'script.powershell/1', 'script.powershell.process_remote_signed/1',
'script.full_maintenance/1', 'helper.system.v1', 'system:run_script'] };
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing([customer]) });
if (url.pathname === '/api/v1/devices' || url.pathname === path.slice(0, path.lastIndexOf('/'))) {
return r.fulfill({ json: listing(url.searchParams.get('view') === 'history' ? (deleted ? [] : [historical]) : [successor]) });
}
if (url.pathname === path && req.method() === 'GET') {
if (url.searchParams.get('agent_id') === old && !deleted) return r.fulfill({ json: historical });
if (url.searchParams.get('agent_id') === active) return r.fulfill({ json: successor });
}
if (url.pathname === path + '/revocation' && req.method() === 'POST') {
expect(url.searchParams.get('agent_id')).toBe(old);
expect(req.headers()['x-csrf-token']).toBe('fixture-csrf');
expect(req.postDataJSON()).toEqual({ reason: 'Neuinstallation bestätigt' });
revoked = true;
return r.fulfill({ json: { asset_id: asset, revoked: true } });
}
if (url.pathname === path && req.method() === 'DELETE') {
expect(url.searchParams.get('agent_id')).toBe(old);
expect(req.headers()['x-rmm-tenant']).toBe(customer.tenant_id);
expect(req.headers()['x-csrf-token']).toBe('fixture-csrf');
expect(req.postData()).toBeNull();
if (++attempts === 1) return r.fulfill({ status: 409, json: { code: 'DEVICE_HAS_OPEN_WORK' } });
deleted = true;
return r.fulfill({ status: 204 });
}
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
});
await page.goto(origin + '/#geraete');
await page.getByRole('button', { name: 'Historie' }).click();
await page.getByRole('button', { name: 'NORD-PC' }).click();
await page.getByText('Gerät verwalten', { exact: true }).click();
await expect(page.getByRole('button', { name: 'Kopplung löschen' })).toHaveCount(0);
await page.getByText('Geräteidentität widerrufen', { exact: true }).click();
await page.getByLabel('Grund für Geräteidentität widerrufen').fill('Neuinstallation bestätigt');
const nonce = await page.getByText('Aktuelle Bestätigungskennung:').locator('code').innerText();
await page.getByLabel('Bestätigungskennung eingeben').fill(nonce);
await page.getByRole('checkbox', { name: 'Ich bestätige' }).check();
await page.getByRole('button', { name: 'Geräteidentität widerrufen · ausdrücklich ausführen' }).click();
await page.getByRole('button', { name: 'Kopplung löschen' }).click();
await expect(page.locator('.warning')).toContainText('NORD-PC');
await expect(page.locator('.warning')).toContainText(customer.name);
await expect(page.getByText('Kopplungs-ID')).toContainText(old);
await page.getByRole('button', { name: 'Abbrechen' }).click();
expect(attempts).toBe(0);
await page.getByRole('button', { name: 'Kopplung löschen' }).click();
await page.getByRole('button', { name: 'Endgültig löschen' }).click();
await expect(page.getByRole('alert')).toContainText('offene Aufträge');
await page.getByRole('button', { name: 'Endgültig löschen' }).click();
await expect(page.getByRole('status')).toContainText('Kopplung von „NORD-PC“ bei „Nord GmbH“ gelöscht.');
await expect(page.getByRole('button', { name: 'NORD-PC' })).toHaveCount(0);
await page.getByRole('button', { name: 'Bestand' }).click();
await page.getByRole('button', { name: 'NORD-PC' }).click();
await expect(page).toHaveURL(new RegExp(active + '$'));
await expect(page.getByText('PowerShell als Dienstkonto und als Administrator (SYSTEM)')).toBeVisible();
await page.getByText('Gerät verwalten', { exact: true }).click();
await expect(page.getByRole('button', { name: 'Kopplung löschen' })).toHaveCount(0);
await expect(page.getByText('Geräteidentität widerrufen', { exact: true })).toBeVisible();
canManage = false;
await page.reload();
await expect(page.getByRole('heading', { name: 'NORD-PC' })).toBeVisible();
await expect(page.getByText('Gerät verwalten', { exact: true })).toHaveCount(0);
expect(attempts).toBe(2);
});
test('moves an existing pairing through the WebUI and waits for target inventory', async ({ page }) => {
const source = { tenant_id: '11111111-1111-4111-8111-111111111111', name: 'Nord GmbH' };
const target = { tenant_id: '22222222-2222-4222-8222-222222222222', name: 'Süd GmbH' };
const device = { tenant_id: source.tenant_id, customer_name: source.name,
asset_id: 'existing-asset', agent_id: 'existing-agent', hostname: 'NORD-PC', os: 'Linux',
capabilities: ['device.customer_transfer/1'], lifecycle: 'current', status: 'online',
recent_jobs: [], volumes: [] };
const path = '/api/v1/tenants/' + source.tenant_id + '/devices/' + device.asset_id;
const move = path + '/customer-transfer';
const transfer = { transfer_id: 'move-fixture', target_tenant_id: target.tenant_id,
target_asset_id: 'new-asset', target_agent_id: 'new-agent', target_hostname: 'NORD-PC' };
let state = '';
let canEnroll = false;
let posts = 0;
const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false,
completeness: 'complete', as_of: new Date().toISOString() });
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false
} }));
await page.route(origin + '/auth/session', r => {
const selected = r.request().headers()['x-rmm-tenant'] ?? source.tenant_id;
return r.fulfill({ json: { principal: 'fixture-operator', tenant_id: selected,
csrf_token: 'move-csrf', testsimulation: false,
permissions: ['inventory:read', ...(selected === source.tenant_id ? ['devices:revoke'] :
canEnroll ? ['devices:enroll'] : [])] } });
});
await page.route(origin + '/api/v1/**', async r => {
const req = r.request(), url = new URL(req.url());
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing([source, target]) });
if (url.pathname === path) return r.fulfill({ json: {
...device, lifecycle: state === 'completed' ? 'revoked' : 'current'
} });
if (url.pathname === move && req.method() === 'GET') {
return r.fulfill({ json: { transfer: state ? { ...transfer, state } : null } });
}
if (req.method() === 'POST') {
expect(req.headers()['x-csrf-token']).toBe('move-csrf');
expect(req.headers()['x-rmm-tenant']).toBe(source.tenant_id);
expect(url.searchParams.get('agent_id')).toBe(device.agent_id);
expect(url.pathname).toBe(move);
expect(req.postDataJSON()).toEqual({ target_tenant_id: target.tenant_id });
posts++;
state = 'pending';
return r.fulfill({ json: { state } });
}
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
});
await page.setViewportSize({ width: 390, height: 844 });
await page.goto(origin + '/#geraete/' + [source.tenant_id, device.asset_id, device.agent_id].join('/'));
await page.getByText('Gerät verwalten', { exact: true }).click();
await page.getByText('Kunden wechseln', { exact: true }).click();
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
await expect(page.getByText('Für diesen Zielkunden fehlt das Recht', { exact: false })).toBeVisible();
const prepare = page.getByRole('button', { name: 'Kundenwechsel starten' });
await expect(prepare).toBeDisabled();
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption('');
canEnroll = true;
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
await prepare.click();
await expect(page.getByText('Der Wechsel ist vorgemerkt.', { exact: false })).toBeVisible();
const destination = page.getByRole('link', { name: 'Neue Kopplung öffnen' });
state = 'enrolled';
await expect(page.getByText('Der Wechsel wird mit der ersten Inventarmeldung', { exact: false }))
.toBeVisible({ timeout: 10000 });
await expect(destination).toHaveCount(0);
state = 'completed';
await expect(page.getByText('Kundenwechsel abgeschlossen.', { exact: false })).toBeVisible({ timeout: 10000 });
await expect(destination).toHaveAttribute('href',
'#geraete/' + target.tenant_id + '/new-asset/new-agent');
expect(posts).toBe(1);
});
test('shows real VM hosts and the Hetzner placeholder without adding a device', async ({ page }) => {
const tenant = '11111111-1111-4111-8111-111111111111';
const path = '/api/v1/tenants/' + tenant;
const customer = { tenant_id: tenant, name: 'Testkunde' };
const base = { ...customer, customer_name: customer.name,
lifecycle: 'current', status: 'online', recent_jobs: [], volumes: [] };
const vm = { ...base, hostname: 'Test-VM', asset_id: 'vm-asset', agent_id: 'vm-agent', device_type: 'virtual' };
const pve = { ...base, hostname: 'pve-01', asset_id: 'pve-asset', agent_id: 'pve-agent',
device_type: 'hypervisor', os: 'Proxmox VE' };
const placeholder = { kind: 'placeholder', provider: 'hetzner', hostname: 'Hetzner Cloud' };
let assigned = false;
const guest = () => ({ ...vm, assigned_hypervisor_asset_id: assigned ? pve.asset_id : null,
hypervisor: assigned ? { kind: 'device', hostname: pve.hostname, asset_id: pve.asset_id, agent_id: pve.agent_id } : placeholder });
const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false,
completeness: 'complete', as_of: new Date().toISOString() });
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
local_login_enabled: true, oidc_configured: false, oidc_login_url: null, dev_login_enabled: false
} }));
await page.route(origin + '/auth/session', r => r.fulfill({ json: {
principal: 'inventory-owner', tenant_id: tenant, csrf_token: 'host-assignment-fixture',
testsimulation: false, permissions: ['inventory:read', 'devices:revoke']
} }));
await page.route(origin + '/api/v1/**', r => {
const req = r.request(), url = new URL(req.url());
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing([customer]) });
if (url.pathname === '/api/v1/devices' || url.pathname === path + '/devices') {
return r.fulfill({ json: listing([guest(), pve]) });
}
if (url.pathname === path + '/devices/' + vm.asset_id) return r.fulfill({ json: guest() });
if (url.pathname === path + '/devices/' + pve.asset_id) return r.fulfill({ json: pve });
if (url.pathname === path + '/hypervisors') {
expect(req.headers()['x-rmm-tenant']).toBe(tenant);
return r.fulfill({ json: { items: [pve], truncated: false } });
}
if (url.pathname === path + '/devices/' + vm.asset_id + '/hypervisor') {
expect(req.method()).toBe('POST');
expect(req.headers()['x-csrf-token']).toBe('host-assignment-fixture');
expect(url.searchParams.get('agent_id')).toBe(vm.agent_id);
const target = req.postDataJSON().hypervisor_asset_id;
expect(target).toBe(assigned ? null : pve.asset_id);
assigned = target === pve.asset_id;
return r.fulfill({ json: { asset_id: vm.asset_id, hypervisor_asset_id: target } });
}
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
});
await page.goto(origin + '/#geraete');
const vmRow = page.getByRole('row').filter({ has: page.getByRole('button', { name: vm.hostname }) });
await expect(vmRow).toContainText('Hetzner Cloud');
await expect(vmRow).toContainText('Platzhalter');
await expect(page.getByRole('button', { name: 'Hetzner Cloud' })).toHaveCount(0);
await expect(page.locator('.fleet-table tbody tr')).toHaveCount(2);
await page.getByRole('button', { name: vm.hostname }).click();
await page.getByText('Gerät verwalten', { exact: true }).click();
await page.getByText('Hypervisor zuordnen', { exact: true }).click();
const hostInput = page.getByRole('combobox', { name: 'Hypervisor auswählen' });
await hostInput.selectOption(pve.asset_id);
await page.getByRole('button', { name: 'Zuordnung speichern' }).click();
await expect(page.getByText('Hypervisor zugeordnet.', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
await page.setViewportSize({ width: 390, height: 844 });
const hostLink = vmRow.getByRole('link', { name: pve.hostname });
await expect(hostLink).toBeVisible();
await expect(vmRow).not.toContainText('Hetzner Cloud');
await hostLink.click();
await expect(page.getByRole('heading', { name: pve.hostname })).toBeVisible();
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
await page.getByRole('button', { name: vm.hostname }).click();
await page.getByText('Gerät verwalten', { exact: true }).click();
await page.getByText('Hypervisor zuordnen', { exact: true }).click();
await hostInput.selectOption('');
await page.getByRole('button', { name: 'Zuordnung speichern' }).click();
await expect(page.getByText('Hostzuordnung entfernt.', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Zur Geräteliste' }).click();
await expect(vmRow).toContainText('Hetzner Cloud');
});