feat(cra): snapshot/history UI + measure-class (code-fix vs process) UI

Snapshot/history: "Snapshot speichern" + a version list (status, date, coverage)
you can click through — makes the CRA Art. 13 running system visible (backend
endpoints already live). Measure-class: each finding shows a remediation-class
badge from its CRA evidence_type ("Code-nah" = scan-locatable, code-fix in the
ticket possible; otherwise Prozess/Doku), and the measures section is relabelled
as the Sollzustand (process/build) — no auto-fix buttons on process measures.
Backend: MappedFinding now carries evidence_type.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Benjamin Admin
2026-06-14 10:02:17 +02:00
parent 05bd0418f8
commit ee1632cd52
7 changed files with 173 additions and 39 deletions
@@ -34,6 +34,31 @@ function TierBadge({ tier, reason }: { tier?: string; reason?: string }) {
) )
} }
const EVIDENCE_LABEL: Record<string, string> = {
code: 'Code-nah',
hybrid: 'Code + Prozess',
process: 'Prozess',
document: 'Dokumentation',
}
// "Code-nah" = der Scan kann es im Quellcode verorten → Code-Fix im Ticket möglich.
// Sonst = Prozess/Organisation: wir benennen den Sollzustand, kein Auto-Fix.
function EvidenceTag({ et }: { et?: string }) {
if (!et || !EVIDENCE_LABEL[et]) return null
const codeish = et === 'code' || et === 'hybrid'
return (
<span
title={codeish ? 'Code-Fix im Ticket möglich (wenn der Scan die Stelle sieht)' : 'Prozess-/Build-Maßnahme — kein Auto-Fix'}
className={`inline-block rounded px-1.5 py-0.5 text-[10px] font-medium ${
codeish
? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300'}`}
>
{EVIDENCE_LABEL[et]}
</span>
)
}
function FindingsTable({ findings }: { findings: CRAFinding[] }) { function FindingsTable({ findings }: { findings: CRAFinding[] }) {
const [open, setOpen] = useState<Record<string, boolean>>({}) const [open, setOpen] = useState<Record<string, boolean>>({})
const toggle = (id: string) => setOpen((o) => ({ ...o, [id]: !o[id] })) const toggle = (id: string) => setOpen((o) => ({ ...o, [id]: !o[id] }))
@@ -58,6 +83,7 @@ function FindingsTable({ findings }: { findings: CRAFinding[] }) {
<td className="py-2 px-4 max-w-xs"> <td className="py-2 px-4 max-w-xs">
<div className="text-gray-800 dark:text-gray-200">{f.title}</div> <div className="text-gray-800 dark:text-gray-200">{f.title}</div>
<div className="text-[10px] text-gray-400">{f.id} · {f.cwe} · {f.location}</div> <div className="text-[10px] text-gray-400">{f.id} · {f.cwe} · {f.location}</div>
<div className="mt-1"><EvidenceTag et={f.evidence_type} /></div>
</td> </td>
<td className="py-2 px-3 text-gray-600 dark:text-gray-300"> <td className="py-2 px-3 text-gray-600 dark:text-gray-300">
<span className="font-medium">{f.primary_requirement}</span> {f.requirement_title} <span className="font-medium">{f.primary_requirement}</span> {f.requirement_title}
@@ -205,8 +231,12 @@ export function CRACyberView({ data }: { data: CRADemo }) {
{/* Recommended measures — full curated text + norm references */} {/* Recommended measures — full curated text + norm references */}
<div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4"> <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4">
<h2 className="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-1">Empfohlene Maßnahmen</h2> <h2 className="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-1">Empfohlene Maßnahmen (Sollzustand)</h2>
<p className="text-[11px] text-gray-400 mb-3">Kuratierte CRA-Maßnahmen aus der BreakPilot-Bibliothek mit Normverweisen.</p> <p className="text-[11px] text-gray-400 mb-3">
Kuratierte CRA-Maßnahmen mit Normverweisen sie beschreiben den <span className="font-medium">umzubauenden Prozess / das Sollziel</span>,
kein Auto-Fix. Konkrete Code-Fixes entstehen separat, wenn der Repo-Scan ein Source-Code-Risiko an einer
Stelle sieht (Findings mit <span className="text-emerald-600 dark:text-emerald-400">Code-nah"</span>).
</p>
<div className="space-y-3"> <div className="space-y-3">
{data.open_measures.map((me) => ( {data.open_measures.map((me) => (
<div key={me.id} className="rounded-lg border border-gray-100 dark:border-gray-700/60 p-3"> <div key={me.id} className="rounded-lg border border-gray-100 dark:border-gray-700/60 p-3">
@@ -0,0 +1,73 @@
'use client'
import { useState } from 'react'
import { SnapshotMeta } from '../_hooks/useCRA'
export function SnapshotPanel({ snapshots, onSave, onView }: {
snapshots: SnapshotMeta[]
onSave: () => Promise<void>
onView: (id: string) => Promise<any>
}) {
const [saving, setSaving] = useState(false)
const [detail, setDetail] = useState<{ version: number; content_md: string } | null>(null)
const save = async () => {
setSaving(true)
try { await onSave() } finally { setSaving(false) }
}
const view = async (id: string) => {
const d = await onView(id)
if (d) setDetail({ version: d.version, content_md: d.content_md })
}
return (
<div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4">
<div className="flex items-start justify-between gap-3">
<div>
<h2 className="text-sm font-semibold text-gray-800 dark:text-gray-200">Verlauf / Snapshots</h2>
<p className="text-[11px] text-gray-400">
Versionierte CRA-Risikobeurteilung über die Zeit die fortlaufende Dokumentation (CRA Art. 13).
</p>
</div>
<button
onClick={save}
disabled={saving}
className="shrink-0 rounded bg-purple-600 hover:bg-purple-700 disabled:opacity-50 text-white text-xs px-3 py-1.5"
>
{saving ? 'Speichert …' : 'Snapshot speichern'}
</button>
</div>
{snapshots.length === 0 ? (
<p className="text-xs text-gray-500 mt-3">Noch kein Snapshot gespeichert.</p>
) : (
<ul className="mt-3 space-y-1">
{snapshots.map((s) => (
<li key={s.id} className="flex items-center justify-between text-xs border-b border-gray-100 dark:border-gray-700/50 py-1">
<span className="text-gray-600 dark:text-gray-300">
<span className="font-medium">v{s.version}</span>
<span className={`ml-2 rounded px-1.5 py-0.5 text-[10px] ${
s.status === 'draft'
? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'
: 'bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400'}`}>{s.status}</span>
<span className="ml-2 text-gray-400">{new Date(s.generated_at).toLocaleString('de-DE')}</span>
<span className="ml-2 text-gray-400">· {s.coverage?.covered?.length ?? 0}/{s.coverage?.total ?? 40} Anforderungen</span>
</span>
<button onClick={() => view(s.id)} className="text-purple-600 hover:underline">ansehen</button>
</li>
))}
</ul>
)}
{detail && (
<div className="mt-3 rounded-lg border border-gray-200 dark:border-gray-700 p-3 bg-gray-50/60 dark:bg-gray-900/30">
<div className="flex items-center justify-between mb-1">
<span className="text-xs font-medium text-gray-700 dark:text-gray-200">Snapshot v{detail.version}</span>
<button onClick={() => setDetail(null)} className="text-[11px] text-gray-400 hover:underline">schließen</button>
</div>
<pre className="text-[11px] text-gray-600 dark:text-gray-300 whitespace-pre-wrap font-mono">{detail.content_md}</pre>
</div>
)}
</div>
)
}
@@ -1,19 +1,24 @@
'use client' 'use client'
import { useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import { CRADemo, CRAFinding, Measure, DEMO_SCENARIO } from './useCRADemo' import { CRADemo, CRAFinding, Measure, DEMO_SCENARIO } from './useCRADemo'
// Live CRA assessment: POST the (demo) findings + the customer's priority weights // Live CRA assessment: POST the (demo) findings + customer weights + the project's
// to POST /api/v1/cra/assess and merge the live, priority-sorted mapping (CRA // safety functions to /api/v1/cra/assess and merge the live, priority-sorted
// requirement, risk, measures, NIST/OWASP crosswalk, priority tier + reason + // mapping with the frontend scenario constants. Also save/list versioned
// quick-win) with the frontend scenario constants (full measure texts + // snapshots (the CRA Art. 13 running system). Falls back to the static scenario
// cyber->safety cross-links). Falls back to the static scenario if unreachable. // if the backend is unreachable.
export type Weights = Record<string, string> // objective -> high|medium|low export type Weights = Record<string, string> // objective -> high|medium|low
// Demo: CE-risk-assessment safety functions of the Kistenhub (would come from the export interface SnapshotMeta {
// project's CE risk assessment in production). The backend bridge decides which id: string
// cyber findings can defeat them (and flags those safety_impact -> P0). version: number
status: string
generated_at: string
coverage?: { covered?: string[]; total?: number }
}
const SAFETY_FUNCTIONS = [ const SAFETY_FUNCTIONS = [
{ {
name: 'Zweihandschaltung + trennende Schutzeinrichtung am Hubwerk', name: 'Zweihandschaltung + trennende Schutzeinrichtung am Hubwerk',
@@ -38,7 +43,6 @@ function merge(live: any): CRADemo {
const meta: Record<string, CRAFinding> = {} const meta: Record<string, CRAFinding> = {}
for (const f of DEMO_SCENARIO.findings) meta[f.id] = f for (const f of DEMO_SCENARIO.findings) meta[f.id] = f
// iterate live.mapped to PRESERVE the backend priority order
const findings: CRAFinding[] = (live.mapped || []).map((m: any) => { const findings: CRAFinding[] = (live.mapped || []).map((m: any) => {
const base = meta[m.finding_id] const base = meta[m.finding_id]
return { return {
@@ -52,6 +56,7 @@ function merge(live: any): CRADemo {
owasp_refs: m.owasp_refs || [], owasp_refs: m.owasp_refs || [],
risk_level: m.risk_level || (base ? base.risk_level : 'LOW'), risk_level: m.risk_level || (base ? base.risk_level : 'LOW'),
measures: m.measures || [], measures: m.measures || [],
evidence_type: m.evidence_type,
priority_tier: m.priority_tier, priority_tier: m.priority_tier,
priority_score: m.priority_score, priority_score: m.priority_score,
quick_win: m.quick_win, quick_win: m.quick_win,
@@ -79,43 +84,56 @@ function merge(live: any): CRADemo {
} }
} }
export function useCRA() { export function useCRA(projectId?: string) {
const [data, setData] = useState<CRADemo | null>(null) const [data, setData] = useState<CRADemo | null>(null)
const [live, setLive] = useState(false) const [live, setLive] = useState(false)
const [weights, setWeights] = useState<Weights>({}) const [weights, setWeights] = useState<Weights>({})
const [snapshots, setSnapshots] = useState<SnapshotMeta[]>([])
const buildPayload = useCallback(() => ({
findings: DEMO_SCENARIO.findings.map((f) => ({
id: f.id, title: f.title, cwe: f.cwe, severity: f.scanner_severity, location: f.location,
})),
weights,
safety_functions: SAFETY_FUNCTIONS,
}), [weights])
useEffect(() => { useEffect(() => {
let cancelled = false let cancelled = false
const payload = {
findings: DEMO_SCENARIO.findings.map((f) => ({
id: f.id, title: f.title, cwe: f.cwe, severity: f.scanner_severity, location: f.location,
})),
weights,
// the bridge decides safety_impact from these (no frontend hardcode)
safety_functions: SAFETY_FUNCTIONS,
}
fetch('/api/v1/cra/assess', { fetch('/api/v1/cra/assess', {
method: 'POST', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(buildPayload()),
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
}) })
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))) .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
.then((j) => { .then((j) => { if (!cancelled) { setData(merge(j)); setLive(true) } })
if (cancelled) return
setData(merge(j))
setLive(true)
})
.catch((err) => { .catch((err) => {
console.error('CRA assess fetch failed, using static scenario:', err) console.error('CRA assess fetch failed, using static scenario:', err)
if (!cancelled) { if (!cancelled) { setData(DEMO_SCENARIO); setLive(false) }
setData(DEMO_SCENARIO)
setLive(false)
}
}) })
return () => { return () => { cancelled = true }
cancelled = true }, [buildPayload])
}
}, [weights])
return { data, live, weights, setWeights } const refreshSnapshots = useCallback(() => {
if (!projectId) return
fetch(`/api/v1/cra/projects/${projectId}/assess-snapshots`)
.then((r) => (r.ok ? r.json() : null))
.then((j) => { if (j) setSnapshots(j.snapshots || []) })
.catch(() => {})
}, [projectId])
useEffect(() => { refreshSnapshots() }, [refreshSnapshots])
const saveSnapshot = useCallback(async () => {
if (!projectId) return
await fetch(`/api/v1/cra/projects/${projectId}/assess-snapshot`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(buildPayload()),
})
refreshSnapshots()
}, [projectId, buildPayload, refreshSnapshots])
const viewSnapshot = useCallback(async (id: string) => {
const r = await fetch(`/api/v1/cra/assess-snapshots/${id}`)
return r.ok ? r.json() : null
}, [])
return { data, live, weights, setWeights, snapshots, saveSnapshot, viewSnapshot }
} }
@@ -27,6 +27,7 @@ export interface CRAFinding {
owasp_refs: OwaspRef[] owasp_refs: OwaspRef[]
risk_level: string risk_level: string
measures: string[] measures: string[]
evidence_type?: string // code | process | hybrid | document — drives the remediation-class badge
// priority layer (set live by the backend prioritizer; optional in the static fallback) // priority layer (set live by the backend prioritizer; optional in the static fallback)
priority_tier?: string priority_tier?: string
priority_score?: number priority_score?: number
@@ -1,11 +1,15 @@
'use client' 'use client'
import { useParams } from 'next/navigation'
import { useCRA } from './_hooks/useCRA' import { useCRA } from './_hooks/useCRA'
import { CRACyberView } from './_components/CRACyberView' import { CRACyberView } from './_components/CRACyberView'
import { WeightsControl } from './_components/WeightsControl' import { WeightsControl } from './_components/WeightsControl'
import { SnapshotPanel } from './_components/SnapshotPanel'
export default function CRAPage() { export default function CRAPage() {
const { data, live, weights, setWeights } = useCRA() const params = useParams()
const projectId = params?.projectId as string | undefined
const { data, live, weights, setWeights, snapshots, saveSnapshot, viewSnapshot } = useCRA(projectId)
if (!data) { if (!data) {
return <p className="text-sm text-gray-500">CRA-Risikobeurteilung wird geladen </p> return <p className="text-sm text-gray-500">CRA-Risikobeurteilung wird geladen </p>
} }
@@ -18,6 +22,7 @@ export default function CRAPage() {
)} )}
<WeightsControl weights={weights} onChange={setWeights} /> <WeightsControl weights={weights} onChange={setWeights} />
<CRACyberView data={data} /> <CRACyberView data={data} />
<SnapshotPanel snapshots={snapshots} onSave={saveSnapshot} onView={viewSnapshot} />
</div> </div>
) )
} }
@@ -94,6 +94,7 @@ class MappedFinding:
primary_requirement: str = "" primary_requirement: str = ""
annex_anchor: str = "" annex_anchor: str = ""
iso27001_ref: list = field(default_factory=list) iso27001_ref: list = field(default_factory=list)
evidence_type: str = "" # code | process | hybrid | document (from the requirement)
risk_level: str = "LOW" risk_level: str = "LOW"
measures: list = field(default_factory=list) measures: list = field(default_factory=list)
nist_refs: list = field(default_factory=list) # NIST 800-53 control IDs (golden-set crosswalk) nist_refs: list = field(default_factory=list) # NIST 800-53 control IDs (golden-set crosswalk)
@@ -189,6 +190,7 @@ def map_finding(f: ScannerFinding) -> MappedFinding:
primary_requirement=primary["req_id"], primary_requirement=primary["req_id"],
annex_anchor=primary.get("annex_anchor", ""), annex_anchor=primary.get("annex_anchor", ""),
iso27001_ref=list(primary.get("iso27001_ref", [])), iso27001_ref=list(primary.get("iso27001_ref", [])),
evidence_type=primary.get("evidence_type", ""),
risk_level=_SEV_BY_RANK.get(risk_rank, "LOW"), risk_level=_SEV_BY_RANK.get(risk_rank, "LOW"),
measures=measures, measures=measures,
nist_refs=refs["nist"], nist_refs=refs["nist"],
@@ -14,6 +14,11 @@ def test_hardcoded_credentials_cwe_maps_to_credential_requirement():
assert m.annex_anchor # spine carries the Annex anchor assert m.annex_anchor # spine carries the Annex anchor
def test_mapped_finding_carries_evidence_type():
m = map_finding(ScannerFinding(id="e", title="default password", cwe="CWE-259", severity="high"))
assert m.evidence_type == "code" # CRA-AI-8 is code-checkable
def test_default_password_is_critical_and_carries_measure_M542(): def test_default_password_is_critical_and_carries_measure_M542():
m = map_finding(ScannerFinding(id="f2", title="Universal default password", cwe="CWE-259", severity="critical")) m = map_finding(ScannerFinding(id="f2", title="Universal default password", cwe="CWE-259", severity="critical"))
assert m.primary_requirement == "CRA-AI-8" assert m.primary_requirement == "CRA-AI-8"