feat(frontend): sprint 5 — templates CRUD pages + nav + picker modal + dropdown

- types.ts: SimulationTemplate, SimulationTemplateCreateInput, SimulationTemplatePatchInput,
  extend SimulationCreateInput with template_id
- api/templates.ts: listTemplates, getTemplate, createTemplate, updateTemplate, deleteTemplate
- hooks/useTemplates.ts: useTemplates, useTemplate, useCreateTemplate, useUpdateTemplate,
  useDeleteTemplate (TanStack Query, invalidates ["templates"])
- TemplatesListPage: /admin/templates — table (name, MITRE count, created by, updated),
  New/Edit/Delete actions, loading/error/empty states
- TemplateFormPage: /admin/templates/new + /admin/templates/:id/edit — controlled form
  with inline MITRE field (picker + matrix modal), ConfirmDialog for delete
- TemplatePickerModal: reusable modal listing templates with empty state (AC-27.6)
- SimulationList: replace "New simulation" link with split-button dropdown
  (Blank → /simulations/new | From template… → TemplatePickerModal + POST template_id)
- Layout: "Templates" nav link (admin | redteam, before "Users")
- App.tsx: /admin/templates routes gated roles=["admin","redteam"]
- 26 new Vitest tests (118 total, 92 original preserved)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Knacky
2026-05-28 06:36:10 +02:00
parent 1f327e9aa8
commit 90fc5bab6c
13 changed files with 1289 additions and 9 deletions

View File

@@ -8,6 +8,8 @@ import { EngagementFormPage } from '@/pages/EngagementFormPage';
import { EngagementDetailPage } from '@/pages/EngagementDetailPage';
import { UsersAdminPage } from '@/pages/UsersAdminPage';
import { SimulationFormPage } from '@/pages/SimulationFormPage';
import { TemplatesListPage } from '@/pages/TemplatesListPage';
import { TemplateFormPage } from '@/pages/TemplateFormPage';
/**
* Router. Auth + role gates handled by <ProtectedRoute />.
@@ -43,6 +45,13 @@ export function App(): JSX.Element {
<Route element={<ProtectedRoute roles={['admin']} />}>
<Route path="/admin/users" element={<UsersAdminPage />} />
</Route>
{/* admin + redteam routes */}
<Route element={<ProtectedRoute roles={['admin', 'redteam']} />}>
<Route path="/admin/templates" element={<TemplatesListPage />} />
<Route path="/admin/templates/new" element={<TemplateFormPage />} />
<Route path="/admin/templates/:id/edit" element={<TemplateFormPage />} />
</Route>
</Route>
</Route>

View File

@@ -0,0 +1,35 @@
import { apiClient } from './client';
import type {
SimulationTemplate,
SimulationTemplateCreateInput,
SimulationTemplatePatchInput,
} from './types';
export async function listTemplates(): Promise<SimulationTemplate[]> {
const { data } = await apiClient.get<SimulationTemplate[]>('/simulation-templates');
return data;
}
export async function getTemplate(id: number): Promise<SimulationTemplate> {
const { data } = await apiClient.get<SimulationTemplate>(`/simulation-templates/${id}`);
return data;
}
export async function createTemplate(
input: SimulationTemplateCreateInput,
): Promise<SimulationTemplate> {
const { data } = await apiClient.post<SimulationTemplate>('/simulation-templates', input);
return data;
}
export async function updateTemplate(
id: number,
patch: SimulationTemplatePatchInput,
): Promise<SimulationTemplate> {
const { data } = await apiClient.patch<SimulationTemplate>(`/simulation-templates/${id}`, patch);
return data;
}
export async function deleteTemplate(id: number): Promise<void> {
await apiClient.delete(`/simulation-templates/${id}`);
}

View File

@@ -104,8 +104,40 @@ export interface Simulation {
created_by: { id: number; username: string };
}
export interface SimulationTemplate {
id: number;
name: string;
description: string | null;
commands: string | null;
prerequisites: string | null;
techniques: MitreTechnique[];
tactics: MitreTacticRef[];
created_at: string;
updated_at: string | null;
created_by: { id: number; username: string };
}
export interface SimulationTemplateCreateInput {
name: string;
description?: string | null;
commands?: string | null;
prerequisites?: string | null;
technique_ids?: string[];
tactic_ids?: string[];
}
export interface SimulationTemplatePatchInput {
name?: string;
description?: string | null;
commands?: string | null;
prerequisites?: string | null;
technique_ids?: string[];
tactic_ids?: string[];
}
export interface SimulationCreateInput {
name: string;
template_id?: number;
}
export interface SimulationPatchInput {

View File

@@ -17,7 +17,7 @@ function themeLabel(theme: Theme): string {
}
export function Layout(): JSX.Element {
const { user, isAdmin, logout } = useAuth();
const { user, isAdmin, isRedteam, logout } = useAuth();
const navigate = useNavigate();
const { theme, cycleTheme } = useTheme();
@@ -78,6 +78,18 @@ export function Layout(): JSX.Element {
>
Engagements
</NavLink>
{isAdmin || isRedteam ? (
<NavLink
to="/admin/templates"
className={({ isActive }) =>
`text-[16px] py-2 px-md ${
isActive ? 'text-ink border-b-2 border-primary -mb-[1px]' : 'text-charcoal'
}`
}
>
Templates
</NavLink>
) : null}
{isAdmin ? (
<NavLink
to="/admin/users"

View File

@@ -1,11 +1,16 @@
import { useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { ChevronDown } from 'lucide-react';
import { extractApiError } from '@/api/client';
import type { SimulationTemplate } from '@/api/types';
import { useAuth } from '@/hooks/useAuth';
import { useEngagementSimulations } from '@/hooks/useSimulations';
import { useEngagementSimulations, useCreateSimulation } from '@/hooks/useSimulations';
import { useToast } from '@/hooks/useToast';
import { LoadingState } from './LoadingState';
import { ErrorState } from './ErrorState';
import { EmptyState } from './EmptyState';
import { SimulationStatusBadge } from './SimulationStatusBadge';
import { TemplatePickerModal } from './TemplatePickerModal';
interface SimulationListProps {
engagementId: number;
@@ -16,6 +21,99 @@ function formatDate(value: string | null): string {
return value.replace('T', ' ').slice(0, 16);
}
function NewSimulationDropdown({ engagementId }: { engagementId: number }): JSX.Element {
const navigate = useNavigate();
const { push } = useToast();
const [open, setOpen] = useState(false);
const [showPicker, setShowPicker] = useState(false);
const btnRef = useRef<HTMLDivElement>(null);
const createMutation = useCreateSimulation(engagementId);
const handleBlank = () => {
setOpen(false);
navigate(`/engagements/${engagementId}/simulations/new`);
};
const handleFromTemplate = () => {
setOpen(false);
setShowPicker(true);
};
const handleSelectTemplate = async (template: SimulationTemplate) => {
try {
const sim = await createMutation.mutateAsync({ name: template.name, template_id: template.id });
setShowPicker(false);
push(`Created "${sim.name}" from template`, 'success');
navigate(`/engagements/${engagementId}/simulations/${sim.id}/edit`);
} catch (err) {
push(extractApiError(err, 'Could not create simulation from template'), 'error');
}
};
return (
<div className="relative" ref={btnRef}>
<div className="inline-flex">
<button
type="button"
className="btn-primary rounded-r-none border-r border-primary-deep"
onClick={handleBlank}
data-testid="new-simulation-btn"
>
New simulation
</button>
<button
type="button"
aria-label="More options"
aria-expanded={open}
className="btn-primary rounded-l-none px-sm"
onClick={() => setOpen((v) => !v)}
data-testid="new-simulation-dropdown-toggle"
>
<ChevronDown size={14} aria-hidden />
</button>
</div>
{open ? (
<div
className="absolute right-0 top-full mt-xxs bg-canvas border border-hairline rounded-md shadow-floating z-20 min-w-[180px]"
role="menu"
>
<button
type="button"
role="menuitem"
className="w-full text-left px-md py-sm text-[14px] text-ink hover:bg-cloud"
onClick={handleBlank}
>
Blank
</button>
<button
type="button"
role="menuitem"
className="w-full text-left px-md py-sm text-[14px] text-ink hover:bg-cloud"
onClick={handleFromTemplate}
data-testid="from-template-btn"
>
From template
</button>
</div>
) : null}
{showPicker ? (
<TemplatePickerModal
engagementId={engagementId}
onClose={() => setShowPicker(false)}
onInstantiated={(simId) => {
setShowPicker(false);
navigate(`/engagements/${engagementId}/simulations/${simId}/edit`);
}}
onSelectTemplate={handleSelectTemplate}
isPending={createMutation.isPending}
/>
) : null}
</div>
);
}
export function SimulationList({ engagementId }: SimulationListProps): JSX.Element {
const { data, isLoading, isError, error, refetch } = useEngagementSimulations(engagementId);
const { canEditEngagements } = useAuth();
@@ -57,13 +155,7 @@ export function SimulationList({ engagementId }: SimulationListProps): JSX.Eleme
<div className="flex items-center justify-between">
<h2 className="text-[24px] font-medium text-ink">Simulations</h2>
{canEditEngagements ? (
<Link
to={`/engagements/${engagementId}/simulations/new`}
className="btn-primary"
data-testid="new-simulation-btn"
>
New simulation
</Link>
<NewSimulationDropdown engagementId={engagementId} />
) : null}
</div>

View File

@@ -0,0 +1,104 @@
import { extractApiError } from '@/api/client';
import type { SimulationTemplate } from '@/api/types';
import { useTemplates } from '@/hooks/useTemplates';
import { LoadingState } from './LoadingState';
import { ErrorState } from './ErrorState';
import { EmptyState } from './EmptyState';
interface TemplatePickerModalProps {
engagementId: number;
onClose: () => void;
onInstantiated: (simId: number) => void;
onSelectTemplate: (template: SimulationTemplate) => void;
isPending?: boolean;
}
function mitreCount(t: SimulationTemplate): string {
const count = t.techniques.length + t.tactics.length;
return count === 0 ? '—' : String(count);
}
export function TemplatePickerModal({
onClose,
onSelectTemplate,
isPending = false,
}: TemplatePickerModalProps): JSX.Element {
const { data, isLoading, isError, error, refetch } = useTemplates();
return (
<div
role="dialog"
aria-modal="true"
aria-labelledby="tpl-picker-title"
className="fixed inset-0 z-50 flex items-center justify-center"
>
<div className="modal-backdrop absolute inset-0" onClick={onClose} aria-hidden="true" />
<div className="relative card-product shadow-floating dark:shadow-floating-dark max-w-xl w-full mx-md flex flex-col gap-md max-h-[80vh] overflow-hidden">
<div className="flex items-center justify-between">
<h2 id="tpl-picker-title" className="text-[20px] font-medium text-ink">
From template
</h2>
<button
type="button"
aria-label="Close"
onClick={onClose}
className="text-graphite hover:text-ink transition-colors text-[20px] leading-none"
>
×
</button>
</div>
<div className="overflow-y-auto flex-1 -mx-xl px-xl">
{isLoading ? <LoadingState label="Loading templates…" /> : null}
{isError ? (
<ErrorState
message={extractApiError(error, 'Could not load templates')}
onRetry={() => refetch()}
/>
) : null}
{!isLoading && !isError && data && data.length === 0 ? (
<EmptyState
title="No templates available"
description="Create one from the Templates page."
/>
) : null}
{!isLoading && !isError && data && data.length > 0 ? (
<table className="w-full text-left" data-testid="template-picker-table">
<thead className="bg-cloud border-b border-hairline">
<tr className="text-[12px] uppercase tracking-[0.5px] text-graphite">
<th className="px-md py-sm">Name</th>
<th className="px-md py-sm">MITRE</th>
<th className="px-md py-sm">Created by</th>
</tr>
</thead>
<tbody>
{data.map((t) => (
<tr
key={t.id}
className="border-b border-hairline last:border-0 hover:bg-cloud cursor-pointer"
onClick={() => !isPending && onSelectTemplate(t)}
data-testid={`template-row-${t.id}`}
>
<td className="px-md py-sm text-ink font-medium">{t.name}</td>
<td className="px-md py-sm text-charcoal text-[14px]">{mitreCount(t)}</td>
<td className="px-md py-sm text-charcoal text-[14px]">{t.created_by.username}</td>
</tr>
))}
</tbody>
</table>
) : null}
</div>
<div className="border-t border-hairline pt-sm">
<button type="button" className="btn-outline-ink" onClick={onClose}>
Cancel
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,62 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
createTemplate,
deleteTemplate,
getTemplate,
listTemplates,
updateTemplate,
} from '@/api/templates';
import type { SimulationTemplateCreateInput, SimulationTemplatePatchInput } from '@/api/types';
function templatesKey() {
return ['templates'] as const;
}
function templateKey(id: number) {
return ['templates', id] as const;
}
export function useTemplates() {
return useQuery({
queryKey: templatesKey(),
queryFn: listTemplates,
});
}
export function useTemplate(id: number | undefined) {
return useQuery({
queryKey: id ? templateKey(id) : ['templates', 'none'],
queryFn: () => getTemplate(id as number),
enabled: typeof id === 'number' && !Number.isNaN(id),
});
}
export function useCreateTemplate() {
const qc = useQueryClient();
return useMutation({
mutationFn: (input: SimulationTemplateCreateInput) => createTemplate(input),
onSuccess: () => qc.invalidateQueries({ queryKey: templatesKey() }),
});
}
export function useUpdateTemplate(id: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: (patch: SimulationTemplatePatchInput) => updateTemplate(id, patch),
onSuccess: () => {
qc.invalidateQueries({ queryKey: templateKey(id) });
qc.invalidateQueries({ queryKey: templatesKey() });
},
});
}
export function useDeleteTemplate() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: number) => deleteTemplate(id),
onSuccess: (_data, id) => {
qc.invalidateQueries({ queryKey: templateKey(id) });
qc.invalidateQueries({ queryKey: templatesKey() });
},
});
}

View File

@@ -0,0 +1,268 @@
import { useEffect, useState, type FormEvent } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { Save, Grid2x2 } from 'lucide-react';
import { extractApiError } from '@/api/client';
import type { MitreTechnique, MitreTacticRef } from '@/api/types';
import { useToast } from '@/hooks/useToast';
import { useCreateTemplate, useDeleteTemplate, useTemplate, useUpdateTemplate } from '@/hooks/useTemplates';
import { FormField, TextArea, TextInput } from '@/components/FormField';
import { LoadingState } from '@/components/LoadingState';
import { ErrorState } from '@/components/ErrorState';
import { ConfirmDialog } from '@/components/ConfirmDialog';
import { MitreTechniqueTag, MitreTacticTag } from '@/components/MitreTechniqueTag';
import { MitreTechniquePicker } from '@/components/MitreTechniquePicker';
import { MitreMatrixModal } from '@/components/MitreMatrixModal';
import type { MatrixSelection } from '@/components/MitreMatrixModal';
interface FormState {
name: string;
description: string;
commands: string;
prerequisites: string;
}
const EMPTY: FormState = { name: '', description: '', commands: '', prerequisites: '' };
export function TemplateFormPage(): JSX.Element {
const { id } = useParams<{ id: string }>();
const templateId = id ? Number(id) : undefined;
const isNew = !templateId;
const navigate = useNavigate();
const { push } = useToast();
const existing = useTemplate(templateId);
const createMutation = useCreateTemplate();
const updateMutation = useUpdateTemplate(templateId ?? 0);
const deleteMutation = useDeleteTemplate();
const [form, setForm] = useState<FormState>(EMPTY);
const [techniques, setTechniques] = useState<MitreTechnique[]>([]);
const [tactics, setTactics] = useState<MitreTacticRef[]>([]);
const [formError, setFormError] = useState<string | null>(null);
const [showMatrix, setShowMatrix] = useState(false);
const [showPicker, setShowPicker] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
useEffect(() => {
if (existing.data) {
const t = existing.data;
setForm({
name: t.name,
description: t.description ?? '',
commands: t.commands ?? '',
prerequisites: t.prerequisites ?? '',
});
setTechniques(t.techniques);
setTactics(t.tactics);
}
}, [existing.data]);
const isPending = createMutation.isPending || updateMutation.isPending;
const onSubmit = async (e: FormEvent) => {
e.preventDefault();
setFormError(null);
if (!form.name.trim()) {
setFormError('Name is required');
return;
}
const payload = {
name: form.name.trim(),
description: form.description.trim() || null,
commands: form.commands.trim() || null,
prerequisites: form.prerequisites.trim() || null,
technique_ids: techniques.map((t) => t.id),
tactic_ids: tactics.map((t) => t.id),
};
try {
if (isNew) {
const created = await createMutation.mutateAsync(payload);
push('Template created', 'success');
navigate(`/admin/templates/${created.id}/edit`, { replace: true });
} else {
await updateMutation.mutateAsync(payload);
push('Template saved', 'success');
}
} catch (err) {
setFormError(extractApiError(err, 'Could not save template'));
}
};
const onDelete = async () => {
if (!templateId) return;
try {
await deleteMutation.mutateAsync(templateId);
push('Template deleted', 'success');
navigate('/admin/templates', { replace: true });
} catch (err) {
push(extractApiError(err, 'Could not delete template'), 'error');
}
setShowDeleteConfirm(false);
};
const handleMatrixApply = ({ techniques: newTech, tactics: newTac }: MatrixSelection) => {
setShowMatrix(false);
setTechniques(newTech);
setTactics(newTac);
};
const handlePickerSelect = (technique: MitreTechnique) => {
if (techniques.some((t) => t.id === technique.id)) return;
setTechniques((prev) => [...prev, technique]);
setShowPicker(false);
};
if (!isNew && existing.isLoading) return <LoadingState label="Loading template…" />;
if (!isNew && existing.isError) {
return (
<ErrorState
message={extractApiError(existing.error, 'Could not load template')}
onRetry={() => existing.refetch()}
/>
);
}
return (
<div className="flex flex-col gap-xl">
<header className="flex items-start justify-between gap-md">
<div className="flex flex-col gap-sm">
<Link to="/admin/templates" className="btn-text-link text-[14px]">
Back to templates
</Link>
<h1 className="text-[44px] font-medium leading-none">
{isNew ? 'New template' : (existing.data?.name ?? 'Edit template')}
</h1>
</div>
{!isNew ? (
<button
type="button"
className="btn-text-link text-bloom-deep"
onClick={() => setShowDeleteConfirm(true)}
disabled={deleteMutation.isPending}
>
Delete
</button>
) : null}
</header>
<form onSubmit={onSubmit} className="card-product flex flex-col gap-lg max-w-2xl">
<FormField label="Name" htmlFor="tpl-name" required error={formError}>
<TextInput
id="tpl-name"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
disabled={isPending}
/>
</FormField>
<FormField label="Description" htmlFor="tpl-desc">
<TextArea
id="tpl-desc"
value={form.description}
onChange={(e) => setForm({ ...form, description: e.target.value })}
disabled={isPending}
placeholder="What does this simulation cover?"
/>
</FormField>
<FormField label="Commands" htmlFor="tpl-commands" hint="One command per line">
<TextArea
id="tpl-commands"
value={form.commands}
onChange={(e) => setForm({ ...form, commands: e.target.value })}
disabled={isPending}
placeholder="e.g. mimikatz.exe&#10;sekurlsa::logonpasswords"
/>
</FormField>
<FormField label="Prerequisites" htmlFor="tpl-prereqs">
<TextArea
id="tpl-prereqs"
value={form.prerequisites}
onChange={(e) => setForm({ ...form, prerequisites: e.target.value })}
disabled={isPending}
placeholder="e.g. Local admin access required"
/>
</FormField>
<div className="flex flex-col gap-sm">
<span className="text-[14px] font-medium text-ink">MITRE Techniques &amp; Tactics</span>
{techniques.length === 0 && tactics.length === 0 ? (
<p className="text-[13px] text-graphite">No techniques selected</p>
) : (
<div className="flex flex-wrap gap-xs" data-testid="techniques-tag-list">
{tactics.map((t) => (
<MitreTacticTag
key={t.id}
tactic={t}
onRemove={() => setTactics((prev) => prev.filter((x) => x.id !== t.id))}
/>
))}
{techniques.map((t) => (
<MitreTechniqueTag
key={t.id}
technique={t}
onRemove={() => setTechniques((prev) => prev.filter((x) => x.id !== t.id))}
/>
))}
</div>
)}
<div className="flex items-center gap-xs max-w-sm">
<div className="flex-1">
{showPicker ? (
<MitreTechniquePicker onSelect={handlePickerSelect} />
) : (
<button
type="button"
className="text-input h-9 text-[13px] text-graphite text-left cursor-text w-full"
onClick={() => setShowPicker(true)}
>
Search technique (e.g. T1059)
</button>
)}
</div>
<button
type="button"
aria-label="Open MITRE matrix"
onClick={() => { setShowPicker(false); setShowMatrix(true); }}
className="flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-md border border-steel text-graphite hover:text-ink hover:border-ink transition-colors"
>
<Grid2x2 size={16} />
</button>
</div>
</div>
<div className="flex items-center gap-md pt-xs border-t border-hairline">
<button type="submit" className="btn-primary" disabled={isPending}>
<Save size={14} aria-hidden /> {isPending ? 'Saving…' : 'Save'}
</button>
<Link to="/admin/templates" className="btn-outline-ink">
Cancel
</Link>
</div>
</form>
<MitreMatrixModal
isOpen={showMatrix}
initialTechniques={techniques}
initialTactics={tactics}
onApply={handleMatrixApply}
onCancel={() => setShowMatrix(false)}
/>
{showDeleteConfirm ? (
<ConfirmDialog
title="Delete template"
description={`Delete "${existing.data?.name ?? 'this template'}"? This cannot be undone. Simulations already created from it are unaffected.`}
confirmLabel="Delete"
onConfirm={onDelete}
onCancel={() => setShowDeleteConfirm(false)}
destructive
/>
) : null}
</div>
);
}

View File

@@ -0,0 +1,121 @@
import { Link } from 'react-router-dom';
import { Plus } from 'lucide-react';
import { extractApiError } from '@/api/client';
import type { SimulationTemplate } from '@/api/types';
import { useDeleteTemplate, useTemplates } from '@/hooks/useTemplates';
import { useToast } from '@/hooks/useToast';
import { LoadingState } from '@/components/LoadingState';
import { ErrorState } from '@/components/ErrorState';
import { EmptyState } from '@/components/EmptyState';
function mitreCount(t: SimulationTemplate): number {
return t.techniques.length + t.tactics.length;
}
function formatDate(value: string | null): string {
if (!value) return '—';
return value.slice(0, 10);
}
export function TemplatesListPage(): JSX.Element {
const { data, isLoading, isError, error, refetch } = useTemplates();
const deleteMutation = useDeleteTemplate();
const { push } = useToast();
const onDelete = async (t: SimulationTemplate) => {
if (!window.confirm(`Delete template "${t.name}"? This cannot be undone.`)) return;
try {
await deleteMutation.mutateAsync(t.id);
push('Template deleted', 'success');
} catch (err) {
push(extractApiError(err, 'Could not delete template'), 'error');
}
};
return (
<div className="flex flex-col gap-xl">
<header className="flex items-end justify-between gap-md">
<div>
<h1 className="text-[44px] font-medium leading-none">Templates</h1>
<p className="text-charcoal text-[16px] mt-sm">
Reusable simulation blueprints for red team operations.
</p>
</div>
<Link to="/admin/templates/new" className="btn-primary">
<Plus size={14} aria-hidden /> New
</Link>
</header>
{isLoading ? <LoadingState label="Loading templates…" /> : null}
{isError ? (
<ErrorState
message={extractApiError(error, 'Could not load templates')}
onRetry={() => refetch()}
/>
) : null}
{!isLoading && !isError && data && data.length === 0 ? (
<EmptyState
title="No templates yet"
description="Create your first template to speed up simulation setup."
action={
<Link to="/admin/templates/new" className="btn-primary">
<Plus size={14} aria-hidden /> New template
</Link>
}
/>
) : null}
{!isLoading && !isError && data && data.length > 0 ? (
<div className="card-product overflow-hidden p-0">
<table className="w-full text-left">
<thead className="bg-cloud border-b border-hairline">
<tr className="text-[12px] uppercase tracking-[0.5px] text-graphite">
<th className="px-xl py-md">Name</th>
<th className="px-xl py-md">MITRE</th>
<th className="px-xl py-md">Created by</th>
<th className="px-xl py-md">Updated</th>
<th className="px-xl py-md text-right">Actions</th>
</tr>
</thead>
<tbody>
{data.map((t) => (
<tr key={t.id} className="border-b border-hairline last:border-0">
<td className="px-xl py-md">
<Link
to={`/admin/templates/${t.id}/edit`}
className="text-ink font-medium hover:underline"
>
{t.name}
</Link>
</td>
<td className="px-xl py-md text-charcoal text-[14px]">
{mitreCount(t) === 0 ? '—' : mitreCount(t)}
</td>
<td className="px-xl py-md text-charcoal">{t.created_by.username}</td>
<td className="px-xl py-md text-charcoal">{formatDate(t.updated_at)}</td>
<td className="px-xl py-md text-right">
<div className="inline-flex gap-sm">
<Link to={`/admin/templates/${t.id}/edit`} className="btn-text-link">
Edit
</Link>
<button
type="button"
className="btn-text-link text-bloom-deep"
onClick={() => onDelete(t)}
disabled={deleteMutation.isPending}
>
Delete
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : null}
</div>
);
}

View File

@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { screen, waitFor, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MockAdapter from 'axios-mock-adapter';
import { apiClient } from '@/api/client';
import { SimulationList } from '@/components/SimulationList';
@@ -105,6 +106,42 @@ describe('SimulationList — admin/redteam', () => {
expect(screen.getByTestId('new-simulation-btn')).toBeInTheDocument();
});
it('shows dropdown toggle button when simulations exist', async () => {
mock.onGet('/engagements/42/simulations').reply(200, SIMULATIONS);
renderWithProviders(<SimulationList engagementId={42} />);
await waitFor(() => {
expect(screen.getByText('Lateral movement test')).toBeInTheDocument();
});
expect(screen.getByTestId('new-simulation-dropdown-toggle')).toBeInTheDocument();
});
it('opens dropdown and shows "From template…" option', async () => {
mock.onGet('/engagements/42/simulations').reply(200, SIMULATIONS);
const user = userEvent.setup();
renderWithProviders(<SimulationList engagementId={42} />);
await waitFor(() => {
expect(screen.getByText('Lateral movement test')).toBeInTheDocument();
});
await user.click(screen.getByTestId('new-simulation-dropdown-toggle'));
expect(screen.getByTestId('from-template-btn')).toBeInTheDocument();
expect(screen.getByText('Blank')).toBeInTheDocument();
});
it('opens TemplatePickerModal when "From template…" is clicked', async () => {
mock.onGet('/engagements/42/simulations').reply(200, SIMULATIONS);
mock.onGet('/simulation-templates').reply(200, []);
const user = userEvent.setup();
renderWithProviders(<SimulationList engagementId={42} />);
await waitFor(() => {
expect(screen.getByText('Lateral movement test')).toBeInTheDocument();
});
await user.click(screen.getByTestId('new-simulation-dropdown-toggle'));
await user.click(screen.getByTestId('from-template-btn'));
await waitFor(() => {
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
});
it('clicking a row uses SPA navigation and does not trigger window.location change', async () => {
mock.onGet('/engagements/42/simulations').reply(200, SIMULATIONS);
const originalHref = window.location.href;

View File

@@ -0,0 +1,219 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { render } from '@testing-library/react';
import MockAdapter from 'axios-mock-adapter';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { apiClient } from '@/api/client';
import { TemplateFormPage } from '@/pages/TemplateFormPage';
import { ToastProvider } from '@/hooks/useToast';
import type { SimulationTemplate } from '@/api/types';
vi.mock('@/hooks/useAuth', () => ({
useAuth: () => ({
user: { id: 1, username: 'alice', role: 'admin', created_at: '2026-01-01' },
status: 'authenticated',
login: vi.fn(),
logout: vi.fn(),
isAdmin: true,
isRedteam: false,
isSoc: false,
canEditEngagements: true,
}),
}));
const TEMPLATE: SimulationTemplate = {
id: 5,
name: 'Mimikatz LSASS Dump',
description: 'Extract NTLM hashes',
commands: 'mimikatz.exe',
prerequisites: 'Local admin',
techniques: [{ id: 'T1003', name: 'OS Credential Dumping', tactics: ['credential-access'] }],
tactics: [{ id: 'TA0006', name: 'Credential Access' }],
created_at: '2026-05-28T00:00:00',
updated_at: null,
created_by: { id: 1, username: 'alice' },
};
function makeClient() {
return new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0, staleTime: 0 },
mutations: { retry: false },
},
});
}
function renderNew() {
const client = makeClient();
return {
...render(
<QueryClientProvider client={client}>
<MemoryRouter initialEntries={['/admin/templates/new']}>
<Routes>
<Route path="/admin/templates/new" element={<ToastProvider><TemplateFormPage /></ToastProvider>} />
<Route path="/admin/templates/:id/edit" element={<ToastProvider><TemplateFormPage /></ToastProvider>} />
</Routes>
</MemoryRouter>
</QueryClientProvider>
),
client,
};
}
function renderEdit(id: number) {
const client = makeClient();
return {
...render(
<QueryClientProvider client={client}>
<MemoryRouter initialEntries={[`/admin/templates/${id}/edit`]}>
<Routes>
<Route path="/admin/templates/:id/edit" element={<ToastProvider><TemplateFormPage /></ToastProvider>} />
<Route path="/admin/templates" element={<div data-testid="templates-list" />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>
),
client,
};
}
describe('TemplateFormPage — new mode', () => {
let mock: MockAdapter;
beforeEach(() => {
mock = new MockAdapter(apiClient);
});
afterEach(() => {
mock.restore();
});
it('renders the form with name field in empty state', () => {
renderNew();
expect(screen.getByLabelText(/Name/i)).toBeInTheDocument();
expect(screen.getByLabelText(/Description/i)).toBeInTheDocument();
expect(screen.getByLabelText(/Commands/i)).toBeInTheDocument();
expect(screen.getByLabelText(/Prerequisites/i)).toBeInTheDocument();
// All inputs should be empty
expect(screen.getByLabelText(/Name/i)).toHaveValue('');
});
it('shows validation error when name is empty on submit', async () => {
const user = userEvent.setup();
renderNew();
// Name field is empty by default — click Save directly
const saveBtn = screen.getByRole('button', { name: /Save/i });
await user.click(saveBtn);
await waitFor(() => {
expect(screen.getByText('Name is required')).toBeInTheDocument();
});
});
it('submits POST when name is filled', async () => {
mock.onPost('/simulation-templates').reply(201, { ...TEMPLATE, id: 99 });
const user = userEvent.setup();
renderNew();
await user.type(screen.getByLabelText(/Name/i), 'My Template');
await user.click(screen.getByRole('button', { name: /Save/i }));
await waitFor(() => {
expect(mock.history.post.length).toBe(1);
});
const body = JSON.parse(mock.history.post[0].data as string) as Record<string, unknown>;
expect(body.name).toBe('My Template');
});
it('shows backend error on name conflict (409)', async () => {
mock.onPost('/simulation-templates').reply(409, { error: 'template name already exists' });
const user = userEvent.setup();
renderNew();
await user.type(screen.getByLabelText(/Name/i), 'Duplicate');
await user.click(screen.getByRole('button', { name: /Save/i }));
await waitFor(() => {
expect(screen.getByText('template name already exists')).toBeInTheDocument();
});
});
it('does not show Delete button in new mode', () => {
renderNew();
expect(screen.queryByText('Delete')).toBeNull();
});
});
describe('TemplateFormPage — edit mode', () => {
let mock: MockAdapter;
beforeEach(() => {
mock = new MockAdapter(apiClient);
});
afterEach(() => {
mock.restore();
});
it('loads existing template data into form', async () => {
mock.onGet('/simulation-templates/5').reply(200, TEMPLATE);
renderEdit(5);
await waitFor(() => {
expect(screen.getByDisplayValue('Mimikatz LSASS Dump')).toBeInTheDocument();
});
expect(screen.getByDisplayValue('Extract NTLM hashes')).toBeInTheDocument();
});
it('shows technique and tactic chips from existing template', async () => {
mock.onGet('/simulation-templates/5').reply(200, TEMPLATE);
renderEdit(5);
await waitFor(() => {
expect(screen.getByTitle('T1003 — OS Credential Dumping')).toBeInTheDocument();
});
expect(screen.getByTitle('TA0006 — Credential Access')).toBeInTheDocument();
});
it('shows Delete button in edit mode', async () => {
mock.onGet('/simulation-templates/5').reply(200, TEMPLATE);
renderEdit(5);
await waitFor(() => {
expect(screen.getByDisplayValue('Mimikatz LSASS Dump')).toBeInTheDocument();
});
expect(screen.getByText('Delete')).toBeInTheDocument();
});
it('submits PATCH on save', async () => {
mock.onGet('/simulation-templates/5').reply(200, TEMPLATE);
mock.onPatch('/simulation-templates/5').reply(200, { ...TEMPLATE, name: 'Updated' });
const user = userEvent.setup();
renderEdit(5);
await waitFor(() => {
expect(screen.getByDisplayValue('Mimikatz LSASS Dump')).toBeInTheDocument();
});
await user.click(screen.getByRole('button', { name: /Save/i }));
await waitFor(() => {
expect(mock.history.patch.length).toBe(1);
});
const body = JSON.parse(mock.history.patch[0].data as string) as Record<string, unknown>;
expect(body.name).toBe('Mimikatz LSASS Dump');
});
it('opens delete confirm dialog and calls DELETE on confirm', async () => {
mock.onGet('/simulation-templates/5').reply(200, TEMPLATE);
mock.onDelete('/simulation-templates/5').reply(204);
const user = userEvent.setup();
renderEdit(5);
await waitFor(() => {
expect(screen.getByText('Delete')).toBeInTheDocument();
});
await user.click(screen.getByText('Delete'));
await waitFor(() => {
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
// Click the Delete button inside the dialog
const dialogDeleteBtn = screen.getAllByText('Delete').find(
(el) => el.tagName === 'BUTTON' && el.closest('[role="dialog"]')
) as HTMLElement;
await user.click(dialogDeleteBtn);
await waitFor(() => {
expect(mock.history.delete.length).toBe(1);
});
});
});

View File

@@ -0,0 +1,151 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MockAdapter from 'axios-mock-adapter';
import { apiClient } from '@/api/client';
import { TemplatePickerModal } from '@/components/TemplatePickerModal';
import { renderWithProviders } from './utils';
import type { SimulationTemplate } from '@/api/types';
const TEMPLATES: SimulationTemplate[] = [
{
id: 1,
name: 'Mimikatz LSASS Dump',
description: null,
commands: null,
prerequisites: null,
techniques: [{ id: 'T1003', name: 'OS Credential Dumping', tactics: [] }],
tactics: [],
created_at: '2026-05-28T00:00:00',
updated_at: null,
created_by: { id: 1, username: 'alice' },
},
{
id: 2,
name: 'PowerShell Empire',
description: null,
commands: null,
prerequisites: null,
techniques: [],
tactics: [{ id: 'TA0002', name: 'Execution' }],
created_at: '2026-05-28T01:00:00',
updated_at: null,
created_by: { id: 1, username: 'alice' },
},
];
const onClose = vi.fn();
const onInstantiated = vi.fn();
const onSelectTemplate = vi.fn();
describe('TemplatePickerModal', () => {
let mock: MockAdapter;
beforeEach(() => {
mock = new MockAdapter(apiClient);
vi.clearAllMocks();
});
afterEach(() => {
mock.restore();
});
it('shows loading state while fetching', () => {
mock.onGet('/simulation-templates').reply(() => new Promise(() => {}));
renderWithProviders(
<TemplatePickerModal
engagementId={1}
onClose={onClose}
onInstantiated={onInstantiated}
onSelectTemplate={onSelectTemplate}
/>
);
expect(screen.getByTestId('loading-state')).toBeInTheDocument();
});
it('shows empty state when no templates', async () => {
mock.onGet('/simulation-templates').reply(200, []);
renderWithProviders(
<TemplatePickerModal
engagementId={1}
onClose={onClose}
onInstantiated={onInstantiated}
onSelectTemplate={onSelectTemplate}
/>
);
await waitFor(() => {
expect(screen.getByTestId('empty-state')).toBeInTheDocument();
});
expect(screen.getByText(/No templates available/i)).toBeInTheDocument();
});
it('lists templates with name and MITRE count', async () => {
mock.onGet('/simulation-templates').reply(200, TEMPLATES);
renderWithProviders(
<TemplatePickerModal
engagementId={1}
onClose={onClose}
onInstantiated={onInstantiated}
onSelectTemplate={onSelectTemplate}
/>
);
await waitFor(() => {
expect(screen.getByTestId('template-picker-table')).toBeInTheDocument();
});
expect(screen.getByText('Mimikatz LSASS Dump')).toBeInTheDocument();
expect(screen.getByText('PowerShell Empire')).toBeInTheDocument();
// T1(1 tech) + 0 tactics = 1 for first, 0 tech + 1 tactic = 1 for second
expect(screen.getAllByText('1').length).toBe(2);
});
it('calls onSelectTemplate when a template row is clicked', async () => {
mock.onGet('/simulation-templates').reply(200, TEMPLATES);
const user = userEvent.setup();
renderWithProviders(
<TemplatePickerModal
engagementId={1}
onClose={onClose}
onInstantiated={onInstantiated}
onSelectTemplate={onSelectTemplate}
/>
);
await waitFor(() => {
expect(screen.getByText('Mimikatz LSASS Dump')).toBeInTheDocument();
});
await user.click(screen.getByTestId('template-row-1'));
expect(onSelectTemplate).toHaveBeenCalledWith(TEMPLATES[0]);
});
it('calls onClose when Cancel is clicked', async () => {
mock.onGet('/simulation-templates').reply(200, TEMPLATES);
const user = userEvent.setup();
renderWithProviders(
<TemplatePickerModal
engagementId={1}
onClose={onClose}
onInstantiated={onInstantiated}
onSelectTemplate={onSelectTemplate}
/>
);
await waitFor(() => {
expect(screen.getByText('Cancel')).toBeInTheDocument();
});
await user.click(screen.getByText('Cancel'));
expect(onClose).toHaveBeenCalledOnce();
});
it('shows error state on fetch failure', async () => {
mock.onGet('/simulation-templates').reply(500, { error: 'Server error' });
renderWithProviders(
<TemplatePickerModal
engagementId={1}
onClose={onClose}
onInstantiated={onInstantiated}
onSelectTemplate={onSelectTemplate}
/>
);
await waitFor(() => {
expect(screen.getByTestId('error-state')).toBeInTheDocument();
});
});
});

View File

@@ -0,0 +1,138 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MockAdapter from 'axios-mock-adapter';
import { apiClient } from '@/api/client';
import { TemplatesListPage } from '@/pages/TemplatesListPage';
import { renderWithProviders } from './utils';
import type { SimulationTemplate } from '@/api/types';
const TEMPLATES: SimulationTemplate[] = [
{
id: 1,
name: 'Mimikatz LSASS Dump',
description: 'Extract NTLM hashes',
commands: 'mimikatz.exe',
prerequisites: 'Local admin',
techniques: [{ id: 'T1003', name: 'OS Credential Dumping', tactics: ['credential-access'] }],
tactics: [{ id: 'TA0006', name: 'Credential Access' }],
created_at: '2026-05-28T00:00:00',
updated_at: null,
created_by: { id: 1, username: 'alice' },
},
{
id: 2,
name: 'PowerShell Empire',
description: null,
commands: null,
prerequisites: null,
techniques: [],
tactics: [],
created_at: '2026-05-28T01:00:00',
updated_at: '2026-05-28T02:00:00',
created_by: { id: 2, username: 'bob' },
},
];
vi.mock('@/hooks/useAuth', () => ({
useAuth: () => ({
user: { id: 1, username: 'alice', role: 'admin', created_at: '2026-01-01' },
status: 'authenticated',
login: vi.fn(),
logout: vi.fn(),
isAdmin: true,
isRedteam: false,
isSoc: false,
canEditEngagements: true,
}),
}));
describe('TemplatesListPage', () => {
let mock: MockAdapter;
beforeEach(() => {
mock = new MockAdapter(apiClient);
});
afterEach(() => {
mock.restore();
});
it('shows loading state initially', () => {
mock.onGet('/simulation-templates').reply(() => new Promise(() => {}));
renderWithProviders(<TemplatesListPage />);
expect(screen.getByTestId('loading-state')).toBeInTheDocument();
});
it('shows error state on failure', async () => {
mock.onGet('/simulation-templates').reply(500, { error: 'Server error' });
renderWithProviders(<TemplatesListPage />);
await waitFor(() => {
expect(screen.getByTestId('error-state')).toBeInTheDocument();
});
});
it('shows empty state when no templates', async () => {
mock.onGet('/simulation-templates').reply(200, []);
renderWithProviders(<TemplatesListPage />);
await waitFor(() => {
expect(screen.getByTestId('empty-state')).toBeInTheDocument();
});
});
it('renders template list with name, MITRE count, created by', async () => {
mock.onGet('/simulation-templates').reply(200, TEMPLATES);
renderWithProviders(<TemplatesListPage />);
await waitFor(() => {
expect(screen.getByText('Mimikatz LSASS Dump')).toBeInTheDocument();
});
expect(screen.getByText('PowerShell Empire')).toBeInTheDocument();
// MITRE count: techniques(1) + tactics(1) = 2 for first template
expect(screen.getByText('2')).toBeInTheDocument();
// Second template: 0 — shown as —
expect(screen.getAllByText('—').length).toBeGreaterThan(0);
expect(screen.getByText('alice')).toBeInTheDocument();
});
it('shows New button', async () => {
mock.onGet('/simulation-templates').reply(200, TEMPLATES);
renderWithProviders(<TemplatesListPage />);
await waitFor(() => {
expect(screen.getByText('Mimikatz LSASS Dump')).toBeInTheDocument();
});
expect(screen.getAllByText(/New/i).length).toBeGreaterThan(0);
});
it('shows Edit and Delete actions', async () => {
mock.onGet('/simulation-templates').reply(200, TEMPLATES);
renderWithProviders(<TemplatesListPage />);
await waitFor(() => {
expect(screen.getByText('Mimikatz LSASS Dump')).toBeInTheDocument();
});
expect(screen.getAllByText('Edit').length).toBe(2);
expect(screen.getAllByText('Delete').length).toBe(2);
});
it('calls delete endpoint on confirm', async () => {
mock.onGet('/simulation-templates').reply(200, TEMPLATES);
mock.onDelete('/simulation-templates/1').reply(204);
// After delete, refetch returns updated list
mock.onGet('/simulation-templates').reply(200, [TEMPLATES[1]]);
const user = userEvent.setup();
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
renderWithProviders(<TemplatesListPage />);
await waitFor(() => {
expect(screen.getAllByText('Delete')[0]).toBeInTheDocument();
});
const deleteButtons = screen.getAllByText('Delete');
await user.click(deleteButtons[0]);
await waitFor(() => {
expect(mock.history.delete.length).toBe(1);
});
confirmSpy.mockRestore();
});
});