115 lines
11 KiB
TypeScript
115 lines
11 KiB
TypeScript
import { record, RecordValue, text, windowsScriptProfile, privilegedScriptProfile, fullMaintenanceScriptProfile, validateScriptIdentityProfile } from './api';
|
|
import { bytes, hashPattern, parseStrictJson, sha256 } from './safety';
|
|
|
|
export interface ScriptPlanJob {
|
|
assetId: string; agentId: string; jobId: string; attemptId: string;
|
|
interpreter: string; identity: string; windowsProfile: string; privilegedProfile: string;
|
|
script: string; scriptHash: string; jobHash: string; scriptBytes: number;
|
|
arguments: string[]; expectedStdout: string | null;
|
|
notBefore: string; startBefore: string; runtimeSeconds: number; outputBytes: number;
|
|
}
|
|
interface Verified { snapshot: string; jobs: ScriptPlanJob[] }
|
|
const verified = new WeakMap<RecordValue, Verified>();
|
|
function canonical(value: unknown): string {
|
|
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
|
if (value && typeof value === 'object') return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
|
|
return JSON.stringify(value);
|
|
}
|
|
function snapshot(plan: RecordValue): string {
|
|
return canonical(Object.fromEntries(['plan_hash', 'plan_payload_bytes', 'plan_payload', 'payload', 'jobs', 'payloads', 'resolved_targets', 'plan_id', 'expires_at'].filter(key => key in plan).map(key => [key, plan[key]])));
|
|
}
|
|
function exact(value: RecordValue, fields: string[]) {
|
|
if (Object.keys(value).some(key => !fields.includes(key)) || fields.some(key => !Object.hasOwn(value, key))) throw new Error('Skriptplan: vollständige bekannte Schemafelder erforderlich');
|
|
}
|
|
function uuid(value: unknown): string {
|
|
const id = text(value, 'Feste Skript-ID');
|
|
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id) || id === '00000000-0000-0000-0000-000000000000') throw new Error('Skriptplan: feste UUID erforderlich');
|
|
return id;
|
|
}
|
|
function integer(value: unknown, min: number, max: number): number {
|
|
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) throw new Error('Skriptplan: ungültiges festes Limit / Generation');
|
|
return value;
|
|
}
|
|
function digest(value: unknown): string { const hash = text(value, 'SHA256'); if (!hashPattern.test(hash)) throw new Error('Skriptplan: exakter SHA256 fehlt'); return hash; }
|
|
function isScript(value: unknown): boolean { return value !== null && typeof value === 'object' && record(value).action === 'run_script'; }
|
|
function validateViews(plan: RecordValue, parsed: RecordValue, jobs: RecordValue[]): void {
|
|
for (const alias of ['plan_payload', 'payload']) if (plan[alias] !== undefined && canonical(plan[alias]) !== canonical(parsed)) throw new Error('Skriptplanansicht widerspricht gespeicherten Bytes');
|
|
if (plan.plan_id !== undefined && plan.plan_id !== parsed.plan_id) throw new Error('Skript-Plan-ID widerspricht gespeicherten Bytes');
|
|
for (const alias of ['jobs', 'payloads', 'resolved_targets']) {
|
|
if (plan[alias] === undefined) continue;
|
|
const list = plan[alias]; if (!Array.isArray(list) || list.length !== jobs.length) throw new Error('Skript-Zielansicht unvollständig oder erweitert');
|
|
const seen = new Set<string>();
|
|
for (const item of list) {
|
|
const view = typeof item === 'string' ? { asset_id: item } : record(item), payload = view.payload === undefined ? null : record(view.payload);
|
|
const asset = uuid(view.asset_id ?? payload?.asset_id), fixed = jobs.find(job => record(job.payload).asset_id === asset);
|
|
if (!fixed || seen.has(asset)) throw new Error('Skript-Zielansicht enthält fremde oder doppelte Ziele'); seen.add(asset);
|
|
const p = record(fixed.payload);
|
|
if (payload) {
|
|
if (Object.keys(view).some(key => !['payload', 'job_payload_hash', 'script_sha256', 'asset_id', 'agent_id', 'job_id', 'attempt_id'].includes(key))
|
|
|| canonical(payload) !== canonical(p) || view.job_payload_hash !== fixed.job_payload_hash
|
|
|| (view.script_sha256 !== undefined && view.script_sha256 !== fixed.script_sha256)
|
|
|| ['agent_id', 'job_id', 'attempt_id'].some(key => view[key] !== undefined && view[key] !== p[key])) throw new Error('Skript-Zielpreview widerspricht gespeicherten Bytes');
|
|
} else if (alias !== 'resolved_targets' || (typeof item !== 'string' && (Object.keys(view).some(key => !['asset_id', 'agent_id'].includes(key)) || view.agent_id !== p.agent_id))) throw new Error('Vollständiger Skript-Zielpayload fehlt');
|
|
}
|
|
}
|
|
}
|
|
/** Verify stored bytes, not a draft textarea or separately formatted JSON view.
|
|
* Reconstruct the Rust JobPayload/Action declaration order for its job hash.
|
|
* This is an approval display check, never a grant of execution rights. */
|
|
export async function verifyScriptPlan(plan: RecordValue): Promise<void> {
|
|
const before = snapshot(plan), old = verified.get(plan);
|
|
if (old && old.snapshot !== before) throw new Error('Skriptplan wurde nach Anzeige verändert');
|
|
const raw = bytes(plan.plan_payload_bytes);
|
|
if (await sha256(raw) !== digest(plan.plan_hash)) throw new Error('Skript-Planhash widerspricht gespeicherten Bytes');
|
|
const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(raw)));
|
|
if (!Array.isArray(parsed.jobs)) throw new Error('Vollständige feste Jobdefinitionen fehlen');
|
|
const jobs = parsed.jobs.map(value => record(value));
|
|
validateViews(plan, parsed, jobs);
|
|
if (!jobs.some(job => isScript(record(job.payload).action))) {
|
|
if (snapshot(plan) !== before) throw new Error('Plan wurde während der Prüfung verändert');
|
|
verified.set(plan, { snapshot: before, jobs: [] }); return;
|
|
}
|
|
exact(parsed, ['schema_version', 'plan_id', 'tenant_id', 'principal', 'reason', 'jobs', 'max_parallel', 'halt_after_failures', ...(Object.hasOwn(parsed, 'recipe_references') ? ['recipe_references'] : []), ...(Object.hasOwn(parsed, 'artifact_references') ? ['artifact_references'] : [])]);
|
|
if (parsed.schema_version !== 1 || !jobs.length || jobs.length > 100) throw new Error('Skriptplan: unbekanntes Schema oder Zielbudget');
|
|
uuid(parsed.plan_id); uuid(parsed.tenant_id); text(parsed.principal, 'Antragsteller'); text(parsed.reason, 'Begründung');
|
|
integer(parsed.max_parallel, 1, 10); integer(parsed.halt_after_failures, 1, Number.MAX_SAFE_INTEGER);
|
|
const result: ScriptPlanJob[] = [], assets = new Set<string>(), attempts = new Set<string>();
|
|
for (const job of jobs) {
|
|
const p = record(job.payload); if (!isScript(p.action)) continue;
|
|
exact(job, ['payload', 'job_payload_hash', 'script_sha256']);
|
|
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), agentId = uuid(p.agent_id), jobId = uuid(p.job_id), attemptId = uuid(p.attempt_id);
|
|
if (p.schema_version !== 1 || p.tenant_id !== parsed.tenant_id || assets.has(assetId) || attempts.has(`${jobId}/${attemptId}`)) throw new Error('Skriptplan: widersprüchliche feste Ziele / Versuche');
|
|
assets.add(assetId); attempts.add(`${jobId}/${attemptId}`);
|
|
integer(p.enrollment_generation, 1, Number.MAX_SAFE_INTEGER); integer(p.assignment_version, 1, Number.MAX_SAFE_INTEGER);
|
|
const action = record(p.action), hasWindowsProfile = Object.hasOwn(action, 'windows_execution_profile'), hasPrivilegedProfile = Object.hasOwn(action, 'privileged_script_profile');
|
|
exact(action, ['action', 'interpreter', 'script_utf8', 'arguments', 'expected_stdout', ...(hasWindowsProfile ? ['windows_execution_profile'] : []), ...(hasPrivilegedProfile ? ['privileged_script_profile'] : [])]);
|
|
const interpreter = text(action.interpreter, 'Interpreter'), identity = text(p.execution_identity, 'Ausführungsidentität'), script = text(action.script_utf8, 'Skriptbytes'), scriptBytes = new TextEncoder().encode(script);
|
|
validateScriptIdentityProfile(action, identity, interpreter);
|
|
const privilegedProfile = privilegedScriptProfile(action, identity);
|
|
if (scriptBytes.length > 32768 || script.includes('\0') || (interpreter === 'powershell' && !/^[\x00-\x7f]*$/.test(script) && !script.startsWith('\ufeff'))) throw new Error('Skriptplan: Interpreter, Identität oder exakte Skriptbytes ungültig');
|
|
const windowsProfile = windowsScriptProfile(action);
|
|
if (!Array.isArray(action.arguments) || action.arguments.length > 32 || action.arguments.some(arg => typeof arg !== 'string' || new TextEncoder().encode(arg).length > 4096 || arg.includes('\0'))
|
|
|| !(action.expected_stdout === null || (typeof action.expected_stdout === 'string' && new TextEncoder().encode(action.expected_stdout).length <= 65536))) throw new Error('Skriptplan: feste Argumente / stdout-Nachbedingung fehlen');
|
|
const notBefore = text(p.not_before, 'Frühester Start'), startBefore = text(p.start_before, 'Startfrist');
|
|
if (!Number.isFinite(Date.parse(notBefore)) || !Number.isFinite(Date.parse(startBefore)) || Date.parse(notBefore) >= Date.parse(startBefore) || (plan.expires_at !== undefined && plan.expires_at !== startBefore)) throw new Error('Skriptplan: widersprüchliche feste Fristen');
|
|
const full = privilegedProfile === fullMaintenanceScriptProfile;
|
|
const runtimeSeconds = integer(p.max_runtime_seconds, 1, full ? interpreter === 'powershell' ? 120 : 300 : 3600), outputBytes = integer(p.max_output_bytes, 1, full ? 65536 : 262144);
|
|
const orderedAction = { action: 'run_script', interpreter, script_utf8: script, arguments: action.arguments, expected_stdout: action.expected_stdout, ...(hasWindowsProfile ? { windows_execution_profile: action.windows_execution_profile } : {}), ...(hasPrivilegedProfile ? { privileged_script_profile: action.privileged_script_profile } : {}) };
|
|
const ordered = { schema_version: p.schema_version, tenant_id: p.tenant_id, asset_id: assetId, agent_id: agentId, enrollment_generation: p.enrollment_generation, assignment_version: p.assignment_version, job_id: jobId, attempt_id: attemptId, action: orderedAction, execution_identity: identity, not_before: notBefore, start_before: startBefore, max_runtime_seconds: runtimeSeconds, max_output_bytes: outputBytes };
|
|
const scriptHash = digest(job.script_sha256), jobHash = digest(job.job_payload_hash);
|
|
if (await sha256(scriptBytes) !== scriptHash || await sha256(new TextEncoder().encode(JSON.stringify(ordered))) !== jobHash) throw new Error('Skript-/Jobhash widerspricht exakten Rust-Payloadbytes');
|
|
result.push({ assetId, agentId, jobId, attemptId, interpreter, identity, windowsProfile, privilegedProfile, script, scriptHash, jobHash, scriptBytes: scriptBytes.length, arguments: [...action.arguments] as string[], expectedStdout: action.expected_stdout as string | null, notBefore, startBefore, runtimeSeconds, outputBytes });
|
|
}
|
|
if (snapshot(plan) !== before) throw new Error('Skriptplan wurde während der Hashprüfung verändert');
|
|
verified.set(plan, { snapshot: before, jobs: result });
|
|
}
|
|
export function scriptPlanJobs(plan: RecordValue): ScriptPlanJob[] {
|
|
const checked = verified.get(plan);
|
|
if (!checked || checked.snapshot !== snapshot(plan)) throw new Error('Skriptplan nicht aus unveränderten gespeicherten Bytes verifiziert');
|
|
return structuredClone(checked.jobs);
|
|
}
|
|
export function scriptApprovalBlockers(plan: RecordValue): string[] {
|
|
try { scriptPlanJobs(plan); return []; } catch (error) { return [error instanceof Error ? error.message : 'Skriptplan nicht verifiziert']; }
|
|
}
|