Add versioned script library, reconcile permit refusals and compact helper captures
This commit is contained in:
+3
-1
@@ -1,3 +1,4 @@
|
||||
import { ScriptLibrary } from './script-library';
|
||||
import { CatalogCheckNotice } from './catalog-check';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
@@ -35,6 +36,7 @@ export function ScriptPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
const jobs = scriptPlanJobs(plan); if (!jobs.length) return null;
|
||||
return <article aria-label="Feste Skriptkonsole vor Genehmigung"><h3>Vollständige feste Skriptaufträge ({jobs.length})</h3><p>Diese Inhalte stammen aus den hashgeprüften gespeicherten Planbytes. Jeder Zielauftrag, Versuch und Skripthash ist fest gebunden.</p>
|
||||
{jobs.map(job => <article key={job.jobId}><h4>Asset {job.assetId}</h4><p>Agent: {job.agentId} · Job: {job.jobId} · Versuch: {job.attemptId}</p>
|
||||
{job.revision && <p>Skriptbibliothek · <strong>{job.revision.name} · Version {job.revision.version}</strong> · {job.revision.id}</p>}
|
||||
<p>Interpreter: {job.interpreter} · Identität: <strong>{job.identity}</strong> · Privilegiertes Profil: <strong>{job.privilegedProfile === fullMaintenanceScriptProfile ? fullMaintenanceScriptProfile : 'bestehendes begrenztes Profil'}</strong> · Windowsprozess: {job.interpreter !== 'powershell' ? 'nicht zutreffend' : job.windowsProfile === 'powershell_51_remote_signed' ? 'Windows PowerShell5.1 RemoteSigned, nur Jobprozess' : 'geerbte Windowsrichtlinie / kein Windows-Prozessoverride'}</p>
|
||||
<p>Frühester Start: {job.notBefore} · Startfrist: {job.startBefore} · Laufzeit: {job.runtimeSeconds}s · Ausgabe: höchstens {job.outputBytes} Bytes</p>
|
||||
<p>Skript: {job.scriptBytes} UTF-8-Bytes · SHA256: <code>{job.scriptHash}</code><br/>Jobpayload-SHA256: <code>{job.jobHash}</code></p>
|
||||
@@ -271,7 +273,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
}
|
||||
function TenantWorkspace({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||||
const [selected, setSelected] = useState<string[]>([]), [planId, setPlan] = useState<string | null>(null), [operationId, setOperation] = useState<string | null>(null);
|
||||
return <><Devices tenantId={tenantId} auth={auth} selected={selected} setSelected={setSelected}/><Planner tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Catalog tenantId={tenantId} auth={auth}/><WindowsMsiCatalog tenantId={tenantId} auth={auth}/><AgentReleaseCatalog tenantId={tenantId} auth={auth}/><TenantControls tenantId={tenantId} auth={auth}/><Operations tenantId={tenantId} open={setOperation}/>{operationId && <OperationDetail key={operationId} tenantId={tenantId} id={operationId} auth={auth} openPlan={setPlan}/ >}{planId && <PlanDetail key={planId} tenantId={tenantId} id={planId} auth={auth} onOperation={setOperation}/>}</>;
|
||||
return <><Devices tenantId={tenantId} auth={auth} selected={selected} setSelected={setSelected}/><ScriptLibrary tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Planner tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Catalog tenantId={tenantId} auth={auth}/><WindowsMsiCatalog tenantId={tenantId} auth={auth}/><AgentReleaseCatalog tenantId={tenantId} auth={auth}/><TenantControls tenantId={tenantId} auth={auth}/><Operations tenantId={tenantId} open={setOperation}/>{operationId && <OperationDetail key={operationId} tenantId={tenantId} id={operationId} auth={auth} openPlan={setPlan}/ >}{planId && <PlanDetail key={planId} tenantId={tenantId} id={planId} auth={auth} onOperation={setOperation}/>}</>;
|
||||
}
|
||||
function App() {
|
||||
const [auth, setAuth] = useState<Session | null>(null), [loading, setLoading] = useState(true), [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -37,6 +37,20 @@ it('projects legacy/Linux root/Windows SYSTEM from the exact shared Rust golden
|
||||
}
|
||||
});
|
||||
|
||||
it('shows the immutable library revision and rejects a different catalog script hash', async () => {
|
||||
const parsed = record(plan('legacy_linux_agent').plan_payload);
|
||||
const job = (parsed.jobs as RecordValue[])[0]!;
|
||||
const ref = { revision_id: '27068008-ae22-4bde-8e54-d81624523a93', name: 'Agentversion', version: 3, script_sha256: job.script_sha256 };
|
||||
async function stored(hash: unknown) {
|
||||
const raw = new TextEncoder().encode(JSON.stringify({ ...parsed, script_revision: { ...ref, script_sha256: hash } }));
|
||||
return { plan_hash: await sha256(raw), plan_payload_bytes: Array.from(raw) };
|
||||
}
|
||||
const good = await stored(ref.script_sha256);
|
||||
await verifyPlanIntegrity(good); await verifyScriptPlan(good);
|
||||
expect(scriptPlanJobs(good)[0]?.revision).toEqual({ id: ref.revision_id, name: ref.name, version: 3 });
|
||||
await expect(verifyScriptPlan(await stored('f'.repeat(64)))).rejects.toThrow('Bibliotheksversion');
|
||||
});
|
||||
|
||||
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] = [];
|
||||
|
||||
@@ -2,6 +2,7 @@ import { canonicalJson, record, RecordValue, text, windowsScriptProfile, privile
|
||||
import { bytes, hashPattern, parseStrictJson, sha256 } from './safety';
|
||||
|
||||
export interface ScriptPlanJob {
|
||||
revision?: { id: string; name: string; version: number };
|
||||
assetId: string; agentId: string; jobId: string; attemptId: string;
|
||||
interpreter: string; identity: string; windowsProfile: string; privilegedProfile: string;
|
||||
script: string; scriptHash: string; jobHash: string; scriptBytes: number;
|
||||
@@ -61,11 +62,19 @@ export async function verifyScriptPlan(plan: RecordValue): Promise<void> {
|
||||
if (!Array.isArray(parsed.jobs)) throw new Error('Vollständige feste Jobdefinitionen fehlen');
|
||||
const jobs = parsed.jobs.map(value => record(value));
|
||||
validateViews(plan, parsed, jobs);
|
||||
let revision: ScriptPlanJob['revision'], revisionHash: string | undefined;
|
||||
if (Object.hasOwn(parsed, 'script_revision')) {
|
||||
const ref = record(parsed.script_revision);
|
||||
exact(ref, ['revision_id','name','version','script_sha256']);
|
||||
revision = { id: uuid(ref.revision_id), name: text(ref.name, 'Skriptname'), version: integer(ref.version, 1, 2147483647) };
|
||||
revisionHash = digest(ref.script_sha256);
|
||||
if (!jobs.length || jobs.some(job => !isScript(record(job.payload).action))) throw new Error('Bibliotheksversion benötigt feste Skriptjobs');
|
||||
}
|
||||
if (!jobs.some(job => isScript(record(job.payload).action))) {
|
||||
if (snapshot(plan) !== before) throw new Error('Plan wurde während der Prüfung verändert');
|
||||
verified.set(plan, { snapshot: before, jobs: [] }); return;
|
||||
}
|
||||
exact(parsed, ['schema_version', 'plan_id', 'tenant_id', 'principal', 'reason', 'jobs', 'max_parallel', 'halt_after_failures', ...(Object.hasOwn(parsed, 'recipe_references') ? ['recipe_references'] : []), ...(Object.hasOwn(parsed, 'artifact_references') ? ['artifact_references'] : [])]);
|
||||
exact(parsed, ['schema_version', 'plan_id', 'tenant_id', 'principal', 'reason', 'jobs', 'max_parallel', 'halt_after_failures', ...(revision ? ['script_revision'] : []), ...(Object.hasOwn(parsed, 'recipe_references') ? ['recipe_references'] : []), ...(Object.hasOwn(parsed, 'artifact_references') ? ['artifact_references'] : [])]);
|
||||
if (parsed.schema_version !== 1 || !jobs.length || jobs.length > 100) throw new Error('Skriptplan: unbekanntes Schema oder Zielbudget');
|
||||
uuid(parsed.plan_id); uuid(parsed.tenant_id); text(parsed.principal, 'Antragsteller'); text(parsed.reason, 'Begründung');
|
||||
integer(parsed.max_parallel, 1, 10); integer(parsed.halt_after_failures, 1, Number.MAX_SAFE_INTEGER);
|
||||
@@ -94,8 +103,9 @@ export async function verifyScriptPlan(plan: RecordValue): Promise<void> {
|
||||
const orderedAction = { action: 'run_script', interpreter, script_utf8: script, arguments: action.arguments, expected_stdout: action.expected_stdout, ...(hasWindowsProfile ? { windows_execution_profile: action.windows_execution_profile } : {}), ...(hasPrivilegedProfile ? { privileged_script_profile: action.privileged_script_profile } : {}) };
|
||||
const ordered = { schema_version: p.schema_version, tenant_id: p.tenant_id, asset_id: assetId, agent_id: agentId, enrollment_generation: p.enrollment_generation, assignment_version: p.assignment_version, job_id: jobId, attempt_id: attemptId, action: orderedAction, execution_identity: identity, not_before: notBefore, start_before: startBefore, max_runtime_seconds: runtimeSeconds, max_output_bytes: outputBytes };
|
||||
const scriptHash = digest(job.script_sha256), jobHash = digest(job.job_payload_hash);
|
||||
if (revisionHash && revisionHash !== scriptHash) throw new Error('Skripthash widerspricht der Bibliotheksversion');
|
||||
if (await sha256(scriptBytes) !== scriptHash || await sha256(new TextEncoder().encode(JSON.stringify(ordered))) !== jobHash) throw new Error('Skript-/Jobhash widerspricht exakten Rust-Payloadbytes');
|
||||
result.push({ assetId, agentId, jobId, attemptId, interpreter, identity, windowsProfile, privilegedProfile, script, scriptHash, jobHash, scriptBytes: scriptBytes.length, arguments: [...action.arguments] as string[], expectedStdout: action.expected_stdout as string | null, notBefore, startBefore, runtimeSeconds, outputBytes });
|
||||
result.push({ ...(revision ? { revision } : {}), assetId, agentId, jobId, attemptId, interpreter, identity, windowsProfile, privilegedProfile, script, scriptHash, jobHash, scriptBytes: scriptBytes.length, arguments: [...action.arguments] as string[], expectedStdout: action.expected_stdout as string | null, notBefore, startBefore, runtimeSeconds, outputBytes });
|
||||
}
|
||||
if (snapshot(plan) !== before) throw new Error('Skriptplan wurde während der Hashprüfung verändert');
|
||||
verified.set(plan, { snapshot: before, jobs: result });
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import React, { FormEvent, useEffect, useState } from 'react';
|
||||
import { objectId, page, record, request, Session, tenantPath, text } from './api';
|
||||
import { allowed } from './safety';
|
||||
|
||||
interface Draft {
|
||||
name: string;
|
||||
interpreter: 'posix_sh' | 'bash' | 'powershell';
|
||||
execution_identity: 'agent_service' | 'root' | 'system';
|
||||
script_utf8: string;
|
||||
}
|
||||
interface Revision extends Draft { revision_id: string; version: number; script_sha256: string }
|
||||
const blank: Draft = { name: '', interpreter: 'posix_sh', execution_identity: 'agent_service', script_utf8: '' };
|
||||
|
||||
function revision(input: unknown): Revision {
|
||||
const row = record(input);
|
||||
if ((row.interpreter !== 'posix_sh' && row.interpreter !== 'bash' && row.interpreter !== 'powershell') ||
|
||||
(row.execution_identity !== 'agent_service' && row.execution_identity !== 'root' && row.execution_identity !== 'system') ||
|
||||
typeof row.version !== 'number' || !Number.isSafeInteger(row.version) || row.version < 1) throw Error('Ungültige Skriptversion');
|
||||
return { name: text(row.name, 'Name'), interpreter: row.interpreter, execution_identity: row.execution_identity,
|
||||
script_utf8: text(row.script_utf8, 'Skript'), revision_id: objectId(row, 'revision'), version: row.version,
|
||||
script_sha256: text(row.script_sha256, 'SHA256') };
|
||||
}
|
||||
|
||||
export function ScriptLibrary({ tenantId, auth, selected, showPlan }: { tenantId: string; auth: Session; selected: string[]; showPlan: (id: string) => void }) {
|
||||
const path = tenantPath(tenantId, '/script-revisions');
|
||||
const canRead = allowed(auth, 'operations:read'), canPlan = allowed(auth, 'operations:plan') && allowed(auth, 'scripts:execute');
|
||||
const [items, setItems] = useState<Revision[]>([]), [cursor, setCursor] = useState<string | null>(null);
|
||||
const [chosen, setChosen] = useState(''), [draft, setDraft] = useState<Draft | null>(null), [base, setBase] = useState(0);
|
||||
const [busy, setBusy] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState('');
|
||||
const stored = items.find(row => row.revision_id === chosen);
|
||||
useEffect(() => {
|
||||
if (!canRead) return;
|
||||
const controller = new AbortController();
|
||||
setBusy(true);
|
||||
request(path, { signal: controller.signal }).then(value => {
|
||||
if (controller.signal.aborted) return;
|
||||
const result = page(value), rows = result.items.map(revision);
|
||||
setItems(rows); setCursor(result.next_cursor); setChosen(rows[0]?.revision_id ?? '');
|
||||
}).catch(err => { if (!controller.signal.aborted) setError(String(err)); })
|
||||
.finally(() => { if (!controller.signal.aborted) setBusy(false); });
|
||||
return () => controller.abort();
|
||||
}, [path, canRead]);
|
||||
|
||||
async function action(work: () => Promise<void>) {
|
||||
setBusy(true); setError(''); setNotice('');
|
||||
try { await work(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
async function more() {
|
||||
const result = page(await request(path + '?cursor=' + encodeURIComponent(cursor!)));
|
||||
const rows = result.items.map(revision);
|
||||
setItems(old => [...old, ...rows.filter(row => !old.some(saved => saved.revision_id === row.revision_id))]); setCursor(result.next_cursor);
|
||||
}
|
||||
async function save(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!draft) return;
|
||||
await action(async () => {
|
||||
const saved = revision(await request(path, { csrf: auth.csrf_token, body: { ...draft, expected_version: base } }));
|
||||
setItems(old => [...old.filter(row => row.revision_id !== saved.revision_id), saved]); setChosen(saved.revision_id);
|
||||
setDraft(null); setNotice(`Version ${saved.version} gespeichert.`);
|
||||
});
|
||||
}
|
||||
function edit(row?: Revision) {
|
||||
setBase(row?.version ?? 0);
|
||||
setDraft(row ? { name: row.name, interpreter: row.interpreter, execution_identity: row.execution_identity, script_utf8: row.script_utf8 } : { ...blank });
|
||||
setError(''); setNotice('');
|
||||
}
|
||||
async function plan(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
if (!stored || !selected.length) return;
|
||||
const form = new FormData(e.currentTarget);
|
||||
await action(async () => {
|
||||
const now = Date.now(), expires = now + Number(form.get('minutes')) * 60000;
|
||||
const body = { targets: { asset_ids: selected }, reason: String(form.get('reason')),
|
||||
schedule: { not_before: new Date(now).toISOString(), start_before: new Date(expires).toISOString() },
|
||||
rollout: { max_parallel: 1, halt_after_failures: 1 }, max_runtime_seconds: Number(form.get('runtime')), max_output_bytes: 65536 };
|
||||
const result = record(await request(path + '/' + encodeURIComponent(stored.revision_id) + '/plan', { csrf: auth.csrf_token, body }));
|
||||
showPlan(objectId(result, 'plan')); setNotice('Plan zur Prüfung geöffnet.');
|
||||
});
|
||||
}
|
||||
if (!canRead) return null;
|
||||
const limit = stored?.execution_identity === 'system' ? 120 : stored?.execution_identity === 'root' ? 300 : 3600;
|
||||
return <section aria-label="Skriptbibliothek"><h2>Skriptbibliothek</h2>
|
||||
{error && <p role="alert" className="error">{error}</p>}{notice && <p role="status">{notice}</p>}
|
||||
{items.length > 0 && <label>Gespeicherte Skriptversion<select value={chosen} disabled={busy || !!draft} onChange={e => setChosen(e.target.value)}>
|
||||
{[...items].sort((a,b) => a.name.localeCompare(b.name) || b.version - a.version).map(row => <option key={row.revision_id} value={row.revision_id}>{row.name} · v{row.version}</option>)}
|
||||
</select></label>}
|
||||
{cursor && <button disabled={busy || !!draft} onClick={() => void action(more)}>Weitere Versionen laden</button>}
|
||||
{stored && !draft && <><p>{stored.interpreter === 'powershell' ? 'Windows PowerShell' : stored.interpreter === 'bash' ? 'Linux bash' : 'Linux sh'} · {stored.execution_identity} · SHA256 <code>{stored.script_sha256}</code></p>
|
||||
<details><summary>Gespeicherten Skripttext anzeigen</summary><pre>{stored.script_utf8}</pre></details></>}
|
||||
{canPlan && !draft && <div><button disabled={busy} onClick={() => edit()}>Neues Skript</button>
|
||||
{stored && <button disabled={busy} onClick={() => edit(stored)}>Neue Version bearbeiten</button>}</div>}
|
||||
{draft && <form onSubmit={save}><fieldset disabled={busy}><legend>{base ? `Neue Version von ${draft.name}` : 'Neues Skript'}</legend>
|
||||
<label>Name<input required maxLength={120} readOnly={base > 0} value={draft.name} onChange={e => setDraft({...draft,name:e.target.value})}/></label>
|
||||
<label>Interpreter<select value={draft.interpreter} onChange={e => setDraft({...draft,interpreter:e.target.value as Draft['interpreter'],execution_identity:'agent_service'})}>
|
||||
<option value="posix_sh">Linux sh</option><option value="bash">Linux bash</option><option value="powershell">Windows PowerShell</option></select></label>
|
||||
<label>Ausführungsidentität<select value={draft.execution_identity} onChange={e => setDraft({...draft,execution_identity:e.target.value as Draft['execution_identity']})}>
|
||||
<option value="agent_service">agent_service</option>{draft.interpreter === 'powershell' ? <option value="system">system</option> : <option value="root">root</option>}</select></label>
|
||||
<label>Skripttext<textarea required rows={9} value={draft.script_utf8} onChange={e => setDraft({...draft,script_utf8:e.target.value})}/></label>
|
||||
<button>Version speichern</button><button type="button" onClick={() => setDraft(null)}>Abbrechen</button>
|
||||
</fieldset></form>}
|
||||
{canPlan && stored && !draft && <form key={stored.revision_id} onSubmit={plan}><fieldset disabled={busy}><legend>Auftrag für {stored.name} · v{stored.version} vorbereiten</legend>
|
||||
<p>{selected.length} ausgewählte Geräte · Ein Gerät gleichzeitig · Stopp beim ersten Fehler · 65536 Byte Ausgabe je Gerät</p>
|
||||
<label>Begründung<input name="reason" required maxLength={1024}/></label>
|
||||
<label>Startfrist in Minuten<input name="minutes" type="number" min={1} max={1440} defaultValue={60} required/></label>
|
||||
<label>Laufzeit je Gerät in Sekunden<input name="runtime" type="number" min={1} max={limit} defaultValue={Math.min(limit,120)} required/></label>
|
||||
<button disabled={!selected.length}>Plan vorbereiten</button>
|
||||
</fieldset></form>}
|
||||
</section>;
|
||||
}
|
||||
Reference in New Issue
Block a user