diff --git a/crates/domain/src/windows_sync_history_case.json b/crates/domain/src/windows_sync_history_case.json new file mode 100644 index 0000000..cbe7d35 --- /dev/null +++ b/crates/domain/src/windows_sync_history_case.json @@ -0,0 +1,43 @@ +{ + "schema_version": 1, + "tenant_id": "11111111-1111-4111-8111-111111111111", + "asset_id": "a176520e-8a91-4e93-a78b-8e7620f430e0", + "agent_id": "63ea15b2-0643-403d-b5b4-cba1288dbea3", + "boot_id": "a9ad0895-5a96-8f2c-8fb6-cfdc2d5225ea", + "enrollment_generation": 1, + "assignment_version": 1, + "connection_generation": 150, + "agent_journal_id": "3dd1dfb5-d586-472a-af28-7fd4d203e90b", + "helper_journal_id": "cb4db2c6-a1b2-4fb3-be9d-1f677de0de2b", + "helper_checkpoint": 1, + "server_head_checkpoint": 6755, + "server_head_decision_id": "b6a3101f-68ad-41c8-be4e-4c7c2bc963d6", + "local_head_checkpoint": 6756, + "local_head_decision_id": "0633a4de-7e52-4e5d-a2a1-59fb134817fe", + "local_helper_decisions": 1, + "server_evidence_sha256": "7ad17c48c74638a015bb62caae16365c6ff44a70f3b1a5a7357b28de7686b3da", + "guest_evidence_sha256": "045adc0363ae91d1aea6dae33940a8df9b45c9090089bf8e5cfb37f9d868151e", + "verification_key_id": "4338aabe7e7ba77428e969750a7a5323d7b7349aa52ef7e1a5f24c90be12ca7a", + "server_observed_at": "2026-11-15T21:35:08.783221+00:00", + "guest_observed_date": "2026-11-15", + "decisions": [ + { + "checkpoint": 6755, + "request_id": "1418b4a3-8370-404d-b29a-920ba9f0f4d7", + "request_sha256": "4c900751a105bd580d48444d6f971374c29fd03bc58ec7fb9db0d165203aaae1", + "decision_id": "b6a3101f-68ad-41c8-be4e-4c7c2bc963d6", + "payload_sha256": "5806d49eed772c4f460ddb97388e8a51ec19df705ac2a55e54114a382aef62f3", + "signature_sha256": "f6cbfee524e287e59130220f33a4e6f3469ee1a817e69235560e7a53f4cc6d6e", + "reason": "CONSISTENT" + }, + { + "checkpoint": 6756, + "request_id": "9eba037c-825f-4a96-be14-cca130c1e83d", + "request_sha256": "b5b7b4508a627a7a10c88c9908792c401d4573d55ba16d3d7b1fa6b18739b3d1", + "decision_id": "0633a4de-7e52-4e5d-a2a1-59fb134817fe", + "payload_sha256": "c6ad2a8016a2b2997f934ad5e2daabc1d585b45d07b94d7d4ed146a10ed303f3", + "signature_sha256": "96caf5401915ca4f8f28ee21ecb8dbfdc3d705c3b89bd40160ff15dbb75a2d08", + "reason": "HELPER_CHECKPOINT_REQUIRED" + } + ] +} diff --git a/docs/windows-profile-acceptance.md b/docs/windows-profile-acceptance.md index 73102fa..b7d9e1d 100644 --- a/docs/windows-profile-acceptance.md +++ b/docs/windows-profile-acceptance.md @@ -414,3 +414,22 @@ Um 21:39:57 UTC bestätigte der Server weiterhin die passive Verbindung 151, dieselbe Boot-ID und die aktive Wiederherstellungssperre. Der Fall ist diagnostisch bestätigt. Die Installation ist für Jobs weiterhin gesperrt und es liegt keine PowerShell-Abnahme vor. + +### Administrativer WebUI-Wiederherstellungsweg in Entwicklung + +Die neue WebUI zeigt für die bestehende Windows-Testinstallation den festen +Historienbeleg mit Serverhead 6755 und lokalem Ablehnungshead 6756. Vor der +Bestätigung prüft sie den kanonischen SHA-256 des gespeicherten Belegs. +Die administrative Bestätigung verlangt eine persönliche OIDC-Sitzung und +die eigene Berechtigung `recovery:confirm`. Sie erzeugt eine befristete +Quittung zur unabhängigen Prüfung auf dem Gast. Das ist eine zusätzliche +menschliche Bediengrenze des neuen Wiederherstellungswegs. Die bisherige +simulierte Jobabnahme bestätigt diese Recovery nicht. + +Typecheck, Produktionsbuild und alle 59 Webtests bestanden lokal. Die vier +gezielten Recovery-Verträge prüften feste Belegbindung, manipulierte Daten, +Sitzungs-/Rechtegrenzen und vollständig gespeicherte Bestätigungsdaten. +Die WebUI ist noch nicht auf dem permanenten Server veröffentlicht. +Die aktuelle Liveauskunft `/auth/config` lieferte HTTP 200 mit +`oidc_configured=false` und `dev_login_enabled=true`. Die Angaben zum +tatsächlichen Identitätsanbieter sind beim Betreiber angefragt. diff --git a/web/src/api.ts b/web/src/api.ts index dfc4a66..c58e70f 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -55,6 +55,11 @@ export async function request(path: string, options: { body?: unknown; csrf?: st } export const tenantPath = (id: string, suffix = '') => `/api/v1/tenants/${encodeURIComponent(id)}${suffix}`; export const objectId = (r: RecordValue, kind: string) => text(r[`${kind}_id`] ?? r.id, `${kind}_id`); +export function canonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; + if (value && typeof value === 'object') return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`; + return JSON.stringify(value); +} 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', 'update_agent'] as const; diff --git a/web/src/main.tsx b/web/src/main.tsx index e3b4144..7046194 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -5,6 +5,7 @@ import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout import './style.css'; import { AdminControl, Catalog, TenantControls } from './management'; import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest, fullMaintenanceWarning } from './safety'; +import { RecoveryReview, recoveryAsset, recoveryTenant } from './recovery-review'; import { Login } from './login'; import { ConsoleOutput, outputText } from './console-output'; import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console'; @@ -99,6 +100,8 @@ function Devices({ tenantId, auth, selected, setSelected }: { tenantId: string; {!list.data ?

Lade Geräte …

: <>
{list.data.items.map(d => { const id = objectId(d, 'asset'); return ; })}
Fest auswählenGerät / Asset-IDPräsenz / GesundheitQuelle / QualitätErhebung / Alter / Empfang
setSelected(e.target.checked ? [...selected, id] : selected.filter(v => v !== id))}/>{id}{stringField(d, 'presence')} / {stringField(d, 'health')}Kontakt: {stringField(d, 'last_contact_at')}{stringField(d, 'source_id')} / {stringField(d, 'quality')}{stringField(d, 'completeness')}{stringField(d, 'observed_at')}Alter: · empfangen: {stringField(d, 'received_at')}
{!list.data.items.length &&

Keine sichtbaren Geräte in diesem Listenabschnitt.

} }

Fester Auswahlsnapshot ({selected.length}): {selected.join(', ') || 'keine Ziele'}

{asset &&

Inventardetail {asset}

{detail.data && <>}
} + {tenantId === recoveryTenant && asset === recoveryAsset && allowed(auth, 'inventory:read') && + } ; } const initialParameters: Record = { diff --git a/web/src/recovery-review.test.ts b/web/src/recovery-review.test.ts new file mode 100644 index 0000000..1c7b2a9 --- /dev/null +++ b/web/src/recovery-review.test.ts @@ -0,0 +1,49 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import { canonicalJson, type Session } from './api'; +import { mayConfirmRecovery, readReview, recoveryAsset, recoveryTenant } from './recovery-review'; +import { sha256 } from './safety'; + +const witness = JSON.parse(readFileSync(new URL('../../crates/domain/src/windows_sync_history_case.json', import.meta.url), 'utf8')); +const human = 'oidc:' + 'a'.repeat(64); +const row = { + request_id: '06e55f7a-0263-4def-b7c3-7d28b1202a51', + status: 'pending_review', tenant_id: recoveryTenant, asset_id: recoveryAsset, agent_id: witness.agent_id, + witness, witness_sha256: 'f29b5afadaf2debab9610282725c2493cb7405784640a4616e1998c304309cab', + confirmed_by: null, confirmed_at: null, receipt_id: null, receipt_valid_until: null, +}; + +describe('Historische Windows-Journalprüfung', () => { + it('liest beide bestätigten Journalstände mit dem kanonischen SHA-256 der gemeinsamen Domainreferenz', async () => { + const review = await readReview({ request: row }); + expect(review?.witness.server_head_checkpoint).toBe(6755); + expect(review?.witness.local_head_checkpoint).toBe(6756); + expect(review?.confirmed).toBeNull(); + }); + + it('verweigert einen geänderten Beleg auch mit passendem neu berechnetem Hash', async () => { + const changed = { ...witness, guest_evidence_sha256: '0'.repeat(64) }; + await expect(readReview({ request: { ...row, witness: changed } })).rejects.toThrow(); + const digest = await sha256(new TextEncoder().encode(canonicalJson(changed))); + await expect(readReview({ request: { ...row, witness: changed, witness_sha256: digest } })).rejects.toThrow(); + await expect(readReview({ request: { ...row, tenant_id: row.request_id } })).rejects.toThrow(); + }); + + it('benötigt eine persönliche OIDC-Sitzung, Tenantmitgliedschaft, CSRF und das unabhängige Recht', () => { + const auth: Session = { principal: { id: human, display_name: 'Operator', simulated: false }, + tenants: [{ tenant_id: recoveryTenant, name: 'Test' }], csrf_token: 'csrf', permissions: ['recovery:confirm'] }; + expect(mayConfirmRecovery(auth)).toBe(true); + for (const changed of [ + { ...auth, principal: { ...auth.principal, simulated: true } }, + { ...auth, principal: { ...auth.principal, id: 'simulated-testprincipal-a' } }, + { ...auth, permissions: ['operations:authorize'] }, { ...auth, tenants: [] }, { ...auth, csrf_token: '' }, + ]) expect(mayConfirmRecovery(changed)).toBe(false); + }); + + it('zeigt eine Quittung erst beim vollständigen bestätigten Antrag', async () => { + await expect(readReview({ request: { ...row, status: 'confirmed' } })).rejects.toThrow(); + const receipt = { status: 'confirmed', confirmed_by: human, confirmed_at: '2026-11-15T22:30:00Z', + receipt_id: 'b09b4e2e-c378-4837-81b1-cae9a8af38e9', receipt_valid_until: '2026-11-15T22:45:00Z' }; + expect((await readReview({ request: { ...row, ...receipt } }))?.confirmed?.receipt).toBe(receipt.receipt_id); + }); +}); diff --git a/web/src/recovery-review.tsx b/web/src/recovery-review.tsx new file mode 100644 index 0000000..20455da --- /dev/null +++ b/web/src/recovery-review.tsx @@ -0,0 +1,131 @@ +import React, { useEffect, useRef, useState } from 'react'; +import { canonicalJson, pretty, record, RecordValue, request, Session, tenantPath } from './api'; +import { allowed, sha256 } from './safety'; + +export const recoveryTenant = '11111111-1111-4111-8111-111111111111'; +export const recoveryAsset = 'a176520e-8a91-4e93-a78b-8e7620f430e0'; +const agent = '63ea15b2-0643-403d-b5b4-cba1288dbea3'; +// Canonical SHA-256 of the single historical case in rmm_domain::windows_sync_history. +const historicalWitnessHash = 'f29b5afadaf2debab9610282725c2493cb7405784640a4616e1998c304309cab'; +const path = tenantPath(recoveryTenant, '/windows-checkpoint-recovery'); +const humanOidc = /^oidc:[0-9a-f]{64}$/; +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + +interface Review { + id: string; + hash: string; + witness: RecordValue; + confirmed: { by: string; at: string; receipt: string; until: string } | null; +} + +export async function readReview(value: unknown): Promise { + const row = record(value).request; + if (row === null) return null; + const r = record(row), w = record(r.witness, 'Wiederherstellungsbeleg'); + const id = r.request_id, hash = r.witness_sha256; + if (typeof id !== 'string' || !uuid.test(id) || typeof hash !== 'string' || hash !== historicalWitnessHash || + r.tenant_id !== recoveryTenant || w.tenant_id !== r.tenant_id || r.asset_id !== recoveryAsset || + w.asset_id !== r.asset_id || r.agent_id !== agent || w.agent_id !== agent || + w.schema_version !== 1 || w.connection_generation !== 150 || + w.server_head_checkpoint !== 6755 || w.local_head_checkpoint !== 6756 || + w.server_head_decision_id !== 'b6a3101f-68ad-41c8-be4e-4c7c2bc963d6' || + w.local_head_decision_id !== '0633a4de-7e52-4e5d-a2a1-59fb134817fe' || + await sha256(new TextEncoder().encode(canonicalJson(w))) !== hash) { + throw new Error('Gerätebindung, Journalstände oder SHA-256 des gespeicherten Belegs stimmen nicht überein.'); + } + if (r.status === 'pending_review' && r.confirmed_by === null && r.confirmed_at === null && + r.receipt_id === null && r.receipt_valid_until === null) return { id, hash, witness: w, confirmed: null }; + if (r.status !== 'confirmed' || typeof r.confirmed_by !== 'string' || !humanOidc.test(r.confirmed_by) || + typeof r.confirmed_at !== 'string' || !Number.isFinite(Date.parse(r.confirmed_at)) || + typeof r.receipt_id !== 'string' || !uuid.test(r.receipt_id) || + typeof r.receipt_valid_until !== 'string' || !Number.isFinite(Date.parse(r.receipt_valid_until)) || + Date.parse(r.receipt_valid_until) <= Date.parse(r.confirmed_at)) { + throw new Error('Unvollständiger Bestätigungsstand.'); + } + return { id, hash, witness: w, confirmed: { by: r.confirmed_by, at: r.confirmed_at, + receipt: r.receipt_id, until: r.receipt_valid_until } }; +} + +export function mayConfirmRecovery(auth: Session): boolean { + return auth.principal.simulated === false && humanOidc.test(auth.principal.id) && + auth.tenants.some(t => t.tenant_id === recoveryTenant) && !!auth.csrf_token && allowed(auth, 'recovery:confirm'); +} + +export function RecoveryReview({ auth }: { auth: Session }) { + const [row, setRow] = useState(undefined); + const [error, setError] = useState(''), [busy, setBusy] = useState(false); + const [reviewed, setReviewed] = useState(false), [revision, setRevision] = useState(0); + const activeSubmit = useRef(null); + const [elapsedReceipt, setElapsedReceipt] = useState(''); + useEffect(() => () => activeSubmit.current?.abort(), []); + useEffect(() => { + const controller = new AbortController(); + setRow(undefined); setReviewed(false); setError(''); + request(path, { signal: controller.signal }).then(readReview).then(response => { + if (!controller.signal.aborted) setRow(response); + }).catch(e => { if (!controller.signal.aborted) setError(String(e)); }); + return () => controller.abort(); + }, [revision]); + + const eligible = mayConfirmRecovery(auth); + const confirmed = row?.confirmed; + const expired = !!confirmed && (confirmed.receipt === elapsedReceipt || Date.parse(confirmed.until) <= Date.now()); + useEffect(() => { + if (!confirmed) return; + const timer = window.setTimeout(() => { + setElapsedReceipt(confirmed.receipt); + setReviewed(false); + }, Math.max(0, Date.parse(confirmed.until) - Date.now())); + return () => window.clearTimeout(timer); + }, [confirmed]); + async function submit() { + if (activeSubmit.current || row === undefined) return; + if (row && (!eligible || !reviewed || (row.confirmed && !expired))) return; + if (!row && !allowed(auth, 'operations:submit')) return; + const controller = new AbortController(); + activeSubmit.current = controller; + setBusy(true); setReviewed(false); setError(''); + try { + const url = row ? path + '/' + row.id + '/confirm' : path; + const body = row ? { witness_sha256: row.hash, reviewed: true, + ...(row.confirmed ? { previous_receipt_id: row.confirmed.receipt } : {}) } : {}; + const reply = await readReview(await request(url, { body, csrf: auth.csrf_token, signal: controller.signal })); + if (!reply || (row && (reply.id !== row.id || reply.hash !== row.hash || !reply.confirmed))) { + throw new Error('Antwort passt nicht zum geprüften Antrag. Bitte den gespeicherten Stand abrufen.'); + } + if (!controller.signal.aborted) setRow(reply); + } catch (e) { + if (!controller.signal.aborted) { setRow(undefined); setError(String(e)); } + } finally { + activeSubmit.current = null; + if (!controller.signal.aborted) setBusy(false); + } + } + return
+

Windows-Journalwiederherstellung

+ {error &&

{error}

} + {row === undefined && !error &&

Prüfantrag wird geladen …

} + {row === null &&

Für diese Testinstallation liegt noch kein Prüfantrag vor.

} + {row === null && allowed(auth, 'operations:submit') && + } + {row && <> +

Antrag {row.id} · Windows-Verbindung {String(row.witness.connection_generation)}

+

Gültiger historischer Serverstand {String(row.witness.server_head_checkpoint)}. + Agent und Helper haben die signierte Ablehnung {String(row.witness.local_head_checkpoint)} gespeichert.

+

Beleg-SHA-256 {row.hash}

+
Öffentliche Server- und Gastbelege
{pretty(row.witness)}
+ {confirmed &&

Bestätigt durch {confirmed.by} am {confirmed.at}. Quittung gültig bis {confirmed.until}.

} + {eligible && confirmed && !expired && + Signierte Quittung herunterladen} + {(!confirmed || expired) && (eligible ? <> +

{confirmed ? 'Die erneute Prüfung stellt eine neue befristete Quittung aus.' : + 'Mit der Bestätigung übernimmt der Server die bereits signierte Ablehnung 6756 als Kontrollstand und stellt eine befristete Quittung für den Gast aus.'} + {' '}Vor einem späteren Job sind der reguläre signierte Abgleich und die gesonderte Plangenehmigung erforderlich.

+ + + :

Die Bestätigung erfordert eine persönliche OIDC-Sitzung mit der Berechtigung recovery:confirm.

)} + } + +
; +} diff --git a/web/src/script-console.ts b/web/src/script-console.ts index 80f3341..237bb86 100644 --- a/web/src/script-console.ts +++ b/web/src/script-console.ts @@ -1,4 +1,4 @@ -import { record, RecordValue, text, windowsScriptProfile, privilegedScriptProfile, fullMaintenanceScriptProfile, validateScriptIdentityProfile } from './api'; +import { canonicalJson, record, RecordValue, text, windowsScriptProfile, privilegedScriptProfile, fullMaintenanceScriptProfile, validateScriptIdentityProfile } from './api'; import { bytes, hashPattern, parseStrictJson, sha256 } from './safety'; export interface ScriptPlanJob { @@ -10,13 +10,9 @@ export interface ScriptPlanJob { } interface Verified { snapshot: string; jobs: ScriptPlanJob[] } const verified = new WeakMap(); -function canonical(value: unknown): string { - if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`; - if (value && typeof value === 'object') return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`; - return JSON.stringify(value); -} + function snapshot(plan: RecordValue): string { - return canonical(Object.fromEntries(['plan_hash', 'plan_payload_bytes', 'plan_payload', 'payload', 'jobs', 'payloads', 'resolved_targets', 'plan_id', 'expires_at'].filter(key => key in plan).map(key => [key, plan[key]]))); + return canonicalJson(Object.fromEntries(['plan_hash', 'plan_payload_bytes', 'plan_payload', 'payload', 'jobs', 'payloads', 'resolved_targets', 'plan_id', 'expires_at'].filter(key => key in plan).map(key => [key, plan[key]]))); } function exact(value: RecordValue, fields: string[]) { if (Object.keys(value).some(key => !fields.includes(key)) || fields.some(key => !Object.hasOwn(value, key))) throw new Error('Skriptplan: vollständige bekannte Schemafelder erforderlich'); @@ -33,7 +29,7 @@ function integer(value: unknown, min: number, max: number): number { function digest(value: unknown): string { const hash = text(value, 'SHA256'); if (!hashPattern.test(hash)) throw new Error('Skriptplan: exakter SHA256 fehlt'); return hash; } function isScript(value: unknown): boolean { return value !== null && typeof value === 'object' && record(value).action === 'run_script'; } function validateViews(plan: RecordValue, parsed: RecordValue, jobs: RecordValue[]): void { - for (const alias of ['plan_payload', 'payload']) if (plan[alias] !== undefined && canonical(plan[alias]) !== canonical(parsed)) throw new Error('Skriptplanansicht widerspricht gespeicherten Bytes'); + for (const alias of ['plan_payload', 'payload']) if (plan[alias] !== undefined && canonicalJson(plan[alias]) !== canonicalJson(parsed)) throw new Error('Skriptplanansicht widerspricht gespeicherten Bytes'); if (plan.plan_id !== undefined && plan.plan_id !== parsed.plan_id) throw new Error('Skript-Plan-ID widerspricht gespeicherten Bytes'); for (const alias of ['jobs', 'payloads', 'resolved_targets']) { if (plan[alias] === undefined) continue; @@ -46,7 +42,7 @@ function validateViews(plan: RecordValue, parsed: RecordValue, jobs: RecordValue const p = record(fixed.payload); if (payload) { if (Object.keys(view).some(key => !['payload', 'job_payload_hash', 'script_sha256', 'asset_id', 'agent_id', 'job_id', 'attempt_id'].includes(key)) - || canonical(payload) !== canonical(p) || view.job_payload_hash !== fixed.job_payload_hash + || canonicalJson(payload) !== canonicalJson(p) || view.job_payload_hash !== fixed.job_payload_hash || (view.script_sha256 !== undefined && view.script_sha256 !== fixed.script_sha256) || ['agent_id', 'job_id', 'attempt_id'].some(key => view[key] !== undefined && view[key] !== p[key])) throw new Error('Skript-Zielpreview widerspricht gespeicherten Bytes'); } else if (alias !== 'resolved_targets' || (typeof item !== 'string' && (Object.keys(view).some(key => !['asset_id', 'agent_id'].includes(key)) || view.agent_id !== p.agent_id))) throw new Error('Vollständiger Skript-Zielpayload fehlt');