feat(identity): add server sessions and audited mail recovery

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:03:46 +03:00
1 parent 20c03288d6
commit 4ee53d9a74
58 files changed
+5359 -567

No files matched your search

+10 -10
View File
@@ -102,7 +102,7 @@ The ML service answers its errors with the same `Problem` schema. Its `ProblemCo
### Identity: sessions, cookie, and CSRF
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, and `ConfirmEmail` are implemented. Login still answers 501 `not_implemented`, and `v1.DenyAllSecurity` rejects every request to a protected operation with 401 `unauthenticated`. Frontend registration and confirmation screens remain placeholders, and login is not implemented.
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. Session security allows only the last three protected operations; other operations that require a session remain closed with 401 `unauthenticated`. Frontend registration and confirmation screens remain placeholders.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -119,15 +119,15 @@ Every operation also declares the `default` problem response.
Registration and verification:
- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email. Login is not implemented yet, so its contract behavior of answering 401 `invalid_credentials` for both an unknown email and a wrong password is not available.
- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email. Login answers the same 401 `invalid_credentials` for an unknown email, a wrong password, or an invalid stored hash; unknown emails and invalid hashes also receive extra Argon2id work. A correct password for an unverified account answers 403 `email_not_verified` and creates no session.
- Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists.
- Registering an unverified email again never changes the password hash, scenario, or onboarding step of the account row. Every registration, the first and each repeat, stores its pending credentials (password hash, scenario, and first onboarding step) on its own verification token, replaces the C1 record, advances the registration version, and invalidates earlier verification tokens. `ConfirmEmail` requires the password chosen for that registration and checks it against the pending hash on the clicked token. In one transaction the server checks the current registration version and its C1 record, consumes the token, verifies the email, applies that token's pending credentials to the account, clears its `pending_*` fields, and records exactly one `identity.email_verified` event. Any refusal leaves the account and token unchanged. An unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers 400 `verification_token_invalid`; an expired token answers 400 `verification_token_expired`. This prevents an address owner who clicks someone else's link from accepting that registrant's password, and vice versa. Confirmation does not create a session or cookie. Login is not implemented. The planned login rule is that an unverified account cannot sign in.
- Implementation of registration and resend. Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). Limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). `ConfirmEmail` also limits each token to 5 attempts per hour and uses the same client limit. A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, and the limiter keys. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend).
- Registering an unverified email again never changes the password hash, scenario, or onboarding step of the account row. Every registration, the first and each repeat, stores its pending credentials (password hash, scenario, and first onboarding step) on its own verification token, replaces the C1 record, advances the registration version, and invalidates earlier verification tokens. `ConfirmEmail` requires the password chosen for that registration and checks it against the pending hash on the clicked token. In one transaction the server checks the current registration version and its C1 record, consumes the token, verifies the email, applies that token's pending credentials to the account, clears its `pending_*` fields, and records exactly one `identity.email_verified` event. Any refusal leaves the account and token unchanged. An unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers 400 `verification_token_invalid`; an expired token answers 400 `verification_token_expired`. This prevents an address owner who clicks someone else's link from accepting that registrant's password, and vice versa. Confirmation does not create a session or cookie; sign-in is a separate endpoint and requires a verified account.
- Implementation of registration, resend, and login. A verified address changes nothing and receives no message during registration (the "you already have an account" notice is not implemented). Mail limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours. `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour, range 1 to 10000) limits registration, confirmation, resend, and login per resolved client address. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (default 10 per hour, range 1 to 10000) limits login by normalized email whether or not an account exists. `ConfirmEmail` also limits each token to 5 attempts per hour and uses the client limit. A refused request answers 429 `rate_limited` with `Retry-After`. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, the limiter keys, and session CSRF. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend).
- Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version with the pending credentials of that registration, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions).
- Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check.
- `ConfirmEmail` takes both `token` and the `password` selected for that registration; clients that sent only a token must be updated. The password follows `LoginPassword`: NFKC normalization and 1 to 128 code points; the registration blocklist is not applied again. `Origin` must match `APP_PUBLIC_URL`; a missing Origin, the literal value null, or a foreign Origin answers 403 `csrf_check_failed`. Confirmation attempts are limited to 5 per token per hour and also use the shared `IDENTITY_CLIENT_HOURLY_LIMIT`; a refused attempt answers 429 `rate_limited` with `Retry-After`.
- The verification link is `<frontend origin>/verify-email#token=<token>`. The frontend confirmation screen is still a placeholder. A client page must remove the fragment with `history.replaceState`, wait for an explicit user action, and post both token and registration password; a link scanner that only opens the page does not consume the token.
- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error, and can offer sign-in after login is implemented. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token.
- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error; after confirmation the user can sign in separately. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token.
Consent C1 and the account:
@@ -138,17 +138,17 @@ Consent C1 and the account:
Sessions and CSRF:
- Planned session behavior: the `sessionCookie` scheme uses `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain; the server will keep sessions in PostgreSQL and identify the caller from the session. Once login is implemented, only a verified account will receive a session, and login will revoke the session from the request and issue a new identifier and CSRF token. Logout will revoke the session server-side. Policy timeouts are 24 hours idle and 7 days absolute; activity extends only the idle deadline. Configuration does not override these values.
- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the session-bound token from `Session.csrf_token`. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`.
- Every unsafe request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). Public identity operations are rate-limited (429 with `Retry-After`).
- Implemented session operations: Login issues a `__Host-lincodex_session` cookie with `Path=/; Secure; HttpOnly; SameSite=Strict`, no Domain, and Expires/Max-Age at the absolute session deadline. PostgreSQL stores only the SHA-256 hash of the cookie token; the current-session GET returns the account and CSRF token after a reload. Successful login transactionally revokes an active session from the request and creates a new one; only a verified account can sign in. Logout revokes the session and clears the cookie; an expired or revoked cookie is also cleared on 401. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` (range `1m` to `30d`) and `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` (range `1m` to `365d`); idle cannot exceed absolute, and invalid values stop startup. Requests extend only the idle deadline.
- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the current session's token from `Session.csrf_token`. The backend derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, compares it in constant time, and does not store it in the database. All instances must share one `IDENTITY_KEY_SECRET` (at least 32 bytes), stable across restarts; changing it invalidates old CSRF values but does not revoke PostgreSQL sessions. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`.
- The contract requires the exact configured public Origin on every unsafe request, including public operations. The backend currently checks the sole `Origin` header against `APP_PUBLIC_URL` for `ConfirmEmail`, `Login`, and `Logout`; `Logout` also requires CSRF. `RegisterAccount` and `ResendEmailVerification` do not currently check Origin, although the contract requires it. The backend does not derive Origin from `Host` or trust forwarded headers for this check. Public identity operations are rate-limited (429 with `Retry-After`).
- Responses with a session or account carry `Cache-Control: no-store`.
- The root `security` requires `sessionCookie`, so an operation that does not declare `security: []` is protected by default.
How the generated server (ogen v1.24.0) evaluates the schemes, and the mapping planned for session authentication, are documented on `v1.DenyAllSecurity` and pinned by `TestGeneratedServerSecurityOrder`:
How the generated server (ogen v1.24.0) evaluates the schemes, and how `v1.SessionSecurity` applies the current session boundary, are pinned by `TestGeneratedServerSecurityOrder`:
- It calls `HandleSessionCookie` before `HandleSessionCsrf` and passes the context returned by a successful call on. An absent value (no cookie, empty `X-CSRF-Token`) does not call the handler, and a handler that returns `ogenerrors.ErrSkipServerSecurity` counts as unsatisfied; both continue with the next scheme, so `HandleSessionCsrf` also runs without a cookie, with the original context.
- Any other handler error stops evaluation and reaches `NewError` as a `SecurityError` whose `Security` is `SessionCookie` or `SessionCsrf`. An unsatisfied requirement reaches `NewError` as a `SecurityError` with `ErrSecurityRequirementIsNotSatisfied` and no `Security` field.
- Planned mapping: `HandleSessionCookie` skips a missing or invalid session; `HandleSessionCsrf` skips when the context has no principal (401) and returns a typed error for a wrong token. `NewError` maps a `SessionCsrf` error and an unsatisfied requirement with a principal in the context to 403 `csrf_check_failed`, and every other security failure to 401 `unauthenticated`. A 401 from `Logout` also clears the cookie.
- Implemented mapping: `HandleSessionCookie` authenticates only `GetCurrentSession`, `GetCurrentAccount`, and `Logout`; missing, unknown, expired, or revoked sessions leave the requirement unsatisfied. `HandleSessionCsrf` checks Origin and the token only for `Logout`; without a principal the result is 401, while a wrong Origin or CSRF token with a valid principal is 403 `csrf_check_failed`. Other protected operations fail the allowlist and remain 401 `unauthenticated`. A 401 from `Logout` also clears the cookie.
### Catalog and questionnaire
+10 -10
View File
@@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Identity: сессии, cookie и CSRF
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification` и `ConfirmEmail` реализованы. Вход еще отвечает 501 `not_implemented`, а `v1.DenyAllSecurity` отклоняет все запросы к защищенным операциям с 401 `unauthenticated`. Экраны регистрации и подтверждения во frontend остаются заглушками, вход еще не реализован.
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session security разрешает только последние три защищенные операции; остальные операции, требующие сессию, остаются закрытыми с 401 `unauthenticated`. Экраны регистрации и подтверждения во frontend остаются заглушками.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -119,15 +119,15 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Регистрация и подтверждение:
- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email. Вход пока не реализован: его предусмотренный контрактом ответ 401 `invalid_credentials` для неизвестного email и неверного пароля пока не доступен.
- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email. Вход отвечает одинаковым 401 `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша; для неизвестного email и некорректного хеша выполняется дополнительная работа Argon2id. Верный пароль неподтвержденной учетной записи дает 403 `email_not_verified` и не создает сессию.
- До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта.
- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля, сценарий и первый шаг онбординга) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует прежние токены. `ConfirmEmail` требует пароль этой регистрации и проверяет его по отложенному хешу именно нажатого токена. В одной транзакции сервер проверяет текущую версию регистрации и связанную с ней запись C1, погашает токен, отмечает email подтвержденным, применяет отложенные данные токена к аккаунту, очищает поля `pending_*` и записывает ровно одно событие `identity.email_verified`. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный или устаревший токен, неверный пароль и отсутствие отложенных данных дают 400 `verification_token_invalid`; истекший токен дает 400 `verification_token_expired`. Так владелец адреса, перешедший по чужой ссылке, не принимает пароль, выбранный другим регистрантом, и наоборот. Подтверждение не создает сессию или cookie. Вход еще не реализован. Планируемое правило для входа: неподтвержденный аккаунт нельзя будет использовать для входа.
- Реализация регистрации и повторной отправки. Подтвержденный адрес: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на адрес (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа; на клиента: `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час). `ConfirmEmail` дополнительно ограничивает каждый токен до 5 попыток в час и использует тот же лимит клиента. Отклоненный запрос дает 429 `rate_limited` с `Retry-After` в целых секундах и не выпускает токен. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток и ключи лимитера. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля, сценарий и первый шаг онбординга) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует прежние токены. `ConfirmEmail` требует пароль этой регистрации и проверяет его по отложенному хешу именно нажатого токена. В одной транзакции сервер проверяет текущую версию регистрации и связанную с ней запись C1, погашает токен, отмечает email подтвержденным, применяет отложенные данные токена к аккаунту, очищает поля `pending_*` и записывает ровно одно событие `identity.email_verified`. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный или устаревший токен, неверный пароль и отсутствие отложенных данных дают 400 `verification_token_invalid`; истекший токен дает 400 `verification_token_expired`. Так владелец адреса, перешедший по чужой ссылке, не принимает пароль, выбранный другим регистрантом, и наоборот. Подтверждение не создает сессию или cookie; вход доступен отдельно и принимает только пароль подтвержденной учетной записи.
- Реализация регистрации, повторной отправки и входа. Подтвержденный адрес при регистрации: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на почту (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа. `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час, диапазон 1..10000) ограничивает регистрацию, подтверждение, повторную отправку и вход по адресу клиента, если он разрешен доверенной цепочкой. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (по умолчанию 10 в час, диапазон 1..10000) ограничивает вход по нормализованному email независимо от наличия аккаунта. `ConfirmEmail` дополнительно ограничивает каждый токен до 5 попыток в час и использует лимит клиента. Отклоненный запрос дает 429 `rate_limited` с `Retry-After`. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток, лимиты и session CSRF. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
- Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии с отложенными данными этой регистрации, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики).
- Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля.
- Запрос `ConfirmEmail` принимает и `token`, и выбранный при этой регистрации `password`; прежние клиенты, отправлявшие только токен, нужно обновить. Пароль обрабатывается по правилам `LoginPassword`: NFKC-нормализация и от 1 до 128 кодовых точек; blocklist регистрации повторно не применяется. `Origin` должен совпадать с `APP_PUBLIC_URL`; отсутствующий Origin, значение null или посторонний Origin дают 403 `csrf_check_failed`. Endpoint ограничивает попытки подтверждения одним токеном до 5 в час и применяет общий лимит клиента `IDENTITY_CLIENT_HOURLY_LIMIT`; отказ по лимиту дает 429 `rate_limited` с `Retry-After`.
- Ссылка подтверждения имеет вид `<frontend origin>/verify-email#token=<token>`. Экран подтверждения во frontend пока остается заглушкой. Клиентская страница должна удалить фрагмент через `history.replaceState`, запросить явное действие пользователя и отправить токен вместе с паролем регистрации; сканер ссылок, который только открывает страницу, не расходует токен.
- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку и вход, когда вход будет реализован. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос.
- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку; после подтверждения пользователь может отдельно войти. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос.
Согласие C1 и аккаунт:
@@ -138,17 +138,17 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Сессии и CSRF:
- Планируемое поведение сессий: cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict` и без Domain; сервер хранит сессии в PostgreSQL и берет вызывающего только из сессии. Когда вход будет реализован, сессию сможет получить только подтвержденный аккаунт, а вход будет отзывать сессию из запроса и выдавать новый идентификатор и CSRF-токен. Выход будет отзывать сессию на сервере. Тайм-ауты по продуктовой политике: 24 часа простоя и 7 дней абсолютного срока; активность продлевает только срок простоя. Эти значения не настраиваются через конфигурацию.
- Схема `sessionCsrf` - заголовок `X-CSRF-Token` с привязанным к сессии токеном из `Session.csrf_token`. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`.
- Любой небезопасный запрос, включая публичные, должен нести `Origin` из настроенного allowlist, иначе 403 `csrf_check_failed` (запланировано; см. [руководство по разработке](../docs/ru/DEVELOPMENT.md#сессии-на-локальном-http)). Публичные операции identity ограничены по частоте (429 с `Retry-After`).
- Реализованные операции сессии: Login выдает cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict`, без Domain, и с Expires/Max-Age до абсолютного срока. PostgreSQL хранит только SHA-256 хеш cookie token; GET текущей сессии возвращает аккаунт и CSRF-токен после перезагрузки. Успешный вход отзывает действующую сессию из запроса и создает новую транзакционно; войти может только подтвержденный аккаунт. Logout отзывает сессию и очищает cookie; устаревшая или отозванная cookie также очищается с ответом 401. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h` (от `1m` до `30d`), а `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h` (от `1m` до `365d`); idle timeout не может превышать absolute lifetime, некорректные значения останавливают запуск. Запросы продлевают только idle deadline.
- Схема `sessionCsrf` - заголовок `X-CSRF-Token` с токеном для текущей сессии из `Session.csrf_token`. Backend выводит его через domain-separated HMAC-SHA-256 из cookie token и `IDENTITY_KEY_SECRET`, сравнивает за постоянное время и не хранит в БД. Все экземпляры должны использовать один `IDENTITY_KEY_SECRET` (не менее 32 байт), одинаковый между перезапусками; смена ключа делает прежние CSRF-токены недействительными, но не отзывает сессии PostgreSQL. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`.
- Контракт требует точный Origin с настроенным публичным origin для любого небезопасного запроса, включая публичные; backend сейчас проверяет единственный заголовок `Origin` на точное совпадение с `APP_PUBLIC_URL` в `ConfirmEmail`, `Login` и `Logout`. Logout дополнительно требует CSRF токен. `RegisterAccount` и `ResendEmailVerification` пока не проверяют Origin, хотя контракт этого требует. Backend не выводит origin из `Host` и не доверяет forwarded headers для этой проверки. Публичные операции identity ограничены по частоте (429 с `Retry-After`).
- Ответы с сессией или аккаунтом несут `Cache-Control: no-store`.
- Корневой `security` требует `sessionCookie`, поэтому операция без явного `security: []` защищена по умолчанию.
Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и какое отображение запланировано для аутентификации сессий, описано в `v1.DenyAllSecurity` и закреплено тестом `TestGeneratedServerSecurityOrder`:
Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и как `v1.SessionSecurity` применяет текущую session boundary, закреплено тестом `TestGeneratedServerSecurityOrder`:
- Он вызывает `HandleSessionCookie` раньше `HandleSessionCsrf` и передает дальше контекст, возвращенный успешным вызовом. Отсутствующее значение (нет cookie, пустой `X-CSRF-Token`) не вызывает обработчик, а обработчик, вернувший `ogenerrors.ErrSkipServerSecurity`, считается невыполненным; в обоих случаях проверка продолжается со следующей схемы, поэтому `HandleSessionCsrf` вызывается и без cookie, с исходным контекстом.
- Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`.
- Запланированное отображение: `HandleSessionCookie` пропускает отсутствующую или недействительную сессию; `HandleSessionCsrf` пропускает проверку, если в контексте нет principal (401), и возвращает типизированную ошибку при неверном токене. `NewError` отображает ошибку `SessionCsrf` и невыполненное требование с principal в контексте в 403 `csrf_check_failed`, а любой другой сбой защиты - в 401 `unauthenticated`. 401 от `Logout` также удаляет cookie.
- Реализованное отображение: `HandleSessionCookie` аутентифицирует только `GetCurrentSession`, `GetCurrentAccount` и `Logout`; для отсутствующей, неизвестной, истекшей или отозванной сессии проверка не выполнена. `HandleSessionCsrf` проверяет Origin и токен только для `Logout`; без principal отказ остается 401, неверный Origin или CSRF с действующим principal дает 403 `csrf_check_failed`. Другие protected operations не проходят allowlist и остаются 401 `unauthenticated`. 401 от `Logout` также очищает cookie.
### Каталог и анкета