Files
faunosteo/apps/app/tests/unit/components.SecurityPanel.test.tsx
T
bchanot 51225cacf6 fix(app): grant expiry ends the chosen day in Paris; species order 0..9999 (V1-2.5 L2)
Owner checkpoint 2026-11-02: expiry 23:59:59.999 Europe/Paris (picker, validation, display), tests under non-Paris zones and DST days; M7 redefines create_species and update_inactive_species with the range check; pgTAP 015 and 022; « Relecteur ou relectrice »; object_conflict EN; setup key selectable, no Copy.
2026-11-02 21:29:33 +01:00

218 lines
10 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } 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 SecurityPanel from '@/components/account/SecurityPanel'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
const QR = 'data:image/svg+xml;utf-8,%3Csvg%3E%3C/svg%3E'
const SECRET = 'JBSWY3DPEHPK3PXP'
const AAL_REFUSED = { name: 'AuthApiError', code: 'insufficient_aal', status: 403, message: 'raw' }
let fake: FakeSupabase
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
useAuthStore.setState({ status: 'signed_in', user: fakeUser() })
fake.auth.mfa.enroll.mockResolvedValue({
data: { id: 'new-1', type: 'totp', friendly_name: 'Laptop', totp: { qr_code: QR, secret: SECRET, uri: 'otpauth://x' } },
error: null,
})
})
afterEach(cleanup)
function mount() {
return render(
<MemoryRouter>
<SecurityPanel />
</MemoryRouter>,
)
}
function factorList() {
return screen.getByRole('list', { name: fr['mfa.factor.list_label'] })
}
async function startEnrolment(user: ReturnType<typeof userEvent.setup>, name = 'Laptop') {
await user.click(await screen.findByRole('button', { name: fr['mfa.enrol.start'] }))
await user.type(screen.getByLabelText(fr['mfa.enrol.name']), name)
await user.click(screen.getByRole('button', { name: fr['mfa.enrol.continue'] }))
}
describe('Security, factors', () => {
it('lists verified and unverified factors with their state and date', async () => {
setMfa(fake, [
fakeFactor({ id: 'f-1', friendly_name: 'Phone' }),
fakeFactor({ id: 'f-2', friendly_name: '', status: 'unverified' }),
])
mount()
await screen.findByText('Phone')
const rows = within(factorList()).getAllByRole('listitem')
expect(rows).toHaveLength(2)
expect(rows[0]).toHaveTextContent(fr['mfa.factor.verified'])
expect(rows[0]).toHaveTextContent(new Date('2026-11-01T10:00:00Z').toLocaleDateString('fr'))
expect(rows[1]).toHaveTextContent(fr['mfa.factor.unnamed'])
expect(rows[1]).toHaveTextContent(fr['mfa.factor.unverified'])
expect(screen.queryByText(fr['mfa.factor.none'])).toBeNull()
})
it('enrols: name, QR code as an image, secret once, then the code verifies it', async () => {
const user = userEvent.setup()
mount()
expect(await screen.findByText(fr['mfa.factor.none'])).toBeInTheDocument()
await startEnrolment(user)
expect(fake.auth.mfa.enroll).toHaveBeenCalledWith({ factorType: 'totp', friendlyName: 'Laptop' })
const qr = await screen.findByRole('img', { name: fr['mfa.enrol.qr_alt'] })
expect(qr).toHaveAttribute('src', QR)
expect(screen.getByText(SECRET)).toBeInTheDocument()
setMfa(fake, [fakeFactor({ id: 'new-1', friendly_name: 'Laptop' })], 'aal2')
await user.type(screen.getByLabelText(fr['mfa.code.label']), '123456')
await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] }))
expect(fake.auth.mfa.challengeAndVerify).toHaveBeenCalledWith({ factorId: 'new-1', code: '123456' })
expect(await screen.findByText(fr['mfa.enrol.done'])).toBeInTheDocument()
expect(screen.queryByText(SECRET)).toBeNull()
expect(screen.queryByRole('img', { name: fr['mfa.enrol.qr_alt'] })).toBeNull()
expect(within(factorList()).getByText('Laptop')).toBeInTheDocument()
expect(fake.auth.mfa.unenroll).not.toHaveBeenCalled()
expect(JSON.stringify(useAuthStore.getState())).not.toContain(SECRET)
})
it('shows the setup key in full as selectable text, with no Copy button', async () => {
const user = userEvent.setup()
mount()
await startEnrolment(user)
const key = await screen.findByText(SECRET)
expect(key.textContent).toBe(SECRET)
expect(key.className).not.toMatch(/select-none/)
expect((key as HTMLElement).style.userSelect).not.toBe('none')
expect(screen.queryByRole('button', { name: /cop(y|ier)/i })).toBeNull()
})
it('cancel removes the unverified factor it created and clears the secret', async () => {
const user = userEvent.setup()
mount()
await startEnrolment(user)
await screen.findByText(SECRET)
await user.click(screen.getByRole('button', { name: fr['common.cancel'] }))
expect(fake.auth.mfa.unenroll).toHaveBeenCalledWith({ factorId: 'new-1' })
expect(screen.queryByText(SECRET)).toBeNull()
expect(await screen.findByRole('button', { name: fr['mfa.enrol.start'] })).toBeInTheDocument()
})
it('leaving the page mid-enrolment removes the unverified factor', async () => {
const user = userEvent.setup()
const view = mount()
await startEnrolment(user)
await screen.findByText(SECRET)
view.unmount()
expect(fake.auth.mfa.unenroll).toHaveBeenCalledWith({ factorId: 'new-1' })
})
it('refuses an empty name without calling GoTrue', async () => {
const user = userEvent.setup()
mount()
await user.click(await screen.findByRole('button', { name: fr['mfa.enrol.start'] }))
await user.click(screen.getByRole('button', { name: fr['mfa.enrol.continue'] }))
expect(screen.getByText(fr['mfa.error.name_required'])).toBeInTheDocument()
expect(fake.auth.mfa.enroll).not.toHaveBeenCalled()
})
it('refuses a 65-character name without calling GoTrue, accepts 64', async () => {
const user = userEvent.setup()
mount()
await user.click(await screen.findByRole('button', { name: fr['mfa.enrol.start'] }))
const field = screen.getByLabelText(fr['mfa.enrol.name'])
await user.type(field, 'a'.repeat(65))
await user.click(screen.getByRole('button', { name: fr['mfa.enrol.continue'] }))
expect(screen.getByText(fr['mfa.error.name_too_long'].replace('{max}', '64'))).toBeInTheDocument()
expect(fake.auth.mfa.enroll).not.toHaveBeenCalled()
await user.clear(field)
await user.type(field, 'b'.repeat(64))
await user.click(screen.getByRole('button', { name: fr['mfa.enrol.continue'] }))
expect(fake.auth.mfa.enroll).toHaveBeenCalledWith({ factorType: 'totp', friendlyName: 'b'.repeat(64) })
})
it('a second factor at aal1 steps up first, then enrols again', async () => {
const user = userEvent.setup()
setMfa(fake, [fakeFactor({ id: 'f-1' })])
fake.auth.mfa.enroll.mockResolvedValueOnce({ data: null, error: AAL_REFUSED })
mount()
await startEnrolment(user)
expect(await screen.findByText(fr['mfa.step_up.required'])).toBeInTheDocument()
await user.type(screen.getByLabelText(fr['mfa.code.label']), '654321')
await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] }))
expect(fake.auth.mfa.challengeAndVerify).toHaveBeenCalledWith({ factorId: 'f-1', code: '654321' })
expect(await screen.findByText(SECRET)).toBeInTheDocument()
expect(fake.auth.mfa.enroll).toHaveBeenCalledTimes(2)
})
it('removes a factor after the confirmation', async () => {
const user = userEvent.setup()
setMfa(fake, [fakeFactor({ id: 'f-1', friendly_name: 'Phone', status: 'unverified' })])
mount()
await user.click(await screen.findByRole('button', { name: fr['mfa.factor.remove'] }))
const dialog = await screen.findByRole('dialog', { name: fr['mfa.remove.title'] })
expect(dialog).toHaveTextContent('Phone')
expect(fake.auth.mfa.unenroll).not.toHaveBeenCalled()
setMfa(fake, [])
await user.click(within(dialog).getByRole('button', { name: fr['mfa.remove.confirm'] }))
expect(fake.auth.mfa.unenroll).toHaveBeenCalledWith({ factorId: 'f-1' })
expect(await screen.findByText(fr['mfa.factor.removed'])).toBeInTheDocument()
expect(await screen.findByText(fr['mfa.factor.none'])).toBeInTheDocument()
})
it('removing a verified factor at aal1 explains aal2, steps up in place, then removes it', async () => {
const user = userEvent.setup()
setMfa(fake, [fakeFactor({ id: 'f-1', friendly_name: 'Phone' })])
fake.auth.mfa.unenroll.mockResolvedValueOnce({ data: null, error: { ...AAL_REFUSED, status: 422 } })
mount()
await user.click(await screen.findByRole('button', { name: fr['mfa.factor.remove'] }))
const dialog = await screen.findByRole('dialog', { name: fr['mfa.remove.title'] })
await user.click(within(dialog).getByRole('button', { name: fr['mfa.remove.confirm'] }))
expect(await screen.findByText(fr['mfa.step_up.required'])).toBeInTheDocument()
await user.type(screen.getByLabelText(fr['mfa.code.label']), '111111')
await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] }))
await waitFor(() => expect(fake.auth.mfa.unenroll).toHaveBeenCalledTimes(2))
expect(await screen.findByText(fr['mfa.factor.removed'])).toBeInTheDocument()
})
})
describe('Security, password', () => {
it('steps up when GoTrue wants aal2 for the password, then sends it again', async () => {
const user = userEvent.setup()
setMfa(fake, [fakeFactor({ id: 'f-1' })])
fake.auth.updateUser
.mockResolvedValueOnce({ data: null, error: { ...AAL_REFUSED, status: 401 } })
.mockResolvedValueOnce({ data: {}, error: null })
mount()
await user.type(screen.getByLabelText(fr['account.security.new_password']), 'CorrectHorse12')
await user.type(screen.getByLabelText(fr['auth.password_confirm']), 'CorrectHorse12')
await user.click(screen.getByRole('button', { name: fr['account.security.change_password'] }))
expect(await screen.findByText(fr['mfa.step_up.required'])).toBeInTheDocument()
await user.type(screen.getByLabelText(fr['mfa.code.label']), '222222')
await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] }))
expect(await screen.findByText(fr['account.security.password_changed'])).toBeInTheDocument()
expect(fake.auth.updateUser).toHaveBeenCalledTimes(2)
expect(fake.auth.updateUser).toHaveBeenLastCalledWith({ password: 'CorrectHorse12' })
})
})