263 lines
11 KiB
TypeScript
263 lines
11 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();
|
|
});
|
|
|
|
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);
|
|
});
|