Files
mimic/frontend/tests/UsersAdminPage.test.tsx

107 lines
3.9 KiB
TypeScript
Raw Normal View History

feat: sprint 1 — auth + CRUD engagements Ship the first feature end-to-end on the UI: users log in with JWT, admins manage user accounts, and any authenticated user (per RBAC) can create, list, view, edit, and delete engagements. Backend (Flask + SQLAlchemy + SQLite, 63 pytest) - User / Engagement models, Alembic 0001 initial schema - argon2 password hashing, JWT bearer (60-min TTL), @login_required and @role_required decorators - 13 API endpoints under /api/*, including last-admin protection on DELETE/PATCH user and JSON 404 on unknown /api/* paths - `flask create-admin` CLI with duplicate / short-password handling Frontend (React + Vite + Tailwind + TanStack Query, 20 vitest) - Inter font bundled locally (no CDN), DESIGN.md tokens in Tailwind - LoginPage / EngagementsList / EngagementForm / EngagementDetail / UsersAdmin pages with role-aware UI - Layout, ProtectedRoute, StatusBadge, FormField, LoadingState, ErrorState, EmptyState, Toast + provider - Axios client: Bearer interceptor, 401 → purge + /login + "Session expirée" toast, 403 → "Accès refusé" toast (declarative <Navigate> for already-authed users, Fragment-keyed admin user rows) Deployment - Single multistage Dockerfile (node:20-alpine → python:3.12-slim) - docker/entrypoint.sh runs `flask db upgrade` before `flask run` - Makefile: build/start/stop/restart/update/logs/create-admin/ update-mitre/test-{backend,frontend,e2e}/clean - .env.example documenting MIMIC_JWT_SECRET / MIMIC_DB_PATH / MIMIC_PORT - SQLite at /data/mimic.sqlite on named volume mimic-data Acceptance suite (Playwright, 36 tests, all 27 ACs) - e2e/ scaffold with playwright.config + auth/api fixtures - One spec per user story (us1-bootstrap through us6-deployment) - Portable via MIMIC_CONTAINER_CMD / MIMIC_BASE_URL (docker or podman) Docs - README.md with quick-start and architecture overview - CHANGELOG.md updated with Sprint 1 deliverables - pyrightconfig.json so the Python LSP sees backend/.venv and resolves the `backend.app.*` absolute imports Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 09:37:53 +02:00
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MockAdapter from 'axios-mock-adapter';
import { apiClient } from '@/api/client';
import { UsersAdminPage } from '@/pages/UsersAdminPage';
import { renderWithProviders } from './utils';
import type { User } from '@/api/types';
// Mock useAuth so the page sees a logged-in admin without hydrating from network.
vi.mock('@/hooks/useAuth', () => ({
useAuth: () => ({
user: { id: 1, username: 'alice', role: 'admin', created_at: '2026-01-01' } as User,
status: 'authenticated',
login: vi.fn(),
logout: vi.fn(),
isAdmin: true,
isRedteam: false,
isSoc: false,
canEditEngagements: true,
}),
}));
const USERS: User[] = [
{ id: 1, username: 'alice', role: 'admin', created_at: '2026-01-01' },
{ id: 2, username: 'bob', role: 'redteam', created_at: '2026-02-01' },
{ id: 3, username: 'carol', role: 'soc', created_at: '2026-03-01' },
];
describe('UsersAdminPage', () => {
let mock: MockAdapter;
beforeEach(() => {
mock = new MockAdapter(apiClient);
mock.onGet('/users').reply(200, USERS);
});
afterEach(() => {
mock.restore();
});
it('renders the list of users from the API', async () => {
renderWithProviders(<UsersAdminPage />);
expect(await screen.findByText('alice')).toBeInTheDocument();
expect(screen.getByText('bob')).toBeInTheDocument();
expect(screen.getByText('carol')).toBeInTheDocument();
});
it('creates a user via POST /users and refreshes the list', async () => {
const newUser: User = { id: 4, username: 'dan', role: 'soc', created_at: '2026-04-01' };
const postSpy = vi.fn().mockReturnValue([201, newUser]);
mock.onPost('/users').reply((config) => postSpy(JSON.parse(config.data)));
const user = userEvent.setup();
renderWithProviders(<UsersAdminPage />);
await screen.findByText('alice');
await user.type(screen.getByLabelText(/^username/i), 'dan');
await user.type(screen.getByLabelText(/^password/i), 'sup3rs4fe!');
// role default is 'redteam'; switch to 'soc' to match newUser
await user.selectOptions(screen.getByLabelText(/^role/i), 'soc');
// After POST, hooks invalidate and the list refetches → return the new list
mock.onGet('/users').reply(200, [...USERS, newUser]);
await user.click(screen.getByRole('button', { name: /^create$/i }));
await waitFor(() => {
expect(postSpy).toHaveBeenCalledWith({
username: 'dan',
password: 'sup3rs4fe!',
role: 'soc',
});
});
expect(await screen.findByText('dan')).toBeInTheDocument();
});
it('opens the password reset form for the row that was clicked (fragment-key regression guard)', async () => {
const user = userEvent.setup();
renderWithProviders(<UsersAdminPage />);
await screen.findByText('bob');
// The "Reset password" button for bob lives in bob's row.
const bobRow = screen.getByText('bob').closest('tr');
expect(bobRow).not.toBeNull();
await user.click(within(bobRow as HTMLElement).getByRole('button', { name: /reset password/i }));
// The reset form for bob (and bob only) must appear.
expect(await screen.findByLabelText(/new password for bob/i)).toBeInTheDocument();
expect(screen.queryByLabelText(/new password for carol/i)).toBeNull();
expect(screen.queryByLabelText(/new password for alice/i)).toBeNull();
});
it('disables the delete button on the current user own row', async () => {
renderWithProviders(<UsersAdminPage />);
await screen.findByText('alice');
const aliceRow = screen.getByText('alice').closest('tr') as HTMLElement;
const bobRow = screen.getByText('bob').closest('tr') as HTMLElement;
expect(within(aliceRow).getByRole('button', { name: /delete/i })).toBeDisabled();
expect(within(bobRow).getByRole('button', { name: /delete/i })).toBeEnabled();
});
});