Add gated agent update planning, preserved handoff and Linux worker ports
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-14 21:48:21 +01:00
parent dc9cb1b096
commit 1e89c4577f
82 changed files with 25052 additions and 69 deletions
+55 -9
View File
@@ -7,9 +7,23 @@ import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers,
import { Login } from './login';
import { ConsoleOutput, outputText } from './console-output';
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
import { agentUpdateWarning, agentUpdatePlanJobs, agentUpdateApprovalBlockers, verifyAgentUpdatePlan, verifyReleaseMetadata, releaseEnvelope, uploadAgentUpdateArtifact } from './agent-updates';
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return <details open><summary>{label}</summary><pre aria-label={label}>{pretty(value)}</pre></details>; }
export function AgentUpdatePlanNotice({ plan }: { plan: RecordValue }) {
try {
const jobs = agentUpdatePlanJobs(plan); if (!jobs.length) return null;
return <article aria-label="Feste Agent-Selbstupdates vor Genehmigung"><h3>Vollständige feste Agent-Selbstupdates ({jobs.length})</h3><p className="warning">{agentUpdateWarning}</p>
{jobs.map(job => <article key={job.jobId}><h4>Asset {job.assetId}</h4><p>Agent: {job.agentId} · Job: {job.jobId} · Versuch: {job.attemptId} · Identität: <strong>{job.identity}</strong></p>
<p>Release: {String(job.manifest.release_id)} · Version: {String(job.manifest.version)} · Plattform: {String(job.manifest.platform)} · Sequenz: {String(job.manifest.release_sequence)}</p>
<p>Manifest-SHA256: <code>{String(job.update.manifest_sha256)}</code> · Job-SHA256: <code>{job.jobHash}</code></p>
<p>Die folgenden Vorgänger-, Codepaar-, Updater-, Keyring- und Peerpinbindungen stammen vollständig aus den unveränderten gespeicherten Planbytes. Gesamtbudget600s, Healthfrist180s; keine allgemeine Reparatur oder neue Freigabe.</p>
<JsonView value={job.update} label={`Vollständige feste Updatebindung für ${job.assetId}`}/>
</article>)}
</article>;
} catch { return <aside role="alert" className="error">Agentupdateplan nicht vollständig aus unveränderten Originalbytes verifiziert. Keine Genehmigung möglich.</aside>; }
}
export function ScriptPlanNotice({ plan }: { plan: RecordValue }) {
try {
const jobs = scriptPlanJobs(plan); if (!jobs.length) return null;
@@ -88,6 +102,7 @@ function Devices({ tenantId, auth, selected, setSelected }: { tenantId: string;
}
const initialParameters: Record<Action, RecordValue> = {
run_script: {}, refresh_inventory: { scope: 'linux.base' }, query_logs: { unit: '', since: '', until: '', max_lines: 1000 }, set_service_state: { unit: '', state: 'running' }, ensure_package: { provider: 'apt', recipe_version: '', package: '', version: '', architecture: 'amd64', installation_context: 'system', apt_manifest: null }, apply_updates: { provider: 'apt', packages: [], reboot_policy: 'never', apt_manifest: null }, reboot: { reason: '', dependency_group: '', reconnect_timeout_seconds: 300 }, apt_native_acceptance: { recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', apt_manifest: null },
update_agent: { release_id: '' },
};
function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; auth: Session; selected: string[]; showPlan: (id: string) => void }) {
const [scriptPlatform, setScriptPlatform] = useState('linux'), [mixedVariants, setMixedVariants] = useState('[]');
@@ -102,16 +117,17 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
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 === 'update_agent' && <p className="warning">{agentUpdateWarning} Nur parameters.release_id aus dem Katalog; keine freien Vorgänger-, Dateipfad-, Artefakt- oder Policywerte. Gesamtbudget600s, Ausgabelimit höchstens65536Bytes. Fehlende frische Gerätepreview ergibt keine Planung.</p>}
{action === 'query_logs' && <p>Windows-MVP nur Quelle windows.eventlog.application.rustdiscovery-mvp-test, Kanal Application, Provider RustDiscovery-MVP-Test, agent_service. Festes UTC-Fenster höchstens24h,1–1000Events,1024–65536Bytes,äußere Joblaufzeit10–120s; inneres kooperatives Abfragebudget höchstens5000ms. Keine freie Kanal-/XPathauswahl und keine Bookmarkfortschreibung. Linux behält seine feste Journalunit.</p>}
{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. 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={!['set_service_state', 'ensure_package', 'run_script'].includes(action) || !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>
<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={!['set_service_state', 'ensure_package', 'run_script', 'update_agent'].includes(action) || !allowed(auth, 'system:execute')}>system · system:execute und Windows-SYSTEM-Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" key={action} type="number" min="1" max="86400" defaultValue={action === 'update_agent' ? '600' : '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>
{action === 'run_script' && <><label>Privilegiertes Skriptprofil<select name="privileged_script_profile" aria-label="Privilegiertes Skriptprofil" key={identity} defaultValue=""><option value="">Bestehendes begrenztes Profil · keine volle Hostwartung</option><option value={fullMaintenanceScriptProfile} disabled={!['root', 'system'].includes(identity) || !allowed(auth, 'scripts:execute')}>full_maintenance_v1 · volle Hostautorität als root/SYSTEM</option></select></label><p className="warning">{fullMaintenanceWarning}</p><p>Die Auswahl erteilt keine Rechte und aktiviert keinen Client. Zentrale und lokale Policy, tatsächliche Zielcapabilities und die spätere Genehmigung werden unabhängig geprüft. SYSTEM erfordert dieses Profil; es gibt keinen automatischen Fallback.</p></>}
{identity === 'root' && action !== 'run_script' && <p className="warning">{rootWarning}</p>}
{identity === 'system' && action !== 'run_script' && <p className="warning">{systemWarning}</p>}
{identity === 'root' && !['run_script', 'update_agent'].includes(action) && <p className="warning">{rootWarning}</p>}
{identity === 'system' && !['run_script', 'update_agent'].includes(action) && <p className="warning">{systemWarning}</p>}
{identity === 'system' && action === 'ensure_package' && <p>MSI: provider=msi, package=rmm-windows-msi-fixture, architecture=x64, installation_context=machine, recipe_version=1 und vollständiges windows_msi_manifest aus dem getrennten MSI-Katalog. Genau zwei eigene Rezepte1.0/1.0→1.1;10–120s,1024–65536Bytes. APT-Manifest fehlt/null. Rezept-/Artefakthash und feste Nachbedingungen werden geprüft. Kein zusätzlicher Artefaktvektor.</p>}
{['ensure_package', 'apply_updates', 'apt_native_acceptance'].includes(action) && <details open><summary>Unveränderte Parameter-/Manifestpreview: gesamte Closure, alte/neue Versionen, Origins, Archivbytes/Hashes und Bindungen</summary><pre>{parameters}</pre><p>Struktur, exakte Transaktionsbytes und Hash werden vor Planung geprüft. Diese Vorschau behauptet keine native Akzeptanz oder Bereitschaft; keine automatische Ergänzung/Reduzierung der Closure.</p></details>}
<label>Feste importierte Artefakt-IDs (optional, maximal 16)<input name="artifact_ids" disabled={identity === 'system' && action === 'ensure_package'} placeholder="MSI leitet genau eine Referenz aus dem Rezept ab; sonst UUIDs, keine URL"/></label>
<label>Feste importierte Artefakt-IDs (optional, maximal 16)<input name="artifact_ids" disabled={action === 'update_agent' || (identity === 'system' && action === 'ensure_package')} placeholder="MSI leitet genau eine Referenz aus dem Rezept ab; sonst UUIDs, keine URL"/></label>
<label>Begründung<input name="reason" required maxLength={1024}/></label><p>Feste Ziele ({selected.length}): {selected.join(', ') || 'keine ausgewählt'}</p>{action === 'reboot' || action === 'apply_updates' || action === 'ensure_package' ? <p className="warning">Zieländerung: Testumfang separat abstimmen. Keine implizite Reboot-/Updateerlaubnis. Neue Versuche und Folgejobs benötigen neue feste Pläne.</p> : null}<button disabled={busy || !selected.length}>Plan erstellen · noch keine Ausführung</button><ErrorBox error={error}/>
</form></section>;
}
@@ -138,15 +154,45 @@ function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session
</section>;
}
function AgentReleaseCatalog({ tenantId, auth }: { tenantId: string; auth: Session }) {
const [cursor, setCursor] = useState<string | null>(null), [revision, setRevision] = useState(0), [source, setSource] = useState('{}'), [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null), [receipts, setReceipts] = useState<unknown[]>([]);
const list = useResource(async signal => {
const result = page(await request(tenantPath(tenantId, `/agent-releases${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`), { signal }));
const items: RecordValue[] = [];
for (const item of result.items) { const release = await verifyReleaseMetadata(item.release_envelope, item.manifest_sha256); if (item.release_id !== release.manifest.release_id) throw new Error('Release-ID widerspricht originalem Manifest'); items.push({ release_id: item.release_id, manifest_sha256: item.manifest_sha256, manifest: release.manifest, signature_and_time_valid: item.signature_and_time_valid === true }); }
return { ...result, items };
}, [tenantId, cursor, revision]);
return <section><h2>Signierter Agent-Releasekatalog</h2><p>Feste Release-ID für update_agent verwenden. Die Planung löst Vorgänger und Peerpinübergang aus frischen gespeicherten Gerätebeobachtungen auf. Ein Katalogeintrag oder passiver Versionscheck erteilt keine Ausführungserlaubnis; fehlende Qualifikation bleibt gesperrt.</p><ErrorBox error={list.error}/>
{list.data && <><PageStatus data={list.data}/><JsonView value={list.data.items} label="Feste Agent-/Helper-Releases und Manifesthashes"/><button disabled={!cursor} onClick={() => setCursor(null)}>Erste Releaseseite</button><button disabled={!list.data.next_cursor} onClick={() => setCursor(list.data?.next_cursor ?? null)}>Nächste Releaseseite</button></>}
<details><summary>Signiertes festes Release mit Agent und Helper veröffentlichen</summary><p>Nur Katalogverwaltung mit catalog:write. Kein Gerätejob und keine Freigabe zur Installation. Dateien werden gegen die festen signierten Längen/Hashes geprüft; erst beide vollständigen Importe erlauben die Releaseveröffentlichung. Bei Fehler keine automatische Wiederholung; vorhandene Teilimportbelege bleiben sichtbar.</p>
<form onSubmit={async event => { event.preventDefault(); setBusy(true); setError(null); setReceipts([]); const form = new FormData(event.currentTarget); try {
if (!allowed(auth, 'catalog:write')) throw new Error('catalog:write unbekannt/nicht erteilt');
const release = releaseEnvelope(parseStrictJson(source)), artifacts = release.manifest.artifacts as RecordValue[];
const files = [form.get('agent_file'), form.get('helper_file')];
if (files.some((file, index) => !(file instanceof File) || file.size !== artifacts[index]!.bytes)) throw new Error('Beide Dateien müssen die exakten Manifestlängen haben');
for (let index = 0; index < 2; index++) { const receipt = await uploadAgentUpdateArtifact(tenantId, artifacts[index]!, files[index] as File, auth.csrf_token); setReceipts(previous => [...previous, receipt]); }
const result = record(await request(tenantPath(tenantId, '/agent-releases'), { body: release.envelope, csrf: auth.csrf_token }));
const published = await verifyReleaseMetadata(result.release_envelope, result.manifest_sha256);
if (published.manifest.release_id !== release.manifest.release_id || JSON.stringify(published.envelope) !== JSON.stringify(release.envelope)) throw new Error('Veröffentlichung widerspricht festem Release');
setReceipts(previous => [...previous, { release_id: published.manifest.release_id, manifest_sha256: result.manifest_sha256 }]); setRevision(n => n + 1);
} catch (error) { setError(errorText(error)); } finally { setBusy(false); } }}>
<label>Vollständiger signierter Release-Envelope JSON<textarea rows={8} value={source} onChange={e => setSource(e.target.value)} spellCheck={false}/></label>
<label>Exakte Agentdatei<input type="file" name="agent_file" required/></label><label>Exakte Helperdatei<input type="file" name="helper_file" required/></label>
<button disabled={busy || !allowed(auth, 'catalog:write')}>Signiertes Codepaar im Katalog veröffentlichen · keine Installation</button><ErrorBox error={error}/>{receipts.length > 0 && <JsonView value={receipts} label="Tatsächliche Teilimport- und Veröffentlichungsbelege"/>}
</form>
</details>
</section>;
}
function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id: string; auth: Session; onOperation: (id: string) => void }) {
const plan = useResource(async signal => { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}`), { signal })); await verifyPlanIntegrity(result); await verifyScriptPlan(result); return result; }, [tenantId, id]);
const plan = useResource(async signal => { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}`), { signal })); await verifyPlanIntegrity(result); await verifyScriptPlan(result); await verifyAgentUpdatePlan(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), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data), ...scriptApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
const recheck = async () => { if (!plan.data) throw new Error('Plan fehlt'); await verifyPlanIntegrity(plan.data); await verifyScriptPlan(plan.data); const errors = [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data), ...scriptApprovalBlockers(plan.data)]; if (errors.length) throw new Error(errors.join('; ')); };
const blockers = plan.data ? [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data), ...scriptApprovalBlockers(plan.data), ...agentUpdateApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
const recheck = async () => { if (!plan.data) throw new Error('Plan fehlt'); await verifyPlanIntegrity(plan.data); await verifyScriptPlan(plan.data); await verifyAgentUpdatePlan(plan.data); const errors = [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data), ...scriptApprovalBlockers(plan.data), ...agentUpdateApprovalBlockers(plan.data)]; if (errors.length) throw new Error(errors.join('; ')); };
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>
<ScriptPlanNotice plan={plan.data}/>
<AgentUpdatePlanNotice plan={plan.data}/><ScriptPlanNotice plan={plan.data}/>
<SystemPlanNotice plan={plan.data}/>
<WindowsMsiPlanNotice plan={plan.data}/>
<PowerShellPlanNotice plan={plan.data}/>
@@ -194,7 +240,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}/><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}/><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);