Share signed job core and verify native Linux then Windows contracts
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
+17
-1
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { approvalBlockers, page, PlanInput, request, session, validateInput } from './api';
|
||||
import { expectedStdout, approvalBlockers, page, PlanInput, request, session, validateInput } from './api';
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
describe('JSON contract boundary', () => {
|
||||
it('refuses missing simulation identity metadata', () => {
|
||||
@@ -49,6 +49,22 @@ describe('JSON contract boundary', () => {
|
||||
validateInput(input); expect(input.parameters.variants).toEqual([variant]);
|
||||
expect(() => validateInput({ ...input, targets: { asset_ids: ['a', 'a'] } })).toThrow('eindeutige');
|
||||
});
|
||||
it('binds explicitly escaped stdout CRLF before planning and leaves text unchanged', () => {
|
||||
expect(expectedStdout('"Hello\\r\\n"', 'json')).toBe('Hello\r\n');
|
||||
expect(expectedStdout('Hello\n', 'text')).toBe('Hello\n');
|
||||
expect(expectedStdout('', 'json')).toBeNull();
|
||||
expect(() => expectedStdout('{}', 'json')).toThrow();
|
||||
expect(() => expectedStdout('x', 'unknown')).toThrow();
|
||||
});
|
||||
it('binds explicit Windows and mixed variants without normalizing script bytes', () => {
|
||||
const windows = { os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: "Write-Output 'hi'\r\n" };
|
||||
const linux = { os_family: 'linux', interpreter: 'posix_sh', encoding: 'utf-8', script_utf8: "printf hi\n" };
|
||||
const input: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['a', 'b'] }, parameters: { variants: [linux, windows], execution_identity: 'agent_service', timeout_seconds: 60, 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 mixed plan' };
|
||||
const original = JSON.stringify(input); validateInput(input); expect(JSON.stringify(input)).toBe(original);
|
||||
for (const variants of [[windows, windows], [{ ...windows, interpreter: 'pwsh' }], [{ ...windows, interpreter: 'bash' }], [{ ...windows, script_utf8: "Write-Output 'é'" }]]) expect(() => validateInput({ ...input, parameters: { ...input.parameters, variants } })).toThrow();
|
||||
expect(() => validateInput({ ...input, parameters: { ...input.parameters, execution_identity: 'root' } })).toThrow('agent_service');
|
||||
validateInput({ ...input, parameters: { ...input.parameters, variants: [{ ...windows, script_utf8: "\ufeffWrite-Output 'é'\r\n" }] } });
|
||||
});
|
||||
it('accepts explicit existing dev simulation evidence but not a principal-name guess', () => {
|
||||
expect(session({ principal: 'sim-test', tenant_id: 't', testsimulation: true, csrf_token: 'csrf' }).principal.simulated).toBe(true);
|
||||
expect(() => session({ principal: 'sim-test', tenant_id: 't', csrf_token: 'csrf' })).toThrow();
|
||||
|
||||
+16
-4
@@ -60,6 +60,13 @@ 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 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 }
|
||||
/** Decode explicit escaped CRLF before planning; never alter approved output bytes. */
|
||||
export function expectedStdout(value: string, format: string): string | null {
|
||||
if (value === '') return null;
|
||||
const output: unknown = format === 'json' ? JSON.parse(value) : format === 'text' ? value : undefined;
|
||||
if (typeof output !== 'string' || new TextEncoder().encode(output).length > 65536) throw new Error('stdout-Nachbedingung benötigt einen String (max.64KiB UTF-8)');
|
||||
return output;
|
||||
}
|
||||
export function validateInput(input: PlanInput): void {
|
||||
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');
|
||||
@@ -68,10 +75,15 @@ export function validateInput(input: PlanInput): void {
|
||||
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 variants = input.parameters.variants;
|
||||
if (!Array.isArray(variants) || !variants.length || !variants.every(v => {
|
||||
const variant = record(v), bytes = typeof variant.script_utf8 === 'string' ? new TextEncoder().encode(variant.script_utf8).length : 0;
|
||||
return bytes > 0 && bytes <= 32768 && !String(variant.script_utf8).includes('\0') && variant.os_family === 'linux' && variant.encoding === 'utf-8' && ['posix_sh', 'bash'].includes(String(variant.interpreter));
|
||||
})) throw new Error('Exakte Linux UTF-8 Skriptbytes und Interpreter erforderlich (max. 32 KiB)');
|
||||
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 : '';
|
||||
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 (!['agent_service', 'root'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich');
|
||||
const required = (key: string) => text(input.parameters[key], `parameters.${key}`);
|
||||
|
||||
+5
-4
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput } from './api';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput } from './api';
|
||||
import './style.css';
|
||||
import { AdminControl, Catalog, TenantControls } from './management';
|
||||
import { allowed, availableActions, parseStrictJson, rootWarning, validateSensitiveInput, verifyPlanIntegrity } from './safety';
|
||||
@@ -37,19 +37,20 @@ const initialParameters: Record<Action, RecordValue> = {
|
||||
run_script: {}, refresh_inventory: { scope: 'linux.base' }, query_logs: { unit: '', since: '', until: '', max_lines: 1000 }, set_service_state: { unit: '', state: 'running' }, ensure_package: { provider: 'apt', recipe_version: '', package: '', version: '', architecture: 'amd64', installation_context: 'system', apt_manifest: null }, apply_updates: { provider: 'apt', packages: [], reboot_policy: 'never', apt_manifest: null }, reboot: { reason: '', dependency_group: '', reconnect_timeout_seconds: 300 }, apt_native_acceptance: { recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', apt_manifest: null },
|
||||
};
|
||||
function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; auth: Session; selected: string[]; showPlan: (id: string) => void }) {
|
||||
const [scriptPlatform, setScriptPlatform] = useState('linux'), [mixedVariants, setMixedVariants] = useState('[]');
|
||||
const [action, setAction] = useState<Action>('run_script'), [parameters, setParameters] = useState('{}'), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);
|
||||
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 params = action === 'run_script' ? { ...common, variants: [{ os_family: 'linux', interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')) }], arguments: [], expected_stdout: f.get('expected') === '' ? null : String(f.get('expected')) } : { ...record(parseStrictJson(parameters)), ...common };
|
||||
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')) }], 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; }
|
||||
validateInput(input); await validateSensitiveInput(input, auth); const plan = record(await request(tenantPath(tenantId, '/operation-plans'), { body: input, csrf: auth.csrf_token })); showPlan(objectId(plan, 'plan'));
|
||||
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
|
||||
<label>Aktion<select aria-label="Aktion" value={action} onChange={e => { const next = availableActions(auth, actions).find(a => a === e.target.value); if (next) { setAction(next); setParameters(pretty(initialParameters[next])); } }}>{availableActions(auth, actions).map(a => <option key={a} value={a}>{a}</option>)}</select></label>
|
||||
{action === '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>Interpreter<select name="interpreter"><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 (LF; keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label><label>Erwartete stdout-Ausgabe (exakt, optional)<textarea name="expected" rows={2} spellCheck={false}/></label></> : <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>}
|
||||
{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; keine ExecutionPolicy-Umgehung. 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></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>}
|
||||
{['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>}
|
||||
@@ -103,7 +104,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
const [tenantId, setTenant] = useState(auth.tenants[0]?.tenant_id ?? ''), [error, setError] = useState<string | null>(null);
|
||||
const options = tenants.data?.items.map(tenant) ?? auth.tenants;
|
||||
useEffect(() => { if (!tenantId && options[0]) setTenant(options[0].tenant_id); }, [options, tenantId]);
|
||||
return <><header><div><h1>RMM <span>Linux Verwaltung</span></h1><p>{auth.principal.display_name} · {auth.principal.id}</p></div><button onClick={async () => { try { await request('/auth/logout', { csrf: auth.csrf_token, body: {} }); logout(); } catch (e) { setError(errorText(e)); } }}>Abmelden</button></header>
|
||||
return <><header><div><h1>RMM <span>Geräteverwaltung</span></h1><p>{auth.principal.display_name} · {auth.principal.id}</p></div><button onClick={async () => { try { await request('/auth/logout', { csrf: auth.csrf_token, body: {} }); logout(); } catch (e) { setError(errorText(e)); } }}>Abmelden</button></header>
|
||||
{auth.principal.simulated && <aside className="simulation" role="status">SIMULIERT · dev/test-Testprincipal · Genehmigung ist eine Entwicklungs-Browsersimulation, kein menschlicher Produktions-Freigabenachweis.</aside>}
|
||||
<main><ErrorBox error={error}/><ErrorBox error={tenants.error}/><label>Mandant<select aria-label="Mandant" value={tenantId} onChange={e => setTenant(e.target.value)}><option value="" disabled>Mandant wählen</option>{options.map(t => <option key={t.tenant_id} value={t.tenant_id}>{t.name} · {t.tenant_id}</option>)}</select></label>{tenantId && <TenantWorkspace key={tenantId} tenantId={tenantId} auth={auth}/>}</main></>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user