diff --git a/tests/browser/order-composer.spec.ts b/tests/browser/order-composer.spec.ts new file mode 100644 index 0000000..8779e6b --- /dev/null +++ b/tests/browser/order-composer.spec.ts @@ -0,0 +1,262 @@ +import { test, expect } from '../../web/node_modules/@playwright/test/index.js'; +import { createServer, type ViteDevServer } from '../../web/node_modules/vite/dist/node/index.js'; +import { createHash, randomUUID } from 'node:crypto'; +import { resolve } from 'node:path'; + +let server: ViteDevServer; +let origin: string; +const principal = 'operator-fixture'; +const tenantId = randomUUID(); +const auth = { + principal: { id: principal, display_name: 'Operator', simulated: true }, + csrf_token: 'fixture', + tenants: [{ tenant_id: tenantId, name: 'Nord' }], + permissions: ['inventory:read', 'operations:read', 'operations:plan', 'operations:submit', 'scripts:execute'] +}; +const linux = { + asset_id: randomUUID(), + agent_id: randomUUID(), + hostname: 'test-linux', + os: 'Debian', + source_id: 'linux.base', + status: 'online', + lifecycle: 'current' +}; +const windows = { + ...linux, + asset_id: randomUUID(), + agent_id: randomUUID(), + hostname: 'test-windows', + os: 'Windows', + source_id: 'windows.base' +}; +const script = { + name: 'Betriebssystem anzeigen', + revision_id: randomUUID(), + interpreter: 'posix_sh', + execution_identity: 'agent_service', + script_utf8: 'uname -s\n', + version: 1 +}; +const hash = (text: string) => createHash('sha256').update(text).digest('hex'); +const listing = (items: unknown[]) => ({ + items, + as_of: new Date().toISOString(), + next_cursor: null, + truncated: false, + completeness: 'complete' +}); +test.beforeAll(async () => { + server = await createServer({ + root: resolve(__dirname, '../../web'), + configFile: false, + server: { host: '127.0.0.1', port: 0 }, + logLevel: 'silent' + }); + await server.listen(); + const a = server.httpServer?.address(); + if (!a || typeof a === 'string') throw Error('Missing fixture port'); + origin = 'http://127.0.0.1:' + a.port; +}); +test.afterAll(async () => { + await server?.close(); +}); + +for (const library of [true, false]) { + test( + library + ? 'pins a revision, blocks an incompatible target and finds the submitted order after a lost response' + : 'submits a one-time script without publishing a library revision', + async ({ page }) => { + let operationId: string | null = null; + let plan: Record | null = null; + const posted: string[] = []; + let issuedVersion = 1; + await page.route(origin + '/fixture', (r) => + r.fulfill({ + contentType: 'text/html', + body: `
` + }) + ); + const api = '/api/v1/tenants/' + tenantId; + await page.route(origin + api + '/**', async (r) => { + const req = r.request(); + const suffix = new URL(req.url()).pathname.slice(api.length); + if (req.method() === 'GET') { + if (suffix === '/devices') return r.fulfill({ json: listing([linux, windows]) }); + if (suffix.startsWith('/devices/')) + return r.fulfill({ json: suffix.endsWith(linux.asset_id) ? linux : windows }); + if (suffix === '/script-revisions') + return r.fulfill({ + json: listing([{ ...script, script_sha256: hash(script.script_utf8), version: issuedVersion }]) + }); + if (suffix === '/operation-plans/' + plan?.plan_id) + return r.fulfill({ json: { ...plan, operation_id: operationId } }); + } else if (req.method() === 'POST') { + posted.push(suffix); + const body = req.postDataJSON(); + expect(req.headers()['x-csrf-token']).toBe(auth.csrf_token); + if (suffix === (library ? '/script-revisions/' + script.revision_id + '/plan' : '/operation-plans')) { + expect(body.targets.asset_ids).toEqual([linux.asset_id]); + expect(body.reason).toBe('Abnahme'); + const content = library ? script.script_utf8 : body.parameters.variants[0].script_utf8; + const action = { + action: 'run_script', + interpreter: 'posix_sh', + script_utf8: content, + arguments: [], + expected_stdout: null + }; + const payload = { + schema_version: 1, + tenant_id: tenantId, + asset_id: linux.asset_id, + agent_id: linux.agent_id, + enrollment_generation: 1, + assignment_version: 1, + job_id: randomUUID(), + attempt_id: randomUUID(), + action, + execution_identity: 'agent_service', + not_before: body.schedule.not_before, + start_before: body.schedule.start_before, + max_runtime_seconds: library ? body.max_runtime_seconds : body.parameters.timeout_seconds, + max_output_bytes: library ? body.max_output_bytes : body.parameters.max_output_bytes + }; + const job = { payload, job_payload_hash: hash(JSON.stringify(payload)), script_sha256: hash(content) }; + const fixed = { + schema_version: 1, + plan_id: randomUUID(), + tenant_id: tenantId, + principal, + reason: body.reason, + jobs: [job], + max_parallel: 1, + halt_after_failures: 1, + ...(library + ? { + script_revision: { + revision_id: script.revision_id, + name: script.name, + version: 1, + script_sha256: job.script_sha256 + } + } + : {}) + }; + const bytes = JSON.stringify(fixed); + plan = { + plan_id: fixed.plan_id, + plan_hash: hash(bytes), + plan_payload_bytes: [...Buffer.from(bytes)], + plan_payload: fixed, + payload: fixed, + jobs: [job], + resolved_targets: [{ asset_id: linux.asset_id, agent_id: linux.agent_id }], + excluded_targets: [], + expires_at: payload.start_before + }; + return r.fulfill({ json: plan }); + } + if (suffix === '/operation-plans/' + plan?.plan_id + '/submit') { + expect(body).toEqual({ idempotency_key: plan!.plan_id }); + operationId = randomUUID(); + if (library) return r.abort('connectionreset'); + return r.fulfill({ + json: { plan_id: plan!.plan_id, plan_hash: plan!.plan_hash, operation_id: operationId } + }); + } + } + return r.fulfill({ status: 404, json: { code: 'unexpected', message: suffix } }); + }); + await page.goto(origin + '/fixture'); + await expect(page.getByRole('checkbox', { name: /test-linux/ })).toBeChecked(); + if (library) await page.getByRole('checkbox', { name: /test-windows/ }).check(); + await page.getByRole('button', { name: 'Weiter zum Skript' }).click(); + if (library) { + await page.getByLabel('Bibliotheksskript').selectOption(script.name); + await expect(page.getByRole('alert')).toContainText('test-windows'); + await expect(page.getByRole('button', { name: 'Zusammenfassung ansehen' })).toBeDisabled(); + await page.getByRole('button', { name: 'Zurück zu Geräten' }).click(); + await page.getByRole('checkbox', { name: /test-windows/ }).uncheck(); + await page.getByRole('button', { name: 'Weiter zum Skript' }).click(); + } else { + await page.getByRole('radio', { name: 'Einmaliges Skript' }).check(); + await page.getByLabel('Skriptinhalt').fill('uname\n'); + } + await page.getByLabel('Begründung').fill('Abnahme'); + await page.getByRole('button', { name: 'Zusammenfassung ansehen' }).click(); + await expect(page.getByRole('heading', { name: 'Zusammenfassung' })).toBeVisible(); + if (library) { + issuedVersion = 2; + await expect(page.getByRole('heading', { name: /Version 1/ })).toBeVisible(); + } + await page.getByRole('button', { name: 'Zur Genehmigung einreichen' }).click(); + if (library) { + await expect(page.getByRole('button', { name: 'Eingereichten Auftrag öffnen' })).toBeVisible(); + await page.reload(); + await page.getByRole('button', { name: 'Eingereichten Auftrag öffnen' }).click(); + } + await expect(page.locator('body')).toHaveAttribute('data-operation', /^[a-f0-9-]{36}$/); + expect(await page.locator('body').getAttribute('data-operation')).toBe(operationId); + expect(posted).toEqual([ + library ? '/script-revisions/' + script.revision_id + '/plan' : '/operation-plans', + '/operation-plans/' + plan!.plan_id + '/submit' + ]); + expect(await page.evaluate(() => sessionStorage.length)).toBe(0); + } + ); +} + +test('publishes versions in the library and keeps the earlier script readable', async ({ page }) => { + const revisions = [{ ...script, script_sha256: hash(script.script_utf8) }]; + const writes: string[] = []; + await page.route(origin + '/fixture', (r) => + r.fulfill({ + contentType: 'text/html', + body: `
` + }) + ); + await page.route(origin + '/api/v1/**', (r) => { + const req = r.request(); + const path = '/api/v1/tenants/' + tenantId + '/script-revisions'; + expect(new URL(req.url()).pathname).toBe(path); + if (req.method() === 'GET') return r.fulfill({ json: listing(revisions) }); + writes.push(path); + expect(req.headers()['x-csrf-token']).toBe(auth.csrf_token); + const body = req.postDataJSON(); + expect(body.expected_version).toBe(revisions.length); + const next = { + ...script, + revision_id: randomUUID(), + script_utf8: body.script_utf8, + script_sha256: hash(body.script_utf8), + version: body.expected_version + 1 + }; + revisions.push(next); + return r.fulfill({ json: next }); + }); + await page.goto(origin + '/fixture'); + await page.getByRole('button', { name: script.name, exact: true }).click(); + await page.getByRole('button', { name: 'Neue Version', exact: true }).click(); + await page.getByLabel('Skriptinhalt').fill('uname -r\n'); + await page.getByRole('button', { name: 'Version veröffentlichen' }).click(); + await expect(page.getByRole('status')).toContainText('Version 2 veröffentlicht.'); + await page.getByText('Frühere Versionen (1)').click(); + await page.getByText('Version 1 · Linux · Shell · Agent-Dienstkonto').click(); + await expect(page.locator('pre').filter({ hasText: 'uname -s' })).toBeVisible(); + await page.getByRole('button', { name: 'Zur Skriptbibliothek' }).click(); + await expect(page.getByRole('row').filter({ hasText: script.name })).toHaveCount(1); + await expect(page.getByRole('row').filter({ hasText: script.name })).toContainText('2'); + expect(writes).toHaveLength(1); +}); diff --git a/web/src/order-composer.tsx b/web/src/order-composer.tsx index 9d24d00..968e5d4 100644 --- a/web/src/order-composer.tsx +++ b/web/src/order-composer.tsx @@ -1,18 +1,59 @@ import { useEffect, useRef, useState, type FormEvent } from 'react'; import { allowed, powerShellApprovalBlockers, validateSensitiveInput, verifyPlanIntegrity } from './safety'; -import { ApiError, approvalBlockers, expectedStdout, fullMaintenanceScriptProfile, objectId, page, record, request, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile, type PlanInput, type RecordValue, type Session } from './api'; +import { + ApiError, + approvalBlockers, + expectedStdout, + fullMaintenanceScriptProfile, + objectId, + page, + record, + request, + tenantPath, + validateInput, + windowsPowerShellRemoteSignedProfile, + type PlanInput, + type RecordValue, + type Session +} from './api'; import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan, windowsUpdateScriptHash } from './script-console'; import { ErrorBox, errorText, useResource } from './resource'; -import { devicePlatform, identityNames, interpreterNames, latestRevisions, loadRevisions, scriptPlatform, type Identity, type Interpreter, type Script } from './script-catalog'; +import { + devicePlatform, + identityNames, + interpreterNames, + latestRevisions, + loadRevisions, + scriptPlatform, + type Identity, + type Interpreter, + type Script +} from './script-catalog'; import { ScriptFields } from './script-library'; -type Props = { tenantId: string; customerName?: string; auth: Session; initialAssetIds: string[]; onSubmitted: (operationId: string) => void }; -type Target = { id: string; name: string; os: string; platform: 'linux' | 'windows' | null; state: string; current: boolean }; +type Props = { + tenantId: string; + customerName?: string; + auth: Session; + initialAssetIds: string[]; + onSubmitted: (operationId: string) => void; +}; +type Target = { + id: string; + name: string; + os: string; + platform: 'linux' | 'windows' | null; + state: string; + current: boolean; +}; function target(row: RecordValue): Target { return { - id: objectId(row, 'asset'), name: typeof row.hostname === 'string' && row.hostname ? row.hostname : objectId(row, 'asset'), - os: typeof row.os === 'string' ? row.os : 'OS unbekannt', platform: devicePlatform(row), - state: row.status === 'online' ? 'Online' : 'Offline', current: row.lifecycle === 'current' + id: objectId(row, 'asset'), + name: typeof row.hostname === 'string' && row.hostname ? row.hostname : objectId(row, 'asset'), + os: typeof row.os === 'string' ? row.os : 'OS unbekannt', + platform: devicePlatform(row), + state: row.status === 'online' ? 'Online' : 'Offline', + current: row.lifecycle === 'current' }; } function emptyScript(interpreter: Interpreter): Script { @@ -30,9 +71,12 @@ function resumeTicket(key: string): Ticket | null { const raw = sessionStorage.getItem(key); if (!raw) return null; data = JSON.parse(raw); - } catch { return null; } + } catch { + return null; + } if (!data || !uuid.test(data.id) || !/^[a-f0-9]{64}$/.test(data.hash) || typeof data.attempted !== 'boolean') { - sessionStorage.removeItem(key); return null; + sessionStorage.removeItem(key); + return null; } return data; } @@ -42,18 +86,35 @@ async function verifiedScriptOrder(value: unknown, tenantId: string, principal: await verifyScriptPlan(plan); const payload = record(plan.plan_payload); const jobs = scriptPlanJobs(plan); - if (payload.tenant_id !== tenantId || payload.principal !== principal || !Array.isArray(payload.jobs) || - !jobs.length || jobs.length !== payload.jobs.length) throw Error('Dieser Skriptplan gehört nicht zu diesem Kunden und Antragsteller.'); - return {plan, jobs, reason: String(payload.reason), maxParallel: Number(payload.max_parallel), halt: Number(payload.halt_after_failures)}; + if ( + payload.tenant_id !== tenantId || + payload.principal !== principal || + !Array.isArray(payload.jobs) || + !jobs.length || + jobs.length !== payload.jobs.length + ) + throw Error('Dieser Skriptplan gehört nicht zu diesem Kunden und Antragsteller.'); + return { + plan, + jobs, + reason: String(payload.reason), + maxParallel: Number(payload.max_parallel), + halt: Number(payload.halt_after_failures) + }; } type Review = Awaited>; function blockers(review: Review) { - return [...approvalBlockers(review.plan), ...powerShellApprovalBlockers(review.plan), ...scriptApprovalBlockers(review.plan)]; + return [ + ...approvalBlockers(review.plan), + ...powerShellApprovalBlockers(review.plan), + ...scriptApprovalBlockers(review.plan) + ]; } function issueMessage(err: unknown) { if (err instanceof ApiError) { if (err.status === 403) return 'Für diese Aktion oder die angeforderten Ausführungsrechte fehlt die Berechtigung.'; - if (err.code === 'SCRIPT_VARIANT_UNAVAILABLE' || err.code.includes('CAPABILITY')) return 'Mindestens ein Zielgerät unterstützt die ausgewählte Ausführung noch nicht. ' + err.code; + if (err.code === 'SCRIPT_VARIANT_UNAVAILABLE' || err.code.includes('CAPABILITY')) + return 'Mindestens ein Zielgerät unterstützt die ausgewählte Ausführung noch nicht. ' + err.code; } return errorText(err); } @@ -86,221 +147,675 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu const [error, setError] = useState(null); const lock = useRef(false); const mounted = useRef(true); - useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []); - const canPlan = ['inventory:read','operations:read','operations:plan','scripts:execute','operations:submit'].every(p => allowed(auth, p)); + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + const canPlan = [ + 'inventory:read', + 'operations:read', + 'operations:plan', + 'scripts:execute', + 'operations:submit' + ].every((p) => allowed(auth, p)); - const devices = useResource(async signal => { - if (!canPlan || ticket || step !== 1) return null; - const params = new URLSearchParams({limit:'40',view:'current'}); - if (query.trim()) params.set('q',query.trim()); - if (cursor) params.set('cursor',cursor); - const batch = page(await request(path('/devices?' + params), {signal})); - return {items: batch.items.map(target), next: batch.next_cursor}; - }, [tenantId, canPlan, query, cursor, step, !!ticket]); - const review = useResource(async signal => { - if (!ticket) return null; - const checked = await verifiedScriptOrder(await request(path('/operation-plans/' + ticket.id), {signal}), tenantId, auth.principal.id); - if (checked.plan.plan_hash !== ticket.hash || objectId(checked.plan,'plan') !== ticket.id) throw Error('Der gespeicherte Plan entspricht nicht dem ausgewählten Auftrag.'); - return checked; - }, [tenantId, ticket?.id, ticket?.hash, auth.principal.id]); - const missingIds = (review.data?.jobs.map(job => job.assetId) ?? initialAssetIds).filter(id => !known[id]); - const restored = useResource(async signal => { - if (!canPlan) return []; - const ids = missingIds; - const results: Target[] = []; - for (let i = 0; i < ids.length; i += 8) { - const chunk = await Promise.all(ids.slice(i, i + 8).map(async id => { - try { return target(record(await request(path('/devices/' + encodeURIComponent(id)), {signal}))); } - catch (err) { if (err instanceof ApiError && err.status === 404) return null; throw err; } - })); - for (const item of chunk) if (item) results.push(item); - } - return results; - }, [tenantId, canPlan, missingIds.join('/')]); - const directory = new Map([...restored.data ?? [], ...Object.values(known), ...devices.data?.items ?? []].map(d => [d.id, d])); - const targets = selected.map(id => directory.get(id)); - 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]); - const revision = scripts.data?.find(r => r.revision_id === revisionId); + const devices = useResource( + async (signal) => { + if (!canPlan || ticket || step !== 1) return null; + const params = new URLSearchParams({ limit: '40', view: 'current' }); + if (query.trim()) params.set('q', query.trim()); + if (cursor) params.set('cursor', cursor); + const batch = page(await request(path('/devices?' + params), { signal })); + return { items: batch.items.map(target), next: batch.next_cursor }; + }, + [tenantId, canPlan, query, cursor, step, !!ticket] + ); + const review = useResource( + async (signal) => { + if (!ticket) return null; + const checked = await verifiedScriptOrder( + await request(path('/operation-plans/' + ticket.id), { signal }), + tenantId, + auth.principal.id + ); + if (checked.plan.plan_hash !== ticket.hash || objectId(checked.plan, 'plan') !== ticket.id) + throw Error('Der gespeicherte Plan entspricht nicht dem ausgewählten Auftrag.'); + return checked; + }, + [tenantId, ticket?.id, ticket?.hash, auth.principal.id] + ); + const missingIds = (review.data?.jobs.map((job) => job.assetId) ?? initialAssetIds).filter((id) => !known[id]); + const restored = useResource( + async (signal) => { + if (!canPlan) return []; + const ids = missingIds; + const results: Target[] = []; + for (let i = 0; i < ids.length; i += 8) { + const chunk = await Promise.all( + ids.slice(i, i + 8).map(async (id) => { + try { + return target(record(await request(path('/devices/' + encodeURIComponent(id)), { signal }))); + } catch (err) { + if (err instanceof ApiError && err.status === 404) return null; + throw err; + } + }) + ); + for (const item of chunk) if (item) results.push(item); + } + return results; + }, + [tenantId, canPlan, missingIds.join('/')] + ); + const directory = new Map( + [...(restored.data ?? []), ...Object.values(known), ...(devices.data?.items ?? [])].map((d) => [d.id, d]) + ); + const targets = selected.map((id) => directory.get(id)); + 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] + ); + const revision = scripts.data?.find((r) => r.revision_id === revisionId); const heads = latestRevisions(scripts.data ?? []); const issues: string[] = []; - if (targets.some(d => !d?.current)) issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.'); - const unidentified = targets.filter(d => d && !d.platform); - if (unidentified.length) issues.push('Das Betriebssystem ist noch nicht bestätigt: ' + unidentified.map(d => d?.name).join(', ')); + if (targets.some((d) => !d?.current)) + issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.'); + const unidentified = targets.filter((d) => d && !d.platform); + if (unidentified.length) + issues.push('Das Betriebssystem ist noch nicht bestätigt: ' + unidentified.map((d) => d?.name).join(', ')); if (mode === 'library' && revision) { - const incompatible = targets.filter(d => d?.platform && d.platform !== scriptPlatform(revision.interpreter)); - if (incompatible.length) issues.push(`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map(d => d?.name).join(', ')}.`); + const incompatible = targets.filter((d) => d?.platform && d.platform !== scriptPlatform(revision.interpreter)); + if (incompatible.length) + 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')) issues.push('Die Berechtigung für ' + identityNames[identity] + ' fehlt.'); + if (identity !== 'agent_service' && !allowed(auth, identity + ':execute')) + issues.push('Die Berechtigung für ' + identityNames[identity] + ' fehlt.'); } - if (mode === 'once' && hasLinux && hasWindows && (linux.execution_identity !== 'agent_service' || windows.execution_identity !== 'agent_service')) issues.push('Die ausgewählten Plattformen benötigen unterschiedliche Rechte. Verwenden Sie das gemeinsame Agent-Dienstkonto oder planen Sie getrennte Aufträge.'); + if ( + mode === 'once' && + hasLinux && + hasWindows && + (linux.execution_identity !== 'agent_service' || windows.execution_identity !== 'agent_service') + ) + issues.push( + 'Die ausgewählten Plattformen benötigen unterschiedliche Rechte. Verwenden Sie das gemeinsame Agent-Dienstkonto oder planen Sie getrennte Aufträge.' + ); const existing = review.data?.plan.operation_id; function saveTicket(next: Ticket | null) { if (next) sessionStorage.setItem(key, JSON.stringify(next)); else sessionStorage.removeItem(key); if (mounted.current) setTicket(next); } - function submitted(id: string) { saveTicket(null); if (mounted.current) onSubmitted(id); } - function toggleTarget(d: Target) { - setKnown(old => ({...old,[d.id]:d})); - setSelected(old => old.includes(d.id) ? old.filter(id => id !== d.id) : [...old, d.id]); + function submitted(id: string) { + saveTicket(null); + if (mounted.current) onSubmitted(id); } - 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; + function toggleTarget(d: Target) { + setKnown((old) => ({ ...old, [d.id]: d })); + setSelected((old) => (old.includes(d.id) ? old.filter((id) => id !== d.id) : [...old, d.id])); + } + 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; async function prepare(e: FormEvent) { e.preventDefault(); if (lock.current || !canPlan || issues.length || !selected.length) return; - lock.current = true; setBusy(true); setError(null); + lock.current = true; + setBusy(true); + setError(null); try { - const schedule = {not_before:new Date(start).toISOString(),start_before:new Date(end).toISOString()}; - if (Date.parse(schedule.start_before) <= Math.max(Date.now(),Date.parse(schedule.not_before))) 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()}; + const schedule = { not_before: new Date(start).toISOString(), start_before: new Date(end).toISOString() }; + if (Date.parse(schedule.start_before) <= Math.max(Date.now(), Date.parse(schedule.not_before))) + 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() }; 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} + csrf: auth.csrf_token, + body: { ...bound, schedule, max_runtime_seconds: runtime, max_output_bytes: limit } }); } else { - const variants = [hasLinux ? linux : null, hasWindows ? windows : null].filter((s): s is Script => !!s).map(s => ({ - os_family:scriptPlatform(s.interpreter),interpreter:s.interpreter,encoding:'utf-8',script_utf8:s.script_utf8, - ...(s.interpreter === 'powershell' ? {windows_execution_profile:windowsPowerShellRemoteSignedProfile} : {}) - })); - const parameters = {variants,execution_identity:identity,arguments:[],expected_stdout:expectedStdout(expected,expectedFormat), - timeout_seconds:runtime,max_output_bytes:limit, - ...(identity === 'system' || (identity === 'root' && fullRoot) ? {privileged_script_profile:fullMaintenanceScriptProfile} : {})}; - const input: PlanInput = {...bound,schedule:{...schedule,offline_policy:'wait_until_deadline'},tenant_id:tenantId,action:'run_script',parameters}; - validateInput(input); await validateSensitiveInput(input, auth); - raw = await request(path('/operation-plans'), {csrf:auth.csrf_token,body:input}); + const variants = [hasLinux ? linux : null, hasWindows ? windows : null] + .filter((s): s is Script => !!s) + .map((s) => ({ + os_family: scriptPlatform(s.interpreter), + interpreter: s.interpreter, + encoding: 'utf-8', + script_utf8: s.script_utf8, + ...(s.interpreter === 'powershell' + ? { windows_execution_profile: windowsPowerShellRemoteSignedProfile } + : {}) + })); + const parameters = { + variants, + execution_identity: identity, + arguments: [], + expected_stdout: expectedStdout(expected, expectedFormat), + timeout_seconds: runtime, + max_output_bytes: limit, + ...(identity === 'system' || (identity === 'root' && fullRoot) + ? { privileged_script_profile: fullMaintenanceScriptProfile } + : {}) + }; + const input: PlanInput = { + ...bound, + schedule: { ...schedule, offline_policy: 'wait_until_deadline' }, + tenant_id: tenantId, + action: 'run_script', + parameters + }; + validateInput(input); + await validateSensitiveInput(input, auth); + raw = await request(path('/operation-plans'), { csrf: auth.csrf_token, body: input }); } if (!mounted.current) return; - const checked = await verifiedScriptOrder(raw,tenantId,auth.principal.id); - const mismatchedJob = checked.jobs.some(j => { - const script = mode === 'library' ? revision : (directory.get(j.assetId)?.platform === 'windows' ? windows : linux); - return !selected.includes(j.assetId) || j.revision?.id !== (mode === 'library' ? revisionId : undefined) - || j.script !== script?.script_utf8 || j.identity !== script.execution_identity || j.interpreter !== script.interpreter - || j.runtimeSeconds !== runtime || j.outputBytes !== limit || !!j.arguments.length - || j.expectedStdout !== (mode === 'library' ? null : expectedStdout(expected, expectedFormat)) - || Date.parse(j.notBefore) !== Date.parse(schedule.not_before) || Date.parse(j.startBefore) !== Date.parse(schedule.start_before); + const checked = await verifiedScriptOrder(raw, tenantId, auth.principal.id); + const mismatchedJob = checked.jobs.some((j) => { + const script = + mode === 'library' ? revision : directory.get(j.assetId)?.platform === 'windows' ? windows : linux; + return ( + !selected.includes(j.assetId) || + j.revision?.id !== (mode === 'library' ? revisionId : undefined) || + j.script !== script?.script_utf8 || + j.identity !== script.execution_identity || + j.interpreter !== script.interpreter || + j.runtimeSeconds !== runtime || + j.outputBytes !== limit || + !!j.arguments.length || + j.expectedStdout !== (mode === 'library' ? null : expectedStdout(expected, expectedFormat)) || + Date.parse(j.notBefore) !== Date.parse(schedule.not_before) || + Date.parse(j.startBefore) !== Date.parse(schedule.start_before) + ); }); - if (mismatchedJob || checked.jobs.length !== selected.length || checked.reason !== bound.reason || - checked.maxParallel !== parallel || checked.halt !== halt) throw Error('Der erstellte Plan weicht von diesem Entwurf ab.'); - const problems = blockers(checked); if (problems.length) throw Error(problems.join(' · ')); - if (mounted.current) saveTicket({id:objectId(checked.plan,'plan'),hash:String(checked.plan.plan_hash),attempted:false}); - } catch (e) { if (mounted.current) setError(issueMessage(e)); } - finally { lock.current = false; if (mounted.current) setBusy(false); } + if ( + mismatchedJob || + checked.jobs.length !== selected.length || + checked.reason !== bound.reason || + checked.maxParallel !== parallel || + checked.halt !== halt + ) + throw Error('Der erstellte Plan weicht von diesem Entwurf ab.'); + const problems = blockers(checked); + if (problems.length) throw Error(problems.join(' · ')); + if (mounted.current) + saveTicket({ id: objectId(checked.plan, 'plan'), hash: String(checked.plan.plan_hash), attempted: false }); + } catch (e) { + if (mounted.current) setError(issueMessage(e)); + } finally { + lock.current = false; + if (mounted.current) setBusy(false); + } } async function submit() { if (!ticket || !review.data || !canPlan || lock.current) return; - lock.current = true; setBusy(true); setError(null); + lock.current = true; + setBusy(true); + setError(null); try { - const fresh = await verifiedScriptOrder(await request(path('/operation-plans/' + ticket.id)),tenantId,auth.principal.id); - if (fresh.plan.plan_hash !== ticket.hash || fresh.plan.plan_id !== ticket.id) throw Error('Der geprüfte Auftrag hat sich geändert.'); - if (typeof fresh.plan.operation_id === 'string') { submitted(fresh.plan.operation_id); return; } - const problems = blockers(fresh); if (problems.length) throw Error(problems.join(' · ')); + const fresh = await verifiedScriptOrder( + await request(path('/operation-plans/' + ticket.id)), + tenantId, + auth.principal.id + ); + if (fresh.plan.plan_hash !== ticket.hash || fresh.plan.plan_id !== ticket.id) + throw Error('Der geprüfte Auftrag hat sich geändert.'); + if (typeof fresh.plan.operation_id === 'string') { + submitted(fresh.plan.operation_id); + return; + } + const problems = blockers(fresh); + if (problems.length) throw Error(problems.join(' · ')); if (!mounted.current) return; - saveTicket({...ticket,attempted:true}); - const operation = record(await request(path('/operation-plans/' + ticket.id + '/submit'), { - csrf:auth.csrf_token,body:{idempotency_key:ticket.id} - })); - if (operation.plan_id !== ticket.id || operation.plan_hash !== ticket.hash) throw Error('Die Antwort gehört nicht zum eingereichten Plan.'); - if (mounted.current) submitted(objectId(operation,'operation')); + saveTicket({ ...ticket, attempted: true }); + const operation = record( + await request(path('/operation-plans/' + ticket.id + '/submit'), { + csrf: auth.csrf_token, + body: { idempotency_key: ticket.id } + }) + ); + if (operation.plan_id !== ticket.id || operation.plan_hash !== ticket.hash) + throw Error('Die Antwort gehört nicht zum eingereichten Plan.'); + if (mounted.current) submitted(objectId(operation, 'operation')); } catch (err) { if (mounted.current) { - if (!ticket.attempted && err instanceof ApiError && err.status >= 400 && err.status < 500) saveTicket({...ticket, attempted:false}); - setError(issueMessage(err)); review.reload(); + if (!ticket.attempted && err instanceof ApiError && err.status >= 400 && err.status < 500) + saveTicket({ ...ticket, attempted: false }); + setError(issueMessage(err)); + review.reload(); } + } finally { + lock.current = false; + if (mounted.current) setBusy(false); } - finally {lock.current = false; if (mounted.current) setBusy(false);} } const stepNumber = ticket ? 3 : step; - return <> -

Neuer Auftrag

-
    {['Geräte','Skript','Zusammenfassung'].map((name,i) =>
  1. {i+1}. {name}
  2. )}
- - {!canPlan ?

Zum Erstellen eines Skriptauftrags benötigen Sie Gerätezugriff sowie Rechte zum Planen und Einreichen von Skriptaufträgen.

: - ticket ?

Zusammenfassung

- {review.data ? <> -

{review.data.jobs[0]?.revision ? `${review.data.jobs[0].revision.name} · Version ${review.data.jobs[0].revision.version}` : 'Einmaliges Skript'}

-

{review.data.reason}

-
Kunde
{customerName ?? auth.tenants.find(t => t.tenant_id === tenantId)?.name ?? tenantId}
-
Ausführen als
{identityNames[review.data.jobs[0]!.identity as Identity]}
-
Frühester Start
{new Date(review.data.jobs[0]!.notBefore).toLocaleString('de-DE')}
-
Startfrist
{new Date(review.data.jobs[0]!.startBefore).toLocaleString('de-DE')}
-
Maximale Laufzeit pro Gerät
{review.data.jobs[0]!.runtimeSeconds} Sekunden
-
Parallelität
{review.data.maxParallel} gleichzeitig · Stopp nach {review.data.halt} Fehlern
-
-

Zielgeräte ({review.data.jobs.length})

-
    {review.data.jobs.map(j =>
  • {directory.get(j.assetId)?.name ?? j.assetId}
  • )}
- {review.data.jobs[0]?.identity !== 'agent_service' &&

Dieser Auftrag erfordert erhöhte Rechte auf den Zielgeräten.

} -
Gebundenen Skriptinhalt ansehen - {[...new Map(review.data.jobs.map(job => [job.scriptHash,job])).values()].map(job =>

{interpreterNames[job.interpreter as Interpreter]}

{job.script}
)} -
- {typeof existing === 'string' ?
: - <>
- {(!ticket.attempted || Date.parse(String(review.data.plan.expires_at)) <= Date.now()) && } - -
} - : review.error ?
- {!ticket.attempted && }
:

Gespeicherter Plan wird geprüft …

} -
: - step === 1 ?

Geräte auswählen

- - {!devices.data && !devices.error &&

Geräte werden geladen …

} - {devices.data && <>
    {devices.data.items.map(d =>
  • )}
{!devices.data.items.length &&

{query ? 'Kein Gerät passt zur Suche.' : 'Keine Geräte im Bestand dieses Kunden.'}

} - {(prior.length > 0 || devices.data.next) &&
-
}} - {selected.filter(id => !devices.data?.items.some(d => d.id === id)).map(id =>

{directory.get(id)?.name ?? id}

)} -
{selected.length} ausgewählt
- {selected.length > 100 &&

Ein Auftrag kann bis zu 100 Geräte enthalten.

} - {restored.data && issues.length > 0 && } -
: -

Skript auswählen

-
-
- {mode === 'library' ? <> - - {scripts.data && !heads.length &&

Für diesen Kunden sind noch keine Skripte veröffentlicht.

} - {revision && <>

{interpreterNames[revision.interpreter]} · {identityNames[revision.execution_identity]}

- {revision.execution_identity !== 'agent_service' &&

Das Skript benötigt erhöhte Rechte auf den ausgewählten Geräten.

}} - : <> - {hasLinux && } - {hasWindows && } - {linux.execution_identity === 'root' && hasLinux && } - } - -
Zeitfenster und Ausführungsoptionen
- - - - - - + return ( + <> +
+

Neuer Auftrag

- {mode === 'once' && <>