feat(admin-ui): RequireAuth gate + RTL component тесты

RequireAuth: гейтит весь UI по аутентификации. Anonymous юзер вместо
красного "AxiosError 401" получает immediate signinRedirect на Keycloak;
authenticated юзер с истёкшим токеном получает silent renew → fallback на
full redirect. Guards против infinite loop:
- auth.isLoading / activeNavigator — bootstrap или signin/signout уже идёт
- ?error= в URL — вернулись с провалом из Keycloak, показываем сообщение
- auth.error без isAuthenticated — Keycloak недоступен, показываем сообщение

main.tsx: RequireAuth обёрнут вокруг Router/Query, чтобы tan-stack-router и
React Query не делали запросов до auth (иначе 401-каскад на старте).

TokenSync: 401 interceptor теперь редиректит и anonymous (раньше срабатывал
только для authenticated с истёкшим токеном), с теми же guards.

RTL component тесты — 22 теста на 3 ключевых компонента:
- SchemaBuilder (7): empty state, add/remove/reorder properties
- PropertyEditor (10): kind change, required/unique toggle, kind-specific
  поля (string→pattern, integer→min/max, enum→values, array_string→uniqueItems),
  move up/down disabled на boundaries
- SchemaDrivenForm (5): identity tab с required, переключение на extra,
  isPending → save disabled, cancel callback, serverError → Alert

Setup:
- vite.config.ts: test block (jsdom env, setup file, css off)
- src/test/setup.ts: jest-dom matchers, cleanup, HTMLCanvasElement.getContext
  stub (lottie-web из @nstart/ui крашит в jsdom без canvas)
- src/test/render.tsx: renderWithI18n helper, форсит ru-RU
  (LanguageDetector в node по умолчанию даёт en-US)

Deps: +@testing-library/react +@testing-library/jest-dom
+@testing-library/user-event +jsdom
This commit is contained in:
Zimin A.N.
2026-05-06 00:11:07 +03:00
parent 01cca3a6f4
commit ab6f6cb860
11 changed files with 1098 additions and 11 deletions
+79
View File
@@ -0,0 +1,79 @@
import { useEffect, type ReactNode } from 'react'
import { useAuth } from 'react-oidc-context'
/**
* Гейтит всё содержимое приложения по аутентификации. Если юзер не залогинен —
* сразу редиректим на Keycloak (без промежуточной страницы "Вы не авторизованы"
* и без красного 401 от axios). Пока auth state ещё определяется — показываем
* нейтральный spinner.
*
* Сценарии:
* - First visit, нет токена → signinRedirect → Keycloak login → redirect_uri →
* onSigninCallback чистит URL → дети рендерятся.
* - Истёк access_token, silent renew не успел → 401 от backend ловится в
* {@link TokenSync} interceptor, который дёргает signinSilent/signinRedirect.
* - Возврат с ошибкой OIDC (?error=access_denied) → не редиректим в цикле,
* показываем сообщение.
*/
export function RequireAuth({ children }: { children: ReactNode }) {
const auth = useAuth()
const oidcError =
typeof window !== 'undefined' &&
new URLSearchParams(window.location.search).get('error')
useEffect(() => {
if (oidcError) return
if (auth.isLoading || auth.activeNavigator) return
if (auth.isAuthenticated) return
auth.signinRedirect().catch((err) => {
// Не уйти на signinRedirect = Keycloak недоступен. Логируем, дальше
// покажем сообщение об ошибке (auth.error будет выставлен).
console.error('[auth] signinRedirect failed', err)
})
}, [auth.isAuthenticated, auth.isLoading, auth.activeNavigator, oidcError])
if (oidcError) {
return (
<div className="min-h-screen flex items-center justify-center p-8">
<div className="max-w-md text-center space-y-2">
<h1 className="text-lg font-primary">Ошибка входа</h1>
<p className="text-sm text-carbon/70">
Keycloak вернул ошибку:{' '}
<code className="font-mono">{oidcError}</code>
</p>
<button
type="button"
className="mt-4 inline-flex items-center justify-center rounded-sm border border-ultramarain text-ultramarain px-4 py-2 text-sm hover:bg-orbit"
onClick={() => {
window.location.href = '/'
}}
>
Попробовать снова
</button>
</div>
</div>
)
}
if (auth.error && !auth.isAuthenticated) {
return (
<div className="min-h-screen flex items-center justify-center p-8">
<div className="max-w-md text-center space-y-2">
<h1 className="text-lg font-primary">Не удалось подключиться к авторизации</h1>
<p className="text-sm text-carbon/70">{auth.error.message}</p>
</div>
</div>
)
}
if (!auth.isAuthenticated) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-sm text-carbon/60 font-secondary">Перенаправление на вход</div>
</div>
)
}
return <>{children}</>
}
+16 -2
View File
@@ -24,13 +24,27 @@ export function TokenSync() {
}
}, [auth.user?.access_token])
// Авто-логин на 401 — токен мог истечь и silent renew не успел.
// 401 → автоматический редирект на Keycloak login. Покрывает два случая:
// 1. anonymous пользователь открыл UI (нет токена вовсе) — сразу на логин
// вместо красного "AxiosError 401".
// 2. authenticated юзер у которого истёк access_token и silent renew не
// успел — пробуем silent, если не вышло — full redirect.
// Guard против infinite loop: не редиректим пока auth.isLoading (initial OIDC
// bootstrap), пока activeNavigator (signin/signout уже идёт), и если url
// содержит ?error= (вернулись с провалом из Keycloak — даём UI показать ошибку).
useEffect(() => {
const id = apiClient.interceptors.response.use(
(r) => r,
(err) => {
if (err.response?.status === 401 && auth.isAuthenticated) {
if (err.response?.status !== 401) return Promise.reject(err)
if (auth.isLoading || auth.activeNavigator) return Promise.reject(err)
if (typeof window !== 'undefined' && window.location.search.includes('error=')) {
return Promise.reject(err)
}
if (auth.isAuthenticated) {
auth.signinSilent().catch(() => auth.signinRedirect())
} else {
auth.signinRedirect()
}
return Promise.reject(err)
},
@@ -0,0 +1,110 @@
import { describe, it, expect, vi } from 'vitest'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithI18n } from '@/test/render'
import { SchemaDrivenForm } from './SchemaDrivenForm'
import type { JsonSchema } from '@/api/client'
const minimalSchema: JsonSchema = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
additionalProperties: false,
required: ['code', 'name'],
'x-id-source': 'code',
properties: {
code: { type: 'string', minLength: 1, 'x-unique': true },
name: { type: 'string', minLength: 1 },
description: { type: 'string' },
},
} as JsonSchema
describe('SchemaDrivenForm', () => {
it('рендерит идентификационный таб с required-полями', () => {
renderWithI18n(
<SchemaDrivenForm
schema={minimalSchema}
supportedLocales={['ru-RU', 'en-US']}
defaultLocale="ru-RU"
mode="create"
isPending={false}
onSubmit={() => {}}
onCancel={() => {}}
/>,
)
// x-id-source: 'code' → бизнес-ключ автогенерится, показывается hint
expect(screen.getByText(/Бизнес-ключ создастся автоматически/)).toBeInTheDocument()
// Required-поля code/name на табе "Идентификация". i18n field.code=Код,
// field.name=Наименование (см. src/i18n.ts).
expect(screen.getByText('Код')).toBeInTheDocument()
expect(screen.getByText('Наименование')).toBeInTheDocument()
})
it('переключение на таб "Дополнительно" показывает optional поля', async () => {
const user = userEvent.setup()
renderWithI18n(
<SchemaDrivenForm
schema={minimalSchema}
supportedLocales={['ru-RU']}
defaultLocale="ru-RU"
mode="create"
isPending={false}
onSubmit={() => {}}
onCancel={() => {}}
/>,
)
// @nstart/ui Tabs использует role="button" не "tab".
await user.click(screen.getByRole('button', { name: /Дополнительно/i }))
// description (optional) теперь виден. i18n field.description=Описание.
expect(screen.getByText('Описание')).toBeInTheDocument()
})
it('disabled Save кнопка пока isPending', () => {
renderWithI18n(
<SchemaDrivenForm
schema={minimalSchema}
supportedLocales={['ru-RU']}
defaultLocale="ru-RU"
mode="create"
isPending={true}
onSubmit={() => {}}
onCancel={() => {}}
/>,
)
const saveBtn = screen.getByRole('button', { name: /Сохранение/i })
expect(saveBtn).toBeDisabled()
})
it('Cancel вызывает onCancel', async () => {
const user = userEvent.setup()
const onCancel = vi.fn()
renderWithI18n(
<SchemaDrivenForm
schema={minimalSchema}
supportedLocales={['ru-RU']}
defaultLocale="ru-RU"
mode="create"
isPending={false}
onSubmit={() => {}}
onCancel={onCancel}
/>,
)
await user.click(screen.getByRole('button', { name: 'Отмена' }))
expect(onCancel).toHaveBeenCalledTimes(1)
})
it('serverError рендерится как Alert', () => {
renderWithI18n(
<SchemaDrivenForm
schema={minimalSchema}
supportedLocales={['ru-RU']}
defaultLocale="ru-RU"
mode="create"
isPending={false}
serverError="Дубликат business_key"
onSubmit={() => {}}
onCancel={() => {}}
/>,
)
expect(screen.getByText('Дубликат business_key')).toBeInTheDocument()
})
})
@@ -0,0 +1,194 @@
import { describe, it, expect, vi } from 'vitest'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithI18n } from '@/test/render'
import { PropertyEditor } from './PropertyEditor'
import type { PropertyDef } from './types'
const baseProp = (overrides: Partial<PropertyDef> = {}): PropertyDef => ({
id: 'prop-1',
name: 'designator',
kind: 'string',
required: false,
unique: false,
...overrides,
})
describe('PropertyEditor', () => {
it('меняет name при вводе → onChange с обновлённым name', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
renderWithI18n(
<PropertyEditor
prop={baseProp({ name: '' })}
index={0}
total={1}
onChange={onChange}
onRemove={() => {}}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
// @nstart/ui TextInput не биндит label через for/id — ищем по placeholder.
const nameInput = screen.getByPlaceholderText('snake_case_key') as HTMLInputElement
await user.type(nameInput, 'n')
// Controlled — value не обновляется без re-render с новым prop, поэтому
// достаточно проверить что onChange выстрелил с ожидаемым name.
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ name: 'n' }))
})
it('toggle required чекбокса → onChange c required:true', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
renderWithI18n(
<PropertyEditor
prop={baseProp({ required: false })}
index={0}
total={1}
onChange={onChange}
onRemove={() => {}}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
await user.click(screen.getByLabelText('Обязательное'))
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ required: true }))
})
it('toggle unique → onChange c unique:true', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
renderWithI18n(
<PropertyEditor
prop={baseProp({ unique: false })}
index={0}
total={1}
onChange={onChange}
onRemove={() => {}}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
// У Checkbox label включает description "Дубликаты по этому полю запрещены"
// — getByLabelText использует match на полный текст label элемента.
await user.click(screen.getByLabelText(/Уникальное/))
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ unique: true }))
})
it('для kind=string показывает minLength/maxLength/pattern', () => {
renderWithI18n(
<PropertyEditor
prop={baseProp({ kind: 'string' })}
index={0}
total={1}
onChange={() => {}}
onRemove={() => {}}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
// @nstart/ui TextInput не биндит label через for/id — проверяем по
// visible-тексту labels.
expect(screen.getByText('minLength')).toBeInTheDocument()
expect(screen.getByText('maxLength')).toBeInTheDocument()
expect(screen.getByText('Pattern (regex)')).toBeInTheDocument()
// Pattern имеет уникальный placeholder — проверяем что input реально есть.
expect(screen.getByPlaceholderText('^[A-Z]{2}$')).toBeInTheDocument()
})
it('для kind=integer показывает minimum/maximum (не string-поля)', () => {
renderWithI18n(
<PropertyEditor
prop={baseProp({ kind: 'integer' })}
index={0}
total={1}
onChange={() => {}}
onRemove={() => {}}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
expect(screen.getByText('minimum')).toBeInTheDocument()
expect(screen.getByText('maximum')).toBeInTheDocument()
expect(screen.queryByText('Pattern (regex)')).not.toBeInTheDocument()
})
it('для kind=enum показывает enum values input с pre-filled значением', () => {
renderWithI18n(
<PropertyEditor
prop={baseProp({ kind: 'enum', enumValues: ['A', 'B'] })}
index={0}
total={1}
onChange={() => {}}
onRemove={() => {}}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
expect(screen.getByText('Значения enum (через запятую)')).toBeInTheDocument()
expect(screen.getByDisplayValue('A, B')).toBeInTheDocument()
})
it('для kind=array_string появляется uniqueItems checkbox', () => {
renderWithI18n(
<PropertyEditor
prop={baseProp({ kind: 'array_string' })}
index={0}
total={1}
onChange={() => {}}
onRemove={() => {}}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
expect(screen.getByLabelText('uniqueItems')).toBeInTheDocument()
})
it('moveUp disabled когда index=0', () => {
renderWithI18n(
<PropertyEditor
prop={baseProp()}
index={0}
total={3}
onChange={() => {}}
onRemove={() => {}}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
expect(screen.getByRole('button', { name: 'Выше' })).toBeDisabled()
})
it('moveDown disabled когда index=total-1', () => {
renderWithI18n(
<PropertyEditor
prop={baseProp()}
index={2}
total={3}
onChange={() => {}}
onRemove={() => {}}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
expect(screen.getByRole('button', { name: 'Ниже' })).toBeDisabled()
})
it('клик Удалить → onRemove', async () => {
const user = userEvent.setup()
const onRemove = vi.fn()
renderWithI18n(
<PropertyEditor
prop={baseProp()}
index={1}
total={3}
onChange={() => {}}
onRemove={onRemove}
onMoveUp={() => {}}
onMoveDown={() => {}}
/>,
)
await user.click(screen.getByRole('button', { name: 'Удалить' }))
expect(onRemove).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,95 @@
import { describe, it, expect, vi } from 'vitest'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithI18n } from '@/test/render'
import { SchemaBuilder } from './SchemaBuilder'
import type { PropertyDef } from './types'
const propsFromKinds = (...kinds: PropertyDef['kind'][]): PropertyDef[] =>
kinds.map((kind, i) => ({
id: `id-${i}`,
name: `field_${i}`,
kind,
required: false,
unique: false,
}))
describe('SchemaBuilder', () => {
it('показывает empty state когда полей нет', () => {
const onChange = vi.fn()
renderWithI18n(<SchemaBuilder properties={[]} onChange={onChange} />)
expect(screen.getByText('Полей нет — добавь первое')).toBeInTheDocument()
})
it('добавляет новое поле через onChange при клике "Добавить поле"', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
renderWithI18n(<SchemaBuilder properties={[]} onChange={onChange} />)
await user.click(screen.getByRole('button', { name: /Добавить поле/i }))
expect(onChange).toHaveBeenCalledTimes(1)
const next = onChange.mock.calls[0][0] as PropertyDef[]
expect(next).toHaveLength(1)
expect(next[0]).toMatchObject({ name: '', kind: 'string', required: false, unique: false })
expect(next[0].id).toBeTruthy()
})
it('рендерит N PropertyEditor по числу properties', () => {
const onChange = vi.fn()
renderWithI18n(
<SchemaBuilder properties={propsFromKinds('string', 'integer', 'enum')} onChange={onChange} />,
)
// По 1 заголовку "Поле #N" на каждый property.
expect(screen.getByText('Поле #1')).toBeInTheDocument()
expect(screen.getByText('Поле #2')).toBeInTheDocument()
expect(screen.getByText('Поле #3')).toBeInTheDocument()
})
it('moveUp поднимает property вверх', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
const initial = propsFromKinds('string', 'integer')
renderWithI18n(<SchemaBuilder properties={initial} onChange={onChange} />)
const upButtons = screen.getAllByRole('button', { name: /Выше/i })
await user.click(upButtons[1])
expect(onChange).toHaveBeenCalledTimes(1)
const next = onChange.mock.calls[0][0] as PropertyDef[]
expect(next[0].kind).toBe('integer')
expect(next[1].kind).toBe('string')
})
it('moveUp на первом элементе — no-op (kbd disabled, onChange не вызывается)', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
renderWithI18n(<SchemaBuilder properties={propsFromKinds('string', 'integer')} onChange={onChange} />)
const upButtons = screen.getAllByRole('button', { name: /Выше/i })
expect(upButtons[0]).toBeDisabled()
await user.click(upButtons[0])
expect(onChange).not.toHaveBeenCalled()
})
it('moveDown на последнем — disabled', () => {
const onChange = vi.fn()
renderWithI18n(<SchemaBuilder properties={propsFromKinds('string', 'integer')} onChange={onChange} />)
const downButtons = screen.getAllByRole('button', { name: /Ниже/i })
expect(downButtons[1]).toBeDisabled()
})
it('removeAt удаляет указанный property', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
const initial = propsFromKinds('string', 'integer', 'enum')
renderWithI18n(<SchemaBuilder properties={initial} onChange={onChange} />)
const deleteButtons = screen.getAllByRole('button', { name: /Удалить/i })
await user.click(deleteButtons[1])
const next = onChange.mock.calls[0][0] as PropertyDef[]
expect(next).toHaveLength(2)
expect(next.map((p) => p.kind)).toEqual(['string', 'enum'])
})
})
+10 -7
View File
@@ -7,6 +7,7 @@ import { AuthProvider } from 'react-oidc-context'
import { routeTree } from './routeTree.gen'
import { oidcAuthConfig } from '@/auth/oidcConfig'
import { TokenSync } from '@/auth/TokenSync'
import { RequireAuth } from '@/auth/RequireAuth'
import './i18n'
import './styles.css'
@@ -28,13 +29,15 @@ createRoot(document.getElementById('root')!).render(
<StrictMode>
<AuthProvider {...oidcAuthConfig}>
<TokenSync />
<QueryClientProvider client={queryClient}>
<NStartUiProvider>
<DatePickerProvider datePicker={DATE_PICKER_LOCALE_RU}>
<RouterProvider router={router} />
</DatePickerProvider>
</NStartUiProvider>
</QueryClientProvider>
<NStartUiProvider>
<RequireAuth>
<QueryClientProvider client={queryClient}>
<DatePickerProvider datePicker={DATE_PICKER_LOCALE_RU}>
<RouterProvider router={router} />
</DatePickerProvider>
</QueryClientProvider>
</RequireAuth>
</NStartUiProvider>
</AuthProvider>
</StrictMode>,
)
+19
View File
@@ -0,0 +1,19 @@
import { render, type RenderOptions } from '@testing-library/react'
import { I18nextProvider } from 'react-i18next'
import type { ReactElement, ReactNode } from 'react'
import i18n from '@/i18n'
// LanguageDetector в jsdom по умолчанию даёт en-US (через navigator.language).
// Для тестов фиксируем ru-RU чтобы не возиться с двумя наборами ассертов.
if (i18n.language !== 'ru-RU') {
void i18n.changeLanguage('ru-RU')
}
const Wrapper = ({ children }: { children: ReactNode }) => (
<I18nextProvider i18n={i18n}>{children}</I18nextProvider>
)
export const renderWithI18n = (ui: ReactElement, opts?: Omit<RenderOptions, 'wrapper'>) =>
render(ui, { wrapper: Wrapper, ...opts })
export { i18n }
+62
View File
@@ -0,0 +1,62 @@
import '@testing-library/jest-dom/vitest'
import { afterEach, vi } from 'vitest'
import { cleanup } from '@testing-library/react'
// @nstart/ui тянет lottie-web (анимация brand-стикеров) prebuilt; lottie при
// импорте инициализирует CanvasRenderingContext, в jsdom его нет → крах
// "Cannot set properties of null (setting fillStyle)". vi.mock не ловит т.к.
// lottie уже вшит в bundle. Стабим прямо HTMLCanvasElement.getContext —
// возвращаем no-op 2D-context, lottie доволен и init не падает.
if (typeof HTMLCanvasElement !== 'undefined' && !HTMLCanvasElement.prototype.getContext) {
// безопасная проверка для любой среды
}
HTMLCanvasElement.prototype.getContext = (() => {
const noop = () => {}
const ctx = new Proxy(
{},
{
get: (target: Record<string, unknown>, prop: string) => {
if (prop in target) return target[prop]
if (
prop === 'measureText'
) {
return () => ({ width: 0 })
}
if (prop === 'getImageData') {
return () => ({ data: new Uint8ClampedArray(4) })
}
if (prop === 'createImageData') {
return () => ({ data: new Uint8ClampedArray(4) })
}
return noop
},
set: (target: Record<string, unknown>, prop: string, value: unknown) => {
target[prop] = value
return true
},
},
)
return () => ctx as unknown as CanvasRenderingContext2D
}) () as never
// нет требований к unused vi импорту
void vi
afterEach(() => {
cleanup()
})
if (!('matchMedia' in window)) {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: (q: string) => ({
matches: false,
media: q,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
onchange: null,
}),
})
}