578 lines
31 KiB
TypeScript
578 lines
31 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 { readFileSync } from 'node:fs';
|
|
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('applies order filters from the first page and clears them on reset', async ({ page }) => {
|
|
const requests: URL[] = [];
|
|
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: auth }));
|
|
await page.route(origin + '/api/v1/**', r => {
|
|
const url = new URL(r.request().url());
|
|
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing(auth.tenants) });
|
|
if (url.pathname.endsWith('/operations')) requests.push(url);
|
|
return r.fulfill({ json: listing([]) });
|
|
});
|
|
await page.goto(origin + '/#auftraege');
|
|
await expect(page.getByText('Für diesen Kunden gibt es noch keine Aufträge.')).toBeVisible();
|
|
const area = page.getByRole('form', { name: 'Aufträge filtern' });
|
|
await area.getByLabel('Auftrag', { exact: true }).fill(' Kernel ');
|
|
await area.getByLabel('Gerät', { exact: true }).fill('test-linux');
|
|
await area.getByLabel('Status', { exact: true }).selectOption('succeeded');
|
|
await area.getByLabel('Von', { exact: true }).fill('2026-11-17');
|
|
await area.getByLabel('Bis einschließlich', { exact: true }).fill('2026-11-17');
|
|
await area.getByRole('button', { name: 'Filtern', exact: true }).click();
|
|
await expect(page.getByText('Keine Aufträge passen zu den Filtern.')).toBeVisible();
|
|
const request = requests.at(-1)?.searchParams;
|
|
expect(request?.get('cursor')).toBeNull();
|
|
expect(request?.get('q')).toBe('Kernel');
|
|
expect(request?.get('device')).toBe('test-linux');
|
|
expect(request?.get('status')).toBe('succeeded');
|
|
expect(Date.parse(request!.get('until')!) - Date.parse(request!.get('from')!)).toBe(86400000);
|
|
await area.getByRole('button', { name: 'Filter zurücksetzen' }).click();
|
|
await expect(page.getByText('Für diesen Kunden gibt es noch keine Aufträge.')).toBeVisible();
|
|
expect(requests.at(-1)?.searchParams.has('device')).toBe(false);
|
|
});
|
|
|
|
test('shows the execution stop and prepares the Windows restart through a versioned administrator script', async ({ page }) => {
|
|
const api = '/api/v1/tenants/' + tenantId;
|
|
const permissions = [...auth.permissions, 'tenant:stop', 'system:execute'];
|
|
let stopped = false, scopeDenied = false;
|
|
const restart = {
|
|
...script, name: 'Windows neu starten', revision_id: randomUUID(), version: 2,
|
|
interpreter: 'powershell', execution_identity: 'system', script_utf8: "Write-Output 'Neustart-Test'\n"
|
|
};
|
|
const writes: unknown[] = [];
|
|
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
|
|
dev_login_enabled: false, local_login_enabled: true, oidc_configured: false, oidc_login_url: null
|
|
} }));
|
|
await page.route(origin + '/auth/session', r => r.fulfill({ json: { ...auth, permissions, principal: { ...auth.principal, simulated: false } } }));
|
|
await page.route(origin + '/api/v1/**', r => {
|
|
const req = r.request(), pathname = new URL(req.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 === api + '/execution-stop' && req.method() === 'GET') {
|
|
return r.fulfill({ json: { tenant_id: tenantId, changes_stopped: stopped } });
|
|
}
|
|
if (pathname === api + '/devices') return r.fulfill({ json: listing([windows]) });
|
|
if (pathname === api + '/script-revisions') return r.fulfill({ json: listing([
|
|
{ ...restart, script_sha256: hash(restart.script_utf8) }
|
|
]) });
|
|
if (req.method() !== 'GET') {
|
|
expect(req.headers()['x-csrf-token']).toBe(auth.csrf_token);
|
|
writes.push({ pathname, body: req.postDataJSON() });
|
|
}
|
|
return scopeDenied
|
|
? r.fulfill({ status: 403, json: { code: 'SCRIPT_HELPER_SCOPE_DENIED' } })
|
|
: r.fulfill({ status: 409, json: { code: 'UNSUPPORTED_CAPABILITY' } });
|
|
});
|
|
|
|
await page.goto(origin + '/#verwaltung/rechte');
|
|
const status = page.getByRole('status', { name: 'Ausführungsstatus' });
|
|
await expect(status).toHaveText('Neue Starts sind freigegeben');
|
|
await expect(page.getByText('Mandantenausführung stoppen', { exact: true })).toBeVisible();
|
|
stopped = true;
|
|
await page.reload();
|
|
await expect(status).toHaveText('Neue Starts sind gestoppt');
|
|
await expect(page.getByText('Mandantenausführung stoppen', { exact: true })).toHaveCount(0);
|
|
await expect(page.getByText('Mandantenausführung wieder zulassen', { exact: true })).toBeVisible();
|
|
expect(writes).toHaveLength(0);
|
|
|
|
await page.goto(origin + '/#auftraege/wartung');
|
|
await page.getByRole('checkbox', { name: /test-windows/ }).check();
|
|
await page.getByRole('button', { name: 'Weiter zum Skript' }).click();
|
|
await page.getByRole('button', { name: 'Neustartskript auswählen' }).click();
|
|
await expect(page.getByRole('combobox', { name: 'Bibliotheksskript', exact: true })).toHaveValue(restart.name);
|
|
await expect(page.getByRole('combobox', { name: 'Version', exact: true })).toHaveValue(restart.revision_id);
|
|
await expect(page.getByRole('combobox', { name: 'Ausführen als', exact: true })).toHaveValue('system');
|
|
await page.getByText('Skriptinhalt anzeigen').click();
|
|
await expect(page.locator('pre')).toHaveText(restart.script_utf8.trim());
|
|
await page.getByLabel('Begründung', { exact: true }).fill('Neustart prüfen');
|
|
expect(writes).toHaveLength(0);
|
|
await page.getByRole('button', { name: 'Zusammenfassung ansehen' }).click();
|
|
await expect(page.getByRole('alert')).toContainText('Skript-Helper für SYSTEM noch nicht als betriebsbereit gemeldet');
|
|
expect(writes).toEqual([{
|
|
pathname: api + '/script-revisions/' + restart.revision_id + '/plan',
|
|
body: expect.objectContaining({
|
|
reason: 'Neustart prüfen', targets: { asset_ids: [windows.asset_id] }, max_runtime_seconds: 120, max_output_bytes: 65536
|
|
})
|
|
}]);
|
|
scopeDenied = true;
|
|
await page.getByRole('button', { name: 'Zusammenfassung ansehen' }).click();
|
|
await expect(page.getByRole('alert')).toContainText('zentrale Richtlinie erlaubt dieses Administratorskript');
|
|
expect(writes).toHaveLength(2);
|
|
});
|
|
|
|
test('offers one Linux command for x86-64 and ARM64 and keeps the code outside both installer commands', async ({ page }) => {
|
|
const token = 'f'.repeat(64), api = '/api/v1/tenants/' + tenantId;
|
|
const requests: 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: { ...auth, permissions: [...auth.permissions, 'devices:enroll'] } }));
|
|
await page.route(origin + '/api/v1/**', r => {
|
|
const req = r.request(), url = new URL(req.url());
|
|
if (req.method() !== 'GET') requests.push(url.pathname);
|
|
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing(auth.tenants) });
|
|
if (url.pathname === api + '/enrollment-tokens') return r.fulfill({ json: {
|
|
token, expires_at: new Date(Date.now() + 900000).toISOString(), bootstrap_origin: 'https://bootstrap.example',
|
|
release_platforms: ['x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu', 'x86_64-pc-windows-gnu']
|
|
} });
|
|
return r.fulfill({ json: { ...listing([]), pending_count: 0 } });
|
|
});
|
|
await page.goto(origin + '/#verwaltung/aufnahme');
|
|
const enroll = page.getByRole('region', { name: 'Gerät aufnehmen' });
|
|
const option = enroll.getByRole('checkbox', { name: /Administratorskripte/ });
|
|
await expect(option).not.toBeChecked();
|
|
await enroll.getByRole('button', { name: 'Einmalcode erstellen' }).click();
|
|
await expect(enroll.getByRole('heading', { name: 'Linux (x86-64 und ARM64)' })).toBeVisible();
|
|
const commands = enroll.locator('pre');
|
|
await expect(commands).toHaveCount(2);
|
|
expect((await commands.allTextContents()).join(' ')).not.toMatch(/enable-admin-scripts|EnableAdministratorScripts/);
|
|
await option.check();
|
|
await expect(commands.nth(0)).toContainText('--enable-admin-scripts');
|
|
await expect(commands.nth(1)).toContainText('-EnableAdministratorScripts');
|
|
await expect(enroll.getByText(/Für jeden Auftrag gelten zusätzlich/)).toBeVisible();
|
|
expect((await commands.allTextContents()).join(' ')).not.toContain(token);
|
|
expect(requests).toEqual([api + '/enrollment-tokens']);
|
|
});
|
|
|
|
test('keeps an old pending device action readable and prevents approval', async ({ page }) => {
|
|
const golden = JSON.parse(readFileSync(resolve(__dirname, '../script_console/codec-golden.json'), 'utf8'));
|
|
const fixed = JSON.parse(Buffer.from(golden[0].plan_payload_bytes).toString('utf8'));
|
|
fixed.plan_id = randomUUID();
|
|
fixed.tenant_id = tenantId;
|
|
const job = fixed.jobs[0];
|
|
const end = new Date(Date.now() + 600000).toISOString();
|
|
job.payload = { ...job.payload, tenant_id: tenantId, asset_id: linux.asset_id, agent_id: linux.agent_id,
|
|
action: { action: 'refresh_inventory', scope: 'linux.base' }, execution_identity: 'agent_service', start_before: end };
|
|
delete job.script_sha256;
|
|
job.job_payload_hash = hash(JSON.stringify(job.payload));
|
|
const bytes = JSON.stringify(fixed);
|
|
const plan = { plan_id: fixed.plan_id, plan_hash: hash(bytes), plan_payload_bytes: [...Buffer.from(bytes)],
|
|
plan_payload: fixed, jobs: fixed.jobs, targets: [linux], resolved_targets: [{ asset_id: linux.asset_id, agent_id: linux.agent_id }],
|
|
excluded_targets: [], expires_at: end, approval_state: 'pending_approval' };
|
|
const writes: 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: { ...auth, permissions: [...auth.permissions, 'plans:approve'] } }));
|
|
await page.route(origin + '/api/v1/**', r => {
|
|
const url = new URL(r.request().url());
|
|
if (r.request().method() !== 'GET') writes.push(url.pathname);
|
|
if (url.pathname.endsWith('/operation-plans/' + fixed.plan_id)) return r.fulfill({ json: plan });
|
|
if (url.pathname === '/api/v1/tenants') return r.fulfill({ json: listing(auth.tenants) });
|
|
return r.fulfill({ json: { ...listing([]), pending_count: 0 } });
|
|
});
|
|
await page.goto(origin + '/#genehmigungen/pruefen/' + tenantId + '/' + fixed.plan_id);
|
|
await expect(page.locator('.review-targets').getByText('test-linux', { exact: true })).toBeVisible();
|
|
await expect(page.getByRole('alert')).toHaveText(/frühere Aktionsart/);
|
|
await page.getByRole('checkbox', { name: /Ich habe die Geräte/ }).check();
|
|
await expect(page.getByRole('button', { name: 'SIMULIERT: Genehmigen' })).toBeDisabled();
|
|
await expect(page.getByRole('button', { name: 'SIMULIERT: Ablehnen' })).toBeEnabled();
|
|
expect(writes).toEqual([]);
|
|
});
|
|
|
|
test('shows the bound script text alongside single and per-device results', 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 golden = JSON.parse(readFileSync(resolve(__dirname, '../script_console/codec-golden.json'), 'utf8')) as
|
|
{ name: string; plan_payload_bytes: number[] }[];
|
|
const [linuxPlan, windowsPlan] = ['legacy_linux_agent', 'windows_system_full'].map(name => {
|
|
const fixture = golden.find(row => row.name === name);
|
|
if (!fixture) throw new Error('Missing script fixture: ' + name);
|
|
return JSON.parse(Buffer.from(fixture.plan_payload_bytes).toString('utf8'));
|
|
});
|
|
const boundJobs = [linuxPlan, windowsPlan].map(({ jobs: [job] }, index) => {
|
|
const { asset_id, agent_id, job_id, attempt_id } = jobs[index]!;
|
|
const payload = { ...job.payload, tenant_id: tenantId, asset_id, agent_id, job_id, attempt_id };
|
|
return { ...job, payload, job_payload_hash: hash(JSON.stringify(payload)) };
|
|
});
|
|
const views = [operationId, multiOperationId].map((id, index) => {
|
|
const planJobs = index === 0 ? boundJobs.slice(0, 1) : boundJobs;
|
|
const plan = { ...linuxPlan, plan_id: randomUUID(), tenant_id: tenantId, jobs: planJobs };
|
|
if (!index) plan.script_revision = {
|
|
revision_id: randomUUID(), name: script.name, version: 2, script_sha256: planJobs[0]!.script_sha256
|
|
};
|
|
const raw = JSON.stringify(plan);
|
|
return { operation_id: id, plan_id: plan.plan_id, plan_hash: hash(raw),
|
|
plan_payload: plan, plan_payload_bytes: [...Buffer.from(raw)] };
|
|
});
|
|
const api = '/api/v1/tenants/' + tenantId;
|
|
const resultReads = new Set<string>();
|
|
let mismatchedPlan = false;
|
|
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);
|
|
const view = views.find(item => item.operation_id === id);
|
|
if (id === operationId || id === multiOperationId) return r.fulfill({ json: {
|
|
operation_id: id, customer_name: 'Nord', title: script.name, action: 'run_script', approval_state: 'approved',
|
|
plan_id: view?.plan_id, plan_hash: view?.plan_hash,
|
|
execution_state: id === operationId ? 'succeeded' : 'partially_succeeded',
|
|
targets: id === operationId ? [linux] : [linux, windows],
|
|
jobs: id === operationId ? jobs.slice(0, 1) : jobs
|
|
} });
|
|
}
|
|
const plan = views.find(view => pathname === api + '/operation-plans/' + view.plan_id);
|
|
if (plan) return r.fulfill({ json: mismatchedPlan ? { ...plan, operation_id: randomUUID() } : plan });
|
|
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();
|
|
const source = page.getByRole('article', { name: 'Skriptinhalt' });
|
|
await expect(source.getByLabel('Gespeicherter Skripttext')).toHaveText(boundJobs[0]!.payload.action.script_utf8.trim());
|
|
await expect(source.getByText('Version 2 · posix_sh')).toBeVisible();
|
|
expect([...resultReads]).toEqual(jobs.slice(0, 1).map(job => job.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();
|
|
await expect(source.getByRole('heading', { name: 'test-linux' })).toBeVisible();
|
|
await expect(source.getByRole('heading', { name: 'test-windows' })).toBeVisible();
|
|
await expect(source.getByLabel('Gespeicherter Skripttext')).toHaveText(boundJobs.map(job => job.payload.action.script_utf8.trim()));
|
|
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);
|
|
resultReads.clear();
|
|
await openOrder(multiOperationId + '/' + jobs[1]!.job_id);
|
|
await expect(page.getByRole('heading', { name: 'Ergebnis für test-windows' })).toBeVisible();
|
|
await expect(page.getByLabel('stderr Textansicht')).toHaveText('Fehler auf Windows');
|
|
expect([...resultReads]).toEqual([jobs[1]!.job_id]);
|
|
resultReads.clear();
|
|
await openOrder(multiOperationId + '/' + randomUUID());
|
|
await expect(page.getByRole('alert')).toContainText('gehört nicht zu diesem Auftrag');
|
|
expect(resultReads.size).toBe(0);
|
|
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390);
|
|
mismatchedPlan = true;
|
|
await page.reload();
|
|
await expect(source.getByRole('alert')).toContainText('konnte diesem Auftrag nicht zugeordnet werden');
|
|
await expect(source.getByLabel('Gespeicherter Skripttext')).toHaveCount(0);
|
|
});
|
|
|
|
for (const scenario of ['library', 'once', 'restart'] as const) {
|
|
const library = scenario !== 'once';
|
|
const restart = scenario === 'restart';
|
|
const revision = restart ? { ...script, name: 'Linux neu starten', execution_identity: 'root', script_utf8: "printf 'Neustart-Test\n'\n" } : script;
|
|
const session = restart ? { ...auth, permissions: [...auth.permissions, 'root:execute'] } : auth;
|
|
const title = {
|
|
library: 'pins a revision, blocks an incompatible target and finds the submitted order after a lost response',
|
|
once: 'submits a one-time script without publishing a library revision',
|
|
restart: 'submits the versioned Linux restart through the ordinary script plan with root identity'
|
|
}[scenario];
|
|
test(title,
|
|
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(session)},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([{ ...revision, script_sha256: hash(revision.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/' + revision.revision_id + '/plan' : '/operation-plans')) {
|
|
expect(body.targets.asset_ids).toEqual([linux.asset_id]);
|
|
expect(body.reason).toBe('Abnahme');
|
|
const content = library ? revision.script_utf8 : body.parameters.variants[0].script_utf8;
|
|
const action = {
|
|
action: 'run_script',
|
|
interpreter: 'posix_sh',
|
|
script_utf8: content,
|
|
arguments: [],
|
|
expected_stdout: null,
|
|
...(restart ? { privileged_script_profile: 'full_maintenance_v1' } : {})
|
|
};
|
|
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: revision.execution_identity,
|
|
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: revision.revision_id,
|
|
name: revision.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(revision.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();
|
|
if (restart) {
|
|
await page.getByRole('button', { name: 'Neustartskript auswählen' }).click();
|
|
await expect(page.getByRole('combobox', { name: 'Ausführen als', exact: true })).toHaveValue('root');
|
|
}
|
|
} 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/' + revision.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 otherScripts = [
|
|
{ ...revisions[0], revision_id: randomUUID(), name: 'Windows Übersicht', interpreter: 'powershell' },
|
|
{ ...revisions[0], revision_id: randomUUID(), name: 'Linux Übersicht', interpreter: 'bash' }
|
|
];
|
|
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';
|
|
const url = new URL(req.url());
|
|
expect(url.pathname).toBe(path);
|
|
if (req.method() === 'GET') return r.fulfill({ json: url.searchParams.has('cursor')
|
|
? listing(otherScripts)
|
|
: { ...listing(revisions), next_cursor: 'second-page' } });
|
|
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');
|
|
const library = page.getByRole('region', { name: 'Skriptbibliothek' });
|
|
await library.getByLabel('Plattform', { exact: true }).selectOption('windows');
|
|
await library.getByRole('searchbox', { name: 'Skriptname' }).fill(' ÜBERSICHT ');
|
|
await expect(library.locator('tbody tr')).toHaveCount(1);
|
|
await expect(library.locator('tbody tr')).toContainText('Windows Übersicht');
|
|
await library.getByLabel('Plattform', { exact: true }).selectOption('linux');
|
|
await expect(library.locator('tbody tr')).toContainText('Linux Übersicht');
|
|
await library.getByRole('searchbox', { name: 'Skriptname' }).fill('ohne Treffer');
|
|
await expect(library.getByText('Keine Skripte passen zu den Filtern.')).toBeVisible();
|
|
await library.getByRole('button', { name: 'Filter zurücksetzen' }).click();
|
|
await expect(library.locator('tbody tr')).toHaveCount(3);
|
|
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);
|
|
});
|