Files
sencho/frontend/src/components/stack/RollbackReadinessSection.tsx
T
Anso f5178889eb feat(recovery): complete authored-project atomic rollback generations (#1819)
* feat(recovery): capture complete authored Compose project for atomic rollback

Replace the root-compose-only backup slot with staged recovery generations that
record the managed inventory, exact Compose invocation, and prior image identity,
and wire the same engine through deploy, update, manual rollback, and Git apply.

* fix(recovery): satisfy CodeQL path barriers and update-guard mock

Inline resolve+startsWith checks at generation/inventory fs sinks and stub getCurrentStackUpdateRecovery in UpdateGuardService tests.

* fix(recovery): drop unused FileSystemService import in generation store test

* fix(recovery): harden authored-project rollback for upgrade and restore safety

Preserve legacy UUID backup rows, restore Git deploy state with files, make multi-file restore recoverable, evaluate policy on the restored target, and fail closed when Git capture cannot cover an apply.

* fix(recovery): unblock Git apply unit tests and CodeQL pre-restore TOCTOU

Mock recovery capture in git-source-service tests after fail-closed apply capture, and re-resolve live paths immediately before pre-restore snapshot reads.

* fix(recovery): fall back to authored inventory when Git manifesto is missing

First Git apply captures before promote, so a missing managed-project manifesto must not block rollback capture when the live stack already has authored files.

* fix(recovery): make authored-project rollback atomic across Git state

Restore the managed-project manifesto with files, keep nullable Git identity on first-apply captures, persist Git side-state in restore intents for startup reconcile, compensate legacy materialize failures, and refuse directory collisions before mutation.

* fix(recovery): satisfy CodeQL path and TOCTOU barriers on manifesto restore

Add inline resolve barriers for manifesto read/clear sinks and remove the access-then-read race when restoring a generation manifesto snapshot.

* fix(recovery): close third-audit rollback generation blockers

Fail closed on incomplete Git inventory fallbacks, execute captured Compose
invocation during recovery, refuse startup and mutations while restore intents
remain unresolved, propagate legacy stale-delete failures, and add Docker-level
exact prior-image coverage plus regression tests.

* fix(recovery): mark acquired before handoff in prior-image Docker test

Match the production updateStack CAS sequence so the exact prior-image
integration test does not fail handoff from the captured phase.

* fix(recovery): close fourth-audit rollback safety blockers

Evaluate policy against held images, use index-based pre-restore snapshots, hold the shared stack lock across Git apply, replay Mesh and empty captured invocations exactly, restore POSIX modes with fail-closed sensitive permissions, keep case-sensitive paths, and link Git auto-deploy health gates. Add regression coverage for these cases.

* test(recovery): fix mocks for health-gate link and authored compose args

Add linkGateOrRetain to the Git apply recovery mock, and mock authoredComposeArgs so the case-collision inventory test is not masked by a missing getComposeDir stub.

* fix(recovery): close fifth-audit rollback safety blockers

Share git_apply locking for webhook auto-apply, fail closed on malformed recovery service records, refuse mixed-image capture, and require exact probe counts with hold-tag eligibility checks.

* fix(recovery): close sixth-audit rollback safety blockers

Preserve the legacy backup slot during generation capture, encrypt sensitive pre-restore snapshots, revert files on a failed health probe without committing Git, fail closed when an absent-file revert would delete a directory, skip Compose one-offs, route manual and scheduled backup through the current generation, and persist runtime image platform identity.

* fix(recovery): close seventh-audit rollback safety blockers

Fleet snapshot restore and restore-all now capture a recovery generation under the stack lock before any authored file write, including on remote nodes.

* fix(recovery): keep pre-deploy generations during health-gate observe

Link deploy recovery generations to the observing gate so backup cannot replace them mid-observe. Distinguish missing hold tags from probe failures, refuse generation release when services metadata is corrupt, classify mixed-replica and coverage refusals, and toast the backend rollback message.

* fix(recovery): wrap webhook deploy case for eslint

const bindings in an unbraced switch case trip no-case-declarations. Match the pull case block.
2026-08-13 03:48:09 -04:00

117 lines
4.5 KiB
TypeScript

import { useEffect, useState } from 'react';
import { AlertTriangle, Ban, Check, CircleHelp, Database, X, type LucideIcon } from 'lucide-react';
import { apiFetch } from '@/lib/api';
import { cn } from '@/lib/utils';
import { useNodes } from '@/context/NodeContext';
// Mirrors the backend payload shape (the frontend never imports backend).
type RollbackItemState = 'ready' | 'missing' | 'unknown' | 'not_covered' | 'blocked' | 'warning';
type RollbackOverall = 'ready' | 'partial' | 'not_ready';
interface RollbackReadinessItem {
id: string;
state: RollbackItemState;
label: string;
detail: string;
}
interface RollbackReadinessReport {
stack: string;
computedAt: number;
overall: RollbackOverall;
items: RollbackReadinessItem[];
/** Partial-revert scope disclosure for Git-managed stacks. */
note?: string;
}
const LABEL_CLASS = 'font-mono text-[10px] uppercase tracking-[0.18em] text-stat-subtitle';
const OVERALL_META: Record<RollbackOverall, { label: string; tone: string }> = {
ready: { label: 'ready', tone: 'border-success/40 bg-success/[0.06] text-success' },
partial: { label: 'partial', tone: 'border-warning/40 bg-warning/[0.06] text-warning' },
not_ready: { label: 'not ready', tone: 'border-destructive/40 bg-destructive/[0.06] text-destructive' },
};
const STATE_META: Record<RollbackItemState, { icon: LucideIcon; tone: string }> = {
ready: { icon: Check, tone: 'text-success' },
missing: { icon: X, tone: 'text-destructive' },
unknown: { icon: CircleHelp, tone: 'text-stat-subtitle' },
not_covered: { icon: Database, tone: 'text-warning' },
blocked: { icon: Ban, tone: 'text-destructive' },
warning: { icon: AlertTriangle, tone: 'text-warning' },
};
/**
* "Would the existing rollback actually save me?" disclosure for the Stack
* Dossier. Read-only; renders nothing while loading, on error, or when the
* active node does not advertise the update-guard capability.
*/
export function RollbackReadinessSection({ stackName }: { stackName: string }) {
const { activeNode, hasCapability } = useNodes();
const nodeId = activeNode?.id;
const enabled = hasCapability('update-guard');
const [report, setReport] = useState<RollbackReadinessReport | null>(null);
useEffect(() => {
setReport(null);
if (!enabled) return;
let cancelled = false;
const load = async () => {
try {
const res = await apiFetch(`/stacks/${stackName}/rollback-readiness`);
if (cancelled) return;
if (!res.ok) {
console.warn('[RollbackReadiness] unavailable for %s:', stackName, res.status);
return;
}
setReport(await res.json() as RollbackReadinessReport);
} catch (e) {
// Render-nothing on failure: the dossier remains fully usable without
// this section. The warn keeps the cause findable in the console.
if (!cancelled) console.warn('[RollbackReadiness] unavailable for %s:', stackName, e);
}
};
void load();
return () => { cancelled = true; };
}, [stackName, nodeId, enabled]);
if (!enabled || !report) return null;
const overall = OVERALL_META[report.overall] ?? OVERALL_META.partial;
return (
<section data-testid="dossier-rollback-readiness">
<div className="mb-1.5 flex items-center gap-2">
<span className={LABEL_CLASS}>rollback readiness</span>
<span
data-testid="rollback-overall"
data-overall={report.overall}
className={cn('rounded-md border px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide', overall.tone)}
>
{overall.label}
</span>
</div>
{report.note && (
<div className="mb-1.5 rounded-md border border-warning/30 bg-warning/[0.06] px-3 py-2 text-[12px] leading-relaxed text-warning">
{report.note}
</div>
)}
<div className="rounded-lg border border-muted bg-card/40 px-3 py-1">
{report.items.map(item => {
const meta = STATE_META[item.state] ?? STATE_META.unknown;
const StateIcon = meta.icon;
return (
<div key={item.id} className="border-t border-muted py-2 first:border-t-0">
<div className="flex items-center gap-2">
<StateIcon className={cn('h-3.5 w-3.5 shrink-0', meta.tone)} strokeWidth={1.5} />
<span className="text-[12px] font-medium text-foreground/90">{item.label}</span>
</div>
<div className="mt-0.5 pl-5 text-[12px] leading-relaxed text-foreground/80">{item.detail}</div>
</div>
);
})}
</div>
</section>
);
}