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
+68
View File
@@ -0,0 +1,68 @@
import { readFileSync } from 'node:fs';
import { expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { PlanInput, record, RecordValue, Session, validateInput } from './api';
import { sha256, validateSensitiveInput, verifyPlanIntegrity } from './safety';
import { verifyScriptPlan } from './script-console';
import { agentUpdateApprovalBlockers, agentUpdatePlanJobs, verifyAgentUpdatePlan, uploadAgentUpdateArtifact } from './agent-updates';
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
// Actual rmm-domain serde/codec output; synthetic signatures are NOT update trust.
const golden = JSON.parse(readFileSync(new URL('../../tests/agent_update/codec-golden.json', import.meta.url), 'utf8')) as Record<string, RecordValue>;
const fixture = (name = 'linux_full') => structuredClone(golden[name]!) as RecordValue;
async function rehashed(change: (raw: RecordValue) => void): Promise<RecordValue> {
const p = fixture(), raw = record(p.payload); change(raw);
const bytes = new TextEncoder().encode(JSON.stringify(raw)); p.plan_payload_bytes = Array.from(bytes); p.plan_hash = await sha256(bytes);
p.payload = raw; p.plan_payload = structuredClone(raw); return p;
}
it('verifies actual Rust Linux General/Full and Windows code-pair plan bytes before display', async () => {
for (const name of Object.keys(golden)) {
const p = fixture(name); expect(agentUpdateApprovalBlockers(p)).not.toEqual([]);
await verifyPlanIntegrity(p); await verifyScriptPlan(p); await verifyAgentUpdatePlan(p);
const jobs = agentUpdatePlanJobs(p); expect(jobs).toHaveLength(1); expect(jobs[0]!.identity).toBe(name === 'windows_pair' ? 'system' : 'root');
expect(jobs[0]!.update.no_reboot).toBe(true); expect(agentUpdateApprovalBlockers(p)).toEqual([]);
jobs[0]!.update.no_reboot = false; expect(agentUpdatePlanJobs(p)[0]!.update.no_reboot).toBe(true);
}
});
it('rejects even rehashed missing/extra artifact authority and inconsistent displayed or changed bytes', async () => {
for (const change of [(p: RecordValue) => { (p.artifact_references as unknown[]).pop(); }, (p: RecordValue) => { (p.artifact_references as unknown[]).push(structuredClone((p.artifact_references as unknown[])[0])); }]) {
await expect(verifyAgentUpdatePlan(await rehashed(change))).rejects.toThrow('Codepaarmenge');
}
const p = fixture(); record(record((p.jobs as unknown[])[0]).payload).execution_identity = 'agent_service';
await expect(verifyAgentUpdatePlan(p)).rejects.toThrow('Zielpreview');
const q = fixture(); await verifyAgentUpdatePlan(q); q.resolved_targets = [];
expect(agentUpdateApprovalBlockers(q)).not.toEqual([]);
const during = fixture(), checking = verifyAgentUpdatePlan(during); during.plan_hash = 'f'.repeat(64); await expect(checking).rejects.toThrow();
});
it('shows all fixed update/recovery bindings without an approval or network side effect', async () => {
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
try {
const { AgentUpdatePlanNotice } = await import('./main'); const p = fixture();
expect(renderToStaticMarkup(<AgentUpdatePlanNotice plan={p}/>)).toContain('role="alert"');
await verifyAgentUpdatePlan(p); const job = agentUpdatePlanJobs(p)[0]!, html = renderToStaticMarkup(<AgentUpdatePlanNotice plan={p}/>);
for (const value of ['root', job.jobId, job.attemptId, job.assetId, job.jobHash, String(job.update.manifest_sha256), 'linux_general_full_v1', 'restore_exact_predecessor_once', 'keyring_sha256', 'health_public_key_hex', 'health_key_pin_sha256', '600s', '180s', 'Kein Hostneustart', 'unknown']) expect(html).toContain(value);
expect(html).not.toMatch(/<(button|input|form)\b/); expect(fetch).not.toHaveBeenCalled();
} finally { vi.unstubAllGlobals(); }
});
it('accepts only a release ID and separate update/root or update/SYSTEM rights at planning', async () => {
const input: PlanInput = { tenant_id: 'tenant', action: 'update_agent', targets: { asset_ids: ['asset'] }, parameters: { release_id: '11111111-1111-4111-8111-111111111111', execution_identity: 'root', timeout_seconds: 600, max_output_bytes: 65536 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'codec only' };
const auth: Session = { principal: { id: 'unit', display_name: 'unit', simulated: true }, csrf_token: 'unit', tenants: [], permissions: ['updates:apply', 'root:execute'] };
validateInput(input); await validateSensitiveInput(input, auth);
for (const permissions of [[], ['root:execute'], ['updates:apply'], ['updates:apply', 'system:execute'], ['scripts:execute', 'root:execute']]) await expect(validateSensitiveInput(input, { ...auth, permissions })).rejects.toThrow();
for (const parameters of [{ ...input.parameters, predecessor: {} }, { ...input.parameters, execution_identity: 'agent_service' }, { ...input.parameters, timeout_seconds: 601 }, { ...input.parameters, max_output_bytes: 65537 }]) expect(() => validateInput({ ...input, parameters })).toThrow();
expect(() => validateInput({ ...input, artifact_ids: [] })).toThrow();
});
it('streams only the selected File to its same-origin descriptor and rejects conflicting receipts', async () => {
const file = new File(['abc'], 'agent-code-only'), arrayBuffer = vi.spyOn(file, 'arrayBuffer').mockRejectedValue(new Error('application must not load the full binary'));
const descriptor = { artifact_id: '11111111-1111-4111-8111-111111111111', sha256: 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', bytes: 3 };
const reply = { artifact_id: descriptor.artifact_id, sha256: descriptor.sha256, size_bytes: 3 };
const fetch = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => reply }); vi.stubGlobal('fetch', fetch);
try {
expect(await uploadAgentUpdateArtifact('tenant', descriptor, file, 'unit-csrf')).toEqual(reply);
expect(fetch).toHaveBeenCalledWith(expect.stringMatching(/^\/api\/v1\/tenants\/tenant\/agent-update-artifacts\?/), expect.objectContaining({ body: file, credentials: 'same-origin', redirect: 'error', headers: { 'Content-Type': 'application/octet-stream', 'X-CSRF-Token': 'unit-csrf' } }));
expect(arrayBuffer).not.toHaveBeenCalled();
await expect(uploadAgentUpdateArtifact('tenant', descriptor, new File(['abcd'], 'wrong-length'), 'unit-csrf')).rejects.toThrow('Dateigröße');
expect(fetch).toHaveBeenCalledTimes(1);
fetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({ ...reply, size_bytes: 4 }) });
await expect(uploadAgentUpdateArtifact('tenant', descriptor, file, 'unit-csrf')).rejects.toThrow('Importbeleg');
} finally { vi.unstubAllGlobals(); }
});
+124
View File
@@ -0,0 +1,124 @@
import { ApiError, record, RecordValue, text, tenantPath } from './api';
export const agentUpdateWarning = 'AGENT-SELBSTUPDATE: Agent und privilegierte Helper werden vorübergehend gestoppt; die Geräteverwaltung kann ausfallen. Genau dieses signierte Codepaar und der gespeicherte Vorgänger sind gebunden. Einmalige Rückkehr nur zum erlaubten exakten Vorgängercode; keine Rücksetzung von Datenbank, Identität oder Historie. Kein Hostneustart und keine automatische Genehmigung. Ein unklarer Ausgang bleibt unknown.';
function exact(value: RecordValue, fields: string[]) { if (Object.keys(value).some(k => !fields.includes(k)) || fields.some(k => !Object.hasOwn(value, k))) throw new Error('Agentupdate: vollständige bekannte Schemafelder erforderlich'); }
function integer(value: unknown, minimum = 1, maximum = Number.MAX_SAFE_INTEGER): number { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum || value > maximum) throw new Error('Agentupdate: festes Ganzzahllimit erforderlich'); return value; }
function digest(value: unknown): string { const hash = text(value, 'Agentupdate-SHA256'); if (!/^[a-f0-9]{64}$/.test(hash)) throw new Error('Agentupdate: exakter SHA256 erforderlich'); return hash; }
function uuid(value: unknown): string { const id = text(value, 'Agentupdate-ID'); if (!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(id) || id === '00000000-0000-0000-0000-000000000000') throw new Error('Agentupdate: feste UUID erforderlich'); return id; }
function same(left: unknown, right: unknown): boolean {
const canonical = (v: unknown): string => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` : v && typeof v === 'object' ? `{${Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, x]) => `${JSON.stringify(k)}:${canonical(x)}`).join(',')}}` : JSON.stringify(v);
return canonical(left) === canonical(right);
}
async function hash(bytes: Uint8Array<ArrayBuffer>): Promise<string> { return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), n => n.toString(16).padStart(2, '0')).join(''); }
const utf8 = (value: unknown): Uint8Array<ArrayBuffer> => new TextEncoder().encode(JSON.stringify(value));
function base64url(value: unknown, maximum: number): Uint8Array<ArrayBuffer> {
if (typeof value !== 'string' || !value || value.length > maximum || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error('Agentupdate: kanonisches Base64url erforderlich');
const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - value.length % 4) % 4)), c => c.charCodeAt(0));
if (btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '') !== value) throw new Error('Agentupdate: nichtkanonisches Base64url');
return bytes;
}
export interface ReleaseView { envelope: RecordValue; manifest: RecordValue; bytes: Uint8Array<ArrayBuffer> }
export function releaseEnvelope(value: unknown): ReleaseView {
const envelope = record(value); exact(envelope, ['schema_version', 'key_id', 'payload_bytes', 'signature']);
if (envelope.schema_version !== 1) throw new Error('Agentupdate: unbekanntes Envelopeschema');
const bytes = base64url(envelope.payload_bytes, 21846), signature = base64url(envelope.signature, 86);
if (!bytes.length || bytes.length > 16384 || signature.length !== 64) throw new Error('Agentupdate: Manifest-/Signaturlimit');
const m = record(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
exact(m, ['schema_version', 'release_id', 'release_sequence', 'version', 'platform', 'published_at', 'expires_at', 'protocol_major', 'state_schema', 'minimum_updater_version', 'artifacts']);
if (m.schema_version !== 1 || !['x86_64-unknown-linux-gnu', 'x86_64-pc-windows-msvc'].includes(String(m.platform)) || typeof m.version !== 'string' || !/^[A-Za-z0-9.+_-]{1,64}$/.test(m.version)
|| !Array.isArray(m.artifacts) || m.artifacts.length !== 2) throw new Error('Agentupdate: festes x64-Codepaar erforderlich');
const artifacts = m.artifacts.map((value, index) => { const a = record(value); exact(a, ['role', 'artifact_id', 'sha256', 'bytes']); if (a.role !== ['agent', 'helper'][index]) throw new Error('Agentupdate: Agent-/Helperreihenfolge'); return { role: a.role, artifact_id: uuid(a.artifact_id), sha256: digest(a.sha256), bytes: integer(a.bytes, 1, 268435456) }; });
if (artifacts[0]!.artifact_id === artifacts[1]!.artifact_id) throw new Error('Agentupdate: doppelte Artefakt-ID');
const manifest = { schema_version: 1, release_id: uuid(m.release_id), release_sequence: integer(m.release_sequence), version: m.version, platform: m.platform, published_at: integer(m.published_at, 0), expires_at: integer(m.expires_at), protocol_major: integer(m.protocol_major), state_schema: integer(m.state_schema), minimum_updater_version: integer(m.minimum_updater_version), artifacts };
if (manifest.expires_at <= manifest.published_at || new TextDecoder().decode(utf8(manifest)) !== new TextDecoder('utf-8', { fatal: true }).decode(bytes)) throw new Error('Agentupdate: exakte kanonische Manifestbytes erforderlich');
return { envelope: { schema_version: 1, key_id: digest(envelope.key_id), payload_bytes: envelope.payload_bytes, signature: envelope.signature }, manifest, bytes };
}
export async function verifyReleaseMetadata(value: unknown, expectedHash: unknown): Promise<ReleaseView> {
const release = releaseEnvelope(value); if (await hash(release.bytes) !== digest(expectedHash)) throw new Error('Agentupdate: Kataloghash widerspricht originalen Manifestbytes'); return release;
}
/** Browser sends the File body directly. It does not allocate a complete binary
* ArrayBuffer or export a session/token. Server verifies complete hash and EOF. */
export async function uploadAgentUpdateArtifact(tenantId: string, descriptor: RecordValue, file: File, csrf: string): Promise<RecordValue> {
const id = uuid(descriptor.artifact_id), expectedHash = digest(descriptor.sha256), size = integer(descriptor.bytes, 1, 268435456);
if (file.size !== size || !csrf) throw new Error('Agentupdate: ausgewählte Dateigröße oder interaktive Sitzung stimmt nicht');
const query = new URLSearchParams({ artifact_id: id, sha256: expectedHash, size_bytes: String(size) });
const response = await fetch(tenantPath(tenantId, `/agent-update-artifacts?${query}`), { method: 'POST', credentials: 'same-origin', cache: 'no-store', redirect: 'error', headers: { 'Content-Type': 'application/octet-stream', 'X-CSRF-Token': csrf }, body: file });
const result = record(await response.json());
if (!response.ok) throw new ApiError(response.status, String(result.code ?? 'HTTP_ERROR'), String(result.message ?? 'Import fehlgeschlagen'), String(result.correlation_id ?? ''));
exact(result, ['artifact_id', 'sha256', 'size_bytes']);
if (result.artifact_id !== id || result.sha256 !== expectedHash || result.size_bytes !== size) throw new Error('Agentupdate: Importbeleg widerspricht festem Artefakt');
return result;
}
/** Shape only; signatures remain independently checked against provisioned trust
* at server and local helper. No public key from a job is trusted by the UI. */
export function validateAgentUpdateAction(value: unknown, identity: unknown): RecordValue {
const action = record(value); exact(action, ['action', 'update']); if (action.action !== 'update_agent') throw new Error('Agentupdate: typisierte Aktion erforderlich');
const u = record(action.update); exact(u, ['schema_version', 'profile', 'release_envelope', 'release_envelope_sha256', 'manifest_sha256', 'predecessor', 'updater', 'peer_pin_transition', 'recovery', 'health_profile', 'health_timeout_seconds', 'no_reboot']);
if (u.schema_version !== 1 || u.profile !== 'fixed_code_pair_v1' || u.recovery !== 'restore_exact_predecessor_once' || u.health_profile !== 'mtls_inventory_sync_v1' || u.health_timeout_seconds !== 180 || u.no_reboot !== true) throw new Error('Agentupdate: fester Apply-/Health-/No-Reboot-Vertrag erforderlich');
const release = releaseEnvelope(u.release_envelope), linux = release.manifest.platform === 'x86_64-unknown-linux-gnu';
if (identity !== (linux ? 'root' : 'system')) throw new Error('Agentupdate: Plattform und Root-/SYSTEM-Identität widersprechen sich');
const old = record(u.predecessor); exact(old, ['release_id', 'release_sequence', 'manifest_sha256', 'installed_record_sha256', 'agent_sha256', 'helper_sha256']);
const predecessor = { release_id: uuid(old.release_id), release_sequence: integer(old.release_sequence), manifest_sha256: digest(old.manifest_sha256), installed_record_sha256: digest(old.installed_record_sha256), agent_sha256: digest(old.agent_sha256), helper_sha256: digest(old.helper_sha256) };
if (predecessor.release_id === release.manifest.release_id || predecessor.release_sequence >= Number(release.manifest.release_sequence)) throw new Error('Agentupdate: exakter älterer Vorgänger erforderlich');
const binding = record(u.updater); exact(binding, ['binary_sha256', 'policy_sha256', 'keyring_generation', 'keyring_sha256', 'health_public_key_hex', 'health_key_pin_sha256']);
const updater = { binary_sha256: digest(binding.binary_sha256), policy_sha256: digest(binding.policy_sha256), keyring_generation: integer(binding.keyring_generation), keyring_sha256: digest(binding.keyring_sha256), health_public_key_hex: digest(binding.health_public_key_hex), health_key_pin_sha256: digest(binding.health_key_pin_sha256) };
const p = record(u.peer_pin_transition); let transition: RecordValue;
if (p.profile === 'unchanged_general_pin_v1') { exact(p, ['profile', 'general_pin_sha256']); if (!linux) throw new Error('Agentupdate: Linux-Pinprofil auf Windows'); transition = { profile: p.profile, general_pin_sha256: digest(p.general_pin_sha256) }; }
else if (p.profile === 'linux_general_full_v1') {
exact(p, ['profile', 'general_pin_sha256', 'full']); if (!linux) throw new Error('Agentupdate: Linux-Fullprofil auf Windows');
const f = record(p.full); exact(f, ['schema_version', 'old_config_sha256', 'new_config_sha256', 'old_pin_sha256', 'new_pin_sha256', 'old_policy_sha256', 'new_policy_sha256', 'old_helper_sha256', 'new_helper_sha256', 'effective_signing_key_id']);
if (f.schema_version !== 1) throw new Error('Agentupdate: unbekanntes Fullpinschema');
const full = { schema_version: 1, old_config_sha256: digest(f.old_config_sha256), new_config_sha256: digest(f.new_config_sha256), old_pin_sha256: digest(f.old_pin_sha256), new_pin_sha256: digest(f.new_pin_sha256), old_policy_sha256: digest(f.old_policy_sha256), new_policy_sha256: digest(f.new_policy_sha256), old_helper_sha256: digest(f.old_helper_sha256), new_helper_sha256: digest(f.new_helper_sha256), effective_signing_key_id: digest(f.effective_signing_key_id) };
if (full.old_helper_sha256 !== predecessor.helper_sha256 || full.new_helper_sha256 !== record((release.manifest.artifacts as unknown[])[1]).sha256 || full.old_config_sha256 === full.new_config_sha256 || full.old_pin_sha256 === full.new_pin_sha256) throw new Error('Agentupdate: Fullpin-Codepaarbindung fehlt');
transition = { profile: p.profile, general_pin_sha256: digest(p.general_pin_sha256), full };
} else if (p.profile === 'windows_code_pair_v1') {
exact(p, ['profile', 'old_settings_sha256', 'new_settings_sha256', 'old_pin_sha256', 'new_pin_sha256']); if (linux) throw new Error('Agentupdate: Windows-Pinprofil auf Linux');
transition = { profile: p.profile, old_settings_sha256: digest(p.old_settings_sha256), new_settings_sha256: digest(p.new_settings_sha256), old_pin_sha256: digest(p.old_pin_sha256), new_pin_sha256: digest(p.new_pin_sha256) };
if (transition.old_settings_sha256 === transition.new_settings_sha256 || transition.old_pin_sha256 === transition.new_pin_sha256) throw new Error('Agentupdate: unveränderte Windows-Pinübergabe');
} else throw new Error('Agentupdate: unbekannter Peerpinübergang');
return { action: 'update_agent', update: { schema_version: 1, profile: 'fixed_code_pair_v1', release_envelope: release.envelope, release_envelope_sha256: digest(u.release_envelope_sha256), manifest_sha256: digest(u.manifest_sha256), predecessor, updater, peer_pin_transition: transition, recovery: 'restore_exact_predecessor_once', health_profile: 'mtls_inventory_sync_v1', health_timeout_seconds: 180, no_reboot: true } };
}
export interface UpdatePlanJob { assetId: string; agentId: string; jobId: string; attemptId: string; identity: string; jobHash: string; update: RecordValue; manifest: RecordValue }
const verified = new WeakMap<RecordValue, { snapshot: string; jobs: UpdatePlanJob[] }>();
const snapshot = (plan: RecordValue) => JSON.stringify(plan);
export async function verifyAgentUpdatePlan(plan: RecordValue): Promise<void> {
const before = snapshot(plan), raw = plan.plan_payload_bytes;
if (!Array.isArray(raw) || !raw.length || raw.length > 1048576 || raw.some(n => !Number.isInteger(n) || n < 0 || n > 255) || await hash(new Uint8Array(raw)) !== digest(plan.plan_hash)) throw new Error('Agentupdate: gespeicherte Planbytes/Hash fehlen');
const original = new TextDecoder('utf-8', { fatal: true }).decode(new Uint8Array(raw)), parsed = record(JSON.parse(original));
if (!Array.isArray(parsed.jobs)) throw new Error('Agentupdate: feste Jobs fehlen');
const list = parsed.jobs.map(value => record(value));
if (!list.some(job => record(record(job.payload).action).action === 'update_agent')) { if (snapshot(plan) !== before) throw new Error('Plan während 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', 'artifact_references']);
if (parsed.schema_version !== 1 || !list.length || list.length > 100 || !Array.isArray(parsed.artifact_references) || parsed.artifact_references.length !== list.length * 2) throw new Error('Agentupdate: vollständige feste Codepaarmenge erforderlich');
const jobs: UpdatePlanJob[] = [], payloads: RecordValue[] = [], fixedJobs: RecordValue[] = [], refs: RecordValue[] = [], seen = new Set<string>();
for (const job of list) {
exact(job, ['payload', 'job_payload_hash', 'script_sha256']); const p = record(job.payload);
exact(p, ['schema_version', 'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'job_id', 'attempt_id', 'action', 'execution_identity', 'not_before', 'start_before', 'max_runtime_seconds', 'max_output_bytes']);
const assetId = uuid(p.asset_id), jobId = uuid(p.job_id), attemptId = uuid(p.attempt_id), identity = text(p.execution_identity, 'Identität');
if (p.schema_version !== 1 || p.tenant_id !== parsed.tenant_id || seen.has(assetId) || seen.has(jobId) || seen.has(attemptId) || job.script_sha256 !== null || p.max_runtime_seconds !== 600) throw new Error('Agentupdate: feste Geräte-/Versuchsbindung oder Gesamtbudget fehlt');
[assetId, jobId, attemptId].forEach(id => seen.add(id)); integer(p.max_output_bytes, 1, 65536);
const action = validateAgentUpdateAction(p.action, identity), update = record(action.update), release = releaseEnvelope(update.release_envelope);
if (await hash(release.bytes) !== update.manifest_sha256 || await hash(utf8(release.envelope)) !== update.release_envelope_sha256) throw new Error('Agentupdate: originale Manifest-/Envelopehashbindung fehlt');
const notBefore = text(p.not_before, 'Startzeit'), startBefore = text(p.start_before, 'Startfrist');
if (!Number.isFinite(Date.parse(notBefore)) || !Number.isFinite(Date.parse(startBefore)) || Date.parse(startBefore) <= Date.parse(notBefore) || startBefore !== plan.expires_at) throw new Error('Agentupdate: feste Fristen widersprechen sich');
const payload = { schema_version: 1, tenant_id: uuid(p.tenant_id), asset_id: assetId, agent_id: uuid(p.agent_id), enrollment_generation: integer(p.enrollment_generation), assignment_version: integer(p.assignment_version), job_id: jobId, attempt_id: attemptId, action, execution_identity: identity, not_before: notBefore, start_before: startBefore, max_runtime_seconds: 600, max_output_bytes: p.max_output_bytes };
if (await hash(utf8(payload)) !== digest(job.job_payload_hash)) throw new Error('Agentupdate: feste Jobpayloadbytes stimmen nicht');
payloads.push(payload); fixedJobs.push({ payload, job_payload_hash: job.job_payload_hash, script_sha256: null });
for (const value of release.manifest.artifacts as unknown[]) { const a = record(value); refs.push({ job_id: jobId, attempt_id: attemptId, artifact: { artifact_id: a.artifact_id, sha256: a.sha256, size_bytes: a.bytes } }); }
jobs.push({ assetId, agentId: payload.agent_id, jobId, attemptId, identity, jobHash: String(job.job_payload_hash), update, manifest: release.manifest });
}
if (!same(refs, parsed.artifact_references)) throw new Error('Agentupdate: zusätzliche/fehlende/doppelte Artefaktberechtigung');
const rebuilt = { schema_version: 1, plan_id: uuid(parsed.plan_id), tenant_id: uuid(parsed.tenant_id), principal: text(parsed.principal, 'Antragsteller'), reason: text(parsed.reason, 'Begründung'), jobs: fixedJobs, max_parallel: integer(parsed.max_parallel, 1, 10), halt_after_failures: integer(parsed.halt_after_failures), artifact_references: refs };
if (new TextDecoder().decode(utf8(rebuilt)) !== original || plan.plan_id !== parsed.plan_id) throw new Error('Agentupdate: exakte kanonische Planbytes erforderlich');
for (const alias of ['payload', 'plan_payload']) if (plan[alias] !== undefined && !same(plan[alias], parsed)) throw new Error('Agentupdate: Planansicht widerspricht gespeicherten Bytes');
if (!Array.isArray(plan.jobs) || plan.jobs.length !== jobs.length || !Array.isArray(plan.resolved_targets) || plan.resolved_targets.length !== jobs.length) throw new Error('Agentupdate: vollständige Zielansicht fehlt');
for (let index = 0; index < jobs.length; index++) {
const fixed = jobs[index]!, view = record(plan.jobs[index]), target = record(plan.resolved_targets[index]);
if (!same(view.payload, payloads[index]) || view.job_payload_hash !== fixed.jobHash || ['asset_id', 'agent_id', 'job_id', 'attempt_id'].some(field => view[field] !== undefined && view[field] !== record(payloads[index])[field])
|| Object.keys(target).some(key => !['asset_id', 'agent_id'].includes(key)) || target.asset_id !== fixed.assetId || target.agent_id !== fixed.agentId) throw new Error('Agentupdate: Zielpreview widerspricht gespeicherten Bytes');
}
if (snapshot(plan) !== before) throw new Error('Agentupdate: Plan während Prüfung verändert');
verified.set(plan, { snapshot: before, jobs });
}
export function agentUpdatePlanJobs(plan: RecordValue): UpdatePlanJob[] { const result = verified.get(plan); if (!result || result.snapshot !== snapshot(plan)) throw new Error('Agentupdateplan nicht unverändert verifiziert'); return structuredClone(result.jobs); }
export function agentUpdateApprovalBlockers(plan: RecordValue): string[] { try { agentUpdatePlanJobs(plan); return []; } catch (error) { return [error instanceof Error ? error.message : 'Agentupdateplan nicht verifiziert']; } }
+7 -1
View File
@@ -57,7 +57,7 @@ export const tenantPath = (id: string, suffix = '') => `/api/v1/tenants/${encode
export const objectId = (r: RecordValue, kind: string) => text(r[`${kind}_id`] ?? r.id, `${kind}_id`);
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 const actions = ['run_script', 'refresh_inventory', 'query_logs', 'set_service_state', 'ensure_package', 'apply_updates', 'reboot', 'apt_native_acceptance', 'update_agent'] as const;
export type Action = typeof actions[number];
export const windowsPowerShellRemoteSignedProfile = 'powershell_51_remote_signed' as const;
export const fullMaintenanceScriptProfile = 'full_maintenance_v1' as const;
@@ -193,6 +193,12 @@ export function validateInput(input: PlanInput): void {
if (profile === fullMaintenanceScriptProfile && (Number(input.parameters.timeout_seconds) > (variants.some(v => record(v).os_family === 'windows') ? 120 : 300) || Number(input.parameters.max_output_bytes) > 65536)) throw new Error('Vollwartung: Linux höchstens300s / Windows höchstens120s und65536Ausgabebytes');
}
if (!['agent_service', 'root', 'system'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich');
if (input.action === 'update_agent') {
const p = input.parameters;
if (Object.keys(p).some(key => !['release_id', 'execution_identity', 'timeout_seconds', 'max_output_bytes'].includes(key)) || input.artifact_ids !== undefined
|| !['root', 'system'].includes(String(p.execution_identity)) || p.timeout_seconds !== 600 || Number(p.max_output_bytes) > 65536) throw new Error('Agentupdate: nur feste Release-ID, Root/SYSTEM,600s/64KiB; keine freien Pins/Artefakte');
msiUuid(p.release_id); return;
}
if (input.parameters.execution_identity === 'system') {
if (input.action === 'run_script') {
if (privilegedScriptProfile(input.parameters, 'system') !== fullMaintenanceScriptProfile) throw new Error('SYSTEM-Skript benötigt ausdrücklich full_maintenance_v1');
+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);
+11
View File
@@ -1,4 +1,5 @@
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid, fullMaintenanceScriptProfile, privilegedScriptProfile, validateScriptIdentityProfile } from './api';
import { validateAgentUpdateAction } from './agent-updates';
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.';
@@ -73,6 +74,11 @@ export function validateAptManifest(value: unknown, acceptance: boolean): Record
}
export async function verifyAptManifest(value: unknown, acceptance: boolean) { const m = validateAptManifest(value, acceptance); if (await sha256(bytes(m.transaction_bytes)) !== m.transaction_sha256) throw new Error('APT Transaktionshash stimmt nicht überein'); }
export async function validateSensitiveInput(input: PlanInput, auth: Session) {
if (input.action === 'update_agent') {
if (!allowed(auth, 'updates:apply') || !['root', 'system'].includes(String(input.parameters.execution_identity))
|| !allowed(auth, input.parameters.execution_identity === 'root' ? 'root:execute' : 'system:execute')) throw new Error('Agentupdate: updates:apply und getrennte Root-/SYSTEM-Rechte erforderlich');
return;
}
if (input.action === 'run_script' && privilegedScriptProfile(input.parameters, input.parameters.execution_identity) === fullMaintenanceScriptProfile && !allowed(auth, 'scripts:execute')) throw new Error('scripts:execute für Vollwartung unbekannt oder nicht erteilt');
if (input.parameters.execution_identity === 'root' && !allowed(auth, 'root:execute')) throw new Error('root:execute unbekannt oder nicht erteilt; keine Rechteerhöhung');
if (input.parameters.execution_identity === 'system') {
@@ -356,6 +362,11 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
}
for (const payload of systemJobs) {
const action = record(payload.action);
if (action.action === 'update_agent') {
validateAgentUpdateAction(action, payload.execution_identity);
if (payload.max_runtime_seconds !== 600 || typeof payload.max_output_bytes !== 'number' || !Number.isSafeInteger(payload.max_output_bytes) || payload.max_output_bytes < 1 || payload.max_output_bytes > 65536) throw new Error('SYSTEM-Agentupdate benötigt festes600s/64KiB-Budget');
continue;
}
if (isMsi(payload)) continue; // Fully validated, hash-bound package projection above.
if (action.action === 'run_script') {
validateScriptIdentityProfile(action, payload.execution_identity, action.interpreter);