Files
faunosteo/apps/app/tests/unit/guards.RequireAdmin.test.tsx
T
bchanot 4744e28986 feat(app): admin and catalogue entries, step-up guard, MFA in Mon compte (V1-2.5 E, F)
Nav hint from own grants and roles (never a control); RequireCatalog, RequireAdmin (no admin read before aal2), Accès non autorisé page, placeholder routes; TOTP factor list, enrolment with QR and one-time secret, removal, inline step-up for aal2 actions, step-up in password reset; auth kind aal2_required. App 601, e2e:ui 227.
2026-11-02 16:49:37 +01:00

179 lines
7.2 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import {
createFakeSupabase,
fakeFactor,
fakeUser,
setMfa,
type FakeSupabase,
} from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import RequireAdmin from '@/app/guards/RequireAdmin'
import RequireAuth from '@/app/guards/RequireAuth'
import RequireCatalog from '@/app/guards/RequireCatalog'
import AccessDenied from '@/components/shell/AccessDenied'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
let fake: FakeSupabase
/** Stands for an admin page: it would request admin data as soon as it renders. */
const adminFetch = vi.fn()
function AdminPage() {
adminFetch()
return <p>admin page</p>
}
function mount(path = '/app/admin') {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/login" element={<p>login page</p>} />
<Route path="/app" element={<RequireAuth />}>
<Route index element={<p>dashboard page</p>} />
<Route path="account" element={<p>account page</p>} />
<Route path="admin" element={<RequireAdmin />}>
<Route index element={<AdminPage />} />
</Route>
<Route path="anatomy" element={<RequireCatalog />}>
<Route index element={<AccessDenied />} />
</Route>
</Route>
</Routes>
</MemoryRouter>,
)
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
adminFetch.mockClear()
useAuthStore.setState({ status: 'signed_in', user: fakeUser(), roles: [], catalogGrants: [] })
})
afterEach(cleanup)
describe('RequireAdmin', () => {
it('renders the admin pages at once on an aal2 session', async () => {
setMfa(fake, [fakeFactor()], 'aal2')
mount()
expect(await screen.findByText('admin page')).toBeInTheDocument()
})
it('asks for a code at aal1 with a verified factor, and requests nothing before it succeeds', async () => {
const user = userEvent.setup()
setMfa(fake, [fakeFactor({ id: 'f-1' })], 'aal1')
mount()
expect(await screen.findByRole('heading', { name: fr['admin.step_up.title'] })).toBeInTheDocument()
expect(adminFetch).not.toHaveBeenCalled()
await user.type(screen.getByLabelText(fr['mfa.code.label']), '12')
await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] }))
expect(await screen.findByText(fr['mfa.error.code_format'])).toBeInTheDocument()
expect(fake.auth.mfa.challengeAndVerify).not.toHaveBeenCalled()
fake.auth.mfa.challengeAndVerify.mockImplementationOnce(async () => {
setMfa(fake, [fakeFactor({ id: 'f-1' })], 'aal2')
return { data: {}, error: null }
})
await user.clear(screen.getByLabelText(fr['mfa.code.label']))
await user.type(screen.getByLabelText(fr['mfa.code.label']), '123 456')
await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] }))
expect(fake.auth.mfa.challengeAndVerify).toHaveBeenCalledWith({ factorId: 'f-1', code: '123456' })
expect(await screen.findByText('admin page')).toBeInTheDocument()
expect(adminFetch).toHaveBeenCalled()
})
it('phrases a refused code and stays on the challenge', async () => {
const user = userEvent.setup()
setMfa(fake, [fakeFactor()], 'aal1')
fake.auth.mfa.challengeAndVerify.mockResolvedValueOnce({
data: null,
error: { name: 'AuthApiError', code: 'mfa_verification_failed', status: 422, message: 'raw' },
})
mount()
await user.type(await screen.findByLabelText(fr['mfa.code.label']), '000000')
await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] }))
expect(await screen.findByText(fr['mfa.failure.invalid_code'])).toBeInTheDocument()
expect(screen.queryByText('raw')).toBeNull()
expect(adminFetch).not.toHaveBeenCalled()
})
it('offers a choice of factor when the account has several verified ones', async () => {
setMfa(fake, [
fakeFactor({ id: 'f-1', friendly_name: 'Phone' }),
fakeFactor({ id: 'f-2', friendly_name: 'Tablet' }),
fakeFactor({ id: 'f-3', friendly_name: 'Old', status: 'unverified' }),
])
mount()
const select = await screen.findByLabelText(fr['mfa.step_up.factor'])
expect(Array.from((select as HTMLSelectElement).options).map((o) => o.text)).toEqual([
'Phone',
'Tablet',
])
})
it('sends an account without a verified factor to Mon compte, Sécurité', async () => {
setMfa(fake, [fakeFactor({ status: 'unverified' })], 'aal1')
mount()
expect(await screen.findByText(fr['admin.step_up.no_factor'])).toBeInTheDocument()
expect(screen.getByRole('link', { name: fr['admin.step_up.to_security'] })).toHaveAttribute(
'href',
'/app/account#security-title',
)
expect(screen.queryByLabelText(fr['mfa.code.label'])).toBeNull()
expect(adminFetch).not.toHaveBeenCalled()
})
it('says when the level cannot be read, then reads it again', async () => {
const user = userEvent.setup()
setMfa(fake, [fakeFactor()], 'aal2')
fake.auth.mfa.getAuthenticatorAssuranceLevel.mockResolvedValueOnce({
data: null,
error: { name: 'AuthRetryableFetchError', status: 0, message: 'raw' },
})
mount()
expect(await screen.findByText(fr['mfa.failure.network'])).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: fr['common.retry'] }))
expect(await screen.findByText('admin page')).toBeInTheDocument()
})
it('sends a signed-out visitor to the login page', () => {
useAuthStore.setState({ status: 'signed_out', user: null })
mount()
expect(screen.getByText('login page')).toBeInTheDocument()
expect(fake.auth.mfa.getAuthenticatorAssuranceLevel).not.toHaveBeenCalled()
})
})
describe('Accès non autorisé', () => {
it('names the refusal, echoes nothing from the address and leads back to /app', async () => {
const user = userEvent.setup()
mount('/app/anatomy?sheet=secret-id')
const heading = screen.getByRole('heading', { name: fr['access_denied.title'] })
expect(heading).toHaveFocus()
expect(screen.getByText(fr['access_denied.body'])).toBeInTheDocument()
expect(document.body).not.toHaveTextContent('secret-id')
await user.click(screen.getByRole('link', { name: fr['access_denied.back'] }))
expect(await screen.findByText('dashboard page')).toBeInTheDocument()
})
it('reads in English', () => {
useLocaleStore.setState({ locale: 'en' })
mount('/app/anatomy')
expect(screen.getByRole('heading', { name: en['access_denied.title'] })).toBeInTheDocument()
expect(screen.getByText("You don't have permission to access this page.")).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Back to dashboard' })).toHaveAttribute('href', '/app')
})
})