Files
rust-discovery/web/src/safety.ts
2026-11-14 05:30:21 +01:00

136 lines
15 KiB
TypeScript

import { Action, PlanInput, RecordValue, Session, record, text, validateSystemService } from './api';
export const hashPattern = /^[0-9a-f]{64}$/;
export const rootWarning = 'HOHES RISIKO: root kann das Zielsystem verändern. Keine automatische Rechteerhöhung; eigener expliziter Plan, Scope, Helper und Genehmigung erforderlich.';
export const systemWarning = 'SYSTEM: ausschließlich fest benannter Windows-Fixturedienst und running/stopped. Eigenes system:execute, unabhängiger Helper und konkrete WebUI-Genehmigung erforderlich. Keine SYSTEM-Shell, kein impliziter Reboot oder Retry.';
export function permissions(auth: Session): string[] | null { return auth.permissions ?? null; }
export function allowed(auth: Session, permission: string): boolean { return permissions(auth)?.includes(permission) === true; }
export function availableActions(auth: Session, base: readonly Action[]): Action[] { return base.filter(a => a !== 'apt_native_acceptance' || auth.principal.simulated === true); }
export function parseStrictJson(source: string): unknown {
if (new TextEncoder().encode(source).length > 1048576) throw new Error('JSON über 1 MiB');
let i = 0;
const space = () => { while (/\s/.test(source[i] ?? '') && i < source.length) i++; };
const string = (): string => { const start = i++; while (i < source.length) { if (source[i] === '\\') i += 2; else if (source[i++] === '"') return JSON.parse(source.slice(start, i)); } throw new Error('Ungültiger JSON-String'); };
const value = (depth: number): void => {
if (depth > 64) throw new Error('JSON zu tief verschachtelt'); space();
if (source[i] === '{') { i++; space(); const keys = new Set<string>(); if (source[i] === '}') { i++; return; }
while (i < source.length) { space(); if (source[i] !== '"') throw new Error('JSON-Objektschlüssel erwartet'); const key = string(); if (keys.has(key)) throw new Error(`Doppeltes JSON-Feld: ${key}`); keys.add(key); space(); if (source[i++] !== ':') throw new Error('JSON-Doppelpunkt erwartet'); value(depth + 1); space(); const end = source[i++]; if (end === '}') return; if (end !== ',') throw new Error('Ungültiges JSON-Objekt'); } throw new Error('Unvollständiges JSON-Objekt'); }
if (source[i] === '[') { i++; space(); if (source[i] === ']') { i++; return; } while (i < source.length) { value(depth + 1); space(); const end = source[i++]; if (end === ']') return; if (end !== ',') throw new Error('Ungültiges JSON-Array'); } throw new Error('Unvollständiges JSON-Array'); }
if (source[i] === '"') { string(); return; }
const token = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(i)); if (!token) throw new Error('Ungültiger JSON-Wert'); i += token[0].length;
};
value(0); space(); if (i !== source.length) throw new Error('Zusätzliche JSON-Daten'); return JSON.parse(source);
}
function exact(r: RecordValue, fields: string[]) { if (Object.keys(r).some(k => !fields.includes(k)) || fields.some(k => !(k in r))) throw new Error('Schemafelder fehlen oder sind unbekannt'); }
function hash(v: unknown) { if (typeof v !== 'string' || !hashPattern.test(v) || /^0{64}$/.test(v)) throw new Error('Exakter SHA-256 fehlt/Platzhalter'); }
export function bytes(value: unknown): Uint8Array<ArrayBuffer> { if (!Array.isArray(value) || !value.length || value.length > 1048576 || value.some(n => !Number.isInteger(n) || n < 0 || n > 255)) throw new Error('Exakte Bytefolge fehlt'); return new Uint8Array(value); }
export async function sha256(value: Uint8Array<ArrayBuffer>): Promise<string> { return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', value)), n => n.toString(16).padStart(2, '0')).join(''); }
function canonical(v: unknown): string { if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`; if (v !== null && typeof v === 'object') return `{${Object.entries(v).sort(([a], [b]) => a.localeCompare(b)).map(([k, x]) => `${JSON.stringify(k)}:${canonical(x)}`).join(',')}}`; return JSON.stringify(v); }
export function validateAptManifest(value: unknown, acceptance: boolean): RecordValue {
const m = record(value, 'apt_manifest');
exact(m, ['type', 'schema_version', 'action', 'execution_profile', 'transaction_sha256', 'resolved_apt_transaction', 'transaction_bytes', 'provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256', 'test_result_id', ...(m.schema_version === 3 ? ['native_retry'] : []), ...(m.schema_version === 4 ? ['native_recovery'] : [])]);
if (m.type !== 'rmm.apt.helper-action' || ![2, 3, 4].includes(Number(m.schema_version)) || typeof m.schema_version !== 'number' || m.execution_profile !== 'dev-test' || m.action !== (acceptance ? 'apt-native-acceptance' : 'apt-execute')) throw new Error('APT Schema 2/3/4 / explizites dev-test-Profil erforderlich');
if (m.schema_version === 3) {
if (!acceptance) throw new Error('Wiederaufnahme nur als eigener nativer Abnahmeplan');
const retry = record(m.native_retry); exact(retry, ['schema_version', 'previous_grant_id', 'previous_attempt_id', 'bootstrap_marker_sha256']);
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
if (retry.schema_version !== 1 || ['previous_grant_id', 'previous_attempt_id'].some(k => typeof retry[k] !== 'string' || !uuid.test(retry[k] as string) || retry[k] === '00000000-0000-0000-0000-000000000000')) throw new Error('Exakte ursprüngliche Grant-/Versuchsbindung erforderlich');
hash(retry.bootstrap_marker_sha256);
}
const recovery = m.schema_version === 4;
if (recovery) {
if (!acceptance) throw new Error('Configure-only benötigt einen eigenen nativen Abnahmeplan');
const ref = record(m.native_recovery); exact(ref, ['schema_version', 'previous_grant_id', 'previous_attempt_id', 'partial_proof_sha256']);
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
if (ref.schema_version !== 1 || ['previous_grant_id', 'previous_attempt_id'].some(k => typeof ref[k] !== 'string' || !uuid.test(ref[k] as string) || ref[k] === '00000000-0000-0000-0000-000000000000')) throw new Error('Exakte geschlossene Partial-Grant-/Versuchsbindung erforderlich');
hash(ref.partial_proof_sha256);
}
for (const k of ['transaction_sha256', 'provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256']) hash(m[k]);
if (typeof m.test_result_id !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(m.test_result_id)) throw new Error('Exakte Testnachweis-ID erforderlich');
const transaction = record(m.resolved_apt_transaction);
exact(transaction, ['schema_version', 'recipe_id', 'recipe_version', 'platform', 'resolver_config_version', 'no_reboot', 'status_fingerprint', 'baseline_sha256', 'packages', ...(recovery ? ['operation'] : [])]);
if (transaction.schema_version !== (recovery ? 2 : 1) || (recovery && transaction.operation !== 'configure_only') || transaction.recipe_version !== '1' || transaction.platform !== 'ubuntu-24.04-amd64' || transaction.resolver_config_version !== 'rmm-apt-local-v1' || transaction.no_reboot !== true) throw new Error('APT Transaktionsschema/Plattform/No-Reboot ungültig');
text(transaction.recipe_id, 'recipe_id'); hash(transaction.status_fingerprint); hash(transaction.baseline_sha256);
if (!Array.isArray(transaction.packages) || !transaction.packages.length || transaction.packages.length > 128) throw new Error('Vollständige Paketclosure erforderlich');
const identities = new Set<string>();
for (const value of transaction.packages) {
const p = record(value); exact(p, ['name', 'architecture', 'old_version', 'new_version', 'origin', 'sha256', 'size', 'archive_path']);
for (const k of ['name', 'architecture', 'new_version', 'origin']) text(p[k], k);
if (p.old_version !== null) text(p.old_version, 'old_version'); hash(p.sha256);
if (typeof p.size !== 'number' || !Number.isSafeInteger(p.size) || p.size < 1 || p.archive_path !== `/var/lib/rmm-apt-transaction/archives/${p.sha256}.deb`) throw new Error('APT Archivgröße/Pfadbindung fehlt');
const id = `${p.name}:${p.architecture}`; if (identities.has(id)) throw new Error('Doppelte Paketidentität'); identities.add(id);
}
const parsed = parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes(m.transaction_bytes)));
if (canonical(parsed) !== canonical(transaction)) throw new Error('Exakte Transaktionsbytes widersprechen Manifestobjekt');
if (acceptance) {
const install = transaction.recipe_id === 'rmm-apt-fixture-install-1.0', update = transaction.recipe_id === 'rmm-apt-fixture-update-1.1';
if ((!install && !update) || (recovery && !install) || transaction.packages.length !== 1) throw new Error('Nur genaue native Fixture-Rezepte erlaubt');
const p = record(transaction.packages[0]);
if (p.name !== 'rmm-mvp-test' || p.architecture !== 'all' || p.origin !== 'rmm-test' || p.size !== 20672 || p.old_version !== (recovery ? '1.0' : install ? null : '1.0') || p.new_version !== (install ? '1.0' : '1.1') || p.sha256 !== (install ? '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867' : 'ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af6027d8a9c00491')) throw new Error('Native Fixture-Bytes/Version/Origin stimmen nicht überein');
}
return m;
}
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.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') {
if (!allowed(auth, 'system:execute')) throw new Error('system:execute unbekannt oder nicht erteilt; root:execute enthält dieses Recht nicht');
if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen');
validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
}
if (input.action === 'apt_native_acceptance') {
if (!auth.principal.simulated || input.parameters.execution_identity !== 'root') throw new Error('APT-Abnahme ausschließlich explizit simuliert und root');
const m = validateAptManifest(input.parameters.apt_manifest, true), t = record(m.resolved_apt_transaction);
if (input.parameters.recipe_id !== t.recipe_id || input.parameters.recipe_version !== t.recipe_version) throw new Error('Äußeres Rezept widerspricht Manifest');
await verifyAptManifest(m, true);
} else if (input.action === 'ensure_package' || input.action === 'apply_updates') {
if (input.parameters.apt_manifest !== undefined && input.parameters.apt_manifest !== null) {
const m = validateAptManifest(input.parameters.apt_manifest, false), t = record(m.resolved_apt_transaction), packages = t.packages;
if (!Array.isArray(packages)) throw new Error('Paketclosure fehlt');
if (input.action === 'ensure_package' && (input.parameters.recipe_version !== t.recipe_version || (input.parameters.recipe_id !== undefined && input.parameters.recipe_id !== t.recipe_id))) throw new Error('Äußere Rezeptbindung widerspricht Manifest');
if (input.action === 'ensure_package' && !packages.some(v => { const p = record(v); return p.name === input.parameters.package && p.new_version === input.parameters.version && p.architecture === input.parameters.architecture; })) throw new Error('Exakte Paketidentität fehlt in Closure');
if (input.action === 'apply_updates' && (!Array.isArray(input.parameters.packages) || input.parameters.packages.length !== packages.length || !input.parameters.packages.every(v => typeof v === 'string' && packages.some(x => { const p = record(x); return v === p.name; })))) throw new Error('Exakte Updateauswahl fehlt in versionsgebundener Closure');
await verifyAptManifest(m, false);
}
}
}
/** Display only definitions decoded from the exact hashed plan bytes. */
export function systemPlanJobs(plan: RecordValue): RecordValue[] {
if (plan.plan_payload_bytes === undefined) return [];
const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes(plan.plan_payload_bytes))));
if (!Array.isArray(parsed.jobs)) return [];
return parsed.jobs.map(value => record(record(value).payload)).filter(payload => payload.execution_identity === 'system');
}
export async function verifyPlanIntegrity(plan: RecordValue) {
if (plan.plan_payload_bytes === undefined && Array.isArray(plan.jobs) && plan.jobs.some(value => {
const payload = record(value).payload;
return payload !== null && typeof payload === 'object' && record(payload).execution_identity === 'system';
})) throw new Error('SYSTEM-Plan benötigt exakte gespeicherte Planbytes');
if (plan.plan_payload_bytes !== undefined) {
const exactBytes = bytes(plan.plan_payload_bytes); hash(plan.plan_hash);
if (await sha256(exactBytes) !== plan.plan_hash) throw new Error('Planhash stimmt nicht mit gespeicherten Bytes überein');
const parsed = parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(exactBytes));
if (plan.plan_payload !== undefined && canonical(parsed) !== canonical(plan.plan_payload)) throw new Error('Planansicht widerspricht gespeicherten Bytes');
}
for (const payload of systemPlanJobs(plan)) {
const action = record(payload.action);
exact(action, ['action', 'unit', 'state']);
if (action.action !== 'set_service_state') throw new Error('SYSTEM-Plan enthält keine typisierte Dienstaktion');
validateSystemService(action.unit, action.state, payload.max_runtime_seconds, payload.max_output_bytes);
}
const jobs = Array.isArray(plan.jobs) ? plan.jobs : Array.isArray(plan.resolved_targets) ? plan.resolved_targets : [];
for (const value of jobs) { if (!value || typeof value !== 'object') continue; const p = record(value).payload; if (!p || typeof p !== 'object') continue; const action = record(p).action;
if (action && typeof action === 'object' && record(action).apt_manifest !== undefined && record(action).apt_manifest !== null) await verifyAptManifest(record(action).apt_manifest, record(action).action === 'apt_native_acceptance');
}
}
export function recipeInput(value: unknown): RecordValue {
const r = record(value); exact(r, ['schema_version', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'reboot_policy']);
if (r.schema_version !== 1 || r.provider !== 'apt' || r.architecture !== 'amd64' || r.installation_context !== 'system' || r.reboot_policy !== 'never') throw new Error('Nur unveränderliches APT/amd64/system/never-Rezept unterstützt');
for (const k of ['package', 'version', 'recipe_version']) { const v = text(r[k], k); if (!/^[A-Za-z0-9_.:+~-]+$/.test(v) || v.startsWith('-')) throw new Error('Exakte Paket-/Rezeptidentität erforderlich; keine URL/Installerargumente'); }
return { schema_version: 1, provider: r.provider, package: r.package, version: r.version, architecture: r.architecture, recipe_version: r.recipe_version, installation_context: r.installation_context, reboot_policy: r.reboot_policy };
}
export function adminIntent(confirmed: boolean, reason: string, nonce: string, expected: string): { reason: string } {
if (!confirmed || !reason.trim() || new TextEncoder().encode(reason).length > 1024 || nonce !== expected || !expected) throw new Error('Explizite Bestätigung, aktuelle Bestätigungskennung und Grund erforderlich');
return { reason };
}