import { afterEach, describe, expect, it, vi } from 'vitest'; import { expectedStdout, approvalBlockers, page, PlanInput, request, session, validateInput } from './api'; afterEach(() => vi.unstubAllGlobals()); describe('JSON contract boundary', () => { it('refuses missing simulation identity metadata', () => { expect(() => session({ principal: { id: 'a', display_name: 'name' }, tenants: [], csrf_token: 'csrf' })).toThrow('Sitzungsprofil'); expect(session({ principal: { id: 'sim', display_name: 'SIMULIERT', simulated: true }, tenants: [], csrf_token: 'csrf' }).principal.simulated).toBe(true); }); it('does not present absent completeness as a complete result', () => { expect(page({ items: [], next_cursor: null }).completeness).toBe('unknown'); expect(page({ items: [], next_cursor: null }).truncated).toBe(true); expect(() => page({ devices: [] })).toThrow('items'); }); const preview = { asset_id: 'asset', job_payload_hash: 'hash', payload: { action: 'refresh_inventory', asset_id: 'asset' } }; const plan = { plan_id: 'p', plan_hash: 'hash', expires_at: new Date(Date.now() + 60000).toISOString(), resolved_targets: [preview], excluded_targets: [], plan_payload: { targets: [preview] } }; it('accepts immutable target previews without execution job or attempt IDs', () => { expect(approvalBlockers(plan)).toEqual([]); expect(approvalBlockers({ ...plan, resolved_targets: [{ ...preview, plan_target_id: 'target' }] })).toEqual([]); expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], payloads: [preview] })).toEqual([]); expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], jobs: [preview] })).toEqual([]); expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], jobs: [{ ...preview, job_id: 'reserved', attempt_id: 'reserved-attempt' }] })).toEqual([]); expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], jobs: [{ job_payload_hash: 'hash', payload: preview.payload }] })).toEqual([]); }); it('fails closed for missing, partial, malformed or contradictory previews', () => { expect(approvalBlockers({ plan_id: 'p', plan_hash: 'hash' })).toContain('Unveränderliche Zielpreviews fehlen'); for (const value of [ { ...plan, resolved_targets: [{ ...preview, job_payload_hash: '' }] }, { ...plan, resolved_targets: [{ ...preview, payload: {} }] }, { ...plan, resolved_targets: [{ ...preview, payload: null }] }, { ...plan, resolved_targets: [{ ...preview, asset_id: '' }] }, { ...plan, resolved_targets: [{ ...preview, payload: { asset_id: 'foreign' } }] }, { ...plan, resolved_targets: ['asset', 'missing'], payloads: [preview] }, { ...plan, resolved_targets: ['foreign'], payloads: [preview] }, { ...plan, resolved_targets: ['asset'], payloads: [null] }, { ...plan, resolved_targets: [null], payloads: [preview] }, { ...plan, excluded_targets: ['missing'] }, { ...plan, resolved_targets: ['asset'], payloads: 'invalid', jobs: [preview] }, { ...plan, resolved_targets: [{ ...preview, payload: null }], jobs: [preview] }, ]) expect(approvalBlockers(value).length).toBeGreaterThan(0); }); it('rejects duplicate assets in both fixed targets and preview lists', () => { expect(approvalBlockers({ ...plan, resolved_targets: [preview, preview] })).toContain('Doppelte asset_id in fester Zielmenge'); expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], payloads: [preview, preview] })).toContain('Doppelte asset_id in Zielpreviews'); expect(approvalBlockers({ ...plan, resolved_targets: ['asset', 'asset'], payloads: [preview] })).toContain('Doppelte asset_id in fester Zielmenge'); }); it('preserves script UTF-8 bytes and refuses duplicate/dynamic targets', () => { const variant = { script_utf8: 'printf hi\r\n', os_family: 'linux', encoding: 'utf-8', interpreter: 'posix_sh' }; const input: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['asset'] }, parameters: { variants: [variant], execution_identity: 'agent_service', timeout_seconds: 60, max_output_bytes: 4096 }, 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: 'test' }; validateInput(input); expect(input.parameters.variants).toEqual([variant]); expect(() => validateInput({ ...input, targets: { asset_ids: ['a', 'a'] } })).toThrow('eindeutige'); }); it('binds explicitly escaped stdout CRLF before planning and leaves text unchanged', () => { expect(expectedStdout('"Hello\\r\\n"', 'json')).toBe('Hello\r\n'); expect(expectedStdout('Hello\n', 'text')).toBe('Hello\n'); expect(expectedStdout('', 'json')).toBeNull(); expect(() => expectedStdout('{}', 'json')).toThrow(); expect(() => expectedStdout('x', 'unknown')).toThrow(); }); it('binds explicit Windows and mixed variants without normalizing script bytes', () => { const windows = { os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: "Write-Output 'hi'\r\n" }; const linux = { os_family: 'linux', interpreter: 'posix_sh', encoding: 'utf-8', script_utf8: "printf hi\n" }; const input: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['a', 'b'] }, parameters: { variants: [linux, windows], execution_identity: 'agent_service', timeout_seconds: 60, max_output_bytes: 4096 }, 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: 'fixed mixed plan' }; const original = JSON.stringify(input); validateInput(input); expect(JSON.stringify(input)).toBe(original); for (const variants of [[windows, windows], [{ ...windows, interpreter: 'pwsh' }], [{ ...windows, interpreter: 'bash' }], [{ ...windows, script_utf8: "Write-Output 'é'" }]]) expect(() => validateInput({ ...input, parameters: { ...input.parameters, variants } })).toThrow(); expect(() => validateInput({ ...input, parameters: { ...input.parameters, execution_identity: 'root' } })).toThrow('agent_service'); validateInput({ ...input, parameters: { ...input.parameters, variants: [{ ...windows, script_utf8: "\ufeffWrite-Output 'é'\r\n" }] } }); }); it('bounds the fixed Event Log source and exact 24h interval without rewriting Linux queries', () => { const base: PlanInput = { tenant_id: 't', action: 'query_logs', targets: { asset_ids: ['a'] }, parameters: { execution_identity: 'agent_service', unit: 'windows.eventlog.application.rustdiscovery-mvp-test', since: '2026-11-14T00:00:00Z', until: '2026-11-15T00:00:00Z', max_lines: 1000, timeout_seconds: 30, max_output_bytes: 4096 }, 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: 'fixed fixture logs' }; const before = JSON.stringify(base); validateInput(base); expect(JSON.stringify(base)).toBe(before); for (const change of [{ execution_identity: 'root' }, { execution_identity: 'system' }, { unit: 'windows.eventlog.security.other' }, { timeout_seconds: 9 }, { timeout_seconds: 121 }, { max_output_bytes: 1023 }, { max_output_bytes: 65537 }, { max_lines: 1001 }, { until: '2026-11-15T00:00:00.000000001Z' }]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, ...change } })).toThrow(); const linux = { ...base, parameters: { ...base.parameters, unit: 'rmm-test.service', execution_identity: 'root', timeout_seconds: 1, max_output_bytes: 512 } }; const original=JSON.stringify(linux); validateInput(linux); expect(JSON.stringify(linux)).toBe(original); expect(() => validateInput({ ...linux, parameters: { ...linux.parameters, until: '2026-11-15T00:59:00Z' } })).toThrow('24Stunden'); }); it('accepts only the fixed Windows process profile without changing inherited variants', () => { const windows = { os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: "Write-Output 'fixed'\r\n" }; const base: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['a'] }, parameters: { variants: [windows], execution_identity: 'agent_service', timeout_seconds: 30, max_output_bytes: 4096 }, 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: 'fixed profile fixture' }; const original = JSON.stringify(base); validateInput(base); expect(JSON.stringify(base)).toBe(original); const profiled = { ...windows, windows_execution_profile: 'powershell_51_remote_signed' }; validateInput({ ...base, parameters: { ...base.parameters, variants: [profiled] } }); expect(() => validateInput({ ...base, parameters: { ...base.parameters, windows_execution_profile: 'powershell_51_remote_signed' } })).toThrow('Skriptvariante'); for (const windows_execution_profile of ['Bypass', 'Unrestricted', 'RemoteSigned', 'inherited', null, {}]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, variants: [{ ...windows, windows_execution_profile }] } })).toThrow('Windows-Ausführungsprofil'); for (const variant of [{ ...profiled, os_family: 'linux' }, { ...profiled, interpreter: 'bash' }, { ...profiled, interpreter: 'pwsh' }]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, variants: [variant] } })).toThrow(); for (const execution_identity of ['root', 'system']) expect(() => validateInput({ ...base, parameters: { ...base.parameters, execution_identity, variants: [profiled] } })).toThrow('agent_service'); }); it('allows SYSTEM only for exact bounded fixture SCM parameters without changing Linux restart', () => { const input: PlanInput = { tenant_id: 't', action: 'set_service_state', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'system', unit: 'RmmDiscoveryFixtureService', state: 'running', timeout_seconds: 30, max_output_bytes: 4096 }, 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: 'fixed SCM plan' }; const before = JSON.stringify(input); validateInput(input); expect(JSON.stringify(input)).toBe(before); validateInput({ ...input, parameters: { ...input.parameters, state: 'stopped' } }); for (const parameters of [ { ...input.parameters, unit: 'Spooler' }, { ...input.parameters, unit: 'RmmDiscoveryFixture*' }, { ...input.parameters, state: 'restarted' }, { ...input.parameters, timeout_seconds: 121 }, { ...input.parameters, max_output_bytes: 65537 }, { ...input.parameters, script_utf8: 'whoami' }, { ...input.parameters, execution_identity: 'SYSTEM' }, ]) expect(() => validateInput({ ...input, parameters })).toThrow(); expect(() => validateInput({ ...input, action: 'refresh_inventory' })).toThrow('SYSTEM'); expect(() => validateInput({ ...input, action: 'run_script', parameters: { ...input.parameters, variants: [{ os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: 'whoami' }] } })).toThrow('agent_service'); validateInput({ ...input, parameters: { ...input.parameters, execution_identity: 'root', unit: 'rmm-mvp-test.service', state: 'restarted', timeout_seconds: 180 } }); }); it('accepts explicit existing dev simulation evidence but not a principal-name guess', () => { expect(session({ principal: 'sim-test', tenant_id: 't', testsimulation: true, csrf_token: 'csrf' }).principal.simulated).toBe(true); expect(() => session({ principal: 'sim-test', tenant_id: 't', csrf_token: 'csrf' })).toThrow(); }); }); describe('same-origin cookie transport', () => { it('sends CSRF and same-origin credentials, never bearer', async () => { const fetch = vi.fn().mockResolvedValue(new Response('{}', { status: 200 })); vi.stubGlobal('fetch', fetch); await request('/api/v1/test', { csrf: 'csrf', body: { plan_hash: 'exact' } }); expect(fetch).toHaveBeenCalledWith('/api/v1/test', expect.objectContaining({ method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': 'csrf' }, body: '{"plan_hash":"exact"}' })); await expect(request('//external.invalid')).rejects.toThrow('gleiche Origin'); expect(fetch).toHaveBeenCalledTimes(1); }); it('retains backend errors and correlation rather than returning fake success', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ code: 'POLICY_DENIED', message: 'denied', correlation_id: 'correlation' }), { status: 403 }))); await expect(request('/api/v1/test')).rejects.toThrow('POLICY_DENIED: denied (Korrelation correlation)'); }); });