diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fb11b5..c00cb49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ ### Добавлено +- обязательная 2FA для администраторов: настройка, льготный срок N дней, + предупреждение с обратным отсчётом и ограничение доступа после срока; - включены настройки безопасности и интерфейса: лимит и окно входов, TTL и попытки TOTP, размер аудита, минимальная длина пароля, период графиков, уровень логов; значения по умолчанию задаются env; diff --git a/README.md b/README.md index 178642b..3a9f255 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,8 @@ docker compose --profile seed run --rm seed стране, экспорт CSV; - страница «Настройки» на вкладках: глобальные пороги риска и домашняя страна, TTL сессий, режим ссылок, интервал сбора и retention, лимиты - входов, TOTP, аудит, пароль, период графиков и уровень логов, шаблоны + входов, TOTP, аудит, пароль, период графиков, уровень логов и обязательная + 2FA с льготным сроком и предупреждением, шаблоны лимитов, статус бэкапов, системная панель и история изменений; будущие настройки видны с версией и неактивны; - аудит с поиском, фильтром по действию и датам, страницами и вкладкой в @@ -209,6 +210,8 @@ curl -fsS http://127.0.0.1:8090/healthz | `TGADMIN_PASSWORD_MIN_LENGTH` | `12` | минимальная длина пароля | | `TGADMIN_DEFAULT_CHART_DAYS` | `30` | период графиков по умолчанию | | `TGADMIN_LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` | +| `TGADMIN_REQUIRE_2FA` | `false` | обязательная 2FA для администраторов | +| `TGADMIN_REQUIRE_2FA_GRACE_DAYS` | `7` | льготный срок на включение 2FA | | `TGADMIN_TOTP_KEY` | пусто | ключ шифрования секретов 2FA, 32 байта в base64; без него включить 2FA нельзя | | `TGADMIN_COOKIE_SECURE` | `true` | `Secure` у cookie; выключайте только для локальной проверки по HTTP | | `VALKEY_URL` | `redis://valkey:6379/0` | подключение к Valkey | @@ -374,6 +377,18 @@ docker compose run --rm tgadmin user totp-reset admin станут недействительны: пользователям придётся сбросить 2FA и включить заново. +### Обязательная 2FA + +На странице «Настройки» → «Безопасность» можно включить обязательную 2FA +для администраторов и задать льготный срок от 0 до 30 дней. Пока срок не +истёк, администратор без 2FA видит предупреждение с числом оставшихся дней. + +После срока вход по паролю остаётся возможным, но доступ к интерфейсу +ограничен: открывается экран настройки 2FA, остальные API отвечают +`403 totp_required`. После включения 2FA доступ возвращается сразу. +Администратор не может отключить 2FA, пока требование активно. Роль +`viewer` требованием не затрагивается. + ## Лимиты telemt В карточке пользователя задаются квота трафика и период, лимиты скорости, diff --git a/cmd/tgadmin/app.go b/cmd/tgadmin/app.go index db363b2..cfebeb2 100644 --- a/cmd/tgadmin/app.go +++ b/cmd/tgadmin/app.go @@ -32,6 +32,7 @@ func newHandler(ctx context.Context, cfg *config.Config) (http.Handler, func() e st.SetLoginPolicy(maxFailures, loginWindow) st.SetAuditMax(svc.AuditMaxEvents(ctx)) _ = logging.Set(svc.LogLevel(ctx)) + _, _, _ = svc.Require2FA(ctx) tc := telemt.New(cfg.TelemtURL, cfg.TelemtToken, 15*time.Second) geo, err := geoip.Open(cfg.GeoIPCity, cfg.GeoIPASN) if err != nil { diff --git a/deploy/.env.example b/deploy/.env.example index 7cc2bcc..4c8ad87 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -11,6 +11,9 @@ TELEMT_API_TOKEN= TELEMT_LINK_MODE=tls # Домашняя страна: её адреса не считаются иностранными TGADMIN_HOME_COUNTRY=RU +# Обязательная 2FA для администраторов и льготный срок в днях +TGADMIN_REQUIRE_2FA=false +TGADMIN_REQUIRE_2FA_GRACE_DAYS=7 # Необязательный JSON статуса бэкапов хоста TGADMIN_BACKUP_STATUS= # UID/GID хоста для каталога deploy/telemt diff --git a/docs/UPGRADE.md b/docs/UPGRADE.md index 9d477f6..128aae0 100644 --- a/docs/UPGRADE.md +++ b/docs/UPGRADE.md @@ -32,8 +32,16 @@ `TGADMIN_LOGIN_MAX_FAILURES=10`, `TGADMIN_LOGIN_WINDOW=15m`, `TGADMIN_TOTP_PENDING_TTL=5m`, `TGADMIN_TOTP_MAX_ATTEMPTS=5`, `TGADMIN_AUDIT_MAX_EVENTS=10000`, `TGADMIN_PASSWORD_MIN_LENGTH=12`, -`TGADMIN_DEFAULT_CHART_DAYS=30`, `TGADMIN_LOG_LEVEL=info`. Их можно +`TGADMIN_DEFAULT_CHART_DAYS=30`, `TGADMIN_LOG_LEVEL=info`, +`TGADMIN_REQUIRE_2FA=false`, `TGADMIN_REQUIRE_2FA_GRACE_DAYS=7`. Их можно переопределить на странице «Настройки»; поведение по умолчанию не меняется. + +При включении обязательной 2FA фиксируется момент включения в +`security:require_2fa_since`. Администраторы без 2FA видят предупреждение с +числом оставшихся дней. После льготного срока вход разрешён, но доступ к +интерфейсу ограничен настройкой 2FA в разделе «Аккаунт». Администратор с +включённой 2FA не может её отключить, пока требование активно. Отключение +требования снимает ограничение; повторное включение начинает новый срок. Формат файла: ```json diff --git a/docs/adr/0004-required-2fa.md b/docs/adr/0004-required-2fa.md new file mode 100644 index 0000000..3a3402f --- /dev/null +++ b/docs/adr/0004-required-2fa.md @@ -0,0 +1,48 @@ +# ADR-0004: обязательная 2FA с льготным сроком + +- Статус: принято +- Дата: 2026-11-25 +- Контекст: версия 1.5.0 + +## Проблема + +2FA доступна, но не обязательна. Администратор может годами работать без +второго фактора. Полностью блокировать вход в день включения требования +нельзя: единственный администратор потеряет доступ и не сможет включить +2FA. + +## Решение + +1. Две активные настройки: `security.require_2fa` и + `security.require_2fa_grace_days` (0–30, по умолчанию 7). +2. При включении фиксируется `security:require_2fa_since`. Дедлайн = + момент включения + льготные дни. Изменение срока пересчитывает дедлайн; + выключение удаляет отметку. +3. Администратор без 2FA видит в интерфейсе предупреждение с числом + оставшихся дней. +4. После дедлайна вход по паролю остаётся возможным, но все API, кроме + `/api/me`, выхода, смены пароля, сессий и настройки TOTP, отвечают + `403 totp_required`. Интерфейс показывает экран настройки 2FA. +5. После включения 2FA ограничение снимается автоматически. +6. Администратор не может отключить 2FA, пока требование активно. +7. Обычные пользователи с ролью `viewer` не затрагиваются. + +## Альтернативы + +1. **Полная блокировка входа после дедлайна.** Единственный админ + блокирует сам себя; нужен CLI или второй админ. Отклонено. +2. **Только предупреждение без ограничения.** Не решает задачу. +3. **Индивидуальные сроки на пользователя.** Гибче, но сложнее; глобального + срока достаточно для малого проекта. +4. **Отдельный экран настройки 2FA без доступа к остальному UI.** Реализован + как ограничение API и принудительный экран аккаунта. + +## Последствия + +- Новый ключ `security:require_2fa_since`, миграция не нужна. +- Требование действует только на администраторов; viewer может работать + без 2FA. +- Если администратор потерял телефон, другой администратор с 2FA может + сбросить его TOTP; после сброса доступ снова ограничится до настройки. +- При включении через env срок начинается при старте приложения. +- Откат на версию без этой функции безопасен: ключ игнорируется. diff --git a/docs/adr/README.md b/docs/adr/README.md index a2ac6c9..874d526 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -10,3 +10,4 @@ | [0001](0001-risk-thresholds-per-client.md) | Пороги риска на клиента | Принято | | [0002](0002-risk-report.md) | Отчёт по риску | Принято | | [0003](0003-settings-registry.md) | Реестр глобальных настроек | Принято | +| [0004](0004-required-2fa.md) | Обязательная 2FA с льготным сроком | Принято | diff --git a/docs/superpowers/specs/2026-11-25-settings-page-design.md b/docs/superpowers/specs/2026-11-25-settings-page-design.md index e8c39bd..099fa80 100644 --- a/docs/superpowers/specs/2026-11-25-settings-page-design.md +++ b/docs/superpowers/specs/2026-11-25-settings-page-design.md @@ -70,6 +70,8 @@ | `password.min_length` | int | active | сразу, к новым паролям | 8–128 | | `ui.default_chart_days` | int | active | сразу | 7–90 | | `log.level` | enum | active | сразу | `debug`, `info`, `warn`, `error` | +| `security.require_2fa` | bool | active | сразу | — | +| `security.require_2fa_grace_days` | int | active | сразу | 0–30 | ### 4.3. Будущие настройки @@ -77,7 +79,6 @@ | Ключ | Версия | Смысл | |---|---|---| -| `security.require_2fa` | 1.5.0 | обязательный 2FA для админов | | `notifications.webhook_url` | 1.5.0 | URL вебхука | | `notifications.webhook_secret` | 1.5.0 | секрет подписи | | `notifications.events` | 1.5.0 | список событий | @@ -165,6 +166,8 @@ TTL у настроек нет. Удаление ключа возвращает | `password.min_length` | проверяется при создании и смене пароля | | `ui.default_chart_days` | отдаётся в `/api/meta`, фронтенд использует для графиков | | `log.level` | динамический `slog.LevelVar` | +| `security.require_2fa` | фиксируется `security:require_2fa_since`, считается дедлайн | +| `security.require_2fa_grace_days` | меняет дедлайн от момента включения | Изменение домашней страны не переписывает уже сохранённую историю. В интерфейсе есть пояснение: новые расчёты используют новую страну, старые diff --git a/frontend/e2e/mock.ts b/frontend/e2e/mock.ts index 647ab51..5e3cf75 100644 --- a/frontend/e2e/mock.ts +++ b/frontend/e2e/mock.ts @@ -216,13 +216,13 @@ const settingsCatalog = { max: 1000, }, { - key: 'security.require_2fa', - title: 'Обязательный 2FA', - description: 'Политика для всех администраторов', - kind: 'bool', + key: 'notifications.webhook_url', + title: 'URL вебхука', + description: 'Доставка событий во внешнюю систему', + kind: 'string', status: 'planned', plannedRelease: '1.5.0', - default: false, + default: '', }, ], }, @@ -253,8 +253,15 @@ const settingsCatalog = { export async function mockApi( page: Page, - options: { totp?: boolean } = {}, + options: { totp?: boolean; require2fa?: boolean; require2faEnforced?: boolean } = {}, ): Promise<{ limitBodies: unknown[]; settingsBodies: unknown[] }> { + const require2fa = options.require2fa + ? { + enabled: true, + enforced: Boolean(options.require2faEnforced), + daysLeft: options.require2faEnforced ? 0 : 7, + } + : undefined; let loggedIn = false; const limitBodies: unknown[] = []; const settingsBodies: unknown[] = []; @@ -280,13 +287,13 @@ export async function mockApi( } if (path === '/api/me') { return loggedIn - ? json(route, { user: { name: 'mcconfig', role: 'admin' }, csrf: 'csrf' }) + ? json(route, { user: { name: 'mcconfig', role: 'admin' }, csrf: 'csrf', require2fa }) : json(route, { error: { code: 'unauthorized', message: 'требуется вход' } }, 401); } if (path === '/api/login' && method === 'POST') { if (options.totp) return json(route, { totpRequired: true }); loggedIn = true; - return json(route, { user: { name: 'mcconfig', role: 'admin' }, csrf: 'csrf' }); + return json(route, { user: { name: 'mcconfig', role: 'admin' }, csrf: 'csrf', require2fa }); } if (path === '/api/login/totp' && method === 'POST') { loggedIn = true; @@ -477,10 +484,12 @@ export async function mockApi( } /** Входит в интерфейс через форму. */ -export async function login(page: Page) { +export async function login(page: Page, waitForApp = true) { await page.goto('/'); await page.locator('input[autocomplete="username"]').fill('admin'); await page.locator('input[type="password"]').fill('secret'); await page.getByRole('button', { name: 'Войти' }).click(); - await page.getByRole('link', { name: 'main', exact: true }).waitFor(); + if (waitForApp) { + await page.getByRole('link', { name: 'main', exact: true }).waitFor(); + } } diff --git a/frontend/e2e/settings.spec.ts b/frontend/e2e/settings.spec.ts index e4499d8..c8b85d6 100644 --- a/frontend/e2e/settings.spec.ts +++ b/frontend/e2e/settings.spec.ts @@ -9,7 +9,7 @@ test('настройки: каталог, planned и сохранение', asyn await expect(page.getByText('Настройки', { exact: true }).last()).toBeVisible(); await page.getByRole('button', { name: 'Безопасность' }).click(); await expect(page.getByText('1.5.0', { exact: true })).toBeVisible(); - await expect(page.getByText('Политика для всех администраторов')).toBeVisible(); + await expect(page.getByText('Доставка событий во внешнюю систему')).toBeVisible(); await page.getByRole('button', { name: 'Бэкапы' }).click(); await expect(page.getByRole('button', { name: 'Снимок сейчас' })).toBeVisible(); await page.getByRole('button', { name: 'Риск' }).click(); @@ -23,3 +23,16 @@ test('настройки: каталог, planned и сохранение', asyn values: { 'risk.warn_ips': 4 }, }); }); + +test('2FA: предупреждение и ограничение доступа', async ({ page }) => { + await mockApi(page, { require2fa: true }); + await login(page); + await expect(page.getByText(/2FA не включена/)).toBeVisible(); +}); + +test('2FA: после срока показывается экран настройки', async ({ page }) => { + await mockApi(page, { require2fa: true, require2faEnforced: true }); + await login(page, false); + await expect(page.getByText('Требуется двухфакторная аутентификация')).toBeVisible(); + await expect(page.getByRole('button', { name: 'Выйти' })).toBeVisible(); +}); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 301a326..0e7289a 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'; -import { Loader, ThemeProvider } from '@gravity-ui/uikit'; +import { Alert, Button, Loader, ThemeProvider } from '@gravity-ui/uikit'; import { api, type Me } from './api'; import Layout from './Layout'; import LoginPage from './pages/LoginPage'; @@ -60,6 +60,35 @@ export default function App() { } }; + const refreshMe = () => { + api + .me() + .then(setMe) + .catch(() => setMe(null)); + }; + + if (me.require2fa?.enforced) { + return ( + + + + + + + void logout()}> + Выйти + + + + + + ); + } + return ( diff --git a/frontend/src/Layout.test.tsx b/frontend/src/Layout.test.tsx index 5660089..8019116 100644 --- a/frontend/src/Layout.test.tsx +++ b/frontend/src/Layout.test.tsx @@ -7,6 +7,21 @@ import { renderUI } from './test/render'; import { stubFetch } from './test/stubFetch'; describe('Layout', () => { + it('показывает предупреждение о сроке 2FA', () => { + stubFetch({ '/api/meta': { version: 'v9.9.9', repo: 'https://example.com/repo' } }); + renderUI( + {}} + theme="dark" + onToggleTheme={() => {}} + > + содержимое + , + ); + expect(screen.getByText(/Через 3 дн/)).toBeInTheDocument(); + }); + it('показывает меню, тему, выход и футер', async () => { stubFetch({ '/api/meta': { version: 'v9.9.9', repo: 'https://example.com/repo' } }); const onLogout = vi.fn(); diff --git a/frontend/src/Layout.tsx b/frontend/src/Layout.tsx index cebd116..83b697c 100644 --- a/frontend/src/Layout.tsx +++ b/frontend/src/Layout.tsx @@ -1,6 +1,6 @@ import { useState, type ReactNode } from 'react'; import { Link, NavLink } from 'react-router-dom'; -import { Button, Label } from '@gravity-ui/uikit'; +import { Alert, Button, Label } from '@gravity-ui/uikit'; import { ArrowRightFromSquare, Moon, Sun } from '@gravity-ui/icons'; import type { Me } from './api'; import Footer from './Footer'; @@ -58,7 +58,19 @@ export default function Layout({ - {children} + + {me.require2fa?.enabled && !me.require2fa.enforced && ( + 0 + ? `2FA не включена. Через ${me.require2fa.daysLeft} дн. доступ к интерфейсу будет ограничен до её включения. Настройте её в разделе «Аккаунт».` + : '2FA не включена. Сегодня истекает льготный срок, после чего доступ будет ограничен. Настройте её в разделе «Аккаунт».' + } + /> + )} + {children} + ); diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 95abad5..24d410f 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -6,9 +6,17 @@ export interface Meta { defaultChartDays?: number; } +export interface Require2FAInfo { + enabled: boolean; + enforced: boolean; + deadline?: string; + daysLeft: number; +} + export interface Me { user: { name: string; role: Role }; csrf: string; + require2fa?: Require2FAInfo; } export interface AdminUser { diff --git a/frontend/src/pages/AccountPage.tsx b/frontend/src/pages/AccountPage.tsx index f26b536..d5b1e22 100644 --- a/frontend/src/pages/AccountPage.tsx +++ b/frontend/src/pages/AccountPage.tsx @@ -24,7 +24,7 @@ function compareSessions(a: SessionItem, b: SessionItem, id: string): number { } } -export default function AccountPage() { +export default function AccountPage({ onMeChange }: { onMeChange?: () => void } = {}) { const [sessions, setSessions] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); @@ -234,6 +234,7 @@ export default function AccountPage() { setTotpCode(''); setMessage('2FA включена. Сохраните резервные коды.'); load(); + onMeChange?.(); }) .catch((err) => setError(err instanceof ApiError ? err.message : 'не удалось включить'), diff --git a/frontend/src/pages/SettingsPage.test.tsx b/frontend/src/pages/SettingsPage.test.tsx index 9b55a8c..9a6082e 100644 --- a/frontend/src/pages/SettingsPage.test.tsx +++ b/frontend/src/pages/SettingsPage.test.tsx @@ -74,13 +74,13 @@ const catalog = { description: 'Входы', settings: [ { - key: 'security.require_2fa', - title: 'Обязательный 2FA', - description: 'Политика для всех администраторов', - kind: 'bool', + key: 'notifications.webhook_url', + title: 'URL вебхука', + description: 'Доставка событий', + kind: 'string', status: 'planned', plannedRelease: '1.5.0', - default: false, + default: '', }, ], }, @@ -100,7 +100,7 @@ describe('SettingsPage', () => { await userEvent.click(screen.getByRole('button', { name: 'Безопасность' })); expect(screen.getByText('1.5.0')).toBeInTheDocument(); - expect(screen.getByText('Политика для всех администраторов')).toBeInTheDocument(); + expect(screen.getByText('Доставка событий')).toBeInTheDocument(); await userEvent.click(screen.getByRole('button', { name: 'Риск' })); const warn = screen.getByPlaceholderText('по умолчанию: 3'); diff --git a/internal/config/config.go b/internal/config/config.go index 78a53b7..210a49c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -13,35 +13,37 @@ import ( // Config — настройки сервиса из переменных окружения. type Config struct { - Listen string - AllowedCIDRs []netip.Prefix - TrustedProxies []netip.Prefix - BaseURL *url.URL - SessionTTL time.Duration - ValkeyURL string - ValkeyPassword string - TelemtURL string - TelemtToken string - LinkMode string - CookieSecure bool - CollectInterval time.Duration - RiskIPsWarn int - RiskIPsHigh int - RiskDistinct7d int - HomeCountry string - Retention time.Duration - LoginMaxFailures int - LoginWindow time.Duration - TOTPPendingTTL time.Duration - TOTPMaxAttempts int - AuditMaxEvents int64 - PasswordMinLength int - DefaultChartDays int - LogLevel string - GeoIPCity string - GeoIPASN string - BackupStatus string - TOTPKey []byte + Listen string + AllowedCIDRs []netip.Prefix + TrustedProxies []netip.Prefix + BaseURL *url.URL + SessionTTL time.Duration + ValkeyURL string + ValkeyPassword string + TelemtURL string + TelemtToken string + LinkMode string + CookieSecure bool + CollectInterval time.Duration + RiskIPsWarn int + RiskIPsHigh int + RiskDistinct7d int + HomeCountry string + Retention time.Duration + LoginMaxFailures int + LoginWindow time.Duration + TOTPPendingTTL time.Duration + TOTPMaxAttempts int + AuditMaxEvents int64 + PasswordMinLength int + DefaultChartDays int + LogLevel string + Require2FA bool + Require2FAGraceDays int + GeoIPCity string + GeoIPASN string + BackupStatus string + TOTPKey []byte } // Load читает конфигурацию. getenv передаётся для тестируемости. @@ -77,6 +79,11 @@ func Load(getenv func(string) string) (*Config, error) { cfg.AuditMaxEvents = int64(getInt(get("TGADMIN_AUDIT_MAX_EVENTS", "10000"), 10000)) cfg.PasswordMinLength = getInt(get("TGADMIN_PASSWORD_MIN_LENGTH", "12"), 12) cfg.DefaultChartDays = getInt(get("TGADMIN_DEFAULT_CHART_DAYS", "30"), 30) + cfg.Require2FA = strings.EqualFold(get("TGADMIN_REQUIRE_2FA", "false"), "true") + cfg.Require2FAGraceDays = getInt(get("TGADMIN_REQUIRE_2FA_GRACE_DAYS", "7"), 7) + if cfg.Require2FAGraceDays < 0 || cfg.Require2FAGraceDays > 30 { + return nil, fmt.Errorf("TGADMIN_REQUIRE_2FA_GRACE_DAYS: от 0 до 30") + } cfg.LogLevel = strings.ToLower(get("TGADMIN_LOG_LEVEL", "info")) switch cfg.LogLevel { case "debug", "info", "warn", "error": diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 58de8f2..ac25131 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -118,6 +118,9 @@ func TestSecurityDefaults(t *testing.T) { if cfg.LogLevel != "info" || cfg.LoginWindow.Minutes() != 15 || cfg.TOTPPendingTTL.Minutes() != 5 { t.Fatalf("безопасность: %+v", cfg) } + if cfg.Require2FA || cfg.Require2FAGraceDays != 7 { + t.Fatalf("2FA: %+v", cfg) + } cfg, err = Load(env(map[string]string{ "TGADMIN_LOGIN_MAX_FAILURES": "4", "TGADMIN_PASSWORD_MIN_LENGTH": "16", diff --git a/internal/settings/settings.go b/internal/settings/settings.go index d96e422..fa5328f 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "math" "regexp" "strconv" "strings" @@ -384,6 +385,15 @@ func (s *Service) Save( if touched("log.level") { _ = logging.Set(s.LogLevel(ctx)) } + if touched("security.require_2fa") { + if s.boolValue("security.require_2fa") { + if _, ok, err := s.st.Require2FASince(ctx); err != nil || !ok { + _ = s.st.SetRequire2FASince(ctx, time.Now().UTC()) + } + } else { + _ = s.st.ClearRequire2FASince(ctx) + } + } return catalog, changes, nil } @@ -571,6 +581,29 @@ func (s *Service) LogLevel(ctx context.Context) string { return s.stringValue("log.level") } +// Require2FA возвращает состояние обязательного 2FA и дедлайн. +func (s *Service) Require2FA(ctx context.Context) (bool, time.Time, int) { + s.ensure(ctx) + s.mu.RLock() + enabled := s.boolValue("security.require_2fa") + grace := s.intValue("security.require_2fa_grace_days") + s.mu.RUnlock() + if !enabled { + return false, time.Time{}, 0 + } + since, ok, err := s.st.Require2FASince(ctx) + if err != nil || !ok { + since = time.Now().UTC() + _ = s.st.SetRequire2FASince(ctx, since) + } + deadline := since.AddDate(0, 0, grace) + left := int(math.Ceil(deadline.Sub(time.Now().UTC()).Hours() / 24)) + if left < 0 { + left = 0 + } + return true, deadline, left +} + // IsActive сообщает, можно ли менять ключ. func (s *Service) IsActive(key string) bool { d, ok := s.by[key] @@ -715,11 +748,21 @@ func (s *Service) build() { }, }) + add(Definition{ + Key: "security.require_2fa", Section: "security", Title: "Обязательный 2FA для админов", + Description: "После льготного срока доступ без 2FA будет ограничен", + Kind: KindBool, Status: Active, Default: cfg.Require2FA, + }) + add(Definition{ + Key: "security.require_2fa_grace_days", Section: "security", Title: "Льготный срок, дней", + Description: "Сколько дней даётся администраторам на включение 2FA", + Kind: KindInt, Status: Active, Default: cfg.Require2FAGraceDays, Min: intp(0), Max: intp(30), + }) + planned := func(key, section, title, desc string, kind Kind, release string, def any) { add(Definition{Key: key, Section: section, Title: title, Description: desc, Kind: kind, Status: Planned, PlannedRelease: release, Default: def}) } - planned("security.require_2fa", "security", "Обязательный 2FA для админов", "Политика для всех администраторов", KindBool, "1.5.0", false) planned("notifications.webhook_url", "notifications", "URL вебхука", "Доставка событий во внешнюю систему", KindString, "1.5.0", "") planned("notifications.webhook_secret", "notifications", "Секрет вебхука", "HMAC-подпись запросов", KindString, "1.5.0", "") planned("notifications.events", "notifications", "События", "Какие события отправлять", KindString, "1.5.0", "") diff --git a/internal/settings/settings_test.go b/internal/settings/settings_test.go index 4f11b5a..30f4e28 100644 --- a/internal/settings/settings_test.go +++ b/internal/settings/settings_test.go @@ -72,9 +72,12 @@ func TestCatalogStatusesAndSecrets(t *testing.T) { if statuses["login.max_failures"] != Active { t.Fatalf("login.max_failures: %s", statuses["login.max_failures"]) } - if statuses["security.require_2fa"] != Planned { + if statuses["security.require_2fa"] != Active { t.Fatalf("security.require_2fa: %s", statuses["security.require_2fa"]) } + if statuses["notifications.webhook_url"] != Planned { + t.Fatalf("notifications.webhook_url: %s", statuses["notifications.webhook_url"]) + } if statuses["network.allowed_cidrs"] != Readonly { t.Fatalf("network.allowed_cidrs: %s", statuses["network.allowed_cidrs"]) } @@ -180,7 +183,7 @@ func TestValidation(t *testing.T) { func TestPlannedAndReadonlyRejected(t *testing.T) { svc, _ := testService(t) ctx := context.Background() - for _, key := range []string{"security.require_2fa", "network.allowed_cidrs", "valkey.password"} { + for _, key := range []string{"notifications.webhook_url", "network.allowed_cidrs", "valkey.password"} { _, _, err := svc.Save(ctx, 0, map[string]json.RawMessage{key: raw(1)}, nil) var invalid *ValidationError if !errors.As(err, &invalid) { @@ -259,3 +262,32 @@ func TestSecuritySettingsApplied(t *testing.T) { } t.Cleanup(func() { _ = logging.Set("info") }) } + +func TestRequire2FAState(t *testing.T) { + svc, st := testService(t) + ctx := context.Background() + if _, _, err := svc.Save(ctx, 0, map[string]json.RawMessage{ + "security.require_2fa": raw(true), + "security.require_2fa_grace_days": raw(7), + }, nil); err != nil { + t.Fatal(err) + } + enabled, deadline, days := svc.Require2FA(ctx) + if !enabled || deadline.IsZero() || days < 6 || days > 7 { + t.Fatalf("2FA: %v %s %d", enabled, deadline, days) + } + if _, ok, err := st.Require2FASince(ctx); err != nil || !ok { + t.Fatalf("отметка включения: %v %v", ok, err) + } + if _, _, err := svc.Save(ctx, 1, map[string]json.RawMessage{ + "security.require_2fa": raw(false), + }, nil); err != nil { + t.Fatal(err) + } + if enabled, _, _ := svc.Require2FA(ctx); enabled { + t.Fatal("2FA должна быть выключена") + } + if _, ok, _ := st.Require2FASince(ctx); ok { + t.Fatal("отметка включения должна быть удалена") + } +} diff --git a/internal/store/settings.go b/internal/store/settings.go index 4533395..f7f84c6 100644 --- a/internal/store/settings.go +++ b/internal/store/settings.go @@ -4,6 +4,7 @@ import ( "context" "errors" "strconv" + "time" "github.com/redis/go-redis/v9" ) @@ -11,6 +12,7 @@ import ( const ( settingsGlobalKey = "settings:global" settingsVersionKey = "settings:version" + require2FASinceKey = "security:require_2fa_since" ) // ErrVersionConflict возвращается, когда настройки уже изменил другой админ. @@ -70,3 +72,29 @@ func (s *Store) SaveGlobalSettings( } return next, nil } + +// Require2FASince возвращает момент включения обязательного 2FA. +func (s *Store) Require2FASince(ctx context.Context) (time.Time, bool, error) { + raw, err := s.rdb.Get(ctx, require2FASinceKey).Result() + if errors.Is(err, redis.Nil) { + return time.Time{}, false, nil + } + if err != nil { + return time.Time{}, false, err + } + t, err := time.Parse(time.RFC3339, raw) + if err != nil { + return time.Time{}, false, nil + } + return t, true, nil +} + +// SetRequire2FASince запоминает момент включения обязательного 2FA. +func (s *Store) SetRequire2FASince(ctx context.Context, at time.Time) error { + return s.rdb.Set(ctx, require2FASinceKey, at.UTC().Format(time.RFC3339), 0).Err() +} + +// ClearRequire2FASince снимает отметку обязательного 2FA. +func (s *Store) ClearRequire2FASince(ctx context.Context) error { + return s.rdb.Del(ctx, require2FASinceKey).Err() +} diff --git a/internal/web/api.go b/internal/web/api.go index 061cc52..ded1020 100644 --- a/internal/web/api.go +++ b/internal/web/api.go @@ -7,6 +7,7 @@ import ( "errors" "log/slog" "net/http" + "strings" "time" "github.com/McConfig/telemt-admin/internal/store" @@ -58,6 +59,10 @@ func (s *Server) withAPISession(next http.Handler) http.Handler { writeError(w, http.StatusUnauthorized, "unauthorized", "учётная запись недоступна") return } + if s.totpRestricted(r.Context(), *u) && !totpAllowedPath(r.URL.Path) { + writeError(w, http.StatusForbidden, "totp_required", "включите двухфакторную аутентификацию") + return + } next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), sessionCtxKey, sess))) }) } @@ -168,3 +173,20 @@ func (s *Server) serverErrorJSON(w http.ResponseWriter, r *http.Request, err err slog.Error("внутренняя ошибка", "path", r.URL.Path, "err", err) writeError(w, http.StatusInternalServerError, "internal", "внутренняя ошибка") } + +func (s *Server) totpRestricted(ctx context.Context, u store.User) bool { + if u.Role != store.RoleAdmin || u.TOTPEnabled { + return false + } + enabled, deadline, _ := s.settings.Require2FA(ctx) + return enabled && time.Now().UTC().After(deadline) +} + +func totpAllowedPath(path string) bool { + switch path { + case "/api/me", "/api/logout", "/api/account/password", + "/api/account/totp", "/api/account/totp/setup", "/api/account/totp/enable": + return true + } + return strings.HasPrefix(path, "/api/account/sessions") +} diff --git a/internal/web/api_auth.go b/internal/web/api_auth.go index 33d90cf..e4be608 100644 --- a/internal/web/api_auth.go +++ b/internal/web/api_auth.go @@ -1,18 +1,27 @@ package web import ( + "context" "net/http" - - "github.com/McConfig/telemt-admin/internal/version" "strings" + "time" "github.com/McConfig/telemt-admin/internal/auth" "github.com/McConfig/telemt-admin/internal/store" + "github.com/McConfig/telemt-admin/internal/version" ) +type require2FAInfo struct { + Enabled bool `json:"enabled"` + Enforced bool `json:"enforced"` + Deadline string `json:"deadline,omitempty"` + DaysLeft int `json:"daysLeft"` +} + type meResponse struct { - User meUser `json:"user"` - CSRF string `json:"csrf"` + User meUser `json:"user"` + CSRF string `json:"csrf"` + Require2FA *require2FAInfo `json:"require2fa,omitempty"` } type meUser struct { @@ -26,7 +35,23 @@ func (s *Server) me(r *http.Request) (meResponse, error) { if err != nil { return meResponse{}, err } - return meResponse{User: meUser{Name: u.Name, Role: string(u.Role)}, CSRF: sess.CSRF}, nil + return s.meForUser(r.Context(), *u, sess.CSRF), nil +} + +func (s *Server) meForUser(ctx context.Context, u store.User, csrf string) meResponse { + out := meResponse{User: meUser{Name: u.Name, Role: string(u.Role)}, CSRF: csrf} + if u.Role != store.RoleAdmin || u.TOTPEnabled { + return out + } + enabled, deadline, daysLeft := s.settings.Require2FA(ctx) + if !enabled { + return out + } + out.Require2FA = &require2FAInfo{ + Enabled: true, Enforced: time.Now().UTC().After(deadline), + Deadline: deadline.UTC().Format(time.RFC3339), DaysLeft: daysLeft, + } + return out } func (s *Server) apiMe(w http.ResponseWriter, r *http.Request) { @@ -115,9 +140,7 @@ func (s *Server) apiLogin(w http.ResponseWriter, r *http.Request) { s.serverErrorJSON(w, r, err) return } - writeJSON(w, http.StatusOK, meResponse{ - User: meUser{Name: username, Role: string(u.Role)}, CSRF: sess.CSRF, - }) + writeJSON(w, http.StatusOK, s.meForUser(r.Context(), *u, sess.CSRF)) } func (s *Server) apiLogout(w http.ResponseWriter, r *http.Request) { diff --git a/internal/web/api_settings_test.go b/internal/web/api_settings_test.go index 06d16fc..93eca37 100644 --- a/internal/web/api_settings_test.go +++ b/internal/web/api_settings_test.go @@ -7,6 +7,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" stgs "github.com/McConfig/telemt-admin/internal/settings" "github.com/McConfig/telemt-admin/internal/store" @@ -53,7 +54,7 @@ func TestSettingsCatalog(t *testing.T) { if activeLogin.Status != stgs.Active || activeLogin.Value.(float64) != 10 { t.Fatalf("login.max_failures: %+v", activeLogin) } - planned := settingsField(t, cat, "security.require_2fa") + planned := settingsField(t, cat, "notifications.webhook_url") if planned.Status != stgs.Planned || planned.PlannedRelease != "1.5.0" { t.Fatalf("planned: %+v", planned) } @@ -114,7 +115,7 @@ func TestSettingsUpdateAndConflict(t *testing.T) { rr = httptest.NewRecorder() s.Handler().ServeHTTP(rr, apiRequest(t, "PUT", "/api/settings", - `{"version":1,"values":{"security.require_2fa":true}}`, tok, csrf)) + `{"version":1,"values":{"notifications.webhook_url":"https://example.com/hook"}}`, tok, csrf)) if rr.Code != http.StatusBadRequest { t.Fatalf("planned: код %d", rr.Code) } @@ -270,3 +271,44 @@ func TestSettingsPasswordPolicyApplies(t *testing.T) { t.Fatalf("длинный пароль: код %d: %s", rr.Code, rr.Body.String()) } } + +func TestRequire2FAEnforcement(t *testing.T) { + s := testServer(t) + ctx := context.Background() + tok, _ := seedSession(t, s, store.RoleAdmin) + if _, _, err := s.settings.Save(ctx, 0, map[string]json.RawMessage{ + "security.require_2fa": json.RawMessage("true"), + "security.require_2fa_grace_days": json.RawMessage("0"), + }, nil); err != nil { + t.Fatal(err) + } + if err := s.store.SetRequire2FASince(ctx, time.Now().Add(-time.Hour)); err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + s.Handler().ServeHTTP(rr, apiRequest(t, "GET", "/api/me", "", tok, "")) + if rr.Code != http.StatusOK { + t.Fatalf("me: код %d", rr.Code) + } + var meResp struct { + Require2FA *require2FAInfo `json:"require2fa"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &meResp); err != nil { + t.Fatal(err) + } + if meResp.Require2FA == nil || !meResp.Require2FA.Enforced { + t.Fatalf("require2fa: %+v", meResp.Require2FA) + } + + rr = httptest.NewRecorder() + s.Handler().ServeHTTP(rr, apiRequest(t, "GET", "/api/users", "", tok, "")) + if rr.Code != http.StatusForbidden { + t.Fatalf("users: код %d: %s", rr.Code, rr.Body.String()) + } + rr = httptest.NewRecorder() + s.Handler().ServeHTTP(rr, apiRequest(t, "GET", "/api/account/totp", "", tok, "")) + if rr.Code != http.StatusOK { + t.Fatalf("totp: код %d", rr.Code) + } +} diff --git a/internal/web/api_totp.go b/internal/web/api_totp.go index d94010d..eea6784 100644 --- a/internal/web/api_totp.go +++ b/internal/web/api_totp.go @@ -278,6 +278,12 @@ func (s *Server) apiTOTPDisable(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusUnauthorized, "unauthorized", "неверный пароль") return } + if u.Role == store.RoleAdmin { + if enabled, _, _ := s.settings.Require2FA(r.Context()); enabled { + writeError(w, http.StatusBadRequest, "totp_required", "нельзя отключить 2FA, пока она обязательна для администраторов") + return + } + } if _, ok := s.verifyCurrentTOTP(u, in.Code); !ok { writeError(w, http.StatusBadRequest, "bad_totp", "неверный код") return @@ -309,6 +315,12 @@ func (s *Server) apiTOTPRecovery(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusUnauthorized, "unauthorized", "неверный пароль") return } + if u.Role == store.RoleAdmin { + if enabled, _, _ := s.settings.Require2FA(r.Context()); enabled { + writeError(w, http.StatusBadRequest, "totp_required", "нельзя отключить 2FA, пока она обязательна для администраторов") + return + } + } if _, ok := s.verifyCurrentTOTP(u, in.Code); !ok { writeError(w, http.StatusBadRequest, "bad_totp", "неверный код") return