Show immutable MSI plans in WebUI using actual Rust codec golden fixtures
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -46,9 +46,35 @@ Lokaler Beleg `devstate/windows-msi-integration/local-qualification.json`,
|
||||
SHA256 `b7bced0a341ffb88af8b584cbe8355ff1021add541004347f609f6136a684b74`,
|
||||
bindet13Quelldateien. Unabhängiger Quellenreview ohne weiteren konkreten Blocker.
|
||||
|
||||
Weiter offen: Linux-first-Nativevertragsnachweise, getrennte WebUI-Erweiterung,
|
||||
Weiter offen: Linux-first-Nativevertragsnachweise, tatsächliche WebUI-Abnahme,
|
||||
Windowsdownload und geschützter SYSTEM-Cache, Helper-/Runtimeverdrahtung und
|
||||
jeweils echte WebUI-genehmigte Installation/Upgrade/Noops. Keine Capability,
|
||||
Helperpolicy oder Clock-/Jobkonfiguration auf der VM wurde geöffnet. Die
|
||||
bisherige UI verweigert SYSTEM-Nicht-SCM-Pläne weiterhin bis zum separaten
|
||||
vorherige UI verweigerte SYSTEM-Nicht-SCM-Pläne bis zum folgenden separaten
|
||||
Schnitt. Quellen/Units sind keine Paketfreigabe.
|
||||
|
||||
## Getrennter WebUI-Quellenschnitt
|
||||
|
||||
Feste SYSTEM-MSI-Auswahl und eigener kleiner Katalogbereich implementiert;
|
||||
APT bleibt getrennt. Anzeige enthält Product-/Upgrade-/gegebenenfalls1.1-
|
||||
PackageCode, Version, Artifact/Rezept/Nutzdateihashes, Vorgänger, feste Argumente
|
||||
und No-Reboot-/Budgetvertrag. Sie stammt aus kopierter typisierter Projection
|
||||
hashgeprüfter gespeicherter Planbytes. Alle Preview-Aliase und spätere Änderungen
|
||||
werden vor Anzeige sowie erneut vor Submit/Genehmigung geprüft. Keine neue
|
||||
Genehmigungsabkürzung oder Policy-/Capabilityveröffentlichung.
|
||||
|
||||
Rootreview fand einen echten Codecfehler: die erste UI-Fassung erwartete
|
||||
`apt_manifest:null`, Rust lässt `None` tatsächlich aus. Die ursprünglichen
|
||||
TS-Fixtures spiegelten diesen Fehler. Eng korrigiert: gespeicherte MSI-Actions
|
||||
verlangen das fehlende Feld; nur das Formular akzeptiert fehlend/null, kein
|
||||
APT-Objekt. Zwei echte, vom unveränderten Rust-Domaincodec erzeugte synthetische
|
||||
PlanPayload-Goldens1.0/1.1 werden nun im bestehenden Webtest verifiziert und
|
||||
gerendert. Keine Signer, realen Geräte oder Nativewirkungen in diesen Fixtures.
|
||||
|
||||
Abschließend42Webtests, Typecheck und Build bestanden; fünf Webdateien und
|
||||
sämtliche Webinputs vor/nach gebunden, Rust13 unverändert. Neuer privater Beleg
|
||||
`devstate/windows-msi-ui/wire-fix-955acab2-35af-4507-bb2b-d7cd1fa49347/qualification.json`,
|
||||
SHA256 `f84d4962ab9a6ef64ef0327fcf7c524efb0bd4064d2416f174a9dfffb524a8a1`.
|
||||
Der ursprüngliche `fe02…`-Beleg bleibt historisch und ist ausdrücklich wegen
|
||||
des Codecfehlers abgelöst. Kein Clouddeployment, Browser-Nativlauf, Installer-
|
||||
oder tatsächlicher WebUI-Freigabenachweis durch diese Quelltests.
|
||||
|
||||
+67
-3
@@ -89,6 +89,66 @@ export function validateWindowsLogLimits(identity: unknown, runtime: unknown, ou
|
||||
|| typeof since !== 'string' || Date.parse(since) < 0) throw new Error('Windows-Fixture-Eventlog nur agent_service,10–120s und1024–65536Bytes');
|
||||
}
|
||||
export interface PlanInput { tenant_id: string; action: Action; targets: { asset_ids: string[] }; parameters: RecordValue; artifact_ids?: string[]; schedule: { not_before: string; start_before: string; offline_policy: 'wait_until_deadline' }; rollout: { max_parallel: number; halt_after_failures: number }; reason: string }
|
||||
export const windowsMsi = {
|
||||
package: 'rmm-windows-msi-fixture', installRecipe: 'rmm-windows-msi-fixture-install-1.0', upgradeRecipe: 'rmm-windows-msi-fixture-upgrade-1.1',
|
||||
product: '{3F070B4B-9C08-4D65-BD41-13D81B884AEC}', upgradedProduct: '{D42BD387-079B-4BBF-A134-0DA7B7A97011}', family: '{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}',
|
||||
payload: 'C:\\Program Files\\RustDiscoveryFixtures\\msi-payload.txt', payload10: '0c90c4fc7233017cc88c0e925095d6662ac57abdb303c7527ef59d02b454fca0', payload11: 'ba0c83deff9eed014009bcd45369b2a356ae909ebf0c1434dc836b0e6d759c49',
|
||||
} as const;
|
||||
export interface MsiPostcondition { product_code: string; product_version: string; payload_path: string; payload_sha256: string; payload_bytes: number }
|
||||
export interface WindowsMsiRecipe {
|
||||
schema_version: 1; recipe_id: string; recipe_version: '1'; platform: 'windows'; upgrade_code: string; architecture: 'x64'; context: 'machine'; command_profile: 'fixture_quiet_no_reboot_v1';
|
||||
artifact: { artifact_id: string; sha256: string; bytes: number }; postcondition: MsiPostcondition; no_reboot: true; package_code?: string; predecessor?: MsiPostcondition;
|
||||
}
|
||||
export interface WindowsMsiManifest { recipe: WindowsMsiRecipe; recipe_sha256: string }
|
||||
function exactMsiFields(value: RecordValue, fields: string[]): void {
|
||||
if (Object.keys(value).some(key => !fields.includes(key)) || fields.some(key => !Object.prototype.hasOwnProperty.call(value, key))) throw new Error('MSI-Schemafelder fehlen oder sind unbekannt');
|
||||
}
|
||||
export function msiDigest(value: unknown): string { if (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value)) throw new Error('Exakter MSI-SHA256 erforderlich'); return value; }
|
||||
export function msiUuid(value: unknown): string { if (typeof value !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) || value === '00000000-0000-0000-0000-000000000000') throw new Error('Exakte MSI-UUID erforderlich'); return value; }
|
||||
function msiInteger(value: unknown, min: number, max: number): number { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) throw new Error('MSI-Limit außerhalb des festen Budgets'); return value; }
|
||||
/** Reconstruct every nested object in Rust declaration order before hashing.
|
||||
* No unknown properties, null options, enum objects or caller-supplied argv.
|
||||
*/
|
||||
export function windowsMsiManifest(value: unknown): WindowsMsiManifest {
|
||||
const m = record(value, 'windows_msi_manifest'); exactMsiFields(m, ['recipe', 'recipe_sha256']);
|
||||
const r = record(m.recipe, 'MSI-Rezept'), upgrade = r.recipe_id === windowsMsi.upgradeRecipe;
|
||||
exactMsiFields(r, ['schema_version', 'recipe_id', 'recipe_version', 'platform', 'upgrade_code', 'architecture', 'context', 'command_profile', 'artifact', 'postcondition', 'no_reboot', ...(upgrade ? ['package_code', 'predecessor'] : [])]);
|
||||
if (r.schema_version !== 1 || (!upgrade && r.recipe_id !== windowsMsi.installRecipe) || r.recipe_version !== '1' || r.platform !== 'windows' || r.upgrade_code !== windowsMsi.family || r.architecture !== 'x64' || r.context !== 'machine' || r.command_profile !== 'fixture_quiet_no_reboot_v1' || r.no_reboot !== true) throw new Error('Nur feste Windows-Machine/x64-MSI-Rezepte mit No-Reboot-Vertrag');
|
||||
const a = record(r.artifact); exactMsiFields(a, ['artifact_id', 'sha256', 'bytes']);
|
||||
const post = (value: unknown): MsiPostcondition => { const p = record(value); exactMsiFields(p, ['product_code', 'product_version', 'payload_path', 'payload_sha256', 'payload_bytes']);
|
||||
if (p.payload_path !== windowsMsi.payload) throw new Error('Exakter MSI-Nutzdateipfad erforderlich');
|
||||
return { product_code: text(p.product_code, 'ProductCode'), product_version: text(p.product_version, 'Produktversion'), payload_path: p.payload_path, payload_sha256: msiDigest(p.payload_sha256), payload_bytes: msiInteger(p.payload_bytes, 1, 65536) };
|
||||
};
|
||||
const p = post(r.postcondition);
|
||||
if (p.product_code !== (upgrade ? windowsMsi.upgradedProduct : windowsMsi.product) || p.product_version !== (upgrade ? '1.1.0' : '1.0.0')) throw new Error('MSI-Produkt/Version widerspricht festem Rezept');
|
||||
const recipe: WindowsMsiRecipe = { schema_version: 1, recipe_id: r.recipe_id as string, recipe_version: '1', platform: 'windows', upgrade_code: windowsMsi.family, architecture: 'x64', context: 'machine', command_profile: 'fixture_quiet_no_reboot_v1',
|
||||
artifact: { artifact_id: msiUuid(a.artifact_id), sha256: msiDigest(a.sha256), bytes: msiInteger(a.bytes, 1, 262144) }, postcondition: p, no_reboot: true };
|
||||
if (upgrade) {
|
||||
const code = text(r.package_code, 'PackageCode');
|
||||
if (!/^\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}$/.test(code) || code === '{00000000-0000-0000-0000-000000000000}' || [windowsMsi.product, windowsMsi.upgradedProduct, windowsMsi.family].some(x => x === code)) throw new Error('Exakter eigener MSI-PackageCode erforderlich');
|
||||
const old = post(r.predecessor);
|
||||
if (p.payload_sha256 !== windowsMsi.payload11 || p.payload_bytes !== 33 || old.product_code !== windowsMsi.product || old.product_version !== '1.0.0' || old.payload_sha256 !== windowsMsi.payload10 || old.payload_bytes !== 33) throw new Error('MSI1.1 benötigt exakt den bekannten1.0-Vorgänger und die feste1.1-Nutzdatei');
|
||||
recipe.package_code = code; recipe.predecessor = old;
|
||||
}
|
||||
return { recipe, recipe_sha256: msiDigest(m.recipe_sha256) };
|
||||
}
|
||||
export function validateWindowsMsiLimits(runtime: unknown, output: unknown): void { msiInteger(runtime, 10, 120); msiInteger(output, 1024, 65536); }
|
||||
/** Stored Action bytes omit apt_manifest=None; WebParameters may accept null. */
|
||||
export function windowsMsiAction(value: RecordValue): RecordValue {
|
||||
exactMsiFields(value, ['action', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'recipe_id', 'windows_msi_manifest']);
|
||||
const m = windowsMsiManifest(value.windows_msi_manifest);
|
||||
if (value.action !== 'ensure_package' || value.provider !== 'msi' || value.package !== windowsMsi.package || value.version !== m.recipe.postcondition.product_version || value.architecture !== 'x64' || value.recipe_version !== m.recipe.recipe_version || value.installation_context !== 'machine' || value.recipe_id !== m.recipe.recipe_id) throw new Error('Äußere MSI-Felder widersprechen Manifest');
|
||||
return { action: 'ensure_package', provider: 'msi', package: windowsMsi.package, version: value.version, architecture: 'x64', recipe_version: m.recipe.recipe_version, installation_context: 'machine', recipe_id: m.recipe.recipe_id, windows_msi_manifest: m };
|
||||
}
|
||||
export function validateWindowsMsiInput(input: PlanInput): WindowsMsiManifest {
|
||||
const p = input.parameters;
|
||||
exactMsiFields(p, ['execution_identity', 'timeout_seconds', 'max_output_bytes', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'recipe_id', 'windows_msi_manifest', ...(Object.prototype.hasOwnProperty.call(p, 'apt_manifest') ? ['apt_manifest'] : [])]);
|
||||
if (input.action !== 'ensure_package' || p.execution_identity !== 'system' || (input.artifact_ids?.length ?? 0) !== 0) throw new Error('MSI ausschließlich als SYSTEM-ensure_package mit automatisch genau einem Artefakt');
|
||||
validateWindowsMsiLimits(p.timeout_seconds, p.max_output_bytes);
|
||||
if (p.apt_manifest !== undefined && p.apt_manifest !== null) throw new Error('APT-Manifest bei MSI nicht zulässig');
|
||||
windowsMsiAction({ action: input.action, provider: p.provider, package: p.package, version: p.version, architecture: p.architecture, recipe_version: p.recipe_version, installation_context: p.installation_context, recipe_id: p.recipe_id, windows_msi_manifest: p.windows_msi_manifest });
|
||||
return windowsMsiManifest(p.windows_msi_manifest);
|
||||
}
|
||||
/** Decode explicit escaped CRLF before planning; never alter approved output bytes. */
|
||||
export function expectedStdout(value: string, format: string): string | null {
|
||||
if (value === '') return null;
|
||||
@@ -118,10 +178,14 @@ export function validateInput(input: PlanInput): void {
|
||||
}
|
||||
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 !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte eigene Windows-Fixturedienste; keine SYSTEM-Shell');
|
||||
validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
|
||||
if (Object.keys(input.parameters).some(k => !['execution_identity', 'unit', 'state', 'timeout_seconds', 'max_output_bytes'].includes(k))) throw new Error('SYSTEM-Dienstauftrag enthält fremde Parameter');
|
||||
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);
|
||||
if (Object.keys(input.parameters).some(k => !['execution_identity', 'unit', 'state', 'timeout_seconds', 'max_output_bytes'].includes(k))) throw new Error('SYSTEM-Dienstauftrag enthält fremde Parameter');
|
||||
}
|
||||
}
|
||||
if (input.parameters.provider === 'msi' || Object.prototype.hasOwnProperty.call(input.parameters, 'windows_msi_manifest')) validateWindowsMsiInput(input);
|
||||
const required = (key: string) => text(input.parameters[key], `parameters.${key}`);
|
||||
if (input.action === 'refresh_inventory') required('scope');
|
||||
if (input.action === 'query_logs') {
|
||||
|
||||
@@ -60,13 +60,17 @@ it('shows fixed SYSTEM identity and service state from stored plan bytes without
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
||||
try {
|
||||
const { SystemPlanNotice } = await import('./main');
|
||||
const payload = { jobs: [{ payload: { execution_identity: 'system', asset_id: 'fixed-asset', action: { action: 'set_service_state', unit: 'RmmDiscoveryFixtureService', state: 'stopped' } } }] };
|
||||
const plan = { plan_payload_bytes: Array.from(new TextEncoder().encode(JSON.stringify(payload))), jobs: [{ payload: { execution_identity: 'root', action: { unit: 'untrusted-view' } } }] };
|
||||
const payload = { jobs: [{ payload: { execution_identity: 'system', asset_id: 'fixed-asset', max_runtime_seconds: 30, max_output_bytes: 4096, action: { action: 'set_service_state', unit: 'RmmDiscoveryFixtureService', state: 'stopped' } } }] };
|
||||
const raw = new TextEncoder().encode(JSON.stringify(payload));
|
||||
const plan = { plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs: [{ payload: { execution_identity: 'root', action: { unit: 'untrusted-view' } } }] };
|
||||
expect(renderToStaticMarkup(<SystemPlanNotice plan={plan}/>)).toContain('role="alert"');
|
||||
await verifyPlanIntegrity(plan);
|
||||
const html = renderToStaticMarkup(<SystemPlanNotice plan={plan}/>);
|
||||
expect(html).toContain('SYSTEM'); expect(html).toContain('system:execute'); expect(html).toContain('Identität: system');
|
||||
for (const expected of ['fixed-asset', 'RmmDiscoveryFixtureService', 'Zielzustand: stopped', 'Keine SYSTEM-Shell']) expect(html).toContain(expected);
|
||||
expect(html).not.toContain('untrusted-view'); expect(html).not.toMatch(/<(button|input|form|pre)\b/);
|
||||
expect(renderToStaticMarkup(<SystemPlanNotice plan={{ plan_payload_bytes: Array.from(new TextEncoder().encode('{"jobs":[]}')) }}/>)).toBe('');
|
||||
const emptyRaw = new TextEncoder().encode('{"jobs":[]}'), empty = { plan_payload_bytes: Array.from(emptyRaw), plan_hash: await sha256(emptyRaw) }; await verifyPlanIntegrity(empty);
|
||||
expect(renderToStaticMarkup(<SystemPlanNotice plan={empty}/>)).toBe('');
|
||||
for (const plan_payload_bytes of [[255], [123], 'invalid']) {
|
||||
const invalid = renderToStaticMarkup(<SystemPlanNotice plan={{ plan_payload_bytes }}/>);
|
||||
expect(invalid).toContain('role="alert"'); expect(invalid).toContain('nicht lesbar');
|
||||
|
||||
+46
-8
@@ -3,18 +3,32 @@ 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 './style.css';
|
||||
import { AdminControl, Catalog, TenantControls } from './management';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs } from './safety';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest } from './safety';
|
||||
import { Login } from './login';
|
||||
|
||||
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 SystemPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
let jobs: RecordValue[];
|
||||
try { jobs = systemPlanJobs(plan); }
|
||||
try { jobs = systemPlanJobs(plan).filter(p => record(p.action).action === 'set_service_state'); }
|
||||
catch { return <aside role="alert" className="error">Gespeicherte Planbytes sind nicht lesbar. Keine verlässliche SYSTEM-Plananzeige; Genehmigungsverifikation muss erfolgreich sein.</aside>; }
|
||||
if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste SYSTEM-Dienstaktionen"><p>{systemWarning}</p><ul>{jobs.map((payload, i) => { const action = record(payload.action); return <li key={i}>Identität: system · Asset: {String(payload.asset_id)} · Dienst: {String(action.unit)} · Zielzustand: {String(action.state)}</li>; })}</ul><p>Diese Definitionen stammen aus den gespeicherten Planbytes; die vollständigen Zielpayloads und Hashes stehen darunter.</p></aside>;
|
||||
}
|
||||
export function WindowsMsiPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = windowsMsiPlanJobs(plan); if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste SYSTEM-MSI-Paketaktionen"><p>{systemWarning}</p><p>Windows · SYSTEM · Machine · x64 · feste MSI-Profile, keine freie Installer-URL/Argumente. Diese Definition stammt ausschließlich aus hashgeprüften gespeicherten Planbytes.</p><ul>{jobs.map((job, i) => <li key={i}>
|
||||
Asset: {job.assetId} · Rezept: {job.recipeId} · Rezept-SHA256: {job.recipeHash}<br/>
|
||||
Artefakt: {job.artifactId} · SHA256: {job.artifactHash} · {job.artifactBytes} Bytes<br/>
|
||||
ProductCode: {job.productCode} · UpgradeCode: {job.upgradeCode} · Version: {job.version} · PackageCode: {job.packageCode ?? 'im historischen1.0-Rezept nicht separat gebunden; vollständiger Artefakthash bleibt fest'}<br/>
|
||||
Nutzdatei: {job.payloadPath} · SHA256: {job.payloadHash} · {job.payloadBytes} Bytes<br/>
|
||||
Vorgänger: {job.predecessor ? `${job.predecessor.product_code} · ${job.predecessor.product_version} · ${job.predecessor.payload_path} · SHA256 ${job.predecessor.payload_sha256} · ${job.predecessor.payload_bytes} Bytes` : 'keine Upgrade-Reparatur; erste1.0-Installation oder separat belegter Noop'}<br/>
|
||||
Fester Aufruf: %SystemRoot%\System32\msiexec.exe {job.arguments.map(arg => JSON.stringify(arg)).join(' ')}<br/>
|
||||
No-Reboot: true · ursprüngliches Gesamtbudget: {job.runtimeSeconds}s · Ausgabelimit: {job.outputBytes} Bytes
|
||||
</li>)}</ul><p>Upgrade1.1 setzt den exakten1.0-Vorgänger voraus und entfernt ihn. Erfolg/Noop benötigen unabhängige rechtzeitige Nachbedingungen.3010 meldet Neustartbedarf ohne Neustart;1641/unklare Wirkung bleiben unknown,1618 Konflikt ohne Retry. Planung und Anzeige behaupten keine native Installer-/Clock-/Helperbereitschaft.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">MSI-Plan ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne unveränderte gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
export function PowerShellPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = powerShellPlanJobs(plan);
|
||||
@@ -73,33 +87,57 @@ 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={action !== 'set_service_state' || !allowed(auth, 'system:execute')}>system · system:execute und Windows-SYSTEM-Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
|
||||
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option><option value="system" disabled={!['set_service_state', 'ensure_package'].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>}
|
||||
{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" placeholder="UUIDs durch Komma getrennt; keine URL"/></label>
|
||||
<label>Feste importierte Artefakt-IDs (optional, maximal 16)<input name="artifact_ids" disabled={identity === 'system' && action === 'ensure_package'} placeholder="MSI leitet genau eine Referenz aus dem Rezept ab; sonst UUIDs, keine URL"/></label>
|
||||
<label>Begründung<input name="reason" required maxLength={1024}/></label><p>Feste Ziele ({selected.length}): {selected.join(', ') || 'keine ausgewählt'}</p>{action === 'reboot' || action === 'apply_updates' || action === 'ensure_package' ? <p className="warning">Zieländerung: Testumfang separat abstimmen. Keine implizite Reboot-/Updateerlaubnis. Neue Versuche und Folgejobs benötigen neue feste Pläne.</p> : null}<button disabled={busy || !selected.length}>Plan erstellen · noch keine Ausführung</button><ErrorBox error={error}/>
|
||||
</form></section>;
|
||||
}
|
||||
function localDate(date: Date) { return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16); }
|
||||
|
||||
function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||||
const [source, setSource] = useState('{}'), [cursor, setCursor] = useState<string | null>(null), [revision, setRevision] = useState(0), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false), [receipt, setReceipt] = useState<unknown>(null);
|
||||
const list = useResource(async signal => {
|
||||
const result = page(await request(tenantPath(tenantId, `/windows-msi-recipes${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`), { signal }));
|
||||
const items: RecordValue[] = [];
|
||||
for (const item of result.items) { const manifest = await verifyWindowsMsiManifest(item.manifest); if (item.sha256 !== manifest.recipe_sha256 || item.recipe_id !== manifest.recipe.recipe_id) throw new Error('MSI-Katalogansicht widerspricht Rezeptbytes'); items.push({ catalog_id: item.catalog_id, recipe_id: manifest.recipe.recipe_id, sha256: manifest.recipe_sha256, manifest }); }
|
||||
return { ...result, items };
|
||||
}, [tenantId, cursor, revision]);
|
||||
return <section><h2>Getrennter unveränderlicher Windows-MSI-Katalog</h2><p>Nur die zwei festen eigenen Machine/x64-Rezepte. Import ist Metadatenpflege mit catalog:write, keine Genehmigung, Installation oder Capabilityfreigabe. Öffentliche MSI-Artefakte werden über den bestehenden Artefaktimport gebunden. Vollständiges geprüftes Manifest für den Parametereditor kopieren.</p><ErrorBox error={list.error}/>
|
||||
{list.data && <><PageStatus data={list.data}/><JsonView value={list.data.items} label="Hashgeprüfte feste MSI-Manifeste"/><button disabled={!cursor} onClick={() => setCursor(null)}>Erste MSI-Rezeptseite</button><button disabled={!list.data.next_cursor} onClick={() => setCursor(list.data?.next_cursor ?? null)}>Nächste MSI-Rezeptseite</button></>}
|
||||
<details><summary>Neues festes MSI-Manifest importieren</summary><form onSubmit={async event => { event.preventDefault(); setBusy(true); setError(null); setReceipt(null); try {
|
||||
if (!allowed(auth, 'catalog:write')) throw new Error('catalog:write unbekannt/nicht erteilt');
|
||||
const manifest = await verifyWindowsMsiManifest(parseStrictJson(source));
|
||||
const result = record(await request(tenantPath(tenantId, '/windows-msi-recipes'), { body: manifest, csrf: auth.csrf_token }));
|
||||
const stored = await verifyWindowsMsiManifest(result.manifest);
|
||||
if (result.sha256 !== manifest.recipe_sha256 || result.recipe_id !== manifest.recipe.recipe_id || JSON.stringify(stored) !== JSON.stringify(manifest)) throw new Error('MSI-Importbeleg widerspricht unveränderlichen Rezeptbytes');
|
||||
setReceipt({ catalog_id: result.catalog_id, manifest: stored }); setRevision(n => n + 1);
|
||||
} catch (error) { setError(errorText(error)); } finally { setBusy(false); } }}><label>Vollständiges MSI-Manifest JSON<textarea rows={10} value={source} onChange={e => setSource(e.target.value)} spellCheck={false}/></label><button disabled={busy || !allowed(auth, 'catalog:write')}>Festes MSI-Manifest importieren · keine Ausführung</button><ErrorBox error={error}/>{receipt !== null && <JsonView value={receipt} label="Verifizierter MSI-Importbeleg"/>}</form></details>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id: string; auth: Session; onOperation: (id: string) => void }) {
|
||||
const plan = useResource(async signal => { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}`), { signal })); await verifyPlanIntegrity(result); 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)] : ['Plan noch nicht geladen'];
|
||||
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('; ')); };
|
||||
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>
|
||||
<SystemPlanNotice plan={plan.data}/>
|
||||
<WindowsMsiPlanNotice plan={plan.data}/>
|
||||
<PowerShellPlanNotice plan={plan.data}/>
|
||||
<QueryLogsPlanNotice plan={plan.data}/>
|
||||
<JsonView value={plan.data} label="Alle festen Zielpreviews, exakte Skriptinhalte/Hashes, Parameter, Rechte, Fristen, Rollout und Nachbedingungen"/>
|
||||
<p className="warning">Genehmigung bindet ausschließlich diesen unveränderlichen Plan. Kein pauschaler Retry, keine Wildcard, kein impliziter Reboot. Unbekannte Wirkung wird nicht automatisch wiederholt. Ein Exitcode allein beweist keine fachliche Wirkung.</p>
|
||||
{blockers.length > 0 && <div role="alert" className="error">Nicht genehmigungsfähig: {blockers.join('; ')}</div>}
|
||||
<button disabled={busy || !!plan.error || blockers.length > 0 || submitted} onClick={async () => { setBusy(true); setError(null); try { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/submit`), { csrf: auth.csrf_token, body: { idempotency_key: idempotency } })); setSubmitted(true); setPending((result.approval_state ?? result.state) === 'pending_approval'); onOperation(objectId(result, 'operation')); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>Antrag absenden · pending_approval</button>
|
||||
<button disabled={busy || !!plan.error || blockers.length > 0 || submitted} onClick={async () => { setBusy(true); setError(null); try { await recheck(); const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/submit`), { csrf: auth.csrf_token, body: { idempotency_key: idempotency } })); setSubmitted(true); setPending((result.approval_state ?? result.state) === 'pending_approval'); onOperation(objectId(result, 'operation')); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>Antrag absenden · pending_approval</button>
|
||||
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)}/>Ich habe sämtliche festen Ziele, Aktionen, Bytes/Hashes, Zielpreviews, Ausführungsprofile/Prozessumfänge und Auswirkungen dieses Plans geprüft.</label>
|
||||
<button className="danger" disabled={!confirmed || busy || !!plan.error || blockers.length > 0 || !(pending || plan.data.approval_state === 'pending_approval')} onClick={async () => { setBusy(true); setError(null); try {
|
||||
const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/authorizations`), { csrf: auth.csrf_token, body: { plan_hash: plan.data?.plan_hash } })); setConfirmed(false); setPending(false); onOperation(objectId(result, 'operation')); plan.reload();
|
||||
await recheck(); const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/authorizations`), { csrf: auth.csrf_token, body: { plan_hash: plan.data?.plan_hash } })); setConfirmed(false); setPending(false); onOperation(objectId(result, 'operation')); plan.reload();
|
||||
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>{auth.principal.simulated ? 'SIMULIERT: Diesen festen Plan ausdrücklich genehmigen' : 'Diesen festen Plan ausdrücklich genehmigen'}</button>
|
||||
<p>Nur für einen bestehenden Antrag pending_approval; Server prüft interaktive Sitzung, Rechte, Tenant, Policy und Frist erneut. Keine automatische Genehmigung.</p>
|
||||
<AdminControl auth={auth} path={tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/revocation`)} permission="plans:revoke" title="Planberechtigung widerrufen" warning="Sperrt neue Starts dieses Plans; laufende Wirkungen folgen sicheren Abbruchregeln, kein Rollback. Ein widerrufener Antrag wird nicht reaktiviert." done={plan.reload}/>
|
||||
@@ -136,7 +174,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
}
|
||||
function TenantWorkspace({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||||
const [selected, setSelected] = useState<string[]>([]), [planId, setPlan] = useState<string | null>(null), [operationId, setOperation] = useState<string | null>(null);
|
||||
return <><Devices tenantId={tenantId} auth={auth} selected={selected} setSelected={setSelected}/><Planner tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Catalog tenantId={tenantId} auth={auth}/><TenantControls tenantId={tenantId} auth={auth}/><Operations tenantId={tenantId} open={setOperation}/>{operationId && <OperationDetail key={operationId} tenantId={tenantId} id={operationId} auth={auth} openPlan={setPlan}/ >}{planId && <PlanDetail key={planId} tenantId={tenantId} id={planId} auth={auth} onOperation={setOperation}/>}</>;
|
||||
return <><Devices tenantId={tenantId} auth={auth} selected={selected} setSelected={setSelected}/><Planner tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Catalog tenantId={tenantId} auth={auth}/><WindowsMsiCatalog tenantId={tenantId} auth={auth}/><TenantControls tenantId={tenantId} auth={auth}/><Operations tenantId={tenantId} open={setOperation}/>{operationId && <OperationDetail key={operationId} tenantId={tenantId} id={operationId} auth={auth} openPlan={setPlan}/ >}{planId && <PlanDetail key={planId} tenantId={tenantId} id={planId} auth={auth} onOperation={setOperation}/>}</>;
|
||||
}
|
||||
function App() {
|
||||
const [auth, setAuth] = useState<Session | null>(null), [loading, setLoading] = useState(true), [error, setError] = useState<string | null>(null);
|
||||
|
||||
+105
-2
@@ -1,8 +1,9 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { actions, PlanInput, Session, request, session } from './api';
|
||||
import { adminIntent, allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, queryLogsApprovalBlockers, queryLogsPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { actions, PlanInput, Session, request, session, windowsMsi, windowsMsiManifest, validateInput } from './api';
|
||||
import { adminIntent, allowed, availableActions, windowsMsiPlanJobs, windowsMsiApprovalBlockers, verifyWindowsMsiManifest, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, queryLogsApprovalBlockers, queryLogsPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { AdminControl } from './management';
|
||||
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
|
||||
|
||||
const auth: Session = { principal: { id: 'test', display_name: 'SIMULIERT', simulated: true }, csrf_token: 'csrf', tenants: [], permissions: ['root:execute', 'devices:revoke'] };
|
||||
describe('immutable PowerShell process profile', () => {
|
||||
@@ -195,3 +196,105 @@ describe('interactive administrative boundary', () => {
|
||||
expect(fetch).toHaveBeenCalledWith('/api/v1/tenants/t/execution-stop', expect.objectContaining({ credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': 'csrf' }, body: '{"reason":"test only","stopped":true}' })); vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
|
||||
// Actual rmm_domain::jobs::encode(PlanPayload) output from the private synthetic
|
||||
// offline harness (no signer, real device, database or native execution).
|
||||
const msiDomainGoldens = [
|
||||
"{\"schema_version\":1,\"plan_id\":\"00000000-0000-4000-8000-000000000006\",\"tenant_id\":\"00000000-0000-4000-8000-000000000001\",\"principal\":\"simulated-unit-only\",\"reason\":\"MSI UI contract, no execution\",\"jobs\":[{\"payload\":{\"schema_version\":1,\"tenant_id\":\"00000000-0000-4000-8000-000000000001\",\"asset_id\":\"00000000-0000-4000-8000-000000000002\",\"agent_id\":\"00000000-0000-4000-8000-000000000003\",\"enrollment_generation\":1,\"assignment_version\":1,\"job_id\":\"00000000-0000-4000-8000-000000000004\",\"attempt_id\":\"00000000-0000-4000-8000-000000000005\",\"action\":{\"action\":\"ensure_package\",\"provider\":\"msi\",\"package\":\"rmm-windows-msi-fixture\",\"version\":\"1.0.0\",\"architecture\":\"x64\",\"recipe_version\":\"1\",\"installation_context\":\"machine\",\"recipe_id\":\"rmm-windows-msi-fixture-install-1.0\",\"windows_msi_manifest\":{\"recipe\":{\"schema_version\":1,\"recipe_id\":\"rmm-windows-msi-fixture-install-1.0\",\"recipe_version\":\"1\",\"platform\":\"windows\",\"upgrade_code\":\"{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}\",\"architecture\":\"x64\",\"context\":\"machine\",\"command_profile\":\"fixture_quiet_no_reboot_v1\",\"artifact\":{\"artifact_id\":\"00000000-0000-4000-8000-000000000010\",\"sha256\":\"abababababababababababababababababababababababababababababababab\",\"bytes\":32768},\"postcondition\":{\"product_code\":\"{3F070B4B-9C08-4D65-BD41-13D81B884AEC}\",\"product_version\":\"1.0.0\",\"payload_path\":\"C:\\\\Program Files\\\\RustDiscoveryFixtures\\\\msi-payload.txt\",\"payload_sha256\":\"0c90c4fc7233017cc88c0e925095d6662ac57abdb303c7527ef59d02b454fca0\",\"payload_bytes\":33},\"no_reboot\":true},\"recipe_sha256\":\"47e4a478f0e3b2976ededa6afa6058d6e56ceec4e0e36cc5950701c1e65190f5\"}},\"execution_identity\":\"system\",\"not_before\":\"2027-01-01T00:00:00Z\",\"start_before\":\"2027-01-01T01:00:00Z\",\"max_runtime_seconds\":30,\"max_output_bytes\":4096},\"job_payload_hash\":\"5df5828c52c2be0b005f31551319e5892a6daa80a4d30c76f95153e24eeec9b1\",\"script_sha256\":null}],\"max_parallel\":1,\"halt_after_failures\":1,\"recipe_references\":[{\"package\":\"rmm-windows-msi-fixture\",\"version\":\"1.0.0\",\"architecture\":\"x64\",\"recipe_version\":\"1\",\"sha256\":\"47e4a478f0e3b2976ededa6afa6058d6e56ceec4e0e36cc5950701c1e65190f5\"}],\"artifact_references\":[{\"job_id\":\"00000000-0000-4000-8000-000000000004\",\"attempt_id\":\"00000000-0000-4000-8000-000000000005\",\"artifact\":{\"artifact_id\":\"00000000-0000-4000-8000-000000000010\",\"sha256\":\"abababababababababababababababababababababababababababababababab\",\"size_bytes\":32768}}]}",
|
||||
"{\"schema_version\":1,\"plan_id\":\"00000000-0000-4000-8000-000000000006\",\"tenant_id\":\"00000000-0000-4000-8000-000000000001\",\"principal\":\"simulated-unit-only\",\"reason\":\"MSI UI contract, no execution\",\"jobs\":[{\"payload\":{\"schema_version\":1,\"tenant_id\":\"00000000-0000-4000-8000-000000000001\",\"asset_id\":\"00000000-0000-4000-8000-000000000002\",\"agent_id\":\"00000000-0000-4000-8000-000000000003\",\"enrollment_generation\":1,\"assignment_version\":1,\"job_id\":\"00000000-0000-4000-8000-000000000004\",\"attempt_id\":\"00000000-0000-4000-8000-000000000005\",\"action\":{\"action\":\"ensure_package\",\"provider\":\"msi\",\"package\":\"rmm-windows-msi-fixture\",\"version\":\"1.1.0\",\"architecture\":\"x64\",\"recipe_version\":\"1\",\"installation_context\":\"machine\",\"recipe_id\":\"rmm-windows-msi-fixture-upgrade-1.1\",\"windows_msi_manifest\":{\"recipe\":{\"schema_version\":1,\"recipe_id\":\"rmm-windows-msi-fixture-upgrade-1.1\",\"recipe_version\":\"1\",\"platform\":\"windows\",\"upgrade_code\":\"{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}\",\"architecture\":\"x64\",\"context\":\"machine\",\"command_profile\":\"fixture_quiet_no_reboot_v1\",\"artifact\":{\"artifact_id\":\"00000000-0000-4000-8000-000000000010\",\"sha256\":\"abababababababababababababababababababababababababababababababab\",\"bytes\":32768},\"postcondition\":{\"product_code\":\"{D42BD387-079B-4BBF-A134-0DA7B7A97011}\",\"product_version\":\"1.1.0\",\"payload_path\":\"C:\\\\Program Files\\\\RustDiscoveryFixtures\\\\msi-payload.txt\",\"payload_sha256\":\"ba0c83deff9eed014009bcd45369b2a356ae909ebf0c1434dc836b0e6d759c49\",\"payload_bytes\":33},\"no_reboot\":true,\"package_code\":\"{AF1C9887-391A-4BFF-B909-BC898300CF90}\",\"predecessor\":{\"product_code\":\"{3F070B4B-9C08-4D65-BD41-13D81B884AEC}\",\"product_version\":\"1.0.0\",\"payload_path\":\"C:\\\\Program Files\\\\RustDiscoveryFixtures\\\\msi-payload.txt\",\"payload_sha256\":\"0c90c4fc7233017cc88c0e925095d6662ac57abdb303c7527ef59d02b454fca0\",\"payload_bytes\":33}},\"recipe_sha256\":\"376d4a05fa43565a302cd1f90514e355e3f89a634d43abb9c31978e740bf7e9c\"}},\"execution_identity\":\"system\",\"not_before\":\"2027-01-01T00:00:00Z\",\"start_before\":\"2027-01-01T01:00:00Z\",\"max_runtime_seconds\":30,\"max_output_bytes\":4096},\"job_payload_hash\":\"33184fcde0395a48dccb5e0cbb4d48f92f59664c8c964db7489d6686a0002546\",\"script_sha256\":null}],\"max_parallel\":1,\"halt_after_failures\":1,\"recipe_references\":[{\"package\":\"rmm-windows-msi-fixture\",\"version\":\"1.1.0\",\"architecture\":\"x64\",\"recipe_version\":\"1\",\"sha256\":\"376d4a05fa43565a302cd1f90514e355e3f89a634d43abb9c31978e740bf7e9c\"}],\"artifact_references\":[{\"job_id\":\"00000000-0000-4000-8000-000000000004\",\"attempt_id\":\"00000000-0000-4000-8000-000000000005\",\"artifact\":{\"artifact_id\":\"00000000-0000-4000-8000-000000000010\",\"sha256\":\"abababababababababababababababababababababababababababababababab\",\"size_bytes\":32768}}]}"
|
||||
] as const;
|
||||
|
||||
// Mirrors the Rust Recipe/Action/Job declaration order, not a preview alias.
|
||||
async function msiFixture(upgrade = false) {
|
||||
const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
|
||||
const old = { product_code: windowsMsi.product, product_version: '1.0.0', payload_path: windowsMsi.payload, payload_sha256: windowsMsi.payload10, payload_bytes: 33 };
|
||||
const recipe = { schema_version: 1, recipe_id: upgrade ? windowsMsi.upgradeRecipe : windowsMsi.installRecipe, recipe_version: '1', platform: 'windows', upgrade_code: windowsMsi.family, architecture: 'x64', context: 'machine', command_profile: 'fixture_quiet_no_reboot_v1', artifact: { artifact_id: id(10), sha256: 'ab'.repeat(32), bytes: 32768 }, postcondition: upgrade ? { ...old, product_code: windowsMsi.upgradedProduct, product_version: '1.1.0', payload_sha256: windowsMsi.payload11 } : old, no_reboot: true, ...(upgrade ? { package_code: '{AF1C9887-391A-4BFF-B909-BC898300CF90}', predecessor: old } : {}) };
|
||||
const manifest = { recipe, recipe_sha256: await sha256(new TextEncoder().encode(JSON.stringify(recipe))) };
|
||||
const action = { action: 'ensure_package', provider: 'msi', package: windowsMsi.package, version: recipe.postcondition.product_version, architecture: 'x64', recipe_version: '1', installation_context: 'machine', recipe_id: recipe.recipe_id, windows_msi_manifest: manifest };
|
||||
const payload = { schema_version: 1, tenant_id: id(1), asset_id: id(2), agent_id: id(3), enrollment_generation: 1, assignment_version: 1, job_id: id(4), attempt_id: id(5), action, execution_identity: 'system', not_before: '2027-01-01T00:00:00Z', start_before: '2027-01-01T01:00:00Z', max_runtime_seconds: 30, max_output_bytes: 4096 };
|
||||
const job = { payload, job_payload_hash: await sha256(new TextEncoder().encode(JSON.stringify(payload))), script_sha256: null };
|
||||
const constructed = { schema_version: 1, plan_id: id(6), tenant_id: id(1), principal: 'simulated-unit-only', reason: 'MSI UI contract, no execution', jobs: [job], max_parallel: 1, halt_after_failures: 1, recipe_references: [{ package: windowsMsi.package, version: action.version, architecture: 'x64', recipe_version: '1', sha256: manifest.recipe_sha256 }], artifact_references: [{ job_id: payload.job_id, attempt_id: payload.attempt_id, artifact: { artifact_id: recipe.artifact.artifact_id, sha256: recipe.artifact.sha256, size_bytes: recipe.artifact.bytes } }] };
|
||||
const golden = msiDomainGoldens[upgrade ? 1 : 0];
|
||||
expect(JSON.stringify(constructed)).toBe(golden); // Independent Rust codec oracle.
|
||||
const plan_payload = parseStrictJson(golden) as typeof constructed;
|
||||
const actualJob = plan_payload.jobs[0]!;
|
||||
const raw = new TextEncoder().encode(golden);
|
||||
const preview = { ...actualJob, job_id: actualJob.payload.job_id, attempt_id: actualJob.payload.attempt_id, asset_id: actualJob.payload.asset_id, agent_id: actualJob.payload.agent_id };
|
||||
const plan = structuredClone({ plan_id: plan_payload.plan_id, plan_payload, payload: plan_payload, plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs: [preview], payloads: [preview], resolved_targets: [{ asset_id: payload.asset_id, agent_id: payload.agent_id }], expires_at: payload.start_before });
|
||||
return { manifest: actualJob.payload.action.windows_msi_manifest, action: actualJob.payload.action, payload: actualJob.payload, plan_payload, plan };
|
||||
}
|
||||
|
||||
describe('fixed SYSTEM MSI UI contract', () => {
|
||||
it('renders only the verified fixed package definition and never issues an approval or download', async () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
||||
try {
|
||||
const { WindowsMsiPlanNotice } = await import('./main');
|
||||
for (const upgrade of [false, true]) {
|
||||
const { plan } = await msiFixture(upgrade);
|
||||
expect(renderToStaticMarkup(<WindowsMsiPlanNotice plan={plan}/>)).toContain('role="alert"');
|
||||
await verifyPlanIntegrity(plan); const html = renderToStaticMarkup(<WindowsMsiPlanNotice plan={plan}/>);
|
||||
for (const value of ['SYSTEM', 'Machine', 'x64', upgrade ? windowsMsi.upgradeRecipe : windowsMsi.installRecipe, windowsMsi.product, windowsMsi.family, 'Rezept-SHA256', 'Artefakt', 'Vorgänger', 'No-Reboot: true', '30s', '4096', '/norestart', 'REBOOT=ReallySuppress', 'ALLUSERS=1', '3010', '1641', '1618']) expect(html).toContain(value);
|
||||
if (upgrade) { expect(html).toContain(windowsMsi.upgradedProduct); expect(html).toContain('AF1C9887'); }
|
||||
else expect(html).toContain('historischen1.0-Rezept nicht separat gebunden');
|
||||
expect(html).not.toMatch(/<(button|input|form|script)\b/); expect(fetch).not.toHaveBeenCalled();
|
||||
plan.jobs[0]!.payload.action.provider = 'foreign-installer';
|
||||
const invalid = renderToStaticMarkup(<WindowsMsiPlanNotice plan={plan}/>); expect(invalid).toContain('role="alert"'); expect(invalid).not.toContain('foreign-installer');
|
||||
}
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
it('checks canonical nested recipe bytes, strict typed inputs and independent SYSTEM rights', async () => {
|
||||
const { manifest, action } = await msiFixture(true);
|
||||
const { action: _action, ...fields } = action;
|
||||
const input: PlanInput = { tenant_id: 't', action: 'ensure_package', targets: { asset_ids: ['a'] }, parameters: { ...fields, execution_identity: 'system', timeout_seconds: 30, max_output_bytes: 4096 }, 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: 'fixed MSI' };
|
||||
const original = JSON.stringify(input); validateInput(input); await validateSensitiveInput(input, { ...auth, permissions: ['system:execute'] }); expect(JSON.stringify(input)).toBe(original);
|
||||
const formNull = { ...input, parameters: { ...input.parameters, apt_manifest: null } }; validateInput(formNull); await validateSensitiveInput(formNull, { ...auth, permissions: ['system:execute'] });
|
||||
const reversed = { ...manifest, recipe: Object.fromEntries(Object.entries(manifest.recipe).reverse()) };
|
||||
expect(await verifyWindowsMsiManifest(reversed)).toEqual(windowsMsiManifest(manifest));
|
||||
await expect(verifyWindowsMsiManifest({ ...manifest, recipe_sha256: 'cd'.repeat(32) })).rejects.toThrow('Rezepthash');
|
||||
for (const permissions of [undefined, [], ['root:execute']]) await expect(validateSensitiveInput(input, { ...auth, permissions })).rejects.toThrow('system:execute');
|
||||
for (const change of [{ execution_identity: 'root' }, { provider: 'apt' }, { architecture: 'amd64' }, { installation_context: 'system' }, { version: '2.0' }, { arguments: ['/quiet'] }, { apt_manifest: {} }, { timeout_seconds: 9 }, { timeout_seconds: 121 }, { max_output_bytes: 1023 }, { max_output_bytes: 65537 }, { windows_msi_manifest: null }]) expect(() => validateInput({ ...input, parameters: { ...input.parameters, ...change } })).toThrow();
|
||||
expect(() => validateInput({ ...input, artifact_ids: [manifest.recipe.artifact.artifact_id] })).toThrow('automatisch');
|
||||
for (const change of [{ architecture: { x64: null } }, { context: 'user' }, { command_profile: { fixture_quiet_no_reboot_v1: null } }, { no_reboot: false }, { installer_url: 'https://example.invalid/a.msi' }, { package_code: null }, { predecessor: { ...manifest.recipe.predecessor, product_version: '0.9' } }]) expect(() => windowsMsiManifest({ ...manifest, recipe: { ...manifest.recipe, ...change } })).toThrow();
|
||||
});
|
||||
it('requires the complete per-job recipe/artifact set and immutable full job hash', async () => {
|
||||
for (const upgrade of [false, true]) {
|
||||
const { plan } = await msiFixture(upgrade);
|
||||
expect(() => windowsMsiPlanJobs(plan)).toThrow('nicht aus hashgeprüften');
|
||||
await verifyPlanIntegrity(plan); const job = windowsMsiPlanJobs(plan)[0]!;
|
||||
expect(job.version).toBe(upgrade ? '1.1.0' : '1.0.0'); expect(job.packageCode !== null).toBe(upgrade); expect(job.arguments).toEqual(['/i', `C:\\ProgramData\\RustDiscoverySystem\\cache\\${'ab'.repeat(32)}.msi`, '/qn', '/norestart', 'REBOOT=ReallySuppress', 'ALLUSERS=1']);
|
||||
expect(windowsMsiApprovalBlockers(plan)).toEqual([]);
|
||||
for (const mutate of [
|
||||
(p: typeof plan.plan_payload) => { p.artifact_references = []; },
|
||||
(p: typeof plan.plan_payload) => { p.artifact_references.push(structuredClone(p.artifact_references[0]!)); },
|
||||
(p: typeof plan.plan_payload) => { p.artifact_references[0]!.artifact.size_bytes++; },
|
||||
(p: typeof plan.plan_payload) => { p.artifact_references[0]!.attempt_id = '00000000-0000-4000-8000-000000000099'; },
|
||||
(p: typeof plan.plan_payload) => { p.recipe_references.push(structuredClone(p.recipe_references[0]!)); },
|
||||
(p: typeof plan.plan_payload) => { p.recipe_references = []; },
|
||||
(p: typeof plan.plan_payload) => { p.jobs[0]!.payload.max_output_bytes++; },
|
||||
(p: typeof plan.plan_payload) => { Object.assign(p.jobs[0]!.payload.action, { apt_manifest: null }); },
|
||||
(p: typeof plan.plan_payload) => { Object.assign(p.jobs[0]!.payload.action, { apt_manifest: {} }); },
|
||||
]) {
|
||||
const changed = structuredClone(plan.plan_payload); mutate(changed); const raw = new TextEncoder().encode(JSON.stringify(changed));
|
||||
await expect(verifyPlanIntegrity({ plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw) })).rejects.toThrow();
|
||||
}
|
||||
}
|
||||
});
|
||||
it('blocks every alias and late mutation without blessing changed bytes or issuing a request', async () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);
|
||||
try {
|
||||
for (const alias of ['jobs', 'payloads', 'resolved_targets', 'payload', 'plan_payload']) {
|
||||
const { plan } = await msiFixture(true); await verifyPlanIntegrity(plan);
|
||||
const object = plan as Record<string, unknown>;
|
||||
if (alias === 'resolved_targets') plan.resolved_targets[0]!.agent_id = '00000000-0000-4000-8000-000000000099';
|
||||
else if (alias === 'jobs' || alias === 'payloads') { const view = structuredClone(plan.jobs); view[0]!.payload.max_runtime_seconds++; object[alias] = view; }
|
||||
else { const view = structuredClone(plan.plan_payload); view.jobs[0]!.payload.action.windows_msi_manifest.recipe.artifact.bytes++; object[alias] = view; }
|
||||
expect(windowsMsiApprovalBlockers(plan).length).toBeGreaterThan(0); await expect(verifyPlanIntegrity(plan)).rejects.toThrow();
|
||||
}
|
||||
const { plan } = await msiFixture(); await verifyPlanIntegrity(plan);
|
||||
const copy = windowsMsiPlanJobs(plan)[0]!; (copy.arguments as string[]).push('FORGED=1'); expect(windowsMsiPlanJobs(plan)[0]!.arguments).not.toContain('FORGED=1');
|
||||
const changed = structuredClone(plan.plan_payload); changed.reason = 'later'; const raw = new TextEncoder().encode(JSON.stringify(changed)); plan.plan_payload_bytes = Array.from(raw); plan.plan_hash = await sha256(raw);
|
||||
await expect(verifyPlanIntegrity(plan)).rejects.toThrow('verändert');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
});
|
||||
|
||||
+123
-12
@@ -1,8 +1,8 @@
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider } 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 } 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 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 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); }
|
||||
@@ -75,8 +75,13 @@ 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 !== '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')) {
|
||||
const original = canonical(input), m = validateWindowsMsiInput(input); await verifyWindowsMsiManifest(m);
|
||||
if (canonical(input) !== original) throw new Error('MSI-Antrag wurde während der Hashprüfung verändert');
|
||||
return;
|
||||
}
|
||||
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');
|
||||
@@ -96,15 +101,13 @@ export async function validateSensitiveInput(input: PlanInput, auth: Session) {
|
||||
}
|
||||
/** 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');
|
||||
powerShellPlanJobs(plan);
|
||||
return structuredClone(verifiedPowerShellPlans.get(plan)!.systemJobs);
|
||||
}
|
||||
export interface PowerShellPlanJob { readonly assetId: string; readonly profile: 'inherited' | 'powershell_51_remote_signed' }
|
||||
// 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 planHash: unknown; readonly planBytes: readonly number[] }
|
||||
interface VerifiedPowerShellPlan { readonly jobs: readonly PowerShellPlanJob[]; readonly logJobs: readonly QueryLogsPlanJob[]; readonly msiJobs: readonly WindowsMsiPlanJob[]; readonly systemJobs: RecordValue[]; readonly planHash: unknown; readonly planBytes: readonly number[] }
|
||||
const verifiedPowerShellPlans = new WeakMap<RecordValue, VerifiedPowerShellPlan>();
|
||||
export function powerShellPlanJobs(plan: RecordValue): readonly PowerShellPlanJob[] {
|
||||
const verified = verifiedPowerShellPlans.get(plan);
|
||||
@@ -116,6 +119,7 @@ export function powerShellPlanJobs(plan: RecordValue): readonly PowerShellPlanJo
|
||||
validatePlanAliases(plan, parsed);
|
||||
validatePowerShellViews(plan, parsed.jobs);
|
||||
validateQueryLogsViews(plan, parsed.jobs);
|
||||
validateMsiViews(plan, parsed.jobs);
|
||||
} else if (scriptPayloads(planTargetPreviews(plan)).some(hasPowerShellProfile)) {
|
||||
throw new Error('PowerShell-Plan benötigt exakte gespeicherte Planbytes');
|
||||
}
|
||||
@@ -153,6 +157,8 @@ function projectPowerShellJobs(jobs: unknown): PowerShellPlanJob[] {
|
||||
}
|
||||
function validatePlanAliases(plan: RecordValue, parsed: unknown): void {
|
||||
for (const alias of ['plan_payload', 'payload']) if (plan[alias] !== undefined && canonical(parsed) !== canonical(plan[alias])) throw new Error('Planansicht widerspricht gespeicherten Bytes');
|
||||
const p = record(parsed);
|
||||
if (scriptPayloads(p.jobs).some(isMsi) && ((plan.plan_id !== undefined && plan.plan_id !== p.plan_id) || (plan.expires_at !== undefined && plan.expires_at !== scriptPayloads(p.jobs)[0]?.start_before))) throw new Error('MSI-Plan-ID/Fristansicht widerspricht gespeicherten Bytes');
|
||||
}
|
||||
function validateFixedViews(plan: RecordValue, rawJobs: unknown, selected: (payload: RecordValue) => boolean, label: string, fields = ['action', 'execution_identity']): void {
|
||||
const rawPayloads = scriptPayloads(rawJobs), views = [planTargetPreviews(plan)];
|
||||
@@ -214,7 +220,95 @@ export function queryLogsApprovalBlockers(plan: RecordValue): string[] {
|
||||
catch (error) { return [error instanceof Error ? error.message : 'Logplan ist nicht verifiziert']; }
|
||||
}
|
||||
|
||||
export async function verifyWindowsMsiManifest(value: unknown): Promise<WindowsMsiManifest> {
|
||||
const m = windowsMsiManifest(value);
|
||||
if (await sha256(new TextEncoder().encode(JSON.stringify(m.recipe))) !== m.recipe_sha256) throw new Error('MSI-Rezepthash widerspricht kanonischen Rust-Rezeptbytes');
|
||||
return m;
|
||||
}
|
||||
function isMsi(payload: RecordValue): boolean {
|
||||
const action = payload.action;
|
||||
return action !== null && typeof action === 'object' && (record(action).provider === 'msi' || Object.prototype.hasOwnProperty.call(action, 'windows_msi_manifest'));
|
||||
}
|
||||
function hasMsiView(plan: RecordValue): boolean {
|
||||
return ['jobs', 'payloads', 'resolved_targets'].some(alias => scriptPayloads(plan[alias]).some(isMsi))
|
||||
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(isMsi) || scriptPayloads(record(plan.payload ?? {}).jobs).some(isMsi);
|
||||
}
|
||||
/** MSI views bind the entire payload, preview identity and hash, not just argv. */
|
||||
function validateMsiViews(plan: RecordValue, rawJobs: unknown): void {
|
||||
const originals = Array.isArray(rawJobs) ? rawJobs.map(job => record(job)) : [];
|
||||
const raw = scriptPayloads(rawJobs);
|
||||
for (const alias of ['jobs', 'payloads', 'resolved_targets']) {
|
||||
const values = plan[alias]; if (values === undefined) continue;
|
||||
if (!Array.isArray(values)) { if (raw.some(isMsi)) throw new Error('MSI-Zielansicht ist keine vollständige Liste'); continue; }
|
||||
if (!raw.some(isMsi) && !scriptPayloads(values).some(isMsi)) continue;
|
||||
if (values.length !== raw.length) throw new Error('MSI-Zielansicht ist unvollständig oder enthält zusätzliche Ziele');
|
||||
const seen = new Set<string>();
|
||||
for (const value of values) {
|
||||
const v = typeof value === 'string' ? { asset_id: value } : record(value);
|
||||
const payload = v.payload === undefined ? null : record(v.payload);
|
||||
const asset = text(v.asset_id ?? payload?.asset_id, 'MSI-Zielasset'), index = raw.findIndex(item => item.asset_id === asset);
|
||||
if (index < 0 || seen.has(asset)) throw new Error('MSI-Zielansicht enthält fremde/doppelte Ziele'); seen.add(asset);
|
||||
const fixed = raw[index]!, original = originals[index]!;
|
||||
if (!isMsi(fixed)) throw new Error('MSI-Ansicht widerspricht gespeichertem Aktionstyp');
|
||||
if (payload) {
|
||||
const allowed = ['payload', 'job_payload_hash', 'script_sha256', 'asset_id', 'agent_id', 'job_id', 'attempt_id'];
|
||||
if (Object.keys(v).some(key => !allowed.includes(key)) || canonical(payload) !== canonical(fixed) || v.job_payload_hash !== original.job_payload_hash || (v.script_sha256 !== undefined && v.script_sha256 !== original.script_sha256)
|
||||
|| ['agent_id', 'job_id', 'attempt_id'].some(key => v[key] !== undefined && v[key] !== fixed[key])) throw new Error('MSI-Zielpreview widerspricht gespeicherten Planbytes');
|
||||
} else if (alias !== 'resolved_targets' || (typeof value !== 'string' && (Object.keys(v).some(key => !['asset_id', 'agent_id'].includes(key)) || v.agent_id !== fixed.agent_id))) throw new Error('Vollständiger MSI-Zielpayload fehlt');
|
||||
}
|
||||
}
|
||||
}
|
||||
export interface WindowsMsiPlanJob {
|
||||
readonly assetId: string; readonly recipeId: string; readonly recipeHash: string;
|
||||
readonly artifactId: string; readonly artifactHash: string; readonly artifactBytes: number;
|
||||
readonly productCode: string; readonly upgradeCode: string; readonly packageCode: string | null; readonly version: string;
|
||||
readonly payloadPath: string; readonly payloadHash: string; readonly payloadBytes: number;
|
||||
readonly predecessor: Readonly<MsiPostcondition> | null; readonly runtimeSeconds: number; readonly outputBytes: number; readonly arguments: readonly string[];
|
||||
}
|
||||
function msiArguments(sha: string): string[] { return ['/i', `C:\\ProgramData\\RustDiscoverySystem\\cache\\${sha}.msi`, '/qn', '/norestart', 'REBOOT=ReallySuppress', 'ALLUSERS=1']; }
|
||||
async function projectMsiJobs(parsed: RecordValue): Promise<WindowsMsiPlanJob[]> {
|
||||
const payloads = scriptPayloads(parsed.jobs); if (!payloads.some(isMsi)) return [];
|
||||
exact(parsed, ['schema_version', 'plan_id', 'tenant_id', 'principal', 'reason', 'jobs', 'max_parallel', 'halt_after_failures', 'recipe_references', 'artifact_references']);
|
||||
if (parsed.schema_version !== 1 || !Array.isArray(parsed.jobs) || !parsed.jobs.length || parsed.jobs.length > 100 || payloads.length !== parsed.jobs.length || payloads.some(p => !isMsi(p)) || !Array.isArray(parsed.recipe_references) || !Array.isArray(parsed.artifact_references)) throw new Error('Vollständiger fester MSI-Plan erforderlich');
|
||||
msiUuid(parsed.plan_id); msiUuid(parsed.tenant_id); text(parsed.principal, 'MSI-Antragsteller'); text(parsed.reason, 'MSI-Grund');
|
||||
if (!Number.isSafeInteger(parsed.max_parallel) || Number(parsed.max_parallel) < 1 || Number(parsed.max_parallel) > 10 || !Number.isSafeInteger(parsed.halt_after_failures) || Number(parsed.halt_after_failures) < 1) throw new Error('MSI-Rolloutlimits fehlen');
|
||||
const projections: WindowsMsiPlanJob[] = [], recipes = new Map<string, RecordValue>(), jobs = new Set<string>(), assets = new Set<string>();
|
||||
for (const value of parsed.jobs) {
|
||||
const j = record(value); exact(j, ['payload', 'job_payload_hash', 'script_sha256']);
|
||||
const p = record(j.payload); exact(p, ['schema_version', 'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'job_id', 'attempt_id', 'action', 'execution_identity', 'not_before', 'start_before', 'max_runtime_seconds', 'max_output_bytes']);
|
||||
const asset = msiUuid(p.asset_id), tuple = `${msiUuid(p.job_id)}/${msiUuid(p.attempt_id)}`; msiUuid(p.agent_id);
|
||||
if (p.schema_version !== 1 || p.tenant_id !== parsed.tenant_id || p.execution_identity !== 'system' || j.script_sha256 !== null || jobs.has(tuple) || assets.has(asset)
|
||||
|| !Number.isSafeInteger(p.enrollment_generation) || Number(p.enrollment_generation) < 1 || !Number.isSafeInteger(p.assignment_version) || Number(p.assignment_version) < 1
|
||||
|| typeof p.not_before !== 'string' || typeof p.start_before !== 'string' || !Number.isFinite(Date.parse(p.not_before)) || !Number.isFinite(Date.parse(p.start_before)) || Date.parse(p.not_before) >= Date.parse(p.start_before)) throw new Error('MSI-Jobidentität/Frist/Generation widerspricht festem Plan');
|
||||
jobs.add(tuple); assets.add(asset); validateWindowsMsiLimits(p.max_runtime_seconds, p.max_output_bytes);
|
||||
const action = windowsMsiAction(record(p.action)), m = await verifyWindowsMsiManifest(action.windows_msi_manifest), r = m.recipe;
|
||||
// JobPayload declaration order and nested Action/Recipe order are fixed.
|
||||
const ordered = { schema_version: p.schema_version, tenant_id: p.tenant_id, asset_id: p.asset_id, agent_id: p.agent_id, enrollment_generation: p.enrollment_generation, assignment_version: p.assignment_version, job_id: p.job_id, attempt_id: p.attempt_id, action, execution_identity: p.execution_identity, not_before: p.not_before, start_before: p.start_before, max_runtime_seconds: p.max_runtime_seconds, max_output_bytes: p.max_output_bytes };
|
||||
if (await sha256(new TextEncoder().encode(JSON.stringify(ordered))) !== j.job_payload_hash) throw new Error('MSI-Jobhash widerspricht festen Rust-Payloadbytes');
|
||||
const recipe = { package: windowsMsi.package, version: r.postcondition.product_version, architecture: 'x64', recipe_version: r.recipe_version, sha256: m.recipe_sha256 };
|
||||
recipes.set(JSON.stringify(recipe), recipe);
|
||||
const refs = parsed.artifact_references.map(value => record(value)).filter(ref => ref.job_id === p.job_id && ref.attempt_id === p.attempt_id);
|
||||
const expectedArtifact = { artifact_id: r.artifact.artifact_id, sha256: r.artifact.sha256, size_bytes: r.artifact.bytes };
|
||||
if (refs.length !== 1) throw new Error('MSI benötigt genau eine Artefaktreferenz pro Job/Versuch');
|
||||
exact(refs[0]!, ['job_id', 'attempt_id', 'artifact']); exact(record(refs[0]!.artifact), ['artifact_id', 'sha256', 'size_bytes']);
|
||||
if (canonical(refs[0]!.artifact) !== canonical(expectedArtifact)) throw new Error('MSI-Artefaktreferenz widerspricht signiertem Rezept');
|
||||
projections.push({ assetId: asset, recipeId: r.recipe_id, recipeHash: m.recipe_sha256, artifactId: r.artifact.artifact_id, artifactHash: r.artifact.sha256, artifactBytes: r.artifact.bytes, productCode: r.postcondition.product_code, upgradeCode: r.upgrade_code, packageCode: r.package_code ?? null, version: r.postcondition.product_version, payloadPath: r.postcondition.payload_path, payloadHash: r.postcondition.payload_sha256, payloadBytes: r.postcondition.payload_bytes, predecessor: r.predecessor ?? null, runtimeSeconds: Number(p.max_runtime_seconds), outputBytes: Number(p.max_output_bytes), arguments: msiArguments(r.artifact.sha256) });
|
||||
}
|
||||
const expectedRecipes = [...recipes.values()].sort((a, b) => { for (const key of ['package', 'version', 'architecture', 'recipe_version', 'sha256']) { if (String(a[key]) < String(b[key])) return -1; if (String(a[key]) > String(b[key])) return 1; } return 0; });
|
||||
for (const value of parsed.recipe_references) exact(record(value), ['package', 'version', 'architecture', 'recipe_version', 'sha256']);
|
||||
if (parsed.artifact_references.length !== payloads.length || canonical(parsed.recipe_references) !== canonical(expectedRecipes)) throw new Error('Vollständige exakte MSI-Rezept-/Artefaktmenge widerspricht gespeichertem Plan');
|
||||
return projections;
|
||||
}
|
||||
export function windowsMsiPlanJobs(plan: RecordValue): readonly WindowsMsiPlanJob[] {
|
||||
powerShellPlanJobs(plan);
|
||||
if (!verifiedPowerShellPlans.get(plan)!.planBytes.length && hasMsiView(plan)) throw new Error('MSI-Plan benötigt exakte gespeicherte Planbytes');
|
||||
return structuredClone(verifiedPowerShellPlans.get(plan)!.msiJobs);
|
||||
}
|
||||
export function windowsMsiApprovalBlockers(plan: RecordValue): string[] { try { windowsMsiPlanJobs(plan); return []; } catch (error) { return [error instanceof Error ? error.message : 'MSI-Plan ist nicht verifiziert']; } }
|
||||
|
||||
export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
// Rechecking a previously displayed object may not bless a replacement plan.
|
||||
if (verifiedPowerShellPlans.has(plan)) { powerShellPlanJobs(plan); windowsMsiPlanJobs(plan); }
|
||||
verifiedPowerShellPlans.delete(plan);
|
||||
const views = planTargetPreviews(plan), hasScriptView = scriptPayloads(views).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(plan.jobs).some(hasPowerShellProfile) || scriptPayloads(plan.payloads).some(hasPowerShellProfile)
|
||||
@@ -225,9 +319,13 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
const hasLogView = ['jobs', 'payloads', 'resolved_targets'].some(alias => scriptPayloads(plan[alias]).some(isQueryLogs))
|
||||
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(isQueryLogs) || scriptPayloads(record(plan.payload ?? {}).jobs).some(isQueryLogs);
|
||||
if (hasLogView && plan.plan_payload_bytes === undefined) throw new Error('Logplan benötigt exakte gespeicherte Planbytes');
|
||||
if (hasMsiView(plan) && plan.plan_payload_bytes === undefined) throw new Error('MSI-Plan benötigt exakte gespeicherte Planbytes');
|
||||
let logJobs: QueryLogsPlanJob[] = [];
|
||||
let powerShellJobs: PowerShellPlanJob[] = [];
|
||||
let msiJobs: WindowsMsiPlanJob[] = [], systemJobs: RecordValue[] = [];
|
||||
let verifiedBytes: readonly number[] = [];
|
||||
let verifiedParsed: RecordValue | null = null;
|
||||
const verifiedHash = plan.plan_hash;
|
||||
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';
|
||||
@@ -238,7 +336,8 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
verifiedBytes = Array.from(exactBytes);
|
||||
const parsed = parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(exactBytes));
|
||||
validatePlanAliases(plan, parsed);
|
||||
const rawJobs = record(parsed).jobs;
|
||||
const parsedPlan = record(parsed), rawJobs = parsedPlan.jobs;
|
||||
verifiedParsed = parsedPlan;
|
||||
powerShellJobs = projectPowerShellJobs(rawJobs);
|
||||
logJobs = projectQueryLogsJobs(rawJobs);
|
||||
if (hasLogView || logJobs.length) validateQueryLogsViews(plan, rawJobs);
|
||||
@@ -246,9 +345,13 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
if (!Array.isArray(rawJobs)) throw new Error('Vollständige feste PowerShell-Zielpayloads fehlen');
|
||||
validatePowerShellViews(plan, rawJobs);
|
||||
}
|
||||
msiJobs = await projectMsiJobs(parsedPlan);
|
||||
validateMsiViews(plan, rawJobs);
|
||||
systemJobs = scriptPayloads(rawJobs).filter(payload => payload.execution_identity === 'system');
|
||||
}
|
||||
for (const payload of systemPlanJobs(plan)) {
|
||||
for (const payload of systemJobs) {
|
||||
const action = record(payload.action);
|
||||
if (isMsi(payload)) continue; // Fully validated, hash-bound package projection above.
|
||||
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);
|
||||
@@ -257,7 +360,15 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
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');
|
||||
}
|
||||
verifiedPowerShellPlans.set(plan, { jobs: powerShellJobs.map(job => Object.freeze({ ...job })), logJobs: logJobs.map(job => Object.freeze({ ...job })), planHash: plan.plan_hash, planBytes: verifiedBytes });
|
||||
// No await after this check: asynchronous hash verification cannot publish a
|
||||
// projection for bytes/views that changed while WebCrypto was running.
|
||||
if (verifiedParsed) {
|
||||
const current = bytes(plan.plan_payload_bytes);
|
||||
if (plan.plan_hash !== verifiedHash || current.length !== verifiedBytes.length || current.some((n, i) => n !== verifiedBytes[i])) throw new Error('Planbytes wurden während der Verifikation verändert');
|
||||
validatePlanAliases(plan, verifiedParsed); validateMsiViews(plan, verifiedParsed.jobs);
|
||||
validatePowerShellViews(plan, verifiedParsed.jobs); validateQueryLogsViews(plan, verifiedParsed.jobs);
|
||||
}
|
||||
verifiedPowerShellPlans.set(plan, { jobs: powerShellJobs.map(job => Object.freeze({ ...job })), logJobs: logJobs.map(job => Object.freeze({ ...job })), msiJobs: structuredClone(msiJobs), systemJobs: structuredClone(systemJobs), planHash: verifiedHash, planBytes: verifiedBytes });
|
||||
}
|
||||
export function recipeInput(value: unknown): RecordValue {
|
||||
const r = record(value); exact(r, ['schema_version', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'reboot_policy']);
|
||||
|
||||
Reference in New Issue
Block a user