69 lines
6.7 KiB
TypeScript
69 lines
6.7 KiB
TypeScript
import { readFileSync } from 'node:fs';
|
|
import { expect, it, vi } from 'vitest';
|
|
import { renderToStaticMarkup } from 'react-dom/server';
|
|
import { PlanInput, record, RecordValue, Session, validateInput } from './api';
|
|
import { sha256, validateSensitiveInput, verifyPlanIntegrity } from './safety';
|
|
import { verifyScriptPlan } from './script-console';
|
|
import { agentUpdateApprovalBlockers, agentUpdatePlanJobs, verifyAgentUpdatePlan, uploadAgentUpdateArtifact } from './agent-updates';
|
|
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
|
|
// Actual rmm-domain serde/codec output; synthetic signatures are NOT update trust.
|
|
const golden = JSON.parse(readFileSync(new URL('../../tests/agent_update/codec-golden.json', import.meta.url), 'utf8')) as Record<string, RecordValue>;
|
|
const fixture = (name = 'linux_full') => structuredClone(golden[name]!) as RecordValue;
|
|
async function rehashed(change: (raw: RecordValue) => void): Promise<RecordValue> {
|
|
const p = fixture(), raw = record(p.payload); change(raw);
|
|
const bytes = new TextEncoder().encode(JSON.stringify(raw)); p.plan_payload_bytes = Array.from(bytes); p.plan_hash = await sha256(bytes);
|
|
p.payload = raw; p.plan_payload = structuredClone(raw); return p;
|
|
}
|
|
it('verifies actual Rust Linux General/Full and Windows code-pair plan bytes before display', async () => {
|
|
for (const name of Object.keys(golden)) {
|
|
const p = fixture(name); expect(agentUpdateApprovalBlockers(p)).not.toEqual([]);
|
|
await verifyPlanIntegrity(p); await verifyScriptPlan(p); await verifyAgentUpdatePlan(p);
|
|
const jobs = agentUpdatePlanJobs(p); expect(jobs).toHaveLength(1); expect(jobs[0]!.identity).toBe(name === 'windows_pair' ? 'system' : 'root');
|
|
expect(jobs[0]!.update.no_reboot).toBe(true); expect(agentUpdateApprovalBlockers(p)).toEqual([]);
|
|
jobs[0]!.update.no_reboot = false; expect(agentUpdatePlanJobs(p)[0]!.update.no_reboot).toBe(true);
|
|
}
|
|
});
|
|
it('rejects even rehashed missing/extra artifact authority and inconsistent displayed or changed bytes', async () => {
|
|
for (const change of [(p: RecordValue) => { (p.artifact_references as unknown[]).pop(); }, (p: RecordValue) => { (p.artifact_references as unknown[]).push(structuredClone((p.artifact_references as unknown[])[0])); }]) {
|
|
await expect(verifyAgentUpdatePlan(await rehashed(change))).rejects.toThrow('Codepaarmenge');
|
|
}
|
|
const p = fixture(); record(record((p.jobs as unknown[])[0]).payload).execution_identity = 'agent_service';
|
|
await expect(verifyAgentUpdatePlan(p)).rejects.toThrow('Zielpreview');
|
|
const q = fixture(); await verifyAgentUpdatePlan(q); q.resolved_targets = [];
|
|
expect(agentUpdateApprovalBlockers(q)).not.toEqual([]);
|
|
const during = fixture(), checking = verifyAgentUpdatePlan(during); during.plan_hash = 'f'.repeat(64); await expect(checking).rejects.toThrow();
|
|
});
|
|
it('shows all fixed update/recovery bindings without an approval or network side effect', async () => {
|
|
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
|
try {
|
|
const { AgentUpdatePlanNotice } = await import('./main'); const p = fixture();
|
|
expect(renderToStaticMarkup(<AgentUpdatePlanNotice plan={p}/>)).toContain('role="alert"');
|
|
await verifyAgentUpdatePlan(p); const job = agentUpdatePlanJobs(p)[0]!, html = renderToStaticMarkup(<AgentUpdatePlanNotice plan={p}/>);
|
|
for (const value of ['root', job.jobId, job.attemptId, job.assetId, job.jobHash, String(job.update.manifest_sha256), 'linux_general_full_v1', 'restore_exact_predecessor_once', 'keyring_sha256', 'health_public_key_hex', 'health_key_pin_sha256', '600s', '180s', 'Kein Hostneustart', 'unknown']) expect(html).toContain(value);
|
|
expect(html).not.toMatch(/<(button|input|form)\b/); expect(fetch).not.toHaveBeenCalled();
|
|
} finally { vi.unstubAllGlobals(); }
|
|
});
|
|
it('accepts only a release ID and separate update/root or update/SYSTEM rights at planning', async () => {
|
|
const input: PlanInput = { tenant_id: 'tenant', action: 'update_agent', targets: { asset_ids: ['asset'] }, parameters: { release_id: '11111111-1111-4111-8111-111111111111', execution_identity: 'root', timeout_seconds: 600, 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: 'codec only' };
|
|
const auth: Session = { principal: { id: 'unit', display_name: 'unit', simulated: true }, csrf_token: 'unit', tenants: [], permissions: ['updates:apply', 'root:execute'] };
|
|
validateInput(input); await validateSensitiveInput(input, auth);
|
|
for (const permissions of [[], ['root:execute'], ['updates:apply'], ['updates:apply', 'system:execute'], ['scripts:execute', 'root:execute']]) await expect(validateSensitiveInput(input, { ...auth, permissions })).rejects.toThrow();
|
|
for (const parameters of [{ ...input.parameters, predecessor: {} }, { ...input.parameters, execution_identity: 'agent_service' }, { ...input.parameters, timeout_seconds: 601 }, { ...input.parameters, max_output_bytes: 65537 }]) expect(() => validateInput({ ...input, parameters })).toThrow();
|
|
expect(() => validateInput({ ...input, artifact_ids: [] })).toThrow();
|
|
});
|
|
it('streams only the selected File to its same-origin descriptor and rejects conflicting receipts', async () => {
|
|
const file = new File(['abc'], 'agent-code-only'), arrayBuffer = vi.spyOn(file, 'arrayBuffer').mockRejectedValue(new Error('application must not load the full binary'));
|
|
const descriptor = { artifact_id: '11111111-1111-4111-8111-111111111111', sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', bytes: 3 };
|
|
const reply = { artifact_id: descriptor.artifact_id, sha256: descriptor.sha256, size_bytes: 3 };
|
|
const fetch = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => reply }); vi.stubGlobal('fetch', fetch);
|
|
try {
|
|
expect(await uploadAgentUpdateArtifact('tenant', descriptor, file, 'unit-csrf')).toEqual(reply);
|
|
expect(fetch).toHaveBeenCalledWith(expect.stringMatching(/^\/api\/v1\/tenants\/tenant\/agent-update-artifacts\?/), expect.objectContaining({ body: file, credentials: 'same-origin', redirect: 'error', headers: { 'Content-Type': 'application/octet-stream', 'X-CSRF-Token': 'unit-csrf' } }));
|
|
expect(arrayBuffer).not.toHaveBeenCalled();
|
|
await expect(uploadAgentUpdateArtifact('tenant', descriptor, new File(['abcd'], 'wrong-length'), 'unit-csrf')).rejects.toThrow('Dateigröße');
|
|
expect(fetch).toHaveBeenCalledTimes(1);
|
|
fetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({ ...reply, size_bytes: 4 }) });
|
|
await expect(uploadAgentUpdateArtifact('tenant', descriptor, file, 'unit-csrf')).rejects.toThrow('Importbeleg');
|
|
} finally { vi.unstubAllGlobals(); }
|
|
});
|