Enable per-order privileged scripts on managed devices

This commit is contained in:
2026-11-18 00:02:17 +01:00
parent 2aa460e337
commit ea87d8141c
20 changed files with 864 additions and 157 deletions
+1 -1
View File
@@ -705,7 +705,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
{route.page === 'auftraege' && (
route.tab === 'neu' ? <>
<a href="#auftraege" className="back-link">← Zu den Aufträgen</a>
<OrderComposer tenantId={customer} customerName={customerName} auth={scoped} initialAssetIds={selected} onSubmitted={afterSubmission} />
<OrderComposer tenantId={customer} customerName={customerName} auth={scoped} initialAssetIds={selected} onSubmitted={afterSubmission} onDraft={showDraft} />
<details className="advanced-order"><summary>Weitere Wartungsaktionen</summary>
<p>Inventur, Dienstverwaltung und weitere Wartungsaufträge planen.</p>
<a className="quiet" href="#auftraege/wartung">Wartungsauftrag planen</a>
+169 -110
View File
@@ -27,6 +27,7 @@ import {
scriptPlatform,
type Identity,
type Interpreter,
type Revision,
type Script
} from './script-catalog';
import { ScriptFields } from './script-library';
@@ -37,6 +38,7 @@ type Props = {
auth: Session;
initialAssetIds: string[];
onSubmitted: (operationId: string) => void;
onDraft: (planId: string) => void;
};
type Target = {
id: string;
@@ -119,21 +121,26 @@ function issueMessage(err: unknown) {
return errorText(err);
}
export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, customerName }: Props) {
export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, onDraft, customerName }: Props) {
const path = (suffix: string) => tenantPath(tenantId, suffix);
const key = 'rmm:order-plan:' + JSON.stringify([auth.principal.id, tenantId]);
const [ticket, setTicket] = useState<Ticket | null>(() => resumeTicket(key));
const [savedTicket, setTicket] = useState<Ticket | null>(() => resumeTicket(key));
const [step, setStep] = useState<1 | 2>(1);
const [selected, setSelected] = useState<string[]>(() => [...new Set(initialAssetIds)]);
const [known, setKnown] = useState<Record<string, Target>>({});
const [query, setQuery] = useState('');
const [cursor, setCursor] = useState<string | null>(null);
const [prior, setPrior] = useState<(string | null)[]>([]);
const [mode, setMode] = useState<'library' | 'once'>('library');
const canCreate = ['inventory:read', 'operations:read', 'operations:plan', 'operations:submit']
.every((permission) => allowed(auth, permission));
const canPlanScript = canCreate && allowed(auth, 'scripts:execute');
const canPlanReboot = canCreate && (allowed(auth, 'root:execute') || allowed(auth, 'system:execute'));
const ticket = canPlanScript ? savedTicket : null;
const [mode, setMode] = useState<'library' | 'once' | 'reboot'>(() => canPlanScript ? 'library' : 'reboot');
const [revisionId, choose] = useState('');
const [libraryIdentity, setLibraryIdentity] = useState<Identity | null>(null);
const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh'));
const [windows, setWindows] = useState<Script>(() => emptyScript('powershell'));
const [fullRoot, setFullRoot] = useState(false);
const [reason, setReason] = useState('');
const [start, setStart] = useState(() => localDate(Date.now()));
const [end, setEnd] = useState(() => localDate(Date.now() + 3600000));
@@ -153,13 +160,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
mounted.current = false;
};
}, []);
const canPlan = [
'inventory:read',
'operations:read',
'operations:plan',
'scripts:execute',
'operations:submit'
].every((p) => allowed(auth, p));
const canPlan = canPlanScript || canPlanReboot;
const devices = useResource(
async (signal) => {
@@ -174,7 +175,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
);
const review = useResource(
async (signal) => {
if (!ticket) return null;
if (!ticket || !canPlanScript) return null;
const checked = await verifiedScriptOrder(
await request(path('/operation-plans/' + ticket.id), { signal }),
tenantId,
@@ -184,7 +185,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
throw Error('Der gespeicherte Plan entspricht nicht dem ausgewählten Auftrag.');
return checked;
},
[tenantId, ticket?.id, ticket?.hash, auth.principal.id]
[tenantId, ticket?.id, ticket?.hash, auth.principal.id, canPlanScript]
);
const missingIds = (review.data?.jobs.map((job) => job.assetId) ?? initialAssetIds).filter((id) => !known[id]);
const restored = useResource(
@@ -216,11 +217,15 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const hasLinux = targets.some((d) => d?.platform === 'linux');
const hasWindows = targets.some((d) => d?.platform === 'windows');
const scripts = useResource(
(signal) => (canPlan && step === 2 && !ticket ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, canPlan, step, !!ticket]
(signal) => (canPlanScript && step === 2 && !ticket && mode === 'library' ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, canPlanScript, step, !!ticket, mode]
);
const revision = scripts.data?.find((r) => r.revision_id === revisionId);
const heads = latestRevisions(scripts.data ?? []);
const identity = mode === 'library'
? libraryIdentity ?? revision?.execution_identity
: (hasWindows ? windows : linux).execution_identity;
const rebootIdentity = hasWindows ? 'system' : 'root';
const issues: string[] = [];
if (targets.some((d) => !d?.current))
issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
@@ -233,10 +238,13 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
issues.push(
`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map((d) => d?.name).join(', ')}.`
);
const identity = revision.execution_identity;
if (identity !== 'agent_service' && !allowed(auth, identity + ':execute'))
if (identity && identity !== 'agent_service' && !allowed(auth, identity + ':execute'))
issues.push('Die Berechtigung für ' + identityNames[identity] + ' fehlt.');
}
if (mode === 'reboot') {
if (selected.length !== 1) issues.push('Wählen Sie ein einzelnes Gerät für den Neustart.');
if (!allowed(auth, rebootIdentity + ':execute')) issues.push('Die Berechtigung für ' + identityNames[rebootIdentity] + ' fehlt.');
}
if (
mode === 'once' &&
hasLinux &&
@@ -263,19 +271,17 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const windowUpdate =
mode === 'library' &&
revision?.script_sha256 === windowsUpdateScriptHash &&
revision.execution_identity === 'system';
const identity =
mode === 'library' ? revision?.execution_identity : (hasWindows ? windows : linux).execution_identity;
const maxRuntime = windowUpdate
? 3600
: identity === 'system'
? 120
: identity === 'root' && (mode === 'library' || fullRoot)
? 300
: 3600;
identity === 'system';
const maxRuntime = windowUpdate ? 3600 : identity === 'system' ? 120 : identity === 'root' ? 300 : 3600;
function chooseLibrary(next: Revision | undefined) {
choose(next?.revision_id ?? '');
setLibraryIdentity(null);
setRuntime(next?.script_sha256 === windowsUpdateScriptHash && next.execution_identity === 'system' ? 3600 : 120);
setLimit(65536);
}
async function prepare(e: FormEvent) {
e.preventDefault();
if (lock.current || !canPlan || issues.length || !selected.length) return;
if (lock.current || !(mode === 'reboot' ? canPlanReboot : canPlanScript) || issues.length || !selected.length) return;
lock.current = true;
setBusy(true);
setError(null);
@@ -285,12 +291,56 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
throw Error('Die Startfrist muss nach dem frühesten Start und in der Zukunft liegen.');
const rollout = { max_parallel: parallel, halt_after_failures: halt };
const bound = { targets: { asset_ids: selected }, rollout, reason: reason.trim() };
if (mode === 'reboot') {
const input: PlanInput = {
...bound,
tenant_id: tenantId,
action: 'reboot',
schedule: { ...schedule, offline_policy: 'wait_until_deadline' },
rollout: { max_parallel: 1, halt_after_failures: 1 },
parameters: {
execution_identity: rebootIdentity,
reason: bound.reason,
dependency_group: 'asset-' + selected[0],
reconnect_timeout_seconds: hasWindows ? 180 : 300,
timeout_seconds: 60,
max_output_bytes: 4096
}
};
validateInput(input);
await validateSensitiveInput(input, auth);
const plan = record(await request(path('/operation-plans'), { csrf: auth.csrf_token, body: input }));
if (!Array.isArray(plan.plan_payload_bytes)) throw Error('Die gespeicherten Bytes des Neustartplans fehlen.');
await verifyPlanIntegrity(plan);
const planId = objectId(plan, 'plan');
const fixed = record(plan.plan_payload);
const jobs = Array.isArray(fixed.jobs) ? fixed.jobs : [];
const job = record(record(jobs[0]).payload);
const action = record(job.action);
if (
fixed.plan_id !== planId || fixed.tenant_id !== tenantId || fixed.principal !== auth.principal.id ||
fixed.reason !== bound.reason || fixed.max_parallel !== 1 || fixed.halt_after_failures !== 1 ||
jobs.length !== 1 || job.asset_id !== selected[0] || job.execution_identity !== rebootIdentity ||
action.action !== 'reboot' || action.reason !== bound.reason ||
action.dependency_group !== input.parameters.dependency_group ||
action.reconnect_timeout_seconds !== input.parameters.reconnect_timeout_seconds ||
job.max_runtime_seconds !== input.parameters.timeout_seconds ||
job.max_output_bytes !== input.parameters.max_output_bytes ||
Date.parse(String(job.not_before)) !== Date.parse(schedule.not_before) ||
Date.parse(String(job.start_before)) !== Date.parse(schedule.start_before)
) throw Error('Der erstellte Neustartplan weicht von diesem Entwurf ab.');
if (mounted.current) onDraft(planId);
return;
}
let raw: unknown;
if (mode === 'library') {
if (!revision) throw Error('Wählen Sie eine Skriptversion.');
raw = await request(path('/script-revisions/' + revision.revision_id + '/plan'), {
csrf: auth.csrf_token,
body: { ...bound, schedule, max_runtime_seconds: runtime, max_output_bytes: limit }
body: {
...bound, schedule, max_runtime_seconds: runtime, max_output_bytes: limit,
...(libraryIdentity ? { execution_identity: libraryIdentity } : {})
}
});
} else {
const variants = [hasLinux ? linux : null, hasWindows ? windows : null]
@@ -311,7 +361,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
expected_stdout: expectedStdout(expected, expectedFormat),
timeout_seconds: runtime,
max_output_bytes: limit,
...(identity === 'system' || (identity === 'root' && fullRoot)
...(identity === 'system' || identity === 'root'
? { privileged_script_profile: fullMaintenanceScriptProfile }
: {})
};
@@ -335,7 +385,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
!selected.includes(j.assetId) ||
j.revision?.id !== (mode === 'library' ? revisionId : undefined) ||
j.script !== script?.script_utf8 ||
j.identity !== script.execution_identity ||
j.identity !== identity ||
j.interpreter !== script.interpreter ||
j.runtimeSeconds !== runtime ||
j.outputBytes !== limit ||
@@ -365,7 +415,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
}
}
async function submit() {
if (!ticket || !review.data || !canPlan || lock.current) return;
if (!ticket || !review.data || !canPlanScript || lock.current) return;
lock.current = true;
setBusy(true);
setError(null);
@@ -413,7 +463,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
<h1>Neuer Auftrag</h1>
</div>
<ol className="order-progress" aria-label="Auftragsschritte">
{['Geräte', 'Skript', 'Zusammenfassung'].map((name, i) => (
{['Geräte', 'Aktion', 'Zusammenfassung'].map((name, i) => (
<li key={name} aria-current={stepNumber === i + 1 ? 'step' : undefined}>
{i + 1}. {name}
</li>
@@ -423,11 +473,11 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
{!canPlan ? (
<section>
<p>
Zum Erstellen eines Skriptauftrags benötigen Sie Gerätezugriff sowie Rechte zum Planen und Einreichen von
Skriptaufträgen.
Zum Erstellen eines Auftrags benötigen Sie Gerätezugriff, Rechte zum Planen und Einreichen und das
Ausführungsrecht für die gewählte Aktion.
</p>
</section>
) : ticket ? (
) : ticket && canPlanScript ? (
<section aria-label="Auftrag prüfen">
<h2>Zusammenfassung</h2>
{review.data ? (
@@ -603,7 +653,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
setError(null);
}}
>
Weiter zum Skript
{canPlanReboot ? 'Weiter zur Aktion' : 'Weiter zum Skript'}
</button>
</div>
{selected.length > 100 && <p role="alert">Ein Auftrag kann bis zu 100 Geräte enthalten.</p>}
@@ -611,18 +661,22 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
</section>
) : (
<section>
<h2>Skript auswählen</h2>
<h2>{canPlanReboot ? 'Aktion auswählen' : 'Skript auswählen'}</h2>
<form onSubmit={prepare}>
<fieldset disabled={busy} className="work-form">
<div className="order-source">
<label>
{canPlanScript && <label>
<input type="radio" name="quelle" checked={mode === 'library'} onChange={() => setMode('library')} />
Aus der Bibliothek
</label>
<label>
</label>}
{canPlanScript && <label>
<input type="radio" name="quelle" checked={mode === 'once'} onChange={() => setMode('once')} />
Einmaliges Skript
</label>
</label>}
{canPlanReboot && <label>
<input type="radio" name="quelle" checked={mode === 'reboot'} onChange={() => setMode('reboot')} />
Gerät neu starten
</label>}
</div>
{mode === 'library' ? (
<>
@@ -632,9 +686,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
required
value={revision?.name ?? ''}
onChange={(e) => {
const next = heads.find((h) => h.name === e.target.value);
choose(next?.revision_id ?? '');
setRuntime(next?.script_sha256 === windowsUpdateScriptHash ? 3600 : 120);
chooseLibrary(heads.find((h) => h.name === e.target.value));
}}
>
<option value="">Skript wählen</option>
@@ -652,15 +704,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
Version
<select
value={revisionId}
onChange={(e) => {
choose(e.target.value);
setRuntime(
scripts.data?.find((r) => r.revision_id === e.target.value)?.script_sha256 ===
windowsUpdateScriptHash
? 3600
: 120
);
}}
onChange={(e) => chooseLibrary(scripts.data?.find((r) => r.revision_id === e.target.value))}
>
{scripts.data
?.filter((r) => r.name === revision.name)
@@ -671,26 +715,39 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
))}
</select>
</label>
<p>
{interpreterNames[revision.interpreter]} · {identityNames[revision.execution_identity]}
</p>
{revision.execution_identity !== 'agent_service' && (
<p className="warning">Das Skript benötigt erhöhte Rechte auf den ausgewählten Geräten.</p>
)}
<p>{interpreterNames[revision.interpreter]}</p>
<label>
Ausführen als
<select value={identity} onChange={(e) => {
const next = e.target.value as Identity;
setLibraryIdentity(next);
setRuntime(revision.script_sha256 === windowsUpdateScriptHash && next === 'system' ? 3600 : 120);
setLimit(65536);
}}>
<option value="agent_service">{identityNames.agent_service}</option>
{(['root', 'system'] as const).filter((value) =>
value === (revision.interpreter === 'powershell' ? 'system' : 'root')
).map((value) => (
<option key={value} value={value} disabled={!allowed(auth, value + ':execute')}>{identityNames[value]}</option>
))}
</select>
</label>
</>
)}
</>
) : (
) : mode === 'once' ? (
<>
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />}
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows />}
{linux.execution_identity === 'root' && hasLinux && (
<label>
<input type="checkbox" checked={fullRoot} onChange={(e) => setFullRoot(e.target.checked)} />
Vollwartung als root anfordern
</label>
)}
</>
) : (
<p className="warning">
Der Auftrag startet das ausgewählte Gerät nach Genehmigung neu. Ausführung als {identityNames[rebootIdentity]}.
Der Agent muss nach dem Neustart wieder Kontakt aufnehmen.
</p>
)}
{mode !== 'reboot' && identity && identity !== 'agent_service' && (
<p className="warning">Der genehmigte Skriptauftrag erhält volle Hostrechte als {identityNames[identity]}.</p>
)}
<label>
Begründung
@@ -707,49 +764,51 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
Startfrist
<input required type="datetime-local" value={end} onChange={(e) => setEnd(e.target.value)} />
</label>
<label>
Laufzeit je Gerät in Sekunden
<input
required
type="number"
min={1}
max={maxRuntime}
value={runtime}
onChange={(e) => setRuntime(Number(e.target.value))}
/>
</label>
<label>
Ausgabelimit in Byte
<input
required
type="number"
min={1}
max={identity === 'agent_service' ? 262144 : 65536}
value={limit}
onChange={(e) => setLimit(Number(e.target.value))}
/>
</label>
<label>
Geräte gleichzeitig
<input
required
type="number"
min={1}
max={10}
value={parallel}
onChange={(e) => setParallel(Number(e.target.value))}
/>
</label>
<label>
Stopp nach Fehlern
<input
required
type="number"
min={1}
value={halt}
onChange={(e) => setHalt(Number(e.target.value))}
/>
</label>
{mode !== 'reboot' && <>
<label>
Laufzeit je Gerät in Sekunden
<input
required
type="number"
min={1}
max={maxRuntime}
value={runtime}
onChange={(e) => setRuntime(Number(e.target.value))}
/>
</label>
<label>
Ausgabelimit in Byte
<input
required
type="number"
min={1}
max={identity === 'agent_service' ? 262144 : 65536}
value={limit}
onChange={(e) => setLimit(Number(e.target.value))}
/>
</label>
<label>
Geräte gleichzeitig
<input
required
type="number"
min={1}
max={10}
value={parallel}
onChange={(e) => setParallel(Number(e.target.value))}
/>
</label>
<label>
Stopp nach Fehlern
<input
required
type="number"
min={1}
value={halt}
onChange={(e) => setHalt(Number(e.target.value))}
/>
</label>
</>}
</div>
{mode === 'once' && (
<>