Files
rust-discovery/tests/browser/order-composer.spec.ts
T

331 lines
15 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 { createHash, randomUUID } from 'node:crypto';
import { resolve } from 'node:path';
let server: ViteDevServer;
let origin: string;
const principal = 'operator-fixture';
const tenantId = randomUUID();
const auth = {
principal: { id: principal, display_name: 'Operator', simulated: true },
csrf_token: 'fixture',
tenants: [{ tenant_id: tenantId, name: 'Nord' }],
permissions: ['inventory:read', 'operations:read', 'operations:plan', 'operations:submit', 'scripts:execute']
};
const linux = {
asset_id: randomUUID(),
agent_id: randomUUID(),
hostname: 'test-linux',
os: 'Debian',
source_id: 'linux.base',
status: 'online',
lifecycle: 'current'
};
const windows = {
...linux,
asset_id: randomUUID(),
agent_id: randomUUID(),
hostname: 'test-windows',
os: 'Windows',
source_id: 'windows.base'
};
const script = {
name: 'Betriebssystem anzeigen',
revision_id: randomUUID(),
interpreter: 'posix_sh',
execution_identity: 'agent_service',
script_utf8: 'uname -s\n',
version: 1
};
const hash = (text: string) => createHash('sha256').update(text).digest('hex');
const listing = (items: unknown[]) => ({
items,
as_of: new Date().toISOString(),
next_cursor: null,
truncated: false,
completeness: 'complete'
});
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 a = server.httpServer?.address();
if (!a || typeof a === 'string') throw Error('Missing fixture port');
origin = 'http://127.0.0.1:' + a.port;
});
test.afterAll(async () => {
await server?.close();
});
test('opens a single result automatically and shows each result at its own device row', async ({ page }) => {
const operationId = randomUUID();
const multiOperationId = randomUUID();
const jobs = [linux, windows].map((device, index) => ({
...device,
job_id: randomUUID(),
attempt_id: randomUUID(),
state: index === 0 ? 'succeeded' : 'failed'
}));
const api = '/api/v1/tenants/' + tenantId;
const resultReads = new Set<string>();
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
dev_login_enabled: true, oidc_configured: false, oidc_login_url: null
} }));
await page.route(origin + '/auth/session', r => r.fulfill({ json: {
principal, tenant_id: tenantId, permissions: auth.permissions, csrf_token: auth.csrf_token, testsimulation: true
} }));
await page.route(origin + '/api/v1/**', async r => {
const pathname = new URL(r.request().url()).pathname;
if (pathname === '/api/v1/tenants') return r.fulfill({ json: listing(auth.tenants) });
if (pathname === '/api/v1/approvals') return r.fulfill({ json: { ...listing([]), pending_count: 0 } });
if (pathname.startsWith(api + '/operations/')) {
const id = pathname.slice((api + '/operations/').length);
if (id === operationId || id === multiOperationId) return r.fulfill({ json: {
operation_id: id, customer_name: 'Nord', title: script.name, approval_state: 'approved',
execution_state: id === operationId ? 'succeeded' : 'partially_succeeded',
targets: [linux, windows], jobs: id === operationId ? [jobs[0]] : jobs
} });
}
const job = jobs.find(item => pathname === api + '/jobs/' + item.job_id);
if (job) {
const success = job.state === 'succeeded';
resultReads.add(job.job_id);
return r.fulfill({ json: { ...job, result: {
exit_code: success ? 0 : 1, output_truncated: false,
stdout: success ? [...Buffer.from('Linux\n')] : [],
stderr: success ? [] : [...Buffer.from('Fehler auf Windows\n')]
} } });
}
return r.fulfill({ status: 404, json: { code: 'UNEXPECTED_FIXTURE_REQUEST' } });
});
const openOrder = (id: string) => page.goto(origin + '/#auftraege/ansehen/' + tenantId + '/' + id);
await openOrder(operationId);
await expect(page.getByRole('heading', { name: 'Ergebnis für test-linux' })).toBeVisible();
await expect(page.getByLabel('stdout Textansicht')).toHaveText('Linux');
await expect(page.getByText('Exitcode 0', { exact: true })).toBeVisible();
expect([...resultReads]).toEqual([jobs[0].job_id]);
await page.setViewportSize({ width: 390, height: 844 });
resultReads.clear();
await openOrder(multiOperationId);
const linuxButton = page.getByRole('button', { name: 'Ergebnis anzeigen für test-linux' });
const windowsButton = page.getByRole('button', { name: 'Ergebnis anzeigen für test-windows' });
await expect(linuxButton).toBeVisible();
await expect(windowsButton).toBeVisible();
expect(resultReads.size).toBe(0);
await linuxButton.click();
const linuxRow = page.getByRole('listitem').filter({ has: page.getByRole('button', { name: 'Ergebnis schließen für test-linux' }) });
await expect(linuxRow.getByLabel('stdout Textansicht')).toHaveText('Linux');
await windowsButton.click();
await expect(linuxButton).toHaveAttribute('aria-expanded', 'false');
await expect(page.getByLabel('stderr Textansicht')).toHaveText('Fehler auf Windows');
await page.getByRole('button', { name: 'Ergebnis schließen für test-windows' }).click();
await expect(page.getByRole('region', { name: 'Gespeichertes Konsolenergebnis' })).toHaveCount(0);
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390);
});
for (const library of [true, false]) {
test(
library
? 'pins a revision, blocks an incompatible target and finds the submitted order after a lost response'
: 'submits a one-time script without publishing a library revision',
async ({ page }) => {
let operationId: string | null = null;
let plan: Record<string, unknown> | null = null;
const posted: string[] = [];
let issuedVersion = 1;
await page.route(origin + '/fixture', (r) =>
r.fulfill({
contentType: 'text/html',
body: `<!doctype html><meta charset="utf-8"/><div id="root"></div><script type="module">
import React from '/node_modules/.vite/deps/react.js';
import ReactDOM from '/node_modules/.vite/deps/react-dom_client.js';
import {OrderComposer} from '/src/order-composer.tsx';
ReactDOM.createRoot(document.querySelector('#root')).render(React.createElement(OrderComposer,{tenantId:'${tenantId}',auth:${JSON.stringify(auth)},initialAssetIds:['${linux.asset_id}'],onSubmitted:id=>document.body.setAttribute('data-operation',id)}));
</script>`
})
);
const api = '/api/v1/tenants/' + tenantId;
await page.route(origin + api + '/**', async (r) => {
const req = r.request();
const suffix = new URL(req.url()).pathname.slice(api.length);
if (req.method() === 'GET') {
if (suffix === '/devices') return r.fulfill({ json: listing([linux, windows]) });
if (suffix.startsWith('/devices/'))
return r.fulfill({ json: suffix.endsWith(linux.asset_id) ? linux : windows });
if (suffix === '/script-revisions')
return r.fulfill({
json: listing([{ ...script, script_sha256: hash(script.script_utf8), version: issuedVersion }])
});
if (suffix === '/operation-plans/' + plan?.plan_id)
return r.fulfill({ json: { ...plan, operation_id: operationId } });
} else if (req.method() === 'POST') {
posted.push(suffix);
const body = req.postDataJSON();
expect(req.headers()['x-csrf-token']).toBe(auth.csrf_token);
if (suffix === (library ? '/script-revisions/' + script.revision_id + '/plan' : '/operation-plans')) {
expect(body.targets.asset_ids).toEqual([linux.asset_id]);
expect(body.reason).toBe('Abnahme');
const content = library ? script.script_utf8 : body.parameters.variants[0].script_utf8;
const action = {
action: 'run_script',
interpreter: 'posix_sh',
script_utf8: content,
arguments: [],
expected_stdout: null
};
const payload = {
schema_version: 1,
tenant_id: tenantId,
asset_id: linux.asset_id,
agent_id: linux.agent_id,
enrollment_generation: 1,
assignment_version: 1,
job_id: randomUUID(),
attempt_id: randomUUID(),
action,
execution_identity: 'agent_service',
not_before: body.schedule.not_before,
start_before: body.schedule.start_before,
max_runtime_seconds: library ? body.max_runtime_seconds : body.parameters.timeout_seconds,
max_output_bytes: library ? body.max_output_bytes : body.parameters.max_output_bytes
};
const job = { payload, job_payload_hash: hash(JSON.stringify(payload)), script_sha256: hash(content) };
const fixed = {
schema_version: 1,
plan_id: randomUUID(),
tenant_id: tenantId,
principal,
reason: body.reason,
jobs: [job],
max_parallel: 1,
halt_after_failures: 1,
...(library
? {
script_revision: {
revision_id: script.revision_id,
name: script.name,
version: 1,
script_sha256: job.script_sha256
}
}
: {})
};
const bytes = JSON.stringify(fixed);
plan = {
plan_id: fixed.plan_id,
plan_hash: hash(bytes),
plan_payload_bytes: [...Buffer.from(bytes)],
plan_payload: fixed,
payload: fixed,
jobs: [job],
resolved_targets: [{ asset_id: linux.asset_id, agent_id: linux.agent_id }],
excluded_targets: [],
expires_at: payload.start_before
};
return r.fulfill({ json: plan });
}
if (suffix === '/operation-plans/' + plan?.plan_id + '/submit') {
expect(body).toEqual({ idempotency_key: plan!.plan_id });
operationId = randomUUID();
if (library) return r.abort('connectionreset');
return r.fulfill({
json: { plan_id: plan!.plan_id, plan_hash: plan!.plan_hash, operation_id: operationId }
});
}
}
return r.fulfill({ status: 404, json: { code: 'unexpected', message: suffix } });
});
await page.goto(origin + '/fixture');
await expect(page.getByRole('checkbox', { name: /test-linux/ })).toBeChecked();
if (library) await page.getByRole('checkbox', { name: /test-windows/ }).check();
await page.getByRole('button', { name: 'Weiter zum Skript' }).click();
if (library) {
await page.getByLabel('Bibliotheksskript').selectOption(script.name);
await expect(page.getByRole('alert')).toContainText('test-windows');
await expect(page.getByRole('button', { name: 'Zusammenfassung ansehen' })).toBeDisabled();
await page.getByRole('button', { name: 'Zurück zu Geräten' }).click();
await page.getByRole('checkbox', { name: /test-windows/ }).uncheck();
await page.getByRole('button', { name: 'Weiter zum Skript' }).click();
} else {
await page.getByRole('radio', { name: 'Einmaliges Skript' }).check();
await page.getByLabel('Skriptinhalt').fill('uname\n');
}
await page.getByLabel('Begründung').fill('Abnahme');
await page.getByRole('button', { name: 'Zusammenfassung ansehen' }).click();
await expect(page.getByRole('heading', { name: 'Zusammenfassung' })).toBeVisible();
if (library) {
issuedVersion = 2;
await expect(page.getByRole('heading', { name: /Version 1/ })).toBeVisible();
}
await page.getByRole('button', { name: 'Zur Genehmigung einreichen' }).click();
if (library) {
await expect(page.getByRole('button', { name: 'Eingereichten Auftrag öffnen' })).toBeVisible();
await page.reload();
await page.getByRole('button', { name: 'Eingereichten Auftrag öffnen' }).click();
}
await expect(page.locator('body')).toHaveAttribute('data-operation', /^[a-f0-9-]{36}$/);
expect(await page.locator('body').getAttribute('data-operation')).toBe(operationId);
expect(posted).toEqual([
library ? '/script-revisions/' + script.revision_id + '/plan' : '/operation-plans',
'/operation-plans/' + plan!.plan_id + '/submit'
]);
expect(await page.evaluate(() => sessionStorage.length)).toBe(0);
}
);
}
test('publishes versions in the library and keeps the earlier script readable', async ({ page }) => {
const revisions = [{ ...script, script_sha256: hash(script.script_utf8) }];
const writes: string[] = [];
await page.route(origin + '/fixture', (r) =>
r.fulfill({
contentType: 'text/html',
body: `<!doctype html><meta charset="utf-8"/><div id="root"></div><script type="module">
import React from '/node_modules/.vite/deps/react.js';
import ReactDOM from '/node_modules/.vite/deps/react-dom_client.js';
import {ScriptLibrary} from '/src/script-library.tsx';
ReactDOM.createRoot(document.querySelector('#root')).render(React.createElement(ScriptLibrary,{tenantId:'${tenantId}',auth:${JSON.stringify(auth)}}));
</script>`
})
);
await page.route(origin + '/api/v1/**', (r) => {
const req = r.request();
const path = '/api/v1/tenants/' + tenantId + '/script-revisions';
expect(new URL(req.url()).pathname).toBe(path);
if (req.method() === 'GET') return r.fulfill({ json: listing(revisions) });
writes.push(path);
expect(req.headers()['x-csrf-token']).toBe(auth.csrf_token);
const body = req.postDataJSON();
expect(body.expected_version).toBe(revisions.length);
const next = {
...script,
revision_id: randomUUID(),
script_utf8: body.script_utf8,
script_sha256: hash(body.script_utf8),
version: body.expected_version + 1
};
revisions.push(next);
return r.fulfill({ json: next });
});
await page.goto(origin + '/fixture');
await page.getByRole('button', { name: script.name, exact: true }).click();
await page.getByRole('button', { name: 'Neue Version', exact: true }).click();
await page.getByLabel('Skriptinhalt').fill('uname -r\n');
await page.getByRole('button', { name: 'Version veröffentlichen' }).click();
await expect(page.getByRole('status')).toContainText('Version 2 veröffentlicht.');
await page.getByText('Frühere Versionen (1)').click();
await page.getByText('Version 1 · Linux · Shell · Agent-Dienstkonto').click();
await expect(page.locator('pre').filter({ hasText: 'uname -s' })).toBeVisible();
await page.getByRole('button', { name: 'Zur Skriptbibliothek' }).click();
await expect(page.getByRole('row').filter({ hasText: script.name })).toHaveCount(1);
await expect(page.getByRole('row').filter({ hasText: script.name })).toContainText('2');
expect(writes).toHaveLength(1);
});