Bind approved Windows PowerShell process policy and prove Linux-first contracts
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -65,6 +65,17 @@ describe('JSON contract boundary', () => {
|
||||
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('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);
|
||||
|
||||
@@ -59,6 +59,14 @@ export const pretty = (v: unknown) => JSON.stringify(v, null, 2);
|
||||
|
||||
export const actions = ['run_script', 'refresh_inventory', 'query_logs', 'set_service_state', 'ensure_package', 'apply_updates', 'reboot', 'apt_native_acceptance'] as const;
|
||||
export type Action = typeof actions[number];
|
||||
export const windowsPowerShellRemoteSignedProfile = 'powershell_51_remote_signed' as const;
|
||||
/** A missing field is inherited policy; a present field is never silently coerced. */
|
||||
export function windowsScriptProfile(value: RecordValue): 'inherited' | typeof windowsPowerShellRemoteSignedProfile {
|
||||
if (!Object.prototype.hasOwnProperty.call(value, 'windows_execution_profile')) return 'inherited';
|
||||
if (value.windows_execution_profile !== windowsPowerShellRemoteSignedProfile || value.interpreter !== 'powershell'
|
||||
|| (value.os_family !== undefined && value.os_family !== 'windows')) throw new Error('Windows-Ausführungsprofil nur powershell_51_remote_signed für Windows PowerShell5.1');
|
||||
return windowsPowerShellRemoteSignedProfile;
|
||||
}
|
||||
export interface PlanInput { tenant_id: string; action: Action; targets: { asset_ids: string[] }; parameters: RecordValue; artifact_ids?: string[]; schedule: { not_before: string; start_before: string; offline_policy: 'wait_until_deadline' }; rollout: { max_parallel: number; halt_after_failures: number }; reason: string }
|
||||
/** Decode explicit escaped CRLF before planning; never alter approved output bytes. */
|
||||
export function expectedStdout(value: string, format: string): string | null {
|
||||
@@ -68,6 +76,7 @@ export function expectedStdout(value: string, format: string): string | null {
|
||||
return output;
|
||||
}
|
||||
export function validateInput(input: PlanInput): void {
|
||||
if (Object.prototype.hasOwnProperty.call(input.parameters, 'windows_execution_profile')) throw new Error('Windows-Ausführungsprofil muss an der festen Windows-Skriptvariante stehen');
|
||||
if (!input.targets.asset_ids.length || new Set(input.targets.asset_ids).size !== input.targets.asset_ids.length) throw new Error('Feste eindeutige Ziele erforderlich');
|
||||
if (!input.reason.trim()) throw new Error('Begründung erforderlich');
|
||||
const start = Date.parse(input.schedule.not_before), end = Date.parse(input.schedule.start_before);
|
||||
@@ -77,6 +86,7 @@ export function validateInput(input: PlanInput): void {
|
||||
const variants = input.parameters.variants;
|
||||
if (!Array.isArray(variants) || !variants.length || variants.length > 2 || !variants.every(v => {
|
||||
const variant = record(v), script = typeof variant.script_utf8 === 'string' ? variant.script_utf8 : '';
|
||||
windowsScriptProfile(variant);
|
||||
const bytes = new TextEncoder().encode(script).length;
|
||||
const platform = variant.os_family === 'linux' && ['posix_sh', 'bash'].includes(String(variant.interpreter))
|
||||
|| variant.os_family === 'windows' && variant.interpreter === 'powershell';
|
||||
|
||||
@@ -1,9 +1,27 @@
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { sha256, verifyPlanIntegrity } from './safety';
|
||||
|
||||
// Import the actual renderer without mounting the application's network effects.
|
||||
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
|
||||
|
||||
it('shows the verified PowerShell process profile before approval without issuing requests', async () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
||||
try {
|
||||
const { PowerShellPlanNotice } = await import('./main');
|
||||
const payload = { jobs: [{ payload: { asset_id: 'fixed-windows', execution_identity: 'agent_service', action: { action: 'run_script', interpreter: 'powershell', script_utf8: 'Write-Output 1\r\n', arguments: [], expected_stdout: '1\r\n', windows_execution_profile: 'powershell_51_remote_signed' } } }] };
|
||||
const raw = new TextEncoder().encode(JSON.stringify(payload)), plan = { plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), plan_payload: payload };
|
||||
expect(renderToStaticMarkup(<PowerShellPlanNotice plan={plan}/>)).toContain('role="alert"');
|
||||
await verifyPlanIntegrity(plan);
|
||||
const html = renderToStaticMarkup(<PowerShellPlanNotice plan={plan}/>);
|
||||
for (const expected of ['fixed-windows', 'Windows PowerShell5.1', 'RemoteSigned', 'nur Jobprozess', 'angeforderte Option']) expect(html).toContain(expected);
|
||||
expect(html).not.toMatch(/<(button|input|form)\b/);
|
||||
plan.plan_payload_bytes[0] = 0;
|
||||
expect(renderToStaticMarkup(<PowerShellPlanNotice plan={plan}/>)).toContain('role="alert"');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
|
||||
it('renders hostile log content only as text, without executable nodes, approval controls or requests', async () => {
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
|
||||
+14
-6
@@ -1,9 +1,9 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput } from './api';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile } from './api';
|
||||
import './style.css';
|
||||
import { AdminControl, Catalog, TenantControls } from './management';
|
||||
import { allowed, availableActions, parseStrictJson, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity } from './safety';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity } from './safety';
|
||||
import { Login } from './login';
|
||||
|
||||
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
|
||||
@@ -15,6 +15,13 @@ export function SystemPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste SYSTEM-Dienstaktionen"><p>{systemWarning}</p><ul>{jobs.map((payload, i) => { const action = record(payload.action); return <li key={i}>Identität: system · Asset: {String(payload.asset_id)} · Dienst: {String(action.unit)} · Zielzustand: {String(action.state)}</li>; })}</ul><p>Diese Definitionen stammen aus den gespeicherten Planbytes; die vollständigen Zielpayloads und Hashes stehen darunter.</p></aside>;
|
||||
}
|
||||
export function PowerShellPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = powerShellPlanJobs(plan);
|
||||
if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste PowerShell-Prozessprofile"><p>Diese Ausführungsoptionen sind an die hashgeprüften gespeicherten Planbytes gebunden.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Windows PowerShell5.1 · agent_service · {job.profile === windowsPowerShellRemoteSignedProfile ? 'RemoteSigned · nur Jobprozess' : 'Geerbte Richtlinie · kein ExecutionPolicy-Prozessparameter'}</li>)}</ul><p>Keine Maschinen-/CurrentUser-/GPO-Änderung durch den Executor. GPO-Vorgaben bleiben wirksam; die angeforderte Option ist kein Nachweis der effektiven Policy.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">PowerShell-Planprofil ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
function ErrorBox({ error }: { error: string | null }) { return error ? <div role="alert" className="error">{error}</div> : null; }
|
||||
function useResource<T>(load: (signal: AbortSignal) => Promise<T>, deps: React.DependencyList, poll = false) {
|
||||
const [data, setData] = useState<T | null>(null), [error, setError] = useState<string | null>(null), [revision, setRevision] = useState(0);
|
||||
@@ -50,14 +57,14 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
|
||||
return <section><h2>Neuen unveränderlichen Plan vorbereiten</h2><p>Nur fest ausgewählte Asset-IDs. Keine Ausführung durch Planung oder Antrag; jede Aktion einschließlich Live-Inventar benötigt Genehmigung.</p>
|
||||
<form onSubmit={async e => { e.preventDefault(); setBusy(true); setError(null); const f = new FormData(e.currentTarget); try {
|
||||
const common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')) };
|
||||
const params = action === 'run_script' ? { ...common, variants: scriptPlatform === 'mixed' ? parseStrictJson(mixedVariants) : [{ os_family: scriptPlatform, interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')) }], arguments: [], expected_stdout: expectedStdout(String(f.get('expected')), String(f.get('expected_format'))) } : { ...record(parseStrictJson(parameters)), ...common };
|
||||
const params = action === 'run_script' ? { ...common, variants: scriptPlatform === 'mixed' ? parseStrictJson(mixedVariants) : [{ os_family: scriptPlatform, interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')), ...(scriptPlatform === 'windows' ? { windows_execution_profile: windowsPowerShellRemoteSignedProfile } : {}) }], arguments: [], expected_stdout: expectedStdout(String(f.get('expected')), String(f.get('expected_format'))) } : { ...record(parseStrictJson(parameters)), ...common };
|
||||
const input: PlanInput = { tenant_id: tenantId, action, targets: { asset_ids: [...selected] }, parameters: params, schedule: { not_before: new Date(String(f.get('not_before'))).toISOString(), start_before: new Date(String(f.get('expires'))).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: Number(f.get('parallel')), halt_after_failures: Number(f.get('failures')) }, reason: String(f.get('reason')) };
|
||||
const ids = String(f.get('artifact_ids') ?? '').split(/[\s,]+/).filter(Boolean); if (ids.length) { if (ids.length > 16 || new Set(ids).size !== ids.length || ids.some(id => !/^[0-9a-f-]{36}$/i.test(id))) throw new Error('Maximal 16 eindeutige feste Artefakt-UUIDs'); input.artifact_ids = ids; }
|
||||
validateInput(input); await validateSensitiveInput(input, auth); const plan = record(await request(tenantPath(tenantId, '/operation-plans'), { body: input, csrf: auth.csrf_token })); showPlan(objectId(plan, 'plan'));
|
||||
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
|
||||
<label>Aktion<select aria-label="Aktion" value={action} onChange={e => { const next = availableActions(auth, actions).find(a => a === e.target.value); if (next) { setAction(next); setParameters(pretty(initialParameters[next])); } }}>{availableActions(auth, actions).map(a => <option key={a} value={a}>{a}</option>)}</select></label>
|
||||
{action === 'apt_native_acceptance' && <p className="warning">NUR SIMULIERTE DEV/TEST-NATIVABNAHME. In Vorbereitung; Backend/Helper/Scope müssen diese eigene Aktion unterstützen. Nur rmm-apt-fixture-install-1.0 oder rmm-apt-fixture-update-1.1, Rezeptversion 1, vollständiges Schema-2-Manifest. null/Platzhalter sind nicht konfiguriert, keine Produktionsaktion, keine automatische Ausführung.</p>}
|
||||
{action === 'run_script' ? <><label>Skriptplattform<select aria-label="Skriptplattform" value={scriptPlatform} onChange={e => setScriptPlatform(e.target.value)}><option value="linux">Linux</option><option value="windows">Windows</option><option value="mixed">Linux und Windows · feste Varianten</option></select></label>{scriptPlatform === 'mixed' ? <label>Exakte Plattformvarianten (JSON)<textarea aria-label="Skriptvarianten" value={mixedVariants} onChange={e => setMixedVariants(e.target.value)} rows={9} spellCheck={false}/></label> : <><label>Interpreter<select name="interpreter" key={scriptPlatform}>{scriptPlatform === 'windows' ? <option value="powershell">powershell · Windows PowerShell 5.1</option> : <><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></>}</select></label><label>Exakte UTF-8 Skriptbytes (keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label></>}<label>Format der stdout-Nachbedingung<select name="expected_format" aria-label="Format der stdout-Nachbedingung"><option value="text">Text · Linux-Default</option><option value="json">JSON-String · explizite CRLF mit \r\n</option></select></label><label>Erwartete stdout-Ausgabe (exakte Rohbytes als UTF-8, optional)<textarea name="expected" rows={2} spellCheck={false}/></label>{scriptPlatform !== 'linux' && <p>PowerShell5.1: -NoLogo -NoProfile -NonInteractive; keine ExecutionPolicy-Umgehung. Nicht-ASCII benötigt ein ausdrücklich enthaltenes UTF-8-BOM vor Hashbildung. Skriptbytes und Ausgabe werden nicht normalisiert. Fehlende Plattform-/Interpreter-/Sync-Capability sperrt den ganzen Plan; kein stiller Zielausschluss.</p>}</> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
|
||||
{action === 'run_script' ? <><label>Skriptplattform<select aria-label="Skriptplattform" value={scriptPlatform} onChange={e => setScriptPlatform(e.target.value)}><option value="linux">Linux</option><option value="windows">Windows</option><option value="mixed">Linux und Windows · feste Varianten</option></select></label>{scriptPlatform === 'mixed' ? <label>Exakte Plattformvarianten (JSON)<textarea aria-label="Skriptvarianten" value={mixedVariants} onChange={e => setMixedVariants(e.target.value)} rows={9} spellCheck={false}/></label> : <><label>Interpreter<select name="interpreter" key={scriptPlatform}>{scriptPlatform === 'windows' ? <option value="powershell">powershell · Windows PowerShell 5.1</option> : <><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></>}</select></label><label>Exakte UTF-8 Skriptbytes (keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label></>}<label>Format der stdout-Nachbedingung<select name="expected_format" aria-label="Format der stdout-Nachbedingung"><option value="text">Text · Linux-Default</option><option value="json">JSON-String · explizite CRLF mit \r\n</option></select></label><label>Erwartete stdout-Ausgabe (exakte Rohbytes als UTF-8, optional)<textarea name="expected" rows={2} spellCheck={false}/></label>{scriptPlatform !== 'linux' && <p>PowerShell5.1: -NoLogo -NoProfile -NonInteractive. Einzelne neue Windowspläne binden fest RemoteSigned nur für den Jobprozess. Bei gemischten Varianten ist powershell_51_remote_signed ausdrücklich an der Windowsvariante zu setzen; fehlendes Profil bleibt geerbt. Jede tatsächliche Prozessoption steht vor Genehmigung je Ziel im festen Plan. Nicht-ASCII benötigt ein ausdrücklich enthaltenes UTF-8-BOM vor Hashbildung. Skriptbytes und Ausgabe werden nicht normalisiert. Fehlende Plattform-/Interpreter-/Sync-Capability sperrt den ganzen Plan; kein stiller Zielausschluss.</p>}</> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
|
||||
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option><option value="system" disabled={action !== 'set_service_state' || !allowed(auth, 'system:execute')}>system · system:execute und Windows-SYSTEM-Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
|
||||
{identity === 'root' && <p className="warning">{rootWarning}</p>}
|
||||
{identity === 'system' && <p className="warning">{systemWarning}</p>}
|
||||
@@ -72,15 +79,16 @@ function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id:
|
||||
const plan = useResource(async signal => { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}`), { signal })); await verifyPlanIntegrity(result); return result; }, [tenantId, id]);
|
||||
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false), [confirmed, setConfirmed] = useState(false), [submitted, setSubmitted] = useState(false), [pending, setPending] = useState(false);
|
||||
const [idempotency] = useState(() => crypto.randomUUID());
|
||||
const blockers = plan.data ? approvalBlockers(plan.data) : ['Plan noch nicht geladen'];
|
||||
const blockers = plan.data ? [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
|
||||
return <section><h2>Unveränderlicher Plan / Genehmigungsdetail</h2><ErrorBox error={plan.error}/><ErrorBox error={error}/>{plan.data && <>
|
||||
<p>Plan-ID: {id}</p><p>Exakter gespeicherter Planhash: <code>{stringField(plan.data, 'plan_hash')}</code></p><p>Feste Ziele: {Array.isArray(plan.data.resolved_targets) ? plan.data.resolved_targets.length : 'unknown'}. Die folgenden Zielpreviews sind unveränderliche Plandefinitionen, keine ausführbaren Jobs oder angelegten Versuche. Diese entstehen erst nach Genehmigung.</p>
|
||||
<SystemPlanNotice plan={plan.data}/>
|
||||
<PowerShellPlanNotice plan={plan.data}/>
|
||||
<JsonView value={plan.data} label="Alle festen Zielpreviews, exakte Skriptinhalte/Hashes, Parameter, Rechte, Fristen, Rollout und Nachbedingungen"/>
|
||||
<p className="warning">Genehmigung bindet ausschließlich diesen unveränderlichen Plan. Kein pauschaler Retry, keine Wildcard, kein impliziter Reboot. Unbekannte Wirkung wird nicht automatisch wiederholt. Ein Exitcode allein beweist keine fachliche Wirkung.</p>
|
||||
{blockers.length > 0 && <div role="alert" className="error">Nicht genehmigungsfähig: {blockers.join('; ')}</div>}
|
||||
<button disabled={busy || !!plan.error || blockers.length > 0 || submitted} onClick={async () => { setBusy(true); setError(null); try { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/submit`), { csrf: auth.csrf_token, body: { idempotency_key: idempotency } })); setSubmitted(true); setPending((result.approval_state ?? result.state) === 'pending_approval'); onOperation(objectId(result, 'operation')); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>Antrag absenden · pending_approval</button>
|
||||
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)}/>Ich habe sämtliche festen Ziele, Aktionen, Bytes/Hashes, Zielpreviews und Auswirkungen dieses Plans geprüft.</label>
|
||||
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)}/>Ich habe sämtliche festen Ziele, Aktionen, Bytes/Hashes, Zielpreviews, Ausführungsprofile/Prozessumfänge und Auswirkungen dieses Plans geprüft.</label>
|
||||
<button className="danger" disabled={!confirmed || busy || !!plan.error || blockers.length > 0 || !(pending || plan.data.approval_state === 'pending_approval')} onClick={async () => { setBusy(true); setError(null); try {
|
||||
const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/authorizations`), { csrf: auth.csrf_token, body: { plan_hash: plan.data?.plan_hash } })); setConfirmed(false); setPending(false); onOperation(objectId(result, 'operation')); plan.reload();
|
||||
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>{auth.principal.simulated ? 'SIMULIERT: Diesen festen Plan ausdrücklich genehmigen' : 'Diesen festen Plan ausdrücklich genehmigen'}</button>
|
||||
|
||||
+36
-1
@@ -1,10 +1,45 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { actions, PlanInput, Session, request, session } from './api';
|
||||
import { adminIntent, allowed, availableActions, parseStrictJson, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { adminIntent, allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { AdminControl } from './management';
|
||||
|
||||
const auth: Session = { principal: { id: 'test', display_name: 'SIMULIERT', simulated: true }, csrf_token: 'csrf', tenants: [], permissions: ['root:execute', 'devices:revoke'] };
|
||||
describe('immutable PowerShell process profile', () => {
|
||||
async function plan(profile: unknown = 'powershell_51_remote_signed', identity = 'agent_service', interpreter = 'powershell') {
|
||||
const action = { action: 'run_script', interpreter, script_utf8: 'Write-Output 1\r\n', arguments: [], expected_stdout: '1\r\n', ...(profile === undefined ? {} : { windows_execution_profile: profile }) };
|
||||
const payload = { asset_id: 'fixed-windows', execution_identity: identity, action }, jobs = [{ asset_id: 'fixed-windows', job_payload_hash: 'a'.repeat(64), payload }];
|
||||
const plan_payload = { jobs }, raw = new TextEncoder().encode(JSON.stringify(plan_payload));
|
||||
return { plan_payload, plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs };
|
||||
}
|
||||
it('requires verified bytes, rejects all profile/view mutations and preserves inherited plans', async () => {
|
||||
const value = await plan(); expect(() => powerShellPlanJobs(value)).toThrow('nicht aus hashgeprüften');
|
||||
await verifyPlanIntegrity(value); expect(powerShellPlanJobs(value)).toEqual([{ assetId: 'fixed-windows', profile: 'powershell_51_remote_signed' }]);
|
||||
expect(powerShellApprovalBlockers(value)).toEqual([]);
|
||||
const changed = structuredClone(value); changed.jobs[0]!.payload.action.windows_execution_profile = 'Bypass';
|
||||
await expect(verifyPlanIntegrity(changed)).rejects.toThrow('widerspricht');
|
||||
const viewOnly = { ...value, jobs: [{ ...value.jobs[0]!, payload: { ...value.jobs[0]!.payload, action: { ...value.jobs[0]!.payload.action, windows_execution_profile: 'Bypass' } } }] };
|
||||
await expect(verifyPlanIntegrity(viewOnly)).rejects.toThrow('widerspricht');
|
||||
const extraAlias = { ...value, resolved_targets: value.jobs, jobs: viewOnly.jobs };
|
||||
await expect(verifyPlanIntegrity(extraAlias)).rejects.toThrow('widerspricht');
|
||||
await expect(verifyPlanIntegrity({ ...value, payloads: viewOnly.jobs })).rejects.toThrow('widerspricht');
|
||||
await expect(verifyPlanIntegrity({ ...value, payload: { jobs: viewOnly.jobs } })).rejects.toThrow('widerspricht');
|
||||
const idsOnly = { ...value, resolved_targets: ['fixed-windows'] }; await verifyPlanIntegrity(idsOnly);
|
||||
for (const alias of ['plan_payload', 'payload']) {
|
||||
const later: Record<string, unknown> = { ...value, [alias]: value.plan_payload };
|
||||
await verifyPlanIntegrity(later); later[alias] = { jobs: viewOnly.jobs };
|
||||
expect(powerShellApprovalBlockers(later).length).toBeGreaterThan(0); expect(() => powerShellPlanJobs(later)).toThrow('widerspricht');
|
||||
}
|
||||
await expect(verifyPlanIntegrity({ ...value, plan_payload_bytes: undefined })).rejects.toThrow('gespeicherte Planbytes');
|
||||
for (const profile of ['Bypass', null, {}, 'powershell_7_remote_signed']) await expect(verifyPlanIntegrity(await plan(profile))).rejects.toThrow('Windows-Ausführungsprofil');
|
||||
for (const identity of ['root', 'system']) await expect(verifyPlanIntegrity(await plan('powershell_51_remote_signed', identity))).rejects.toThrow('agent_service');
|
||||
await expect(verifyPlanIntegrity(await plan('powershell_51_remote_signed', 'agent_service', 'bash'))).rejects.toThrow();
|
||||
const inherited = await plan(undefined); delete inherited.plan_payload.jobs[0]!.payload.action.windows_execution_profile;
|
||||
const raw = new TextEncoder().encode(JSON.stringify(inherited.plan_payload)); inherited.plan_payload_bytes = Array.from(raw); inherited.plan_hash = await sha256(raw);
|
||||
await verifyPlanIntegrity(inherited); expect(powerShellPlanJobs(inherited)[0]?.profile).toBe('inherited');
|
||||
value.plan_payload_bytes[0] = 0; expect(powerShellApprovalBlockers(value).length).toBeGreaterThan(0); expect(() => powerShellPlanJobs(value)).toThrow('verändert');
|
||||
});
|
||||
});
|
||||
async function manifest(acceptance = true) {
|
||||
const transaction = { schema_version: 1, recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', platform: 'ubuntu-24.04-amd64', resolver_config_version: 'rmm-apt-local-v1', no_reboot: true, status_fingerprint: 'a'.repeat(64), baseline_sha256: 'b'.repeat(64), packages: [{ name: 'rmm-mvp-test', architecture: 'all', old_version: null, new_version: '1.0', origin: 'rmm-test', sha256: '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867', size: 20672, archive_path: '/var/lib/rmm-apt-transaction/archives/74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867.deb' }] };
|
||||
const raw = new TextEncoder().encode(JSON.stringify(transaction));
|
||||
|
||||
+90
-2
@@ -1,4 +1,4 @@
|
||||
import { Action, PlanInput, RecordValue, Session, record, text, validateSystemService } from './api';
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile } from './api';
|
||||
|
||||
export const hashPattern = /^[0-9a-f]{64}$/;
|
||||
export const rootWarning = 'HOHES RISIKO: root kann das Zielsystem verändern. Keine automatische Rechteerhöhung; eigener expliziter Plan, Scope, Helper und Genehmigung erforderlich.';
|
||||
@@ -101,7 +101,87 @@ export function systemPlanJobs(plan: RecordValue): RecordValue[] {
|
||||
if (!Array.isArray(parsed.jobs)) return [];
|
||||
return parsed.jobs.map(value => record(record(value).payload)).filter(payload => payload.execution_identity === 'system');
|
||||
}
|
||||
export interface PowerShellPlanJob { readonly assetId: string; readonly profile: 'inherited' | 'powershell_51_remote_signed' }
|
||||
// Only successful verification writes this cache. Projection is copied from the
|
||||
// verified bytes; later mutations of API views cannot change the displayed plan.
|
||||
interface VerifiedPowerShellPlan { readonly jobs: readonly PowerShellPlanJob[]; readonly planHash: unknown; readonly planBytes: readonly number[] }
|
||||
const verifiedPowerShellPlans = new WeakMap<RecordValue, VerifiedPowerShellPlan>();
|
||||
export function powerShellPlanJobs(plan: RecordValue): readonly PowerShellPlanJob[] {
|
||||
const verified = verifiedPowerShellPlans.get(plan);
|
||||
if (!verified) throw new Error('PowerShell-Plan wurde nicht aus hashgeprüften gespeicherten Bytes verifiziert');
|
||||
if (verified.planBytes.length) {
|
||||
const current = bytes(plan.plan_payload_bytes);
|
||||
if (plan.plan_hash !== verified.planHash || current.length !== verified.planBytes.length || verified.planBytes.some((value, i) => current[i] !== value)) throw new Error('PowerShell-Planbytes wurden nach Verifikation verändert');
|
||||
const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(current)));
|
||||
validatePlanAliases(plan, parsed);
|
||||
validatePowerShellViews(plan, parsed.jobs);
|
||||
} else if (scriptPayloads(planTargetPreviews(plan)).some(hasPowerShellProfile)) {
|
||||
throw new Error('PowerShell-Plan benötigt exakte gespeicherte Planbytes');
|
||||
}
|
||||
return verified.jobs.map(job => ({ ...job }));
|
||||
}
|
||||
export function powerShellApprovalBlockers(plan: RecordValue): string[] {
|
||||
try { powerShellPlanJobs(plan); return []; }
|
||||
catch (error) { return [error instanceof Error ? error.message : 'PowerShell-Profil ist nicht verifiziert']; }
|
||||
}
|
||||
function scriptPayloads(jobs: unknown): RecordValue[] {
|
||||
if (!Array.isArray(jobs)) return [];
|
||||
return jobs.flatMap(job => {
|
||||
if (!job || typeof job !== 'object') return [];
|
||||
const payload = record(job).payload;
|
||||
return payload && typeof payload === 'object' ? [record(payload)] : [];
|
||||
});
|
||||
}
|
||||
function hasPowerShellProfile(payload: RecordValue): boolean {
|
||||
if (Object.prototype.hasOwnProperty.call(payload, 'windows_execution_profile')) throw new Error('Windows-Ausführungsprofil muss Teil der festen Skriptaktion sein');
|
||||
const action = payload.action;
|
||||
return action !== null && typeof action === 'object' && (record(action).interpreter === 'powershell'
|
||||
|| Object.prototype.hasOwnProperty.call(action, 'windows_execution_profile'));
|
||||
}
|
||||
function projectPowerShellJobs(jobs: unknown): PowerShellPlanJob[] {
|
||||
return scriptPayloads(jobs).filter(hasPowerShellProfile).map(payload => {
|
||||
const action = record(payload.action);
|
||||
if (action.action !== 'run_script' || action.interpreter !== 'powershell' || payload.execution_identity !== 'agent_service') throw new Error('PowerShell-Profil benötigt Windows PowerShell5.1 als agent_service');
|
||||
exact(action, ['action', 'interpreter', 'script_utf8', 'arguments', 'expected_stdout', ...(Object.prototype.hasOwnProperty.call(action, 'windows_execution_profile') ? ['windows_execution_profile'] : [])]);
|
||||
if (typeof action.script_utf8 !== 'string' || !action.script_utf8 || new TextEncoder().encode(action.script_utf8).length > 32768 || action.script_utf8.includes('\0')
|
||||
|| (!/^[\x00-\x7f]*$/.test(action.script_utf8) && !action.script_utf8.startsWith('\ufeff'))
|
||||
|| !Array.isArray(action.arguments) || action.arguments.length > 32 || action.arguments.some(arg => typeof arg !== 'string' || new TextEncoder().encode(arg).length > 4096 || arg.includes('\0'))
|
||||
|| !(action.expected_stdout === null || (typeof action.expected_stdout === 'string' && new TextEncoder().encode(action.expected_stdout).length <= 65536))) throw new Error('Vollständige unveränderte PowerShell-Skriptaktion erforderlich');
|
||||
return { assetId: text(payload.asset_id, 'PowerShell-Zielasset'), profile: windowsScriptProfile(action) };
|
||||
});
|
||||
}
|
||||
function validatePlanAliases(plan: RecordValue, parsed: unknown): void {
|
||||
for (const alias of ['plan_payload', 'payload']) if (plan[alias] !== undefined && canonical(parsed) !== canonical(plan[alias])) throw new Error('Planansicht widerspricht gespeicherten Bytes');
|
||||
}
|
||||
function validatePowerShellViews(plan: RecordValue, rawJobs: unknown): void {
|
||||
const rawPayloads = scriptPayloads(rawJobs), views = [planTargetPreviews(plan)];
|
||||
for (const alias of ['jobs', 'payloads', 'resolved_targets']) {
|
||||
if (plan[alias] !== undefined && !Array.isArray(plan[alias])) throw new Error('PowerShell-Zielpreview ist keine vollständige Liste');
|
||||
if (Array.isArray(plan[alias])) views.push(plan[alias]);
|
||||
}
|
||||
for (const collection of new Set(views)) if (collection !== null) {
|
||||
// IDs-only target lists remain metadata. Every supplied payload-bearing
|
||||
// alias, however, must describe the same complete fixed PowerShell jobs.
|
||||
if (!collection.some(value => value !== null && typeof value === 'object' && !Array.isArray(value) && 'payload' in value)) continue;
|
||||
const viewPayloads = scriptPayloads(collection);
|
||||
for (const fixed of rawPayloads.filter(hasPowerShellProfile)) if (!viewPayloads.some(view => view.asset_id === fixed.asset_id)) throw new Error('PowerShell-Zielpreview fehlt im festen Plan');
|
||||
for (const view of viewPayloads) {
|
||||
const raw = rawPayloads.find(payload => payload.asset_id === view.asset_id);
|
||||
if ((hasPowerShellProfile(view) || (raw && hasPowerShellProfile(raw))) && (!raw || canonical(raw.action) !== canonical(view.action)
|
||||
|| raw.execution_identity !== view.execution_identity)) throw new Error('PowerShell-Zielpreview widerspricht gespeicherten Planbytes');
|
||||
}
|
||||
}
|
||||
}
|
||||
export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
verifiedPowerShellPlans.delete(plan);
|
||||
const views = planTargetPreviews(plan), hasScriptView = scriptPayloads(views).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(plan.jobs).some(hasPowerShellProfile) || scriptPayloads(plan.payloads).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(plan.resolved_targets).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(record(plan.payload ?? {}).jobs).some(hasPowerShellProfile);
|
||||
if (hasScriptView && plan.plan_payload_bytes === undefined) throw new Error('PowerShell-Plan benötigt exakte gespeicherte Planbytes');
|
||||
let powerShellJobs: PowerShellPlanJob[] = [];
|
||||
let verifiedBytes: readonly number[] = [];
|
||||
if (plan.plan_payload_bytes === undefined && Array.isArray(plan.jobs) && plan.jobs.some(value => {
|
||||
const payload = record(value).payload;
|
||||
return payload !== null && typeof payload === 'object' && record(payload).execution_identity === 'system';
|
||||
@@ -109,8 +189,15 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
if (plan.plan_payload_bytes !== undefined) {
|
||||
const exactBytes = bytes(plan.plan_payload_bytes); hash(plan.plan_hash);
|
||||
if (await sha256(exactBytes) !== plan.plan_hash) throw new Error('Planhash stimmt nicht mit gespeicherten Bytes überein');
|
||||
verifiedBytes = Array.from(exactBytes);
|
||||
const parsed = parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(exactBytes));
|
||||
if (plan.plan_payload !== undefined && canonical(parsed) !== canonical(plan.plan_payload)) throw new Error('Planansicht widerspricht gespeicherten Bytes');
|
||||
validatePlanAliases(plan, parsed);
|
||||
const rawJobs = record(parsed).jobs;
|
||||
powerShellJobs = projectPowerShellJobs(rawJobs);
|
||||
if (hasScriptView || powerShellJobs.length) {
|
||||
if (!Array.isArray(rawJobs)) throw new Error('Vollständige feste PowerShell-Zielpayloads fehlen');
|
||||
validatePowerShellViews(plan, rawJobs);
|
||||
}
|
||||
}
|
||||
for (const payload of systemPlanJobs(plan)) {
|
||||
const action = record(payload.action);
|
||||
@@ -122,6 +209,7 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
for (const value of jobs) { if (!value || typeof value !== 'object') continue; const p = record(value).payload; if (!p || typeof p !== 'object') continue; const action = record(p).action;
|
||||
if (action && typeof action === 'object' && record(action).apt_manifest !== undefined && record(action).apt_manifest !== null) await verifyAptManifest(record(action).apt_manifest, record(action).action === 'apt_native_acceptance');
|
||||
}
|
||||
verifiedPowerShellPlans.set(plan, { jobs: powerShellJobs.map(job => Object.freeze({ ...job })), planHash: plan.plan_hash, planBytes: verifiedBytes });
|
||||
}
|
||||
export function recipeInput(value: unknown): RecordValue {
|
||||
const r = record(value); exact(r, ['schema_version', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'reboot_policy']);
|
||||
|
||||
Reference in New Issue
Block a user