Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled
- Add must_change_password field to User model with migration b023 - Add POST /auth/change-password endpoint with password policy validation - Add require_password_changed dependency to block requests until password is changed - Add ChangePasswordModal with live password policy checklist (forced on first login) - Show password policy in CreateUserModal and EditUserModal - Fix backend permissions: tests, campaigns, templates, reports, evidence, worklogs - red_tech/blue_tech: execute only, cannot create tests/campaigns/templates - red_lead/blue_lead: create/edit tests/campaigns/templates, generate reports, no system access - viewer: read-only everywhere, can generate reports - Fix frontend role checks across TestDetailPage, TestDetailHeader, TeamTabs, TestsPage, CampaignsPage, CampaignDetailPage, Sidebar
580 lines
21 KiB
TypeScript
580 lines
21 KiB
TypeScript
import { useParams, useNavigate } from "react-router-dom";
|
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import { useState, useEffect, useCallback } from "react";
|
|
import { Loader2, AlertCircle, ArrowLeft } from "lucide-react";
|
|
|
|
import {
|
|
getTestById,
|
|
updateTestRed,
|
|
updateTestBlue,
|
|
startExecution,
|
|
submitRedEvidence,
|
|
submitBlueEvidence,
|
|
validateAsRedLead,
|
|
validateAsBlueLead,
|
|
reopenTest,
|
|
pauseTimer,
|
|
resumeTimer,
|
|
getTestTimeline,
|
|
getRetestChain,
|
|
} from "../api/tests";
|
|
import { uploadEvidence, getEvidence } from "../api/evidence";
|
|
import { useAuth } from "../context/AuthContext";
|
|
import type { TestResult, TeamSide, TestTimelineEntry } from "../types/models";
|
|
|
|
import TestDetailHeader from "../components/test-detail/TestDetailHeader";
|
|
import TeamTabs from "../components/test-detail/TeamTabs";
|
|
import ValidationModal from "../components/test-detail/ValidationModal";
|
|
import ConfirmDialog from "../components/ConfirmDialog";
|
|
import JiraLinkPanel from "../components/JiraLinkPanel";
|
|
import WorklogTimeline from "../components/WorklogTimeline";
|
|
|
|
// ── Page Component ─────────────────────────────────────────────────
|
|
|
|
export default function TestDetailPage() {
|
|
const { testId } = useParams<{ testId: string }>();
|
|
const navigate = useNavigate();
|
|
const queryClient = useQueryClient();
|
|
const { user } = useAuth();
|
|
|
|
// ── State ──────────────────────────────────────────────────────
|
|
|
|
const [validationModal, setValidationModal] = useState<{
|
|
open: boolean;
|
|
side: "red" | "blue";
|
|
}>({ open: false, side: "red" });
|
|
|
|
const [confirmReopen, setConfirmReopen] = useState(false);
|
|
|
|
const [redDraft, setRedDraft] = useState({
|
|
procedure_text: "",
|
|
tool_used: "",
|
|
attack_success: false,
|
|
red_summary: "",
|
|
});
|
|
|
|
const [blueDraft, setBlueDraft] = useState<{
|
|
detection_result: TestResult | "";
|
|
blue_summary: string;
|
|
}>({
|
|
detection_result: "",
|
|
blue_summary: "",
|
|
});
|
|
|
|
const [toast, setToast] = useState<{ message: string; type: "success" | "error" } | null>(null);
|
|
|
|
// ── Queries ────────────────────────────────────────────────────
|
|
|
|
const {
|
|
data: test,
|
|
isLoading,
|
|
error,
|
|
} = useQuery({
|
|
queryKey: ["test", testId],
|
|
queryFn: () => getTestById(testId!),
|
|
enabled: !!testId,
|
|
});
|
|
|
|
const {
|
|
data: timeline = [],
|
|
isLoading: isTimelineLoading,
|
|
} = useQuery({
|
|
queryKey: ["test-timeline", testId],
|
|
queryFn: () => getTestTimeline(testId!),
|
|
enabled: !!testId,
|
|
});
|
|
|
|
const { data: retestChain = [] } = useQuery({
|
|
queryKey: ["retest-chain", testId],
|
|
queryFn: () => getRetestChain(testId!),
|
|
enabled: !!testId && !!test && (test.retest_of !== null || test.retest_count > 0),
|
|
});
|
|
|
|
// Hydrate drafts from test data
|
|
useEffect(() => {
|
|
if (test) {
|
|
setRedDraft({
|
|
procedure_text: test.procedure_text || "",
|
|
tool_used: test.tool_used || "",
|
|
attack_success: test.attack_success ?? false,
|
|
red_summary: test.red_summary || "",
|
|
});
|
|
setBlueDraft({
|
|
detection_result: test.detection_result || "",
|
|
blue_summary: test.blue_summary || "",
|
|
});
|
|
}
|
|
}, [test]);
|
|
|
|
// ── Toast helper ───────────────────────────────────────────────
|
|
|
|
const showToast = useCallback((message: string, type: "success" | "error") => {
|
|
setToast({ message, type });
|
|
setTimeout(() => setToast(null), 5000);
|
|
}, []);
|
|
|
|
/** Extract a user-friendly error message from Axios or generic errors. */
|
|
const extractError = useCallback((err: unknown): string => {
|
|
if (err && typeof err === "object" && "response" in err) {
|
|
const resp = (err as { response?: { data?: { detail?: string | { message?: string } } } }).response;
|
|
const detail = resp?.data?.detail;
|
|
if (typeof detail === "string") return detail;
|
|
if (detail && typeof detail === "object" && "message" in detail) return (detail as { message: string }).message;
|
|
}
|
|
if (err instanceof Error) return err.message;
|
|
return "An unexpected error occurred";
|
|
}, []);
|
|
|
|
const invalidateAll = useCallback(() => {
|
|
queryClient.invalidateQueries({ queryKey: ["test", testId] });
|
|
queryClient.invalidateQueries({ queryKey: ["test-timeline", testId] });
|
|
queryClient.invalidateQueries({ queryKey: ["techniques"] });
|
|
}, [queryClient, testId]);
|
|
|
|
// ── Mutations ──────────────────────────────────────────────────
|
|
|
|
// Red field save (auto-save on blur would come later; for now Save button or transitions)
|
|
const saveRedMutation = useMutation({
|
|
mutationFn: () =>
|
|
updateTestRed(testId!, {
|
|
procedure_text: redDraft.procedure_text || undefined,
|
|
tool_used: redDraft.tool_used || undefined,
|
|
attack_success: redDraft.attack_success,
|
|
red_summary: redDraft.red_summary || undefined,
|
|
}),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
showToast("Red Team fields saved", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
const saveBlueMutation = useMutation({
|
|
mutationFn: () =>
|
|
updateTestBlue(testId!, {
|
|
detection_result: (blueDraft.detection_result as TestResult) || undefined,
|
|
blue_summary: blueDraft.blue_summary || undefined,
|
|
}),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
showToast("Blue Team fields saved", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
// State transitions
|
|
const startExecMutation = useMutation({
|
|
mutationFn: () => startExecution(testId!),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
showToast("Test execution started", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
const submitRedMutation = useMutation({
|
|
mutationFn: () => submitRedEvidence(testId!),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
showToast("Submitted to Blue Team", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
const submitBlueMutation = useMutation({
|
|
mutationFn: () => submitBlueEvidence(testId!),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
showToast("Submitted for review", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
const validateRedLeadMutation = useMutation({
|
|
mutationFn: (payload: { red_validation_status: "approved" | "rejected"; red_validation_notes?: string }) =>
|
|
validateAsRedLead(testId!, payload),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
setValidationModal({ open: false, side: "red" });
|
|
showToast("Red Lead validation submitted", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
const validateBlueLeadMutation = useMutation({
|
|
mutationFn: (payload: { blue_validation_status: "approved" | "rejected"; blue_validation_notes?: string }) =>
|
|
validateAsBlueLead(testId!, payload),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
setValidationModal({ open: false, side: "blue" });
|
|
showToast("Blue Lead validation submitted", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
const reopenMutation = useMutation({
|
|
mutationFn: () => reopenTest(testId!),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
setConfirmReopen(false);
|
|
showToast("Test reopened", "success");
|
|
},
|
|
onError: (err: unknown) => {
|
|
setConfirmReopen(false);
|
|
showToast(extractError(err), "error");
|
|
},
|
|
});
|
|
|
|
// Timer pause/resume
|
|
const pauseTimerMutation = useMutation({
|
|
mutationFn: () => pauseTimer(testId!),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
showToast("Timer paused", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
const resumeTimerMutation = useMutation({
|
|
mutationFn: () => resumeTimer(testId!),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
showToast("Timer resumed", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
// Evidence upload
|
|
const uploadMutation = useMutation({
|
|
mutationFn: ({ file, team }: { file: File; team: TeamSide }) =>
|
|
uploadEvidence(testId!, file, team),
|
|
onSuccess: () => {
|
|
invalidateAll();
|
|
showToast("Evidence uploaded", "success");
|
|
},
|
|
onError: (err: unknown) => showToast(extractError(err), "error"),
|
|
});
|
|
|
|
// ── Handlers ───────────────────────────────────────────────────
|
|
|
|
const handleDownload = async (evidenceId: string) => {
|
|
try {
|
|
const ev = await getEvidence(evidenceId);
|
|
if (ev.download_url) {
|
|
window.open(ev.download_url, "_blank");
|
|
}
|
|
} catch (err) {
|
|
console.error("Failed to get download URL:", err);
|
|
}
|
|
};
|
|
|
|
const handleRedFieldChange = (field: string, value: string | boolean) => {
|
|
setRedDraft((prev) => ({ ...prev, [field]: value }));
|
|
};
|
|
|
|
const handleBlueFieldChange = (field: string, value: string) => {
|
|
setBlueDraft((prev) => ({ ...prev, [field]: value }));
|
|
};
|
|
|
|
const handleUploadEvidence = async (file: File, team: TeamSide) => {
|
|
await uploadMutation.mutateAsync({ file, team });
|
|
};
|
|
|
|
const handleValidationSubmit = (
|
|
side: "red" | "blue",
|
|
status: "approved" | "rejected",
|
|
notes: string,
|
|
) => {
|
|
if (side === "red") {
|
|
validateRedLeadMutation.mutate({
|
|
red_validation_status: status,
|
|
red_validation_notes: notes || undefined,
|
|
});
|
|
} else {
|
|
validateBlueLeadMutation.mutate({
|
|
blue_validation_status: status,
|
|
blue_validation_notes: notes || undefined,
|
|
});
|
|
}
|
|
};
|
|
|
|
const isTransitioning =
|
|
startExecMutation.isPending ||
|
|
submitRedMutation.isPending ||
|
|
submitBlueMutation.isPending ||
|
|
reopenMutation.isPending;
|
|
|
|
// ── Loading / Error states ─────────────────────────────────────
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="flex h-64 items-center justify-center">
|
|
<Loader2 className="h-8 w-8 animate-spin text-cyan-400" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (error || !test) {
|
|
return (
|
|
<div className="flex h-64 flex-col items-center justify-center gap-2">
|
|
<AlertCircle className="h-10 w-10 text-red-400" />
|
|
<p className="text-red-400">Failed to load test</p>
|
|
<button
|
|
onClick={() => navigate("/tests")}
|
|
className="mt-2 flex items-center gap-1 text-sm text-cyan-400 hover:underline"
|
|
>
|
|
<ArrowLeft className="h-4 w-4" />
|
|
Back to tests
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
const formatDate = (dateStr: string | null) => {
|
|
if (!dateStr) return "\u2014";
|
|
return new Date(dateStr).toLocaleDateString("en-US", {
|
|
year: "numeric",
|
|
month: "short",
|
|
day: "numeric",
|
|
hour: "2-digit",
|
|
minute: "2-digit",
|
|
});
|
|
};
|
|
|
|
const role = user?.role ?? "";
|
|
const canSaveRed =
|
|
(test.state === "draft" || test.state === "red_executing") &&
|
|
(role === "red_tech" || role === "red_lead" || role === "admin");
|
|
const canSaveBlue =
|
|
test.state === "blue_evaluating" &&
|
|
(role === "blue_tech" || role === "blue_lead" || role === "admin");
|
|
|
|
// ── Render ─────────────────────────────────────────────────────
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
{/* Back button */}
|
|
<button
|
|
onClick={() => navigate(-1)}
|
|
className="flex items-center gap-1 text-sm text-gray-400 hover:text-cyan-400 transition-colors"
|
|
>
|
|
<ArrowLeft className="h-4 w-4" />
|
|
Back
|
|
</button>
|
|
|
|
{/* Header with progress bar and actions */}
|
|
<TestDetailHeader
|
|
test={test}
|
|
user={user}
|
|
isTransitioning={isTransitioning}
|
|
onStartExecution={() => startExecMutation.mutate()}
|
|
onSubmitRed={() => submitRedMutation.mutate()}
|
|
onSubmitBlue={() => submitBlueMutation.mutate()}
|
|
onOpenValidateModal={(side) => setValidationModal({ open: true, side })}
|
|
onReopen={() => setConfirmReopen(true)}
|
|
onPauseTimer={() => pauseTimerMutation.mutate()}
|
|
onResumeTimer={() => resumeTimerMutation.mutate()}
|
|
isTogglingTimer={pauseTimerMutation.isPending || resumeTimerMutation.isPending}
|
|
/>
|
|
|
|
{/* Content: Tabs + Sidebar */}
|
|
<div className="grid gap-6 lg:grid-cols-3">
|
|
{/* Main: Team Tabs */}
|
|
<div className="lg:col-span-2 space-y-4">
|
|
<TeamTabs
|
|
test={test}
|
|
user={user}
|
|
timeline={timeline}
|
|
isTimelineLoading={isTimelineLoading}
|
|
onRedFieldChange={handleRedFieldChange}
|
|
redDraft={redDraft}
|
|
onBlueFieldChange={handleBlueFieldChange}
|
|
blueDraft={blueDraft}
|
|
onUploadEvidence={handleUploadEvidence}
|
|
isUploading={uploadMutation.isPending}
|
|
onDownloadEvidence={handleDownload}
|
|
/>
|
|
|
|
{/* Save buttons */}
|
|
{(canSaveRed || canSaveBlue) && (
|
|
<div className="flex justify-end gap-3">
|
|
{canSaveRed && (
|
|
<button
|
|
onClick={() => saveRedMutation.mutate()}
|
|
disabled={saveRedMutation.isPending}
|
|
className="flex items-center gap-1.5 rounded-lg bg-orange-600 px-4 py-2 text-sm font-medium text-white hover:bg-orange-500 disabled:opacity-50 transition-colors"
|
|
>
|
|
{saveRedMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
|
|
Save Red Team Fields
|
|
</button>
|
|
)}
|
|
{canSaveBlue && (
|
|
<button
|
|
onClick={() => saveBlueMutation.mutate()}
|
|
disabled={saveBlueMutation.isPending}
|
|
className="flex items-center gap-1.5 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500 disabled:opacity-50 transition-colors"
|
|
>
|
|
{saveBlueMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
|
|
Save Blue Team Fields
|
|
</button>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Sidebar: Metadata */}
|
|
<div className="space-y-6">
|
|
<div className="rounded-xl border border-gray-800 bg-gray-900 p-6">
|
|
<h2 className="mb-4 text-lg font-semibold text-white">Details</h2>
|
|
<dl className="space-y-4">
|
|
<div>
|
|
<dt className="text-xs font-medium uppercase text-gray-500">Description</dt>
|
|
<dd className="mt-1 text-sm text-gray-300">
|
|
{test.description || "\u2014"}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt className="text-xs font-medium uppercase text-gray-500">Platform</dt>
|
|
<dd className="mt-1 text-sm text-gray-300 capitalize">
|
|
{test.platform || "\u2014"}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt className="text-xs font-medium uppercase text-gray-500">Creator</dt>
|
|
<dd className="mt-1 text-sm text-gray-300">
|
|
{test.created_by || "\u2014"}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt className="text-xs font-medium uppercase text-gray-500">Created</dt>
|
|
<dd className="mt-1 text-sm text-gray-300">
|
|
{formatDate(test.created_at)}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt className="text-xs font-medium uppercase text-gray-500">Execution Date</dt>
|
|
<dd className="mt-1 text-sm text-gray-300">
|
|
{formatDate(test.execution_date)}
|
|
</dd>
|
|
</div>
|
|
{test.red_validated_at && (
|
|
<div>
|
|
<dt className="text-xs font-medium uppercase text-gray-500">Red Validated</dt>
|
|
<dd className="mt-1 text-sm text-gray-300">
|
|
{formatDate(test.red_validated_at)}
|
|
</dd>
|
|
</div>
|
|
)}
|
|
{test.blue_validated_at && (
|
|
<div>
|
|
<dt className="text-xs font-medium uppercase text-gray-500">Blue Validated</dt>
|
|
<dd className="mt-1 text-sm text-gray-300">
|
|
{formatDate(test.blue_validated_at)}
|
|
</dd>
|
|
</div>
|
|
)}
|
|
</dl>
|
|
</div>
|
|
|
|
{/* Retest Chain */}
|
|
{(test.retest_of || test.retest_count > 0 || retestChain.length > 1) && (
|
|
<div className="rounded-xl border border-gray-800 bg-gray-900 p-6">
|
|
<h2 className="mb-4 text-lg font-semibold text-white">Retest Chain</h2>
|
|
{test.retest_of && (
|
|
<div className="mb-3">
|
|
<span className="text-xs font-medium uppercase text-gray-500">
|
|
Retest {test.retest_count} / 3
|
|
</span>
|
|
<div className="mt-1 h-2 w-full rounded-full bg-gray-800 overflow-hidden">
|
|
<div
|
|
className="h-full rounded-full bg-cyan-500 transition-all"
|
|
style={{ width: `${(test.retest_count / 3) * 100}%` }}
|
|
/>
|
|
</div>
|
|
</div>
|
|
)}
|
|
<div className="space-y-2">
|
|
{retestChain.map((entry) => (
|
|
<button
|
|
key={entry.id}
|
|
onClick={() => entry.id !== testId && navigate(`/tests/${entry.id}`)}
|
|
className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 text-left text-sm transition-colors ${
|
|
entry.id === testId
|
|
? "border-cyan-500/30 bg-cyan-900/30 text-cyan-400"
|
|
: "border-gray-700 bg-gray-800/50 text-gray-300 hover:border-cyan-500/30 hover:text-cyan-400"
|
|
}`}
|
|
>
|
|
<div className="flex items-center gap-2 truncate">
|
|
<span className="truncate text-xs">
|
|
{entry.retest_of ? `#${entry.retest_count}` : "Original"}
|
|
</span>
|
|
<span className="truncate">{entry.name}</span>
|
|
</div>
|
|
<span className={`shrink-0 rounded-full px-2 py-0.5 text-xs ${
|
|
entry.state === "validated"
|
|
? "bg-green-900/50 text-green-400"
|
|
: entry.state === "rejected"
|
|
? "bg-red-900/50 text-red-400"
|
|
: "bg-gray-800/50 text-gray-500"
|
|
}`}>
|
|
{entry.state || "draft"}
|
|
</span>
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Jira Integration */}
|
|
<JiraLinkPanel entityType="test" entityId={testId!} />
|
|
|
|
{/* Time Tracking */}
|
|
<WorklogTimeline entityType="test" entityId={testId!} />
|
|
</div>
|
|
</div>
|
|
|
|
{/* Confirm Reopen Dialog */}
|
|
<ConfirmDialog
|
|
open={confirmReopen}
|
|
title="Reopen Test"
|
|
message="This will move the test back to Draft state and clear all validation decisions. The Red/Blue workflow will need to be restarted. Are you sure?"
|
|
confirmLabel="Reopen"
|
|
variant="warning"
|
|
isLoading={reopenMutation.isPending}
|
|
onConfirm={() => reopenMutation.mutate()}
|
|
onCancel={() => setConfirmReopen(false)}
|
|
/>
|
|
|
|
{/* Validation Modal */}
|
|
{validationModal.open && (
|
|
<ValidationModal
|
|
side={validationModal.side}
|
|
test={test}
|
|
isSubmitting={
|
|
validationModal.side === "red"
|
|
? validateRedLeadMutation.isPending
|
|
: validateBlueLeadMutation.isPending
|
|
}
|
|
onSubmit={(status, notes) =>
|
|
handleValidationSubmit(validationModal.side, status, notes)
|
|
}
|
|
onClose={() => setValidationModal({ open: false, side: "red" })}
|
|
/>
|
|
)}
|
|
|
|
{/* Toast notification */}
|
|
{toast && (
|
|
<div
|
|
className={`fixed bottom-6 right-6 z-50 rounded-lg border px-4 py-3 text-sm shadow-lg backdrop-blur transition-all ${
|
|
toast.type === "success"
|
|
? "border-green-500/30 bg-green-900/90 text-green-300"
|
|
: "border-red-500/30 bg-red-900/90 text-red-300"
|
|
}`}
|
|
>
|
|
{toast.message}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|