import { test, expect } from '../../web/node_modules/@playwright/test/index.js'; import { readFileSync, lstatSync, writeFileSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; import { createHash } from 'node:crypto'; import { login } from './helpers'; function object(value: unknown): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Object required'); return value as Record; } function bytes(value: unknown): Buffer { if (!Array.isArray(value) || !value.every(n => Number.isInteger(n) && n >= 0 && n <= 255)) throw new Error('Exact byte array required'); return Buffer.from(value); } function text(value: unknown): string { if (typeof value !== 'string' || !value) throw new Error('Text required'); return value; } test('simulated human prepares root request through UI only, without approving', async ({ page }) => { test.skip(process.env.RMM_E2E_PROFILE !== 'dev/test' || process.env.RMM_E2E_MODE !== 'mvp-prepare'); const file = process.env.RMM_E2E_CASE_FILE; if (!file) throw new Error('Protected root preparation file required'); const metadata = lstatSync(file); if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.uid !== process.getuid?.() || (metadata.mode & 0o777) !== 0o600 || metadata.size > 1048576) throw new Error('Unsafe root preparation file'); const expected = object(JSON.parse(readFileSync(file, 'utf8'))); expect(expected.phase).toBe('prepare'); expect(expected.profile).toBe('dev/test'); expect(expected.expected_principal).toBe('simulated-testprincipal-a'); const request = object(expected.request), params = object(request.parameters); expect(params.execution_identity).toBe('root'); expect(object(request.targets).asset_ids).toEqual([expected.asset_id]); expect(['run_script', 'query_logs', 'set_service_state', 'apt_native_acceptance', 'ensure_package', 'apply_updates', 'reboot']).toContain(request.action); let authorizationRequests = 0; page.on('request', r => { if (new URL(r.url()).pathname.endsWith('/authorizations')) authorizationRequests++; }); const sessionResponse = page.waitForResponse(r => new URL(r.url()).pathname === '/auth/session' && r.status() === 200); await login(page); const session = object(await (await sessionResponse).json()); expect(session.testsimulation).toBe(true); expect(session.principal).toBe(expected.expected_principal); expect(session.approval_origin).toBe('dev_test_browser_simulation'); await expect(page.getByLabel('Mandant', { exact: true })).toHaveValue(text(expected.tenant_id)); await page.getByRole('checkbox', { name: `Ziel ${text(expected.asset_id)}`, exact: true }).check(); await page.getByLabel('Aktion', { exact: true }).selectOption(text(request.action)); if (request.action === 'run_script') { const variants = params.variants; if (!Array.isArray(variants) || variants.length !== 1) throw new Error('One exact script variant required'); const variant = object(variants[0]); await page.getByRole('combobox', { name: 'Interpreter', exact: true }).selectOption(text(variant.interpreter)); await page.getByLabel('Exakte UTF-8 Skriptbytes', { exact: false }).fill(text(variant.script_utf8)); await page.getByLabel('Erwartete stdout-Ausgabe', { exact: false }).fill(text(params.expected_stdout)); } else { await page.getByLabel('Aktionsparameter', { exact: true }).fill(JSON.stringify(params)); } await page.getByLabel('Ausführungsidentität', { exact: true }).selectOption('root'); await page.getByLabel('Laufzeitlimit (s)', { exact: true }).fill(String(params.timeout_seconds)); await page.getByLabel('Ausgabelimit (Bytes)', { exact: true }).fill(String(params.max_output_bytes)); // Runner fixes browser/Node TZ to UTC. The actual UI's minute-precision form // selects an explicit future minute; all resulting exact bytes are reviewed // again in the separate approval test before any executable job can exist. const start = new Date(Math.ceil(Date.now() / 60000) * 60000); await page.getByLabel('Frühester Start (lokale Zeit)', { exact: true }).fill(start.toISOString().slice(0, 16)); await page.getByLabel('Startfrist / Ablauf (lokale Zeit)', { exact: true }).fill(new Date(start.getTime() + 15 * 60000).toISOString().slice(0, 16)); await page.getByLabel('Maximal parallel', { exact: true }).fill('1'); await page.getByLabel('Stopp nach Fehlern', { exact: true }).fill('1'); await page.getByLabel('Begründung', { exact: true }).fill(text(request.reason)); await page.getByRole('button', { name: 'Plan erstellen · noch keine Ausführung' }).click(); const detail = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Unveränderlicher Plan / Genehmigungsdetail', exact: true }) }); await expect(detail.locator('pre[aria-label^="Alle festen Zielpreviews"]')).toBeVisible(); const plan = object(JSON.parse(await detail.locator('pre[aria-label^="Alle festen Zielpreviews"]').innerText())); expect(createHash('sha256').update(bytes(plan.plan_payload_bytes)).digest('hex')).toBe(plan.plan_hash); await detail.getByRole('button', { name: 'Antrag absenden · pending_approval' }).click(); const op = page.locator('section').filter({ has: page.getByRole('heading', { name: /^Antrag \/ Ausführung / }) }); await expect(op.locator('pre').first()).toContainText('"job_count": 0'); const operation = object(JSON.parse(await op.locator('pre').first().innerText())); expect(operation.approval_state).toBe('pending_approval'); expect(operation.execution_state).toBeNull(); expect(authorizationRequests).toBe(0); const output = resolve(text(expected.output_file)); if (dirname(output) !== dirname(resolve(file))) throw new Error('Private same-directory output required'); writeFileSync(output, JSON.stringify({ plan, operation }), { mode: 0o600, flag: 'wx' }); await page.getByRole('button', { name: 'Abmelden', exact: true }).click(); }); test('one opted-in immutable dev/test action: inspect all fixed bytes → UI click only', async ({ page }) => { test.skip(process.env.RMM_E2E_PROFILE !== 'dev/test' || process.env.RMM_E2E_MODE !== 'mvp-actions', 'Explicit dev/test simulation only'); const file = process.env.RMM_E2E_CASE_FILE; if (!file) throw new Error('Protected expected case file required'); const metadata = lstatSync(file); if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.uid !== process.getuid?.() || (metadata.mode & 0o777) !== 0o600 || metadata.size > 1048576) throw new Error('Unsafe expected case file'); const expected = object(JSON.parse(readFileSync(file, 'utf8'))); expect(expected.profile).toBe('dev/test'); expect(expected.expected_principal).toBe('simulated-testprincipal-a'); expect(['hello', 'refresh_inventory', 'query_logs', 'service_setup', 'service_start', 'service_stop', 'apt_native_install', 'apt_native_update', 'ensure_package', 'apply_updates', 'cancel_queued', 'expired_offline', 'reboot_last']).toContain(expected.case); const sessionResponse = page.waitForResponse(r => new URL(r.url()).pathname === '/auth/session' && r.status() === 200); await login(page); const session = object(await (await sessionResponse).json()); expect(session.testsimulation).toBe(true); expect(session.approval_origin).toBe('dev_test_browser_simulation'); expect(session.principal).toBe(expected.expected_principal); await expect(page.getByLabel('Mandant', { exact: true })).toHaveValue(text(expected.tenant_id)); const operation = text(expected.operation_id); await page.getByRole('button', { name: operation, exact: true }).click(); const op = page.locator('section').filter({ has: page.getByRole('heading', { name: `Antrag / Ausführung ${operation}`, exact: true }) }); await expect(op.locator('p.warning')).toContainText('Antrag: pending_approval'); await expect(op.locator('pre').first()).toContainText('"job_count": 0'); await expect(op.locator('pre').first()).toContainText('"execution_state": null'); await op.getByRole('button', { name: 'Unveränderlichen Plan zur Prüfung öffnen' }).click(); const detail = page.locator('section').filter({ has: page.getByRole('heading', { name: 'Unveränderlicher Plan / Genehmigungsdetail', exact: true }) }); await expect(detail.locator('pre[aria-label^="Alle festen Zielpreviews"]')).toBeVisible(); const plan = object(JSON.parse(await detail.locator('pre[aria-label^="Alle festen Zielpreviews"]').innerText())); expect(plan.plan_hash).toBe(expected.plan_hash); expect(bytes(plan.plan_payload_bytes)).toEqual(bytes(expected.plan_payload_bytes)); expect(createHash('sha256').update(bytes(plan.plan_payload_bytes)).digest('hex')).toBe(expected.plan_hash); const targets = plan.resolved_targets; const jobs = plan.jobs; if (!Array.isArray(targets) || !Array.isArray(jobs) || targets.length !== 1 || jobs.length !== 1) throw new Error('Exactly one fixed VM target/job required'); expect(object(targets[0])).toEqual({ agent_id: expected.agent_id, asset_id: expected.asset_id }); const job = object(jobs[0]); const payload = object(job.payload); expect(payload).toEqual(expected.job_payload); expect(job.job_payload_hash).toBe(expected.job_payload_hash); expect(payload.tenant_id).toBe(expected.tenant_id); expect(payload.agent_id).toBe(expected.agent_id); expect(payload.asset_id).toBe(expected.asset_id); expect(Number.isInteger(payload.enrollment_generation) && Number(payload.enrollment_generation) > 0).toBe(true); expect(Number.isInteger(payload.assignment_version) && Number(payload.assignment_version) > 0).toBe(true); expect(Date.parse(text(payload.start_before))).toBeGreaterThan(Date.now()); expect(Number(payload.max_output_bytes)).toBeLessThanOrEqual(65536); const action = object(payload.action); if (expected.case === 'hello' || expected.case === 'cancel_queued' || expected.case === 'expired_offline') { expect(payload.execution_identity).toBe('agent_service'); expect(action).toEqual({ action: 'run_script', interpreter: 'posix_sh', script_utf8: "printf '%s\\n' 'Hello World'\n", arguments: [], expected_stdout: 'Hello World\n' }); } else if (expected.case === 'service_setup') { expect(payload.execution_identity).toBe('root'); expect(action.action).toBe('run_script'); expect(action.interpreter).toBe('posix_sh'); expect(action.arguments).toEqual([]); expect(action.expected_stdout).toBe('RMM test unit prepared\n'); expect(createHash('sha256').update(text(action.script_utf8)).digest('hex')).toBe('3e299e84021beaa4cbdce6fa63eda193f6f123aba86368890fe20684c43e78ae'); expect(payload.max_runtime_seconds).toBe(60); } else if (expected.case === 'refresh_inventory') { expect(payload.execution_identity).toBe('agent_service'); expect(action).toEqual({ action: 'refresh_inventory', scope: 'linux.base' }); } else if (expected.case === 'query_logs') { // A cloud root log check must keep its explicit helper/policy-bound identity. expect(payload.execution_identity).toBe(object(expected.job_payload).execution_identity); expect(['agent_service', 'root']).toContain(payload.execution_identity); expect(action.action).toBe('query_logs'); expect(action.unit).toBe('rmm-mvp-test.service'); expect(action.max_lines).toBe(50); expect(Date.parse(text(action.until)) - Date.parse(text(action.since))).toBe(300000); } else if (['apt_native_install', 'apt_native_update', 'ensure_package', 'apply_updates'].includes(text(expected.case))) { expect(payload.execution_identity).toBe('root'); const native = expected.case === 'apt_native_install' || expected.case === 'apt_native_update'; const upgrade = expected.case === 'apt_native_update' || expected.case === 'apply_updates' || expected.case === 'ensure_package'; expect(action.action).toBe(native ? 'apt_native_acceptance' : expected.case); const manifest = object(action.apt_manifest); expect(manifest.type).toBe('rmm.apt.helper-action'); expect(manifest.schema_version).toBe(2); expect(manifest.action).toBe(native ? 'apt-native-acceptance' : 'apt-execute'); expect(manifest.execution_profile).toBe('dev-test'); const transaction = object(manifest.resolved_apt_transaction); expect(JSON.parse(bytes(manifest.transaction_bytes).toString('utf8'))).toEqual(transaction); expect(createHash('sha256').update(bytes(manifest.transaction_bytes)).digest('hex')).toBe(manifest.transaction_sha256); expect(transaction.recipe_id).toBe(upgrade ? 'rmm-apt-fixture-update-1.1' : 'rmm-apt-fixture-install-1.0'); expect(transaction.recipe_version).toBe('1'); expect(transaction.platform).toBe('ubuntu-24.04-amd64'); expect(transaction.no_reboot).toBe(true); const pin = upgrade ? 'ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af6027d8a9c00491' : '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867'; expect(transaction.packages).toEqual([{ name: 'rmm-mvp-test', architecture: 'all', old_version: upgrade ? '1.0' : null, new_version: upgrade ? '1.1' : '1.0', origin: 'rmm-test', sha256: pin, size: 20672, archive_path: `/var/lib/rmm-apt-transaction/archives/${pin}.deb` }]); for (const key of ['provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256']) expect(text(manifest[key])).toMatch(/^[a-f0-9]{64}$/); if (expected.case === 'apply_updates') { expect(action.packages).toEqual(['rmm-mvp-test']); expect(action.reboot_policy).toBe('never'); } if (expected.case === 'ensure_package') { expect(action.package).toBe('rmm-mvp-test'); expect(action.version).toBe('1.1'); } } else if (expected.case === 'reboot_last') { expect(payload.execution_identity).toBe('root'); expect(action).toEqual({ action: 'reboot', reason: 'Explicit final Linux VM dev/test acceptance', dependency_group: 'single-test-vm', reconnect_timeout_seconds: 180 }); expect(payload.max_runtime_seconds).toBe(240); } else { expect(payload.execution_identity).toBe('root'); expect(action).toEqual({ action: 'set_service_state', unit: 'rmm-mvp-test.service', state: expected.case === 'service_start' ? 'running' : 'stopped' }); expect(payload.max_runtime_seconds).toBe(180); } const approve = detail.getByRole('button', { name: 'SIMULIERT: Diesen festen Plan ausdrücklich genehmigen', exact: true }); await expect(approve).toBeDisabled(); await detail.getByRole('checkbox', { name: 'Ich habe sämtliche festen Ziele', exact: false }).check(); await expect(approve).toBeEnabled(); await approve.click(); // Deliberately no API client, injected fetch, route or direct approval request. await expect(op.locator('p.warning')).toContainText('Antrag: approved'); await expect(op.locator('pre').first()).toContainText('"job_count": 1'); await page.getByRole('button', { name: 'Abmelden', exact: true }).click(); });