Files
rust-discovery/web/src/script-console.test.tsx
T
2026-11-14 16:35:11 +01:00

86 lines
8.1 KiB
TypeScript

import { readFileSync } from 'node:fs';
import { expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { fullMaintenanceScriptProfile, PlanInput, record, RecordValue, Session, validateInput } from './api';
import { sha256, validateSensitiveInput, verifyPlanIntegrity } from './safety';
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
// The same fixture is produced and checked by rmm-domain's actual Rust codec.
const golden = JSON.parse(readFileSync(new URL('../../tests/script_console/codec-golden.json', import.meta.url), 'utf8')) as RecordValue[];
function plan(name: string): RecordValue {
const fixture = golden.find(value => value.name === name); if (!fixture) throw new Error('Rust golden case missing');
const parsed = record(JSON.parse(new TextDecoder().decode(new Uint8Array(fixture.plan_payload_bytes as number[]))));
const jobs = (parsed.jobs as RecordValue[]).map(job => ({ ...structuredClone(job), ...Object.fromEntries(['asset_id', 'agent_id', 'job_id', 'attempt_id'].map(key => [key, record(job.payload)[key]])) }));
return { plan_id: parsed.plan_id, plan_hash: fixture.plan_hash, plan_payload_bytes: structuredClone(fixture.plan_payload_bytes), payload: parsed, plan_payload: structuredClone(parsed), jobs, resolved_targets: jobs.map(job => ({ asset_id: job.asset_id, agent_id: job.agent_id })), excluded_targets: [], expires_at: record(jobs[0]!.payload).start_before };
}
function first(value: RecordValue): RecordValue { return record((record(value.plan_payload).jobs as RecordValue[])[0]!.payload); }
async function changedBytes(name: string, change: (payload: RecordValue, job: RecordValue) => void): Promise<RecordValue> {
const p = plan(name), parsed = structuredClone(record(p.plan_payload)), job = (parsed.jobs as RecordValue[])[0]!;
change(record(job.payload), job);
const raw = new TextEncoder().encode(JSON.stringify(parsed));
// No aliases: still reject invalid exact bytes or their internal hashes.
return { plan_hash: await sha256(raw), plan_payload_bytes: Array.from(raw) };
}
it('projects legacy/Linux root/Windows SYSTEM from the exact shared Rust golden bytes', async () => {
for (const fixture of golden) {
const p = plan(String(fixture.name)); expect(scriptApprovalBlockers(p).length).toBeGreaterThan(0);
await verifyPlanIntegrity(p); await verifyScriptPlan(p);
const view = scriptPlanJobs(p); expect(view).toHaveLength(1);
const job = view[0]!, original = first(p), action = record(original.action);
expect(job).toMatchObject({ assetId: original.asset_id, agentId: original.agent_id, jobId: original.job_id, attemptId: original.attempt_id, script: action.script_utf8, identity: original.execution_identity, scriptHash: fixture.script_sha256, jobHash: fixture.job_payload_hash });
expect(job.privilegedProfile).toBe(fixture.name === 'legacy_linux_agent' ? 'bounded' : fullMaintenanceScriptProfile);
expect(scriptApprovalBlockers(p)).toEqual([]);
job.script = 'mutated return copy'; expect(scriptPlanJobs(p)[0]!.script).toBe(action.script_utf8);
expect(await sha256(new Uint8Array(fixture.job_payload_bytes as number[]))).toBe(fixture.job_payload_hash);
}
});
it('rejects view, byte and fixed identity/budget/profile tampering before and after display', async () => {
for (const alias of ['payload', 'plan_payload', 'jobs', 'resolved_targets']) {
const p = plan('linux_root_full'); await verifyScriptPlan(p); p[alias] = [];
expect(scriptApprovalBlockers(p).length).toBeGreaterThan(0); await expect(verifyScriptPlan(p)).rejects.toThrow('verändert');
}
const p = plan('windows_system_full'); (p.plan_payload_bytes as number[])[0] = 0;
await expect(verifyScriptPlan(p)).rejects.toThrow('Planhash');
for (const [field, value] of [['execution_identity', 'agent_service'], ['max_runtime_seconds', 121], ['max_output_bytes', 65537]] as const) {
await expect(verifyScriptPlan(await changedBytes('windows_system_full', payload => { payload[field] = value; }))).rejects.toThrow();
}
for (const profile of [null, 'unknown', {}]) await expect(verifyScriptPlan(await changedBytes('linux_root_full', payload => { record(payload.action).privileged_script_profile = profile; }))).rejects.toThrow();
await expect(verifyScriptPlan(await changedBytes('windows_system_full', payload => { delete record(payload.action).privileged_script_profile; }))).rejects.toThrow('PowerShell');
for (const key of ['job_payload_hash', 'script_sha256']) await expect(verifyScriptPlan(await changedBytes('linux_root_full', (_payload, job) => { job[key] = 'a'.repeat(64); }))).rejects.toThrow('hash');
});
it('binds every supplied alias and refuses asynchronous mutation during hashing', async () => {
const p = plan('linux_root_full');
const copy = structuredClone(p); copy.jobs = [];
await expect(verifyScriptPlan(copy)).rejects.toThrow('Zielansicht');
const q = plan('linux_root_full'), check = verifyScriptPlan(q);
q.plan_payload_bytes = [123, 125]; await expect(check).rejects.toThrow('verändert');
const hashSwap = plan('legacy_linux_agent'); await verifyScriptPlan(hashSwap); hashSwap.plan_hash = 'f'.repeat(64);
expect(() => scriptPlanJobs(hashSwap)).toThrow('unveränderten');
});
it('shows full fixed script/profile/identities before approval and has no approval or network side effects', async () => {
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
try {
const { ScriptPlanNotice } = await import('./main');
const p = plan('windows_system_full'); expect(renderToStaticMarkup(<ScriptPlanNotice plan={p}/>)).toContain('role="alert"');
await verifyPlanIntegrity(p); await verifyScriptPlan(p);
const html = renderToStaticMarkup(<ScriptPlanNotice plan={p}/>), view = scriptPlanJobs(p)[0]!;
for (const value of ['full_maintenance_v1', 'system', 'powershell', 'RemoteSigned', 'SYSTEM stdout', 'SYSTEM stderr', '\\u000d', view.assetId, view.jobId, view.attemptId, view.scriptHash, view.jobHash, '30s', '4096', 'Keine Sandbox- oder No-Reboot-Zusage', 'Agent, PKI']) expect(html).toContain(value);
expect(html).not.toMatch(/<(button|input|form)\b/); expect(fetch).not.toHaveBeenCalled();
} finally { vi.unstubAllGlobals(); }
});
it('requires separate script/root/SYSTEM scopes and an explicit correctly placed profile at planning', async () => {
const input: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'system', privileged_script_profile: fullMaintenanceScriptProfile, variants: [{ os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: 'Write-Output 1\r\n', windows_execution_profile: 'powershell_51_remote_signed' }], arguments: [], expected_stdout: null, timeout_seconds: 120, max_output_bytes: 65536 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'unit only, no native execution' };
const auth: Session = { principal: { id: 'simulated', display_name: 'SIMULIERT', simulated: true }, csrf_token: 'unit', tenants: [], permissions: ['scripts:execute', 'system:execute'] };
validateInput(input); await validateSensitiveInput(input, auth);
for (const permissions of [[], ['system:execute'], ['scripts:execute', 'root:execute']]) await expect(validateSensitiveInput(input, { ...auth, permissions })).rejects.toThrow();
for (const profile of [null, 'other', {}]) expect(() => validateInput({ ...input, parameters: { ...input.parameters, privileged_script_profile: profile } })).toThrow();
expect(() => validateInput({ ...input, parameters: { ...input.parameters, privileged_script_profile: undefined } })).toThrow();
for (const parameters of [{ ...input.parameters, timeout_seconds: 121 }, { ...input.parameters, max_output_bytes: 65537 }, { ...input.parameters, execution_identity: 'agent_service' }, { ...input.parameters, execution_identity: 'root' }]) expect(() => validateInput({ ...input, parameters })).toThrow();
});