feat: add approval bound full maintenance script console and executors
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
+63
-6
@@ -1,6 +1,6 @@
|
||||
# Linux-MVP WebUI
|
||||
|
||||
React/TypeScript, no runtime demo data, no desktop/terminal/hypervisor integration.
|
||||
React/TypeScript, no runtime demo data, no desktop/PTY/hypervisor integration.
|
||||
Build assets: **`web/dist/`**; serve `index.html` and `/assets/*` from the TLS backend
|
||||
on the same origin. Do not proxy authentication to a different origin. All API URLs
|
||||
are relative; cookies use `credentials: same-origin`, mutations use `X-CSRF-Token`.
|
||||
@@ -10,8 +10,64 @@ No token or password persistence, raw HTML rendering, automatic approval or retr
|
||||
|
||||
From `web/`: `npm ci`, `npm run typecheck`, `npm test`, `npm run build`.
|
||||
`npm run dev` binds loopback, but is not the authenticated TLS acceptance setup.
|
||||
The authoritative runtime is the backend serving `web/dist` at
|
||||
`https://rmm-dev.internal:18443`. No certificate-verification bypass is supported.
|
||||
The current server is `discovery.ease-technologies.de`; management access uses the
|
||||
configured SSH tunnel and verified TLS. Earlier local `rmm-dev.internal:18443`
|
||||
examples below are historical. The notebook is development only, without an RMM
|
||||
server or enrolled agent. No certificate-verification bypass is supported.
|
||||
|
||||
## Script console (specification 1.20, source implementation)
|
||||
|
||||
`run_script` remains a durable plan/request, not a PTY or interactive terminal.
|
||||
The planner accepts complete fixed POSIX/Bash or Windows PowerShell5.1 scripts.
|
||||
The optional action-wide `parameters.privileged_script_profile` is exactly
|
||||
`full_maintenance_v1`; missing preserves the existing bounded mode, while present
|
||||
null/unknown values fail. Full maintenance requires root on Linux or SYSTEM on
|
||||
Windows, plus `scripts:execute` and the separate root/system scope. SYSTEM scripts
|
||||
require the explicit profile. The UI selection grants no permission: central/local
|
||||
opt-in, target capabilities, independent helper checks and actual WebUI approval
|
||||
remain necessary. Full authority includes filesystem, network and services, and
|
||||
can alter the agent/PKI or cause a reboot. It has no sandbox/no-reboot promise.
|
||||
The profile budgets are Linux 1–300s, Windows 1–120s, at most 32768 script bytes
|
||||
and 65536 output bytes. RemoteSigned, when explicitly bound, remains limited to
|
||||
the approved Windows job process.
|
||||
|
||||
Before submit/approval, `src/script-console.ts` projects every script from the
|
||||
SHA256-verified stored plan bytes. It checks full payload structure, fixed
|
||||
target/job/attempt IDs, script SHA256 and the job SHA256 reconstructed in Rust
|
||||
declaration order. Every supplied payload/target alias must agree. It snapshots
|
||||
the checked views, rejects later mutation and rechecks immediately before each
|
||||
submit/approval action. The displayed script, arguments, identity, profiles,
|
||||
budgets, deadlines and hashes come from that projection, never the draft editor.
|
||||
Control characters, CR, BOM and bidi controls are made visible in the text view;
|
||||
the full original JSON and stored bytes remain available. Existing pending-only
|
||||
submission and interactivity/CSRF checks remain in force.
|
||||
|
||||
`src/console-output.tsx` displays the actual stored job status and final stdout/
|
||||
stderr. Status polling is every four seconds; output arrives with the durable
|
||||
result. There is no incremental output stream. Null result, empty output,
|
||||
unknown exit code, unknown outcome, requested cancellation and truncation are
|
||||
distinct. UTF-8 is a display attempt, not a claimed source encoding; invalid
|
||||
UTF-8 is marked and original bytes can be downloaded as inert `.bin` files.
|
||||
Terminal escapes and bidi controls are visible, never interpreted. Agent output
|
||||
is React text and cannot create HTML, approval controls or follow-up jobs.
|
||||
|
||||
MCP already dispatches plan/submit/read-results to the same server application
|
||||
functions. Shared PlanRequest/Action schemas expose the profile; MCP has no
|
||||
approval tool and its bearer context cannot become an interactive approval
|
||||
session. No independent MCP execution or approval path was added.
|
||||
|
||||
Local typechecking and renderer tests are source evidence only. Native Linux/
|
||||
Windows runs, deployment and actual UI/MCP acceptance remain separate gates.
|
||||
Actually executed on 2026-11-14 for this source slice: `npm ci --ignore-scripts
|
||||
--no-audit --no-fund`, `npm run typecheck`, `npm test` (49 passed across seven
|
||||
files), `npm run build` (TypeScript and Vite passed). Five script-console tests
|
||||
read `../tests/script_console/codec-golden.json` directly: the same three actual
|
||||
Rust codec families cover legacy Linux agent, Linux root/full and Windows
|
||||
SYSTEM/full with RemoteSigned. Checks cover full displayed script/target/attempt/
|
||||
profile/budgets/hashes, all aliases, mutation during/after verification and
|
||||
independent scopes. Two output tests cover hostile HTML/terminal/bidi bytes,
|
||||
unknown/cancellation/truncation, invalid encodings and absent/invalid results.
|
||||
No browser, server, VM job, approval or deployment was executed in these checks.
|
||||
|
||||
## JSON adapter contract
|
||||
|
||||
@@ -70,9 +126,10 @@ All business endpoints are under `/api/v1/tenants/{tenant}`:
|
||||
asset_id can also come from the exact payload. Every target requires a nonempty
|
||||
exact payload and payload hash; preview coverage must equal the fixed target set,
|
||||
duplicate asset IDs and contradictory payload asset IDs are rejected.
|
||||
`job_id`/`attempt_id` are **not prerequisites** for planning, submission or approval:
|
||||
if present they are optional fixed plan references, not proof of executable jobs
|
||||
or persisted attempts. Actual jobs/attempts are created only after approval.
|
||||
Script plans require the reserved `job_id`/`attempt_id` from the exact stored
|
||||
payload, as well as matching script/job hashes. These are fixed definitions,
|
||||
not proof of executable jobs or persisted attempts. Actual execution rows are
|
||||
created only after approval.
|
||||
Exact payload metadata and script/package hashes must be included. UI does not
|
||||
recompute the plan hash from JSON. Missing fixed targets/previews/payload/hash or
|
||||
excluded targets block submission and approval. All fields are shown, not just
|
||||
|
||||
+20
-2
@@ -60,6 +60,18 @@ 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 type Action = typeof actions[number];
|
||||
export const windowsPowerShellRemoteSignedProfile = 'powershell_51_remote_signed' as const;
|
||||
export const fullMaintenanceScriptProfile = 'full_maintenance_v1' as const;
|
||||
export function privilegedScriptProfile(value: RecordValue, identity: unknown): 'bounded' | typeof fullMaintenanceScriptProfile {
|
||||
if (!Object.hasOwn(value, 'privileged_script_profile')) return 'bounded';
|
||||
if (value.privileged_script_profile !== fullMaintenanceScriptProfile || !['root', 'system'].includes(String(identity))) throw new Error('Vollwartungsprofil ausschließlich full_maintenance_v1 mit root/system; kein null oder geerbtes Privileg');
|
||||
return fullMaintenanceScriptProfile;
|
||||
}
|
||||
export function validateScriptIdentityProfile(value: RecordValue, identity: unknown, interpreter: unknown): void {
|
||||
const profile = privilegedScriptProfile(value, identity);
|
||||
if (interpreter === 'powershell') {
|
||||
if (identity !== 'agent_service' && !(identity === 'system' && profile === fullMaintenanceScriptProfile)) throw new Error('PowerShell nur agent_service oder ausdrücklich SYSTEM/full_maintenance_v1');
|
||||
} else if (!['posix_sh', 'bash'].includes(String(interpreter)) || !['agent_service', 'root'].includes(String(identity))) throw new Error('Linux-Skript benötigt agent_service/root und festen Shellinterpreter');
|
||||
}
|
||||
/** A missing field is inherited policy; a present field is never silently coerced. */
|
||||
export function windowsScriptProfile(value: RecordValue): 'inherited' | typeof windowsPowerShellRemoteSignedProfile {
|
||||
if (!Object.prototype.hasOwnProperty.call(value, 'windows_execution_profile')) return 'inherited';
|
||||
@@ -157,6 +169,7 @@ export function expectedStdout(value: string, format: string): string | null {
|
||||
return output;
|
||||
}
|
||||
export function validateInput(input: PlanInput): void {
|
||||
if (Object.hasOwn(input.parameters, 'privileged_script_profile') && input.action !== 'run_script') throw new Error('Vollwartungsprofil ausschließlich für run_script');
|
||||
if (Object.prototype.hasOwnProperty.call(input.parameters, 'windows_execution_profile')) throw new Error('Windows-Ausführungsprofil muss an der festen Windows-Skriptvariante stehen');
|
||||
if (!input.targets.asset_ids.length || new Set(input.targets.asset_ids).size !== input.targets.asset_ids.length) throw new Error('Feste eindeutige Ziele erforderlich');
|
||||
if (!input.reason.trim()) throw new Error('Begründung erforderlich');
|
||||
@@ -164,21 +177,26 @@ export function validateInput(input: PlanInput): void {
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start || end <= Date.now()) throw new Error('Ungültige oder abgelaufene Frist');
|
||||
for (const n of [input.rollout.max_parallel, input.rollout.halt_after_failures, input.parameters.timeout_seconds, input.parameters.max_output_bytes]) if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 1) throw new Error('Limits müssen positive Ganzzahlen sein');
|
||||
if (input.action === 'run_script') {
|
||||
const profile = privilegedScriptProfile(input.parameters, input.parameters.execution_identity);
|
||||
const variants = input.parameters.variants;
|
||||
if (!Array.isArray(variants) || !variants.length || variants.length > 2 || !variants.every(v => {
|
||||
const variant = record(v), script = typeof variant.script_utf8 === 'string' ? variant.script_utf8 : '';
|
||||
if (Object.hasOwn(variant, 'privileged_script_profile')) throw new Error('Privilegiertes Skriptprofil muss aktionsweit in parameters stehen');
|
||||
windowsScriptProfile(variant);
|
||||
validateScriptIdentityProfile(input.parameters, input.parameters.execution_identity, variant.interpreter);
|
||||
const bytes = new TextEncoder().encode(script).length;
|
||||
const platform = variant.os_family === 'linux' && ['posix_sh', 'bash'].includes(String(variant.interpreter))
|
||||
|| variant.os_family === 'windows' && variant.interpreter === 'powershell';
|
||||
return bytes > 0 && bytes <= 32768 && !script.includes('\0') && variant.encoding === 'utf-8' && platform
|
||||
&& (variant.os_family !== 'windows' || /^[\x00-\x7f]*$/.test(script) || script.startsWith('\ufeff'));
|
||||
}) || new Set(variants.map(v => record(v).os_family)).size !== variants.length) throw new Error('Je Plattform genau eine passende UTF-8 Variante (max.32KiB); PowerShell5.1: ASCII oder explizites UTF-8-BOM vor Hashbildung');
|
||||
if (variants.some(v => record(v).os_family === 'windows') && input.parameters.execution_identity !== 'agent_service') throw new Error('Windows PowerShell benötigt agent_service; kein SYSTEM-/Root-Fallback');
|
||||
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.parameters.execution_identity === 'system') {
|
||||
if (input.action === 'ensure_package') validateWindowsMsiInput(input);
|
||||
if (input.action === 'run_script') {
|
||||
if (privilegedScriptProfile(input.parameters, 'system') !== fullMaintenanceScriptProfile) throw new Error('SYSTEM-Skript benötigt ausdrücklich full_maintenance_v1');
|
||||
} else if (input.action === 'ensure_package') validateWindowsMsiInput(input);
|
||||
else {
|
||||
if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte eigene Windows-Fixturedienste oder feste MSI-Rezepte; keine SYSTEM-Shell');
|
||||
validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { ConsoleOutput, outputBytes, outputText } from './console-output';
|
||||
|
||||
it('renders hostile output as inert text, reports real status and preserves exact raw bytes', () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);
|
||||
try {
|
||||
const hostile = '<script>fetch("/approve")</script>\r\n\x1b[2J\u202eapprove', raw = Array.from(new TextEncoder().encode(hostile));
|
||||
const job = { state: 'unknown', attempt_id: 'fixed-attempt', revision: 4, cancel_requested: true, result: { stdout: raw, stderr: [], exit_code: null, error_code: 'TIMEOUT', output_truncated: true, reboot_required: false } };
|
||||
const before = JSON.stringify(job), html = renderToStaticMarkup(<ConsoleOutput job={job}/>);
|
||||
for (const expected of ['unknown', 'fixed-attempt', 'TIMEOUT', 'unknown / nicht gemeldet', 'nur ein Ausschnitt', 'keinen Live-Ausgabestream', 'Abbruch angefordert', 'neuen genehmigten Plan', '<script>', '\\u000d', '\\u001b', '\\u202e', JSON.stringify(raw)]) expect(html).toContain(expected);
|
||||
expect(html).not.toMatch(/<(script|img|iframe|form|input)\b/i);
|
||||
expect(html).not.toContain('onclick='); expect(fetch).not.toHaveBeenCalled(); expect(JSON.stringify(job)).toBe(before);
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
|
||||
it('distinguishes no result, empty bytes, invalid encoding, invalid bytes and missing truncation evidence', () => {
|
||||
const pending = renderToStaticMarkup(<ConsoleOutput job={{ state: 'running', result: null }}/>);
|
||||
expect(pending).toContain('Noch kein gespeichertes Ergebnis'); expect(pending).not.toContain('(leere Ausgabe)');
|
||||
const partial = renderToStaticMarkup(<ConsoleOutput job={{ state: 'failed', result: { stdout: [255, 0, 13, 10], stderr: [] } }}/>);
|
||||
expect(partial).toContain('kein gültiges UTF-8'); expect(partial).toContain('Vollständigkeit ist nicht bestätigt'); expect(partial).toContain('(leere Ausgabe)');
|
||||
const bad = renderToStaticMarkup(<ConsoleOutput job={{ state: 'failed', result: { stdout: [256], stderr: 'not bytes', output_truncated: false } }}/>);
|
||||
expect(bad.match(/Keine verlässliche Textansicht/g)).toHaveLength(2);
|
||||
for (const raw of [undefined, 'hello', [1.5], [-1], [256]]) expect(() => outputBytes(raw)).toThrow();
|
||||
const bytes = outputBytes([239, 187, 191, 65, 13, 10]);
|
||||
expect(outputText(bytes).text).toBe('\\ufeffA\\u000d\n'); expect(Array.from(bytes)).toEqual([239, 187, 191, 65, 13, 10]);
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { record, RecordValue, stringField } from './api';
|
||||
|
||||
/** The wire format carries bytes, not an encoding declaration. Never guess a
|
||||
* Windows code page or interpret output as HTML, terminal escapes or actions. */
|
||||
export function outputBytes(value: unknown): Uint8Array<ArrayBuffer> {
|
||||
if (!Array.isArray(value) || value.length > 262144 || value.some(byte => !Number.isInteger(byte) || byte < 0 || byte > 255)) throw new Error('Ungültige oder zu große Ausgabebytes');
|
||||
return new Uint8Array(value);
|
||||
}
|
||||
export function outputText(raw: Uint8Array<ArrayBuffer>): { text: string; encoding: string } {
|
||||
let decoded: string, encoding: string;
|
||||
try { decoded = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw); encoding = 'UTF-8 lesbar; Quellencoding nicht separat belegt'; }
|
||||
catch { decoded = new TextDecoder('utf-8', { ignoreBOM: true }).decode(raw); encoding = 'Encoding unbekannt / kein gültiges UTF-8: Ersatzzeichen nur in der Textansicht'; }
|
||||
// Make terminal/control and bidi characters visible. In particular CR cannot
|
||||
// visually overwrite an earlier line; CRLF remains recognizable as such.
|
||||
return { text: decoded.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g,
|
||||
char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`), encoding };
|
||||
}
|
||||
function download(raw: Uint8Array<ArrayBuffer>, name: 'stdout' | 'stderr') {
|
||||
const url = URL.createObjectURL(new Blob([raw], { type: 'application/octet-stream' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = url; link.download = `${name}.bin`; link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
function OutputChannel({ value, name }: { value: unknown; name: 'stdout' | 'stderr' }) {
|
||||
try {
|
||||
const raw = outputBytes(value), view = outputText(raw);
|
||||
return <div><h4>{name} · {raw.length} gespeicherte Bytes</h4><p className="muted">{view.encoding}. Steuerzeichen werden sichtbar als \\uXXXX dargestellt; Rohbytes bleiben erhalten.</p>
|
||||
<pre className="console-output" aria-label={`${name} Textansicht`}>{raw.length ? view.text : '(leere Ausgabe)'}</pre>
|
||||
<button type="button" onClick={() => download(raw, name)}>{name} als unveränderte Rohbytes herunterladen</button>
|
||||
<details><summary>{name} Originalbytes (dezimal)</summary><pre>{JSON.stringify(Array.from(raw))}</pre></details>
|
||||
</div>;
|
||||
} catch (error) { return <p role="alert" className="error">{name}: {error instanceof Error ? error.message : 'Ausgabe nicht lesbar'}. Keine verlässliche Textansicht.</p>; }
|
||||
}
|
||||
export function ConsoleOutput({ job }: { job: RecordValue }) {
|
||||
const state = stringField(job, 'state');
|
||||
return <section aria-label="Gespeichertes Konsolenergebnis"><h3>Konsolenergebnis</h3>
|
||||
<p role="status">Zustand: <strong>{state}</strong> · Versuch: {stringField(job, 'attempt_id')} · Revision: {typeof job.revision === 'number' ? job.revision : 'unknown'}</p>
|
||||
<p>Die Ansicht fragt den gespeicherten Zustand alle 4 Sekunden ab. stdout/stderr erscheinen nach Eingang des Ergebnisses; es gibt keinen Live-Ausgabestream.</p>
|
||||
{state === 'unknown' && <p className="warning">Wirkung oder Ergebnis unklar. Keine automatische Wiederholung; ein neuer Versuch benötigt Abgleich und einen neuen genehmigten Plan.</p>}
|
||||
{job.cancel_requested === true && <p className="warning">Abbruch angefordert; dies bestätigt weder Prozessende noch Rollback.</p>}
|
||||
{job.pending_reason != null && <p>Wartegrund: {String(job.pending_reason)}</p>}
|
||||
{job.result == null ? <p>Noch kein gespeichertes Ergebnis. Fehlende Ausgabe ist kein Erfolgsnachweis.</p> : <Result value={job.result}/>}
|
||||
</section>;
|
||||
}
|
||||
function Result({ value }: { value: unknown }) {
|
||||
try {
|
||||
const result = record(value, 'Jobergebnis');
|
||||
return <><p>Exitcode: {typeof result.exit_code === 'number' && Number.isInteger(result.exit_code) ? result.exit_code : 'unknown / nicht gemeldet'} · Fehlercode: {typeof result.error_code === 'string' && result.error_code ? result.error_code : 'nicht gemeldet'}</p>
|
||||
<p className={result.output_truncated === false ? 'muted' : 'warning'}>Ausgabe begrenzt: {typeof result.output_truncated === 'boolean' ? String(result.output_truncated) : 'unknown'}. {result.output_truncated === true ? 'Die gespeicherten Bytes sind nur ein Ausschnitt.' : result.output_truncated !== false ? 'Vollständigkeit ist nicht bestätigt.' : 'Keine Trunkierung gemeldet.'}</p>
|
||||
<p>Neustartbedarf: {typeof result.reboot_required === 'boolean' ? String(result.reboot_required) : 'unknown'}. Ein Exitcode 0 bestätigt Prozessabschluss; fachliche Nachbedingungen stehen im vollständigen Ergebnis.</p>
|
||||
<p>Ausgabe ist nicht vertrauenswürdiger Text vom Zielgerät. Sie erteilt keine Genehmigung und wird nicht als Anweisung ausgeführt.</p>
|
||||
<OutputChannel name="stdout" value={result.stdout}/><OutputChannel name="stderr" value={result.stderr}/></>;
|
||||
} catch { return <p className="error" role="alert">Ergebnisformat unbekannt; vollständige Originaldaten stehen darunter.</p>; }
|
||||
}
|
||||
+32
-12
@@ -1,13 +1,31 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile } from './api';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile, fullMaintenanceScriptProfile } from './api';
|
||||
import './style.css';
|
||||
import { AdminControl, Catalog, TenantControls } from './management';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest } from './safety';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest, fullMaintenanceWarning } from './safety';
|
||||
import { Login } from './login';
|
||||
import { ConsoleOutput, outputText } from './console-output';
|
||||
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
|
||||
|
||||
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>{pretty(value)}</pre></details>; }
|
||||
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 ScriptPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = scriptPlanJobs(plan); if (!jobs.length) return null;
|
||||
return <article aria-label="Feste Skriptkonsole vor Genehmigung"><h3>Vollständige feste Skriptaufträge ({jobs.length})</h3><p>Diese Inhalte stammen aus den hashgeprüften gespeicherten Planbytes. Jeder Zielauftrag, Versuch und Skripthash ist fest gebunden.</p>
|
||||
{jobs.map(job => <article key={job.jobId}><h4>Asset {job.assetId}</h4><p>Agent: {job.agentId} · Job: {job.jobId} · Versuch: {job.attemptId}</p>
|
||||
<p>Interpreter: {job.interpreter} · Identität: <strong>{job.identity}</strong> · Privilegiertes Profil: <strong>{job.privilegedProfile === fullMaintenanceScriptProfile ? fullMaintenanceScriptProfile : 'bestehendes begrenztes Profil'}</strong> · Windowsprozess: {job.interpreter !== 'powershell' ? 'nicht zutreffend' : job.windowsProfile === 'powershell_51_remote_signed' ? 'Windows PowerShell5.1 RemoteSigned, nur Jobprozess' : 'geerbte Windowsrichtlinie / kein Windows-Prozessoverride'}</p>
|
||||
<p>Frühester Start: {job.notBefore} · Startfrist: {job.startBefore} · Laufzeit: {job.runtimeSeconds}s · Ausgabe: höchstens {job.outputBytes} Bytes</p>
|
||||
<p>Skript: {job.scriptBytes} UTF-8-Bytes · SHA256: <code>{job.scriptHash}</code><br/>Jobpayload-SHA256: <code>{job.jobHash}</code></p>
|
||||
{job.privilegedProfile === fullMaintenanceScriptProfile ? <p className="warning">{fullMaintenanceWarning}</p> : job.identity === 'root' && <p className="warning">{rootWarning}</p>}
|
||||
<p>Vollständiger Skripttext; Steuerzeichen, BOM und CR werden sichtbar als \uXXXX dargestellt. LF bleibt Zeilenumbruch. Kein Kürzen oder Normalisieren der gespeicherten Bytes.</p>
|
||||
<pre aria-label={`Vollständiges Skript für ${job.assetId}`}>{outputText(new TextEncoder().encode(job.script)).text}</pre>
|
||||
<p>Feste Argumente (JSON): <code>{JSON.stringify(job.arguments)}</code></p><p>stdout-Nachbedingung (JSON): <code>{JSON.stringify(job.expectedStdout)}</code>{job.expectedStdout === null && ' · keine zusätzliche fachliche stdout-Prüfung gebunden'}</p>
|
||||
</article>)}
|
||||
</article>;
|
||||
} catch { return <aside role="alert" className="error">Skriptplan ist nicht vollständig aus unveränderten gespeicherten Bytes verifiziert. Keine Genehmigung möglich.</aside>; }
|
||||
}
|
||||
export function SystemPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
let jobs: RecordValue[];
|
||||
try { jobs = systemPlanJobs(plan).filter(p => record(p.action).action === 'set_service_state'); }
|
||||
@@ -33,7 +51,7 @@ export function PowerShellPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = powerShellPlanJobs(plan);
|
||||
if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste PowerShell-Prozessprofile"><p>Diese Ausführungsoptionen sind an die hashgeprüften gespeicherten Planbytes gebunden.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Windows PowerShell5.1 · agent_service · {job.profile === windowsPowerShellRemoteSignedProfile ? 'RemoteSigned · nur Jobprozess' : 'Geerbte Richtlinie · kein ExecutionPolicy-Prozessparameter'}</li>)}</ul><p>Keine Maschinen-/CurrentUser-/GPO-Änderung durch den Executor. GPO-Vorgaben bleiben wirksam; die angeforderte Option ist kein Nachweis der effektiven Policy.</p></aside>;
|
||||
return <aside className="warning" aria-label="Feste PowerShell-Prozessprofile"><p>Diese Ausführungsoptionen sind an die hashgeprüften gespeicherten Planbytes gebunden.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Windows PowerShell5.1 · {job.identity ?? 'agent_service'} · {job.profile === windowsPowerShellRemoteSignedProfile ? 'RemoteSigned · nur Jobprozess' : 'Geerbte Richtlinie · kein ExecutionPolicy-Prozessparameter'}</li>)}</ul><p>Keine Maschinen-/CurrentUser-/GPO-Änderung durch den Executor. GPO-Vorgaben bleiben wirksam; die angeforderte Option ist kein Nachweis der effektiven Policy.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">PowerShell-Planprofil ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
export function QueryLogsPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
@@ -77,7 +95,7 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
|
||||
const [identity, setIdentity] = useState('agent_service');
|
||||
return <section><h2>Neuen unveränderlichen Plan vorbereiten</h2><p>Nur fest ausgewählte Asset-IDs. Keine Ausführung durch Planung oder Antrag; jede Aktion einschließlich Live-Inventar benötigt Genehmigung.</p>
|
||||
<form onSubmit={async e => { e.preventDefault(); setBusy(true); setError(null); const f = new FormData(e.currentTarget); try {
|
||||
const common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')) };
|
||||
const common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')), ...(action === 'run_script' && f.get('privileged_script_profile') === fullMaintenanceScriptProfile ? { privileged_script_profile: fullMaintenanceScriptProfile } : {}) };
|
||||
const params = action === 'run_script' ? { ...common, variants: scriptPlatform === 'mixed' ? parseStrictJson(mixedVariants) : [{ os_family: scriptPlatform, interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')), ...(scriptPlatform === 'windows' ? { windows_execution_profile: windowsPowerShellRemoteSignedProfile } : {}) }], arguments: [], expected_stdout: expectedStdout(String(f.get('expected')), String(f.get('expected_format'))) } : { ...record(parseStrictJson(parameters)), ...common };
|
||||
const input: PlanInput = { tenant_id: tenantId, action, targets: { asset_ids: [...selected] }, parameters: params, schedule: { not_before: new Date(String(f.get('not_before'))).toISOString(), start_before: new Date(String(f.get('expires'))).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: Number(f.get('parallel')), halt_after_failures: Number(f.get('failures')) }, reason: String(f.get('reason')) };
|
||||
const ids = String(f.get('artifact_ids') ?? '').split(/[\s,]+/).filter(Boolean); if (ids.length) { if (ids.length > 16 || new Set(ids).size !== ids.length || ids.some(id => !/^[0-9a-f-]{36}$/i.test(id))) throw new Error('Maximal 16 eindeutige feste Artefakt-UUIDs'); input.artifact_ids = ids; }
|
||||
@@ -87,9 +105,10 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
|
||||
{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'].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>
|
||||
{identity === 'root' && <p className="warning">{rootWarning}</p>}
|
||||
{identity === 'system' && <p className="warning">{systemWarning}</p>}
|
||||
<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>
|
||||
{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 === '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>
|
||||
@@ -120,13 +139,14 @@ function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session
|
||||
}
|
||||
|
||||
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); 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); 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)] : ['Plan noch nicht geladen'];
|
||||
const recheck = async () => { if (!plan.data) throw new Error('Plan fehlt'); await verifyPlanIntegrity(plan.data); const errors = [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(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)] : ['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('; ')); };
|
||||
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}/>
|
||||
<SystemPlanNotice plan={plan.data}/>
|
||||
<WindowsMsiPlanNotice plan={plan.data}/>
|
||||
<PowerShellPlanNotice plan={plan.data}/>
|
||||
@@ -160,7 +180,7 @@ function OperationDetail({ tenantId, id, auth, openPlan }: { tenantId: string; i
|
||||
function JobDetail({ tenantId, id, auth }: { tenantId: string; id: string; auth: Session }) {
|
||||
const job = useResource(async signal => record(await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}`), { signal })), [tenantId, id], true);
|
||||
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);
|
||||
return <article><h3>Job {id}</h3><ErrorBox error={job.error}/><ErrorBox error={error}/><p>verifying = Nachprüfung läuft · unknown = Wirkung unklar, kein Retry · awaiting_reboot = autorisierter Folgejob nötig. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.</p>{job.data && <JsonView value={job.data} label="Versuch, Zustand, pending_reason, Output/stdout/stderr, Trunkierung, Nachprüfungen und Ergebnis"/>}
|
||||
return <article><h3>Job {id}</h3><ErrorBox error={job.error}/><ErrorBox error={error}/><p>verifying = Nachprüfung läuft · unknown = Wirkung unklar, kein Retry · awaiting_reboot = autorisierter Folgejob nötig. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.</p>{job.data && <><ConsoleOutput job={job.data}/><JsonView value={job.data} label="Vollständige Originaldaten: Versuch, Zustand, Ausgabe, Trunkierung, Nachprüfungen und Ergebnis"/></>}
|
||||
<form onSubmit={async e => { e.preventDefault(); const reason = new FormData(e.currentTarget).get('reason'); setBusy(true); setError(null); try { await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}/cancel`), { csrf: auth.csrf_token, body: { reason } }); job.reload(); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}><label>Abbruchgrund<input name="reason" required/></label><button disabled={busy}>Abbruch anfordern · nicht zurückrollen</button></form></article>;
|
||||
}
|
||||
function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
|
||||
+18
-6
@@ -1,8 +1,9 @@
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid } from './api';
|
||||
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';
|
||||
|
||||
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 (running/stopped) oder eigenes festes MSI-Rezept. Eigenes system:execute, unabhängiger Helper und konkrete WebUI-Genehmigung erforderlich. Keine SYSTEM-Shell, kein impliziter Reboot oder Retry.';
|
||||
export const fullMaintenanceWarning = 'VOLLE HOSTWARTUNG · full_maintenance_v1: Das genehmigte Skript läuft als root/SYSTEM mit vollständiger Hostautorität, einschließlich Netzwerk, Dateisystem und Diensten. Es kann auch Agent, PKI und Schutzmechanismen ändern oder einen Neustart auslösen. Keine Sandbox- oder No-Reboot-Zusage. scripts:execute plus root:execute/system:execute, lokaler und zentraler Opt-in, passende Capability, unabhängiger Helper und konkrete WebUI-Genehmigung bleiben erforderlich.';
|
||||
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); }
|
||||
@@ -72,10 +73,13 @@ 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 === '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') {
|
||||
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' && input.action !== 'ensure_package') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen oder feste MSI-Rezepte');
|
||||
if (input.action === 'run_script') {
|
||||
if (privilegedScriptProfile(input.parameters, 'system') !== fullMaintenanceScriptProfile) throw new Error('SYSTEM ausschließlich für typisierte Aktionen oder explizit full_maintenance_v1');
|
||||
} else if (input.action !== 'set_service_state' && input.action !== 'ensure_package') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen oder feste MSI-Rezepte');
|
||||
if (input.action === 'set_service_state') validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(input.parameters, 'windows_msi_manifest') || (input.action === 'ensure_package' && input.parameters.execution_identity === 'system')) {
|
||||
@@ -104,7 +108,7 @@ export function systemPlanJobs(plan: RecordValue): RecordValue[] {
|
||||
powerShellPlanJobs(plan);
|
||||
return structuredClone(verifiedPowerShellPlans.get(plan)!.systemJobs);
|
||||
}
|
||||
export interface PowerShellPlanJob { readonly assetId: string; readonly profile: 'inherited' | 'powershell_51_remote_signed' }
|
||||
export interface PowerShellPlanJob { readonly assetId: string; readonly profile: 'inherited' | 'powershell_51_remote_signed'; readonly identity?: 'system' }
|
||||
// Only successful verification writes this cache. Projection is copied from the
|
||||
// verified bytes; later mutations of API views cannot change the displayed plan.
|
||||
interface VerifiedPowerShellPlan { readonly jobs: readonly PowerShellPlanJob[]; readonly logJobs: readonly QueryLogsPlanJob[]; readonly msiJobs: readonly WindowsMsiPlanJob[]; readonly systemJobs: RecordValue[]; readonly planHash: unknown; readonly planBytes: readonly number[] }
|
||||
@@ -146,13 +150,14 @@ function hasPowerShellProfile(payload: RecordValue): boolean {
|
||||
function projectPowerShellJobs(jobs: unknown): PowerShellPlanJob[] {
|
||||
return scriptPayloads(jobs).filter(hasPowerShellProfile).map(payload => {
|
||||
const action = record(payload.action);
|
||||
if (action.action !== 'run_script' || action.interpreter !== 'powershell' || payload.execution_identity !== 'agent_service') throw new Error('PowerShell-Profil benötigt Windows PowerShell5.1 als agent_service');
|
||||
exact(action, ['action', 'interpreter', 'script_utf8', 'arguments', 'expected_stdout', ...(Object.prototype.hasOwnProperty.call(action, 'windows_execution_profile') ? ['windows_execution_profile'] : [])]);
|
||||
if (action.action !== 'run_script' || action.interpreter !== 'powershell') throw new Error('PowerShell-Profil benötigt Windows PowerShell5.1 als agent_service oder explizit SYSTEM');
|
||||
validateScriptIdentityProfile(action, payload.execution_identity, action.interpreter);
|
||||
exact(action, ['action', 'interpreter', 'script_utf8', 'arguments', 'expected_stdout', ...(Object.prototype.hasOwnProperty.call(action, 'windows_execution_profile') ? ['windows_execution_profile'] : []), ...(Object.hasOwn(action, 'privileged_script_profile') ? ['privileged_script_profile'] : [])]);
|
||||
if (typeof action.script_utf8 !== 'string' || !action.script_utf8 || new TextEncoder().encode(action.script_utf8).length > 32768 || action.script_utf8.includes('\0')
|
||||
|| (!/^[\x00-\x7f]*$/.test(action.script_utf8) && !action.script_utf8.startsWith('\ufeff'))
|
||||
|| !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('Vollständige unveränderte PowerShell-Skriptaktion erforderlich');
|
||||
return { assetId: text(payload.asset_id, 'PowerShell-Zielasset'), profile: windowsScriptProfile(action) };
|
||||
return { assetId: text(payload.asset_id, 'PowerShell-Zielasset'), profile: windowsScriptProfile(action), ...(payload.execution_identity === 'system' ? { identity: 'system' as const } : {}) };
|
||||
});
|
||||
}
|
||||
function validatePlanAliases(plan: RecordValue, parsed: unknown): void {
|
||||
@@ -352,6 +357,13 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
for (const payload of systemJobs) {
|
||||
const action = record(payload.action);
|
||||
if (isMsi(payload)) continue; // Fully validated, hash-bound package projection above.
|
||||
if (action.action === 'run_script') {
|
||||
validateScriptIdentityProfile(action, payload.execution_identity, action.interpreter);
|
||||
if (privilegedScriptProfile(action, payload.execution_identity) !== fullMaintenanceScriptProfile || action.interpreter !== 'powershell'
|
||||
|| !Number.isInteger(payload.max_runtime_seconds) || Number(payload.max_runtime_seconds) < 1 || Number(payload.max_runtime_seconds) > 120
|
||||
|| !Number.isInteger(payload.max_output_bytes) || Number(payload.max_output_bytes) < 1 || Number(payload.max_output_bytes) > 65536) throw new Error('SYSTEM-Skript benötigt explizites Vollwartungsprofil und feste Budgets');
|
||||
continue;
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { fullMaintenanceScriptProfile, PlanInput, record, RecordValue, Session, validateInput } from './api';
|
||||
import { sha256, validateSensitiveInput, verifyPlanIntegrity } from './safety';
|
||||
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
|
||||
|
||||
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
|
||||
// The same fixture is produced and checked by rmm-domain's actual Rust codec.
|
||||
const golden = JSON.parse(readFileSync(new URL('../../tests/script_console/codec-golden.json', import.meta.url), 'utf8')) as RecordValue[];
|
||||
function plan(name: string): RecordValue {
|
||||
const fixture = golden.find(value => value.name === name); if (!fixture) throw new Error('Rust golden case missing');
|
||||
const parsed = record(JSON.parse(new TextDecoder().decode(new Uint8Array(fixture.plan_payload_bytes as number[]))));
|
||||
const jobs = (parsed.jobs as RecordValue[]).map(job => ({ ...structuredClone(job), ...Object.fromEntries(['asset_id', 'agent_id', 'job_id', 'attempt_id'].map(key => [key, record(job.payload)[key]])) }));
|
||||
return { plan_id: parsed.plan_id, plan_hash: fixture.plan_hash, plan_payload_bytes: structuredClone(fixture.plan_payload_bytes), payload: parsed, plan_payload: structuredClone(parsed), jobs, resolved_targets: jobs.map(job => ({ asset_id: job.asset_id, agent_id: job.agent_id })), excluded_targets: [], expires_at: record(jobs[0]!.payload).start_before };
|
||||
}
|
||||
function first(value: RecordValue): RecordValue { return record((record(value.plan_payload).jobs as RecordValue[])[0]!.payload); }
|
||||
async function changedBytes(name: string, change: (payload: RecordValue, job: RecordValue) => void): Promise<RecordValue> {
|
||||
const p = plan(name), parsed = structuredClone(record(p.plan_payload)), job = (parsed.jobs as RecordValue[])[0]!;
|
||||
change(record(job.payload), job);
|
||||
const raw = new TextEncoder().encode(JSON.stringify(parsed));
|
||||
// No aliases: still reject invalid exact bytes or their internal hashes.
|
||||
return { plan_hash: await sha256(raw), plan_payload_bytes: Array.from(raw) };
|
||||
}
|
||||
|
||||
it('projects legacy/Linux root/Windows SYSTEM from the exact shared Rust golden bytes', async () => {
|
||||
for (const fixture of golden) {
|
||||
const p = plan(String(fixture.name)); expect(scriptApprovalBlockers(p).length).toBeGreaterThan(0);
|
||||
await verifyPlanIntegrity(p); await verifyScriptPlan(p);
|
||||
const view = scriptPlanJobs(p); expect(view).toHaveLength(1);
|
||||
const job = view[0]!, original = first(p), action = record(original.action);
|
||||
expect(job).toMatchObject({ assetId: original.asset_id, agentId: original.agent_id, jobId: original.job_id, attemptId: original.attempt_id, script: action.script_utf8, identity: original.execution_identity, scriptHash: fixture.script_sha256, jobHash: fixture.job_payload_hash });
|
||||
expect(job.privilegedProfile).toBe(fixture.name === 'legacy_linux_agent' ? 'bounded' : fullMaintenanceScriptProfile);
|
||||
expect(scriptApprovalBlockers(p)).toEqual([]);
|
||||
job.script = 'mutated return copy'; expect(scriptPlanJobs(p)[0]!.script).toBe(action.script_utf8);
|
||||
expect(await sha256(new Uint8Array(fixture.job_payload_bytes as number[]))).toBe(fixture.job_payload_hash);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects view, byte and fixed identity/budget/profile tampering before and after display', async () => {
|
||||
for (const alias of ['payload', 'plan_payload', 'jobs', 'resolved_targets']) {
|
||||
const p = plan('linux_root_full'); await verifyScriptPlan(p); p[alias] = [];
|
||||
expect(scriptApprovalBlockers(p).length).toBeGreaterThan(0); await expect(verifyScriptPlan(p)).rejects.toThrow('verändert');
|
||||
}
|
||||
const p = plan('windows_system_full'); (p.plan_payload_bytes as number[])[0] = 0;
|
||||
await expect(verifyScriptPlan(p)).rejects.toThrow('Planhash');
|
||||
for (const [field, value] of [['execution_identity', 'agent_service'], ['max_runtime_seconds', 121], ['max_output_bytes', 65537]] as const) {
|
||||
await expect(verifyScriptPlan(await changedBytes('windows_system_full', payload => { payload[field] = value; }))).rejects.toThrow();
|
||||
}
|
||||
for (const profile of [null, 'unknown', {}]) await expect(verifyScriptPlan(await changedBytes('linux_root_full', payload => { record(payload.action).privileged_script_profile = profile; }))).rejects.toThrow();
|
||||
await expect(verifyScriptPlan(await changedBytes('windows_system_full', payload => { delete record(payload.action).privileged_script_profile; }))).rejects.toThrow('PowerShell');
|
||||
for (const key of ['job_payload_hash', 'script_sha256']) await expect(verifyScriptPlan(await changedBytes('linux_root_full', (_payload, job) => { job[key] = 'a'.repeat(64); }))).rejects.toThrow('hash');
|
||||
});
|
||||
|
||||
it('binds every supplied alias and refuses asynchronous mutation during hashing', async () => {
|
||||
const p = plan('linux_root_full');
|
||||
const copy = structuredClone(p); copy.jobs = [];
|
||||
await expect(verifyScriptPlan(copy)).rejects.toThrow('Zielansicht');
|
||||
const q = plan('linux_root_full'), check = verifyScriptPlan(q);
|
||||
q.plan_payload_bytes = [123, 125]; await expect(check).rejects.toThrow('verändert');
|
||||
const hashSwap = plan('legacy_linux_agent'); await verifyScriptPlan(hashSwap); hashSwap.plan_hash = 'f'.repeat(64);
|
||||
expect(() => scriptPlanJobs(hashSwap)).toThrow('unveränderten');
|
||||
});
|
||||
|
||||
it('shows full fixed script/profile/identities before approval and has no approval or network side effects', async () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
||||
try {
|
||||
const { ScriptPlanNotice } = await import('./main');
|
||||
const p = plan('windows_system_full'); expect(renderToStaticMarkup(<ScriptPlanNotice plan={p}/>)).toContain('role="alert"');
|
||||
await verifyPlanIntegrity(p); await verifyScriptPlan(p);
|
||||
const html = renderToStaticMarkup(<ScriptPlanNotice plan={p}/>), view = scriptPlanJobs(p)[0]!;
|
||||
for (const value of ['full_maintenance_v1', 'system', 'powershell', 'RemoteSigned', 'SYSTEM stdout', 'SYSTEM stderr', '\\u000d', view.assetId, view.jobId, view.attemptId, view.scriptHash, view.jobHash, '30s', '4096', 'Keine Sandbox- oder No-Reboot-Zusage', 'Agent, PKI']) expect(html).toContain(value);
|
||||
expect(html).not.toMatch(/<(button|input|form)\b/); expect(fetch).not.toHaveBeenCalled();
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
|
||||
it('requires separate script/root/SYSTEM scopes and an explicit correctly placed profile at planning', async () => {
|
||||
const input: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'system', privileged_script_profile: fullMaintenanceScriptProfile, variants: [{ os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: 'Write-Output 1\r\n', windows_execution_profile: 'powershell_51_remote_signed' }], arguments: [], expected_stdout: null, timeout_seconds: 120, 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: 'unit only, no native execution' };
|
||||
const auth: Session = { principal: { id: 'simulated', display_name: 'SIMULIERT', simulated: true }, csrf_token: 'unit', tenants: [], permissions: ['scripts:execute', 'system:execute'] };
|
||||
validateInput(input); await validateSensitiveInput(input, auth);
|
||||
for (const permissions of [[], ['system:execute'], ['scripts:execute', 'root:execute']]) await expect(validateSensitiveInput(input, { ...auth, permissions })).rejects.toThrow();
|
||||
for (const profile of [null, 'other', {}]) expect(() => validateInput({ ...input, parameters: { ...input.parameters, privileged_script_profile: profile } })).toThrow();
|
||||
expect(() => validateInput({ ...input, parameters: { ...input.parameters, privileged_script_profile: undefined } })).toThrow();
|
||||
for (const parameters of [{ ...input.parameters, timeout_seconds: 121 }, { ...input.parameters, max_output_bytes: 65537 }, { ...input.parameters, execution_identity: 'agent_service' }, { ...input.parameters, execution_identity: 'root' }]) expect(() => validateInput({ ...input, parameters })).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
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']; }
|
||||
}
|
||||
Reference in New Issue
Block a user